/* gnu_java_awt_peer_wce_WCEURLImage.c
   Copyright (C) 2005 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 <aygshell.h>
#include <jni.h>
#include <assert.h>
#include "wce-peer.h"
#include <gnu_java_awt_peer_wce_WCEURLImage.h>
#include "GIFFile.h"


static jfieldID g_bitmapHandle_id;
static jfieldID g_preferredBltAPI_id;
static jfieldID g_transparentColor_id;
static jfieldID g_animationData_id;

/**
 * アニメーション描画用クラス
 */
class AnimationData {
public:
	int currentFrameIndex;
	unsigned int loopRemains;
	
	GIFFile* gifFile;
	DWORD* keyFrame;

	AnimationData(GIFFile* gif) : currentFrameIndex(-1), keyFrame(NULL) {
		gifFile = gif;
		this->loopRemains = gif->getLoopCount();
	}

	~AnimationData() {
		delete gifFile;
	}
};


/*
 * Class:     gnu_java_awt_peer_wce_WCEURLImage
 * Method:    initIDs
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCEURLImage_initIDs(JNIEnv *env, jclass clazz) {
	g_bitmapHandle_id     = env->GetFieldID(clazz, "bitmapHandle", "I");
	g_preferredBltAPI_id  = env->GetFieldID(clazz, "preferredBltAPI", "I");
	g_transparentColor_id = env->GetFieldID(clazz, "transparentColor", "I");
	g_animationData_id    = env->GetFieldID(clazz, "animationData", "I");

	if (! g_bitmapHandle_id || ! g_preferredBltAPI_id || ! g_transparentColor_id || ! g_animationData_id) {
		jclass ae = env->FindClass("java/awt/AWTError");	
		env->ThrowNew(ae, "Cannot get field id");
	}
}

static HBITMAP createRGB565DIB(int width, int height, WORD** bits) {
	BITMAPINFO_RGB565 biBMP = {0};

	biBMP.bmiHeader.biSize        = sizeof(BITMAPINFOHEADER);
	biBMP.bmiHeader.biBitCount    = 16;
	biBMP.bmiHeader.biCompression = BI_BITFIELDS;	// biBitCount = 16, biCompression = BI_BITFIELDSの場合はRGB565を意味する
	biBMP.bmiHeader.biPlanes      = 1;
	biBMP.bmiHeader.biWidth       = width;
	biBMP.bmiHeader.biHeight      = -height;	// トップダウンDIB
	biBMP.dwRedMask               = 0x1f << (5 + 6);
	biBMP.dwGreenMask             = 0x3f << 5;
	biBMP.dwBlueMask              = 0x1f;
	return CreateDIBSection(NULL,
						  (BITMAPINFO*) &biBMP,
						  DIB_RGB_COLORS,
						  (VOID**) bits,
						  NULL,
						  0);
}

static HBITMAP create32bppDIB(int width, int height, DWORD** bits) {
	BITMAPINFO bitmapinfo = {0};
	bitmapinfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	bitmapinfo.bmiHeader.biWidth = width;
	bitmapinfo.bmiHeader.biHeight = - height;	// トップダウンDIBにする
	bitmapinfo.bmiHeader.biPlanes = 1;
	bitmapinfo.bmiHeader.biBitCount = 32;
	bitmapinfo.bmiHeader.biCompression = BI_RGB;
	return CreateDIBSection(NULL,
							&bitmapinfo,
							DIB_RGB_COLORS,
							(VOID**) bits,
							NULL,
							0);
}


/*
 * Class:     gnu_java_awt_peer_wce_WCEURLImage
 * Method:    deleteNativeAnimationData
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCEURLImage_deleteNativeAnimationData(JNIEnv *env, jobject obj, jint data) {
	AnimationData* animationData = (AnimationData*) data;
	delete animationData;
}


/*
 * Class:     gnu_java_awt_peer_wce_WCEURLImage
 * Method:    createNativeBitmapHandle
 * Signature: (ILjava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_wce_WCEURLImage_createNativeBitmapHandle(JNIEnv *env,
																					   jobject obj,
																					   jint windowHandle,
																					   jstring filename) {
	HBITMAP hbitmap = NULL;
	_TCHAR* buff = get_string_chars(env, filename);
	// バッファ内の '/' をすべて '\' に置き換える
	int len = _tcslen(buff);
	int i;
	for (i = 0; i < len; ++i) {
		if (buff[i] == '/') {
			buff[i] = '\\';
		}
	}

	// ToDo: イメージファイルを統一的に扱うクラスを作成する
	GIFFile* gif = new GIFFile(buff);
	if (gif->isValid()) {
		bool transparentBlt = gif->hasTransparentColor();
		const int animationFrameCount = gif->getAnimationFrameCount();
		for (int i = 0; i < animationFrameCount; ++i) {
			GIFFile* aframe = gif->getAnimationFrame(i);
			transparentBlt = aframe->hasTransparentColor();
			if (transparentBlt) {
				break;
			}
		}

		// DIBを作成し、渡されたイメージの内容をコピーする
		if (! transparentBlt) {
			// 透明色が存在しない場合、RGB565形式で格納する
			WORD* bits;
			hbitmap = createRGB565DIB(gif->getGlobalWidth(), gif->getGlobalHeight(), &bits);
			if (hbitmap) {
				gif->drawRGB565(bits);
			}
		} else {
			// 透明色が存在する場合は、32bppで格納する
			DWORD* bits;
			hbitmap = create32bppDIB(gif->getGlobalWidth(), gif->getGlobalHeight(), &bits);
			if (hbitmap) {
				gif->draw(bits);
				if (transparentBlt) {
					jfieldID fid = env->GetFieldID(env->GetObjectClass(obj), "preferredBltAPI", "I");
					env->SetIntField(obj, fid, gnu_java_awt_peer_wce_WCEURLImage_TRANSPARENT_BLT);

					jint transparentColor = gif->getTransparentColor();
					fid = env->GetFieldID(env->GetObjectClass(obj), "transparentColor", "I");
					env->SetIntField(obj, fid, transparentColor);
				}
			}
		}

		if (animationFrameCount > 0) {
			// animationData フィールドにオブジェクトのアドレスを設定する
			AnimationData* animationData = new AnimationData(gif);
			env->SetIntField(obj, g_animationData_id, (jint) animationData);
		} else {
			// 不要なので削除
			delete gif;
		}

	} else {
		// GIFファイル以外
		// ToDo:不正なフォーマットのファイルを読ませるとハングしてしまう不具合への対応
		delete gif;
		hbitmap = SHLoadImageFile(buff);
	}

	free(buff);
	if (hbitmap) {
		BITMAP bitmap;
		// ビットマップの幅と高さを取得し、setDimension()メソッドを呼び出す
		if (GetObject(hbitmap, sizeof(BITMAP), &bitmap)) {
			jclass clazz = env->GetObjectClass(obj);
			if (! clazz) {
				throw_AWTError(env, "GetObjectClass() failed.");
			} else {
				jmethodID mid = env->GetMethodID(clazz,
												 "setDimension",
												 "(II)V");
				if (mid) {
					env->CallVoidMethod(obj,
										mid,
										bitmap.bmWidth,
										bitmap.bmHeight);
				}
			}
		}
	}
	return (jint) hbitmap;
}

/*
 * Class:     gnu_java_awt_peer_wce_WCEURLImage
 * Method:    nextNativeAnimationFrame
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_wce_WCEURLImage_nextNativeAnimationFrame(JNIEnv *env, jobject obj, jint data) {
	AnimationData* animationData = (AnimationData*) data;
	GIFFile* gif = animationData->gifFile;

	// 表示用ビットマップに描画する
	GIFFile* targetGif = NULL;
	unsigned int index = animationData->currentFrameIndex;
	if (-1 == index) {
		targetGif = gif;
	} else {
		targetGif = gif->getAnimationFrame(index);
	}

	HBITMAP hBitmap = (HBITMAP) env->GetIntField(obj, g_bitmapHandle_id);
	if (hBitmap) {
		BITMAP bm = {0};
		if (GetObject(hBitmap, sizeof(BITMAP), &bm)) {
			if (bm.bmWidth == targetGif->getGlobalWidth() && bm.bmHeight == targetGif->getGlobalHeight()) {
				if (bm.bmBitsPixel == 32) {
					targetGif->draw((DWORD*) bm.bmBits);
				} else if (bm.bmBitsPixel == 16) {
					targetGif->drawRGB565((WORD*) bm.bmBits);
				}
			}
		}
	}

	// 次のフレームに進める
	index++;
	unsigned int frameCount = gif->getAnimationFrameCount();
	if (index >= frameCount) {
		if (! gif->getLoopCount() || (gif->getLoopCount() && animationData->loopRemains)) {
			// 先頭のフレームに戻る
			index = -1;
			animationData->loopRemains--;
		} else {
			index = frameCount - 1;
		}
	}
	animationData->currentFrameIndex = index;

	return targetGif->getDuration();
}

