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

This file is part of GNU Classpath.

GNU Classpath 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.

GNU Classpath 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 GNU Classpath; 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. */

#include <windows.h>
#include <jni.h>
#include "wce-peer.h"
#include <gnu_java_awt_peer_wce_font_WCEFontPeer.h>

/**
 * Font定数
 */
#define Font_PLAIN		0
#define Font_BOLD		1
#define Font_ITALIC		2 

#define SERIF		_T("SERIF")
#define MONOSPACED	_T("MONOSPACED")
#define DIALOGINPUT	_T("DIALOGINPUT")


// static variables
static jclass g_Rectangle2D_Float_class;
static jmethodID g_Rectangle2D_Float_mid;

/**
 * callback function.
 */
static int CALLBACK EnumFontFamProc(
  const LOGFONT FAR* lpelf, 
  const TEXTMETRIC FAR* lpntm, 
  DWORD FontType, 
  LPARAM lParam
)
{
  // copy LOGFONT.
  LOGFONT* dest = (LOGFONT*) lParam;
  *dest = *lpelf;
  return 0;
}

/*
 * Class:     gnu_java_awt_peer_wce_font_WCEFontPeer
 * Method:    createNativeFont
 * Signature: (ILjava/lang/String;II)I
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_wce_font_WCEFontPeer_createNativeFont(JNIEnv *env, jobject peer_obj, jstring name, jint style, jfloat size) {
  jint font_name_length = (*env)->GetStringLength(env, name);
  LOGFONT lf;
  _TCHAR* font_name = (_TCHAR*) malloc(sizeof(_TCHAR) * (font_name_length + 1));
  if (! font_name)
  {
    return 0;
  }
  else
  {
    // initialize LOGFONT structure;
    HDC hdc = GetDC(NULL);

    const jchar* tmp = (*env)->GetStringChars(env, name, NULL);
    _tcsncpy(font_name, tmp, font_name_length);
    font_name[font_name_length] = _T('\0');
    (*env)->ReleaseStringChars(env, name, tmp);

    lf.lfFaceName[0] = _T('\0');
    EnumFontFamilies(hdc, font_name, EnumFontFamProc, (LPARAM) &lf);
    if (lf.lfFaceName[0] == _T('\0'))
    {
      // get system font information.
      HFONT hFont = GetStockObject(SYSTEM_FONT);
      if (! GetObject(hFont, sizeof(lf), &lf))
      {
        throw_AWTError_with_error_code(env, "GetObject() failed.", GetLastError());
        free(font_name);
        ReleaseDC(NULL, hdc);
        return 0;
      }
    }
    // set font size
    // http://msdn.microsoft.com/en-us/library/aa911419.aspx
    lf.lfHeight = (LONG) (-size * GetDeviceCaps(hdc, LOGPIXELSY) / 72);
    lf.lfWidth  = 0;

    ReleaseDC(NULL, hdc);

    // setup lfPitchAndFamily and lfFaceName
    if (_tcsicmp(SERIF, font_name) == 0)
    {
      lf.lfPitchAndFamily = DEFAULT_PITCH | FF_ROMAN;
      lf.lfFaceName[0] = _T('\0');
    }
    else if (_tcsicmp(MONOSPACED, font_name) == 0)
    {
      lf.lfPitchAndFamily = FIXED_PITCH | FF_MODERN;
      _tcscpy(lf.lfFaceName, _T("Courier"));
    }
    else if (_tcsicmp(DIALOGINPUT, font_name) == 0)
    {
      lf.lfPitchAndFamily = DEFAULT_PITCH | FF_SWISS;
      _tcscpy(lf.lfFaceName, _T("Courier New"));
    }
    free(font_name);

    // set font style
    if ((style & Font_BOLD) == Font_BOLD)
    {
      lf.lfWeight = FW_BOLD;
    }
    else      
    {
      lf.lfWeight = FW_NORMAL;
    }
    if ((style & Font_ITALIC) == Font_ITALIC)
    {
      lf.lfItalic = TRUE;
    }
    else
    {
      lf.lfItalic = FALSE;
    }

    // set font quality
    lf.lfQuality = DEFAULT_QUALITY;

    return (jint) CreateFontIndirect(&lf);
  }
}

/*
 * Class:     gnu_java_awt_peer_wce_font_WCEFontPeer
 * Method:    disposeNative
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_font_WCEFontPeer_disposeNative(JNIEnv *env, jobject peer_obj, jint fontHandle) {
  DeleteObject((HFONT) fontHandle);
}

/*
 * Class:     gnu_java_awt_peer_wce_font_WCEFontPeer
 * Method:    getNativeStringBounds
 * Signature: (I[C)Ljava/awt/geom/Rectangle2D$Double;
 */
JNIEXPORT jobject JNICALL Java_gnu_java_awt_peer_wce_font_WCEFontPeer_getNativeStringBounds(JNIEnv *env, jobject peer_obj, jint fontHandle, jcharArray target) {
  // SIZE size;
  RECT rect = {0};
  HFONT hOldFont;
  HFONT hFont = (HFONT) fontHandle;
  HDC hdc;
  jchar* target_pointer;
  jint length;
  LONG tmAscent;
  TEXTMETRIC textmetric;
	
  length = (*env)->GetArrayLength(env, target);
  target_pointer = (*env)->GetCharArrayElements(env, target, NULL);
  if (! target_pointer)
  {
    return NULL;
  }

  // Get text size.
  hdc = GetDC(NULL);
  hOldFont = SelectObject(hdc, hFont);

  // GetTextExtentPoint(hdc, target_pointer, length, &size);
  if (! DrawText(hdc, target_pointer, length, &rect, DT_CALCRECT))
  {
    DWORD dwError = GetLastError();
    rect.left = rect.right = rect.top = rect.bottom = 0;
  }
  GetTextMetrics(hdc, &textmetric);
  SelectObject(hdc, hOldFont);
  ReleaseDC(NULL, hdc);
	
  (*env)->ReleaseCharArrayElements(env, target, target_pointer, 0);
	
  tmAscent = textmetric.tmAscent;

  // Rectangle2D.Float を生成して返す
  if (! g_Rectangle2D_Float_class)
  {
    g_Rectangle2D_Float_class = (*env)->FindClass(env, "java/awt/geom/Rectangle2D$Float");
    if (! g_Rectangle2D_Float_class)
    {
      throw_AWTError(env, "Failed to load Rectangle2D.Float");
      return NULL;
    }
  }
  if (! g_Rectangle2D_Float_mid)
  {
    g_Rectangle2D_Float_mid = (*env)->GetMethodID(env,
                                                  g_Rectangle2D_Float_class,
                                                  "<init>",
                                                  "(FFFF)V");
    if (! g_Rectangle2D_Float_mid)
    {
      throw_AWTError(env, "Failed to get construtor method id.");
      return NULL;
    }
  }
  return (*env)->NewObject(env,
			 g_Rectangle2D_Float_class,
			 g_Rectangle2D_Float_mid,
			 (jfloat) 0.0,		        // x
			 (jfloat) -tmAscent,		        // y(ベースラインにあわせる）
			 (jfloat) rect.right - rect.left,	// width
			 (jfloat) rect.bottom - rect.top);	// height
}