/* WCEFontPeer.java
   Copyright (C) 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.

This file is part of Mysaifu JVM.

Mysaifu JVM is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.

Mysaifu JVM is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with Mysaifu JVM; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package gnu.java.awt.peer.wce.font;

import gnu.java.awt.peer.ClasspathFontPeer;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.FontMetrics;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.LineMetrics;
import java.awt.font.TextAttribute;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
import java.text.CharacterIterator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;

public class WCEFontPeer
    extends ClasspathFontPeer
{
  /**
   * FreeTypeFace property key.
   */
  public static final String FREE_TYPE_FACE_KEY = "gnu.java.awt.peer.wce.font.WCEFontPeer.freeTypeFace";

  /**
   * the native font handle.
   */
  private int fontHandle;

  /**
   * FreeTypeFace
   */
  private FreeTypeFace face;

  /**
   * creates a new WCEFontPeer object.
   * 
   * @param name logical name.
   * @param style the style.
   * @param size the size.
   */
  public WCEFontPeer(String name, int style, int size)
  {
    super(name, style, size);
  }

  public WCEFontPeer(String name, Map attrs)
  {
    super(name, attrs);
    FreeTypeFace face = (FreeTypeFace) attrs.get(FREE_TYPE_FACE_KEY);
    if (face != null)
      {
        logicalName = "Dialog";
        this.face = face;
        familyName = face.getFamilyName();
      }
  }

  /**
   * ネイティブフォントハンドルを返す
   */
  public int getFontHandle()
  {
    if (this.fontHandle == 0)
      {
        this.fontHandle = createNativeFont(this.logicalName, this.style,
                                           this.size);
      }
    return this.fontHandle;
  }

  private native int createNativeFont(String name, int style, float size);

  /**
   * ネイティブフォントリソースを開放する。
   */
  public void dispose()
  {
    if (this.fontHandle != 0)
      {
        disposeNative(this.fontHandle);
        this.fontHandle = 0;
      }
  }

  /**
   * ネイティブフォントリソースを開放する。
   */
  private native void disposeNative(int fontHandle);

  protected void finalize()
  {
    dispose();
  }

  public boolean canDisplay(Font font, int c)
  {
    // FIXME: inquire with pango
    return true;
  }

  public int canDisplayUpTo(Font font, CharacterIterator i, int start, int limit)
  {
    // ToDo: implement
    return -1;  // -1 means all characters are displayable.
  }

  public String getSubFamilyName(Font font, Locale locale)
  {
    throw new UnsupportedOperationException();
  }

  public String getPostScriptName(Font font)
  {
    throw new UnsupportedOperationException();
  }

  public int getNumGlyphs(Font font)
  {
    throw new UnsupportedOperationException();
  }

  public int getMissingGlyphCode(Font font)
  {
    throw new UnsupportedOperationException();
  }

  public byte getBaselineFor(Font font, char c)
  {
    throw new UnsupportedOperationException();
  }

  public String getGlyphName(Font font, int glyphIndex)
  {
    throw new UnsupportedOperationException();
  }

  public GlyphVector createGlyphVector(Font font, FontRenderContext frc,
                                       CharacterIterator ci)
  {
    List<Character> list = new ArrayList<Character>();
    for (char c = ci.first(); c != CharacterIterator.DONE; c = ci.next())
      {
        list.add(c);
      }
    final int size = list.size();
    char[] tmp = new char[size];
    for (int i = 0; i < size; ++i)
      {
        tmp[i] = list.get(i).charValue();
      }
    return layoutGlyphVector(font, frc, tmp, 0, tmp.length,
                             Font.LAYOUT_LEFT_TO_RIGHT);
  }

  public GlyphVector createGlyphVector(Font font, FontRenderContext ctx,
                                       int[] glyphCodes)
  {
    throw new UnsupportedOperationException();
  }

  public GlyphVector layoutGlyphVector(Font font, FontRenderContext frc,
                                       char[] chars, int start, int limit,
                                       int flags)
  {
    try
      {
        if (face != null)
          {
            return new FreeTypeGlyphVector(face, font, frc, chars, start,
                                           limit, flags);
          }
        else
          {
            return new WCEGlyphVector(font, new String(chars, start, limit
                                                                     - start),
                                      frc, flags);
          }
      }
    catch (FreeTypeException ftfe)
      {
        ftfe.printStackTrace();
        return null;
      }

  }

  public FontMetrics getFontMetrics(Font font)
  {
    if (this.face != null)
      {
        return new FreeTypeFontMetrics(font, this.face);
      }
    else
      {
        return new WCEFontMetrics(font);
      }
  }

  public boolean hasUniformLineMetrics(Font font)
  {
    throw new UnsupportedOperationException();
  }

  public LineMetrics getLineMetrics(Font font, CharacterIterator ci, int begin,
                                    int limit, FontRenderContext rc)
  {
    return new WCEFontLineMetrics(getFontMetrics(font), limit - begin);
  }

  public Rectangle2D getMaxCharBounds(Font font, FontRenderContext rc)
  {
    throw new UnsupportedOperationException();
  }

  public Rectangle2D getStringBounds(Font font, CharacterIterator ci,
                                     int begin, int limit, FontRenderContext frc)
  {
    char[] target = toCharArray(ci, begin, limit);
    Rectangle2D.Float r = getNativeStringBounds(getFontHandle(), target);
    // ToDo: FontRenderContext を使用して座標変換処理を行う
    return r;
  }

  /**
   * CharacterIteratorからStringオブジェクトを生成する。
   */
  private char[] toCharArray(CharacterIterator iter, int begin, int limit)
  {
    char[] result = new char[limit - begin];
    iter.setIndex(begin);
    for (int index = 0; index < result.length; index++)
      {
        result[index] = iter.current();
        iter.next();
      }
    return result;
  }

  /**
   * 指定されたフォントハンドルを使用して、char[] 配列内の文字が占める 画面上の大きさを返す。
   * 
   * @param fontHandle フォントハンドル
   * @param target 検証対象となる文字の配列
   */
  protected native Rectangle2D.Float getNativeStringBounds(int fontHandle,
                                                           char[] target);

  /**
   * LineMetrics (Copy from Gtk peer)
   */
  protected class WCEFontLineMetrics
      extends LineMetrics
  {
    FontMetrics fm;

    int nchars;

    public WCEFontLineMetrics(FontMetrics m, int n)
    {
      fm = m;
      nchars = n;
    }

    public float getAscent()
    {
      return (float) fm.getAscent();
    }

    public int getBaselineIndex()
    {
      return Font.ROMAN_BASELINE;
    }

    public float[] getBaselineOffsets()
    {
      return new float[3];
    }

    public float getDescent()
    {
      return (float) fm.getDescent();
    }

    public float getHeight()
    {
      return (float) fm.getHeight();
    }

    public float getLeading()
    {
      return getHeight() - (getAscent() + getDescent());
    }

    public int getNumChars()
    {
      return nchars;
    }

    public float getStrikethroughOffset()
    {
      return 0.f;
    }

    public float getStrikethroughThickness()
    {
      return 0.f;
    }

    public float getUnderlineOffset()
    {
      return 0.f;
    }

    public float getUnderlineThickness()
    {
      return 0.f;
    }
  }

  /**
   * Implementation of {@link Font#deriveFont(int, float)}
   * 
   * @param font the font this peer is being called from. This may be useful if
   *          you are sharing peers between Font objects. Otherwise it may be
   *          ignored.
   */
  public Font deriveFont(Font font, int style, float size)
  {
    Map attrs = new HashMap();
    getStandardAttributes(attrs);
    copyStyleToAttrs(style, attrs);
    copySizeToAttrs(size, attrs);
    attrs.put(FREE_TYPE_FACE_KEY, this.face);
    return tk().getFont(logicalName, attrs);
  }

  /**
   * Implementation of {@link Font#deriveFont(float)}
   * 
   * @param font the font this peer is being called from. This may be useful if
   *          you are sharing peers between Font objects. Otherwise it may be
   *          ignored.
   */

  public Font deriveFont(Font font, float size)
  {
    Map attrs = new HashMap();
    getStandardAttributes(attrs);
    copySizeToAttrs(size, attrs);
    attrs.put(FREE_TYPE_FACE_KEY, this.face);
    return tk().getFont(logicalName, attrs);
  }

  /**
   * Implementation of {@link Font#deriveFont(int)}
   * 
   * @param font the font this peer is being called from. This may be useful if
   *          you are sharing peers between Font objects. Otherwise it may be
   *          ignored.
   */

  public Font deriveFont(Font font, int style)
  {
    Map attrs = new HashMap();
    getStandardAttributes(attrs);
    copyStyleToAttrs(style, attrs);
    attrs.put(FREE_TYPE_FACE_KEY, this.face);
    return tk().getFont(logicalName, attrs);
  }

  /**
   * Implementation of {@link Font#deriveFont(int, AffineTransform)}
   * 
   * @param font the font this peer is being called from. This may be useful if
   *          you are sharing peers between Font objects. Otherwise it may be
   *          ignored.
   */

  public Font deriveFont(Font font, int style, AffineTransform t)
  {
    Map attrs = new HashMap();
    getStandardAttributes(attrs);
    copyStyleToAttrs(style, attrs);
    copyTransformToAttrs(t, attrs);
    attrs.put(FREE_TYPE_FACE_KEY, this.face);
    return tk().getFont(logicalName, attrs);
  }

  /**
   * Implementation of {@link Font#deriveFont(AffineTransform)}
   * 
   * @param font the font this peer is being called from. This may be useful if
   *          you are sharing peers between Font objects. Otherwise it may be
   *          ignored.
   */
  public Font deriveFont(Font font, AffineTransform t)
  {
    Map attrs = new HashMap();
    getStandardAttributes(attrs);
    copyTransformToAttrs(t, attrs);
    attrs.put(FREE_TYPE_FACE_KEY, this.face);
    return tk().getFont(logicalName, attrs);
  }

  /**
   * Implementation of {@link Font#deriveFont(Map)}
   * 
   * @param font the font this peer is being called from. This may be useful if
   *          you are sharing peers between Font objects. Otherwise it may be
   *          ignored.
   */
  public Font deriveFont(Font font, Map attrs)
  {
    attrs.put(FREE_TYPE_FACE_KEY, this.face);
    return tk().getFont(logicalName, attrs);
  }

  public FreeTypeFace getFreeTypeFace()
  {
    return this.face;
  }
}
