/* gnu_java_awt_peer_wce_font_FreeTypeFace.cpp
   Copyright (C) 2008 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 <gnu_java_awt_peer_wce_font_FreeTypeFace.h>
#include "FreeTypeFace.h"

/*
 * Class:     gnu_java_awt_peer_wce_font_FreeTypeFace
 * Method:    createNativeFromFile
 * Signature: (Ljava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_wce_font_FreeTypeFace_createNativeFromFile
  (JNIEnv *env, jobject obj, jstring fileName)
{
    const jsize len = env->GetStringLength(fileName);
    const jchar* src = env->GetStringChars(fileName, NULL);

    int buflen = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR) src, len, NULL, 0, NULL, NULL);
    char* fname = (char*) ::malloc(buflen + 1);
    if (! fname)
    {
      jclass clazz = env->FindClass("java/lang/OutOfMemoryError");
      env->ThrowNew(clazz, "Cannot allocate a buffer for string");
      return 0;
    }

    WideCharToMultiByte(CP_ACP, 0, (LPCWSTR) src, len, fname, buflen + 1, NULL, NULL);
    fname[buflen] = '\0';
    FreeTypeFace* data = new FreeTypeFace();
    FT_Error error = data->loadFrom(fname);
    free(fname);
    env->ReleaseStringChars(fileName, src);
    if (error)
    {
	delete data;
	jclass clazz = env->FindClass("java/awt/FontFormatException");
	env->ThrowNew(clazz, data->getErrorMessage(error));
    }
    return (jint) data;
}

/*
 * Class:     gnu_java_awt_peer_wce_font_FreeTypeFace
 * Method:    createNativeFromStream
 * Signature: (Ljava/io/InputStream;)I
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_wce_font_FreeTypeFace_createNativeFromStream
  (JNIEnv *env, jobject obj, jobject inputStream)
{
  FreeTypeFace* result = NULL;
  jbyteArray arr = env->NewByteArray(16 * 1024);
  jmethodID mid = env->GetMethodID(env->GetObjectClass(inputStream), "read", "([B)I");
  if (! arr || ! mid)
  {
    return 0;
  }
  const jsize arraySize = env->GetArrayLength(arr);
  const size_t defaultBufferSize = 64 * 1024;

  // Initialize buffer
  int bufferSize = defaultBufferSize;
  unsigned char* buffer = (unsigned char*) ::malloc(defaultBufferSize);
  if (! buffer)
  {
    jclass clazz = env->FindClass("java/lang/OutOfMemoryError");
    env->ThrowNew(clazz, "Cannot allocate a buffer for string");
    return 0;
  }

  // read all data from the stream.
  jsize totalSize = 0;
  jint len;

  while ((len = env->CallIntMethod(inputStream, mid, arr)) != -1)
  {
    if (env->ExceptionCheck())
    {
      break;
    }
    if (totalSize + len >= bufferSize)
    {
      // expands the buffer.
      bufferSize += defaultBufferSize;
      buffer = (unsigned char*) ::realloc(buffer, bufferSize);
      if (! buffer)
      {
        break;
      }
    }
    // copy data from the stream.
    jbyte* src = env->GetByteArrayElements(arr, NULL);
    memcpy(buffer + totalSize, src, len);
    totalSize += len;
    env->ReleaseByteArrayElements(arr, src, 0);
  }
  if (buffer)
  {
    // adjust buffer size.
    bufferSize = totalSize;
    buffer = (unsigned char*) ::realloc(buffer, totalSize);
    if (buffer)
    {
      result = new FreeTypeFace();
      FT_Error error = result->loadFrom(buffer, bufferSize);
      if (error)
      {
        const char* msg = result->getErrorMessage(error);
        delete result;
	free(buffer);
	result = NULL;

        jclass clazz = env->FindClass("java/awt/FontFormatException");
        env->ThrowNew(clazz, msg);
      }
    }
  }
  return (jint) result;
}


/*
 * Class:     gnu_java_awt_peer_wce_font_FreeTypeFace
 * Method:    initNative
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_font_FreeTypeFace_initNative
  (JNIEnv *env, jclass clazz)
{
  int error = FreeTypeFace::initialize();
  if ( error )
  {
    jclass clazz = env->FindClass("java/awt/AWTError");
    env->ThrowNew(clazz, "Failed to initialize FreeType");
  }
}
/*
 * Class:     gnu_java_awt_peer_wce_font_FreeTypeFace
 * Method:    getNativeFamilyName
 * Signature: (I)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_gnu_java_awt_peer_wce_font_FreeTypeFace_getNativeFamilyName
  (JNIEnv *env, jobject obj, jint nativePointer)
{
    FreeTypeFace* data = (FreeTypeFace*) nativePointer;
    FT_Face face = data->getFace();
    FT_String* name = face->family_name;
    return env->NewStringUTF(name);
}

/*
 * Class:     gnu_java_awt_peer_wce_font_FreeTypeFace
 * Method:    setNativeCharSize
 * Signature: (IF)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_font_FreeTypeFace_setNativeCharSize
  (JNIEnv *env, jobject obj, jint nativePointer, jfloat size)
{
  FreeTypeFace* data = (FreeTypeFace*) nativePointer;
  data->setSize((FT_F26Dot6)(size * 64.0f));
}

/*
 * Class:     gnu_java_awt_peer_wce_font_FreeTypeFace
 * Method:    getNativeFontMetrics
 * Signature: (IF)[F
 */
JNIEXPORT jfloatArray JNICALL Java_gnu_java_awt_peer_wce_font_FreeTypeFace_getNativeFontMetrics
  (JNIEnv *env, jobject obj, jint nativePointer, jfloat size)
{
  FreeTypeFace* data = (FreeTypeFace*) nativePointer;
  data->setSize((FT_F26Dot6)(size * 64.0f));

  jfloatArray result = env->NewFloatArray(6);
  if (result)
  {
    FT_Face face = data->getFace();
    FT_Size size = face->size;
    jfloat* values = env->GetFloatArrayElements(result, NULL);
    values[gnu_java_awt_peer_wce_font_FreeTypeFace_LEADING_INDEX] = (size->metrics.height - size->metrics.ascender + size->metrics.descender) / 64.0f;
    values[gnu_java_awt_peer_wce_font_FreeTypeFace_ASCENT_INDEX] = size->metrics.ascender / 64.0f;
    values[gnu_java_awt_peer_wce_font_FreeTypeFace_DESCENT_INDEX] = -size->metrics.descender / 64.0f;
    values[gnu_java_awt_peer_wce_font_FreeTypeFace_MAXASCENT_INDEX] = size->metrics.ascender / 64.0f;
    values[gnu_java_awt_peer_wce_font_FreeTypeFace_MAXDESCENT_INDEX] = -size->metrics.descender / 64.0f;
    values[gnu_java_awt_peer_wce_font_FreeTypeFace_MAXADVANCE_INDEX] = size->metrics.max_advance / 64.0f;
    env->ReleaseFloatArrayElements(result, values, 0);
  }
  return result;
}

/*
 * Class:     gnu_java_awt_peer_wce_font_FreeTypeFace
 * Method:    getNativeCharsWidth
 * Signature: (IF[CII)F
 */
JNIEXPORT jfloat JNICALL Java_gnu_java_awt_peer_wce_font_FreeTypeFace_getNativeCharsWidth
  (JNIEnv *env, jobject obj, jint nativePointer, jfloat size, jcharArray text, jint offset, jint length)
{
  FreeTypeFace* data = (FreeTypeFace*) nativePointer;
  jchar* ca = env->GetCharArrayElements(text, NULL);
  FT_F26Dot6 width = data->getWidth((FT_F26Dot6) (size*64.0f), (const _TCHAR*) (ca + offset), length);
  env->ReleaseCharArrayElements(text, ca, 0);
  return (jfloat) (width / 64.0f);
}

/*
 * Class:     gnu_java_awt_peer_wce_font_FreeTypeFace
 * Method:    disposeNative
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_font_FreeTypeFace_disposeNative
  (JNIEnv *env, jobject obj, jint nativePointer)

{
    FreeTypeFace* data = (FreeTypeFace*) nativePointer;
    delete data;
}