/* gnu_java_awt_peer_wce_WCEImageProducer.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 <jni.h>
#include "wce-peer.h"
#include <gnu_java_awt_peer_wce_WCEImageProducer.h>

#define ImageConsumer_COMPLETESCANLINES 4 
#define ImageConsumer_IMAGEABORTED 4 
#define ImageConsumer_IMAGEERROR 1 
#define ImageConsumer_RANDOMPIXELORDER 1 
#define ImageConsumer_SINGLEFRAME 16 
#define ImageConsumer_SINGLEFRAMEDONE 2 
#define ImageConsumer_SINGLEPASS 8 
#define ImageConsumer_STATICIMAGEDONE 3 
#define ImageConsumer_TOPDOWNLEFTRIGHT 2 

static jmethodID g_setDimensions_id, g_setPixels_id, g_imageComplete_id;

/*
 * Class:     gnu_java_awt_peer_wce_WCEImageProducer
 * Method:    initIDs
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCEImageProducer_initIDs(JNIEnv *env, jclass clazz) {
	// インタフェースImageConsumerのメソッドIDを取得しておく
	jclass consumer_class = (*env)->FindClass(env, "java/awt/image/ImageConsumer");
	if (! consumer_class) {
		// エラーリターン
		jclass clazz = (*env)->FindClass(env, "java/awt/AWTError");
		if (clazz) {
			(*env)->ThrowNew(env, clazz, "Failed to find ImageConsumer");
		}
		return;
	}

	g_setDimensions_id = (*env)->GetMethodID(env, consumer_class, "setDimensions", "(II)V");
	g_setPixels_id = (*env)->GetMethodID(env, consumer_class, "setPixels", "(IIIILjava/awt/image/ColorModel;[III)V");
	g_imageComplete_id = (*env)->GetMethodID(env, consumer_class, "imageComplete", "(I)V");
}

/*
 * Class:     gnu_java_awt_peer_wce_WCEImageProducer
 * Method:    startNativeProduction
 * Signature: (I[Ljava/awt/image/ImageConsumer;)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCEImageProducer_startNativeProduction(JNIEnv *env, jobject peer_obj, jint windowHandle, jint bitmapHandle, jobjectArray c) {
	// 以下の順番でImageConsumerにイメージデータを転送する
	// 1. DIBを作成する
	// 2. DIBにイメージを描画する
	// 3. ImageConsumer.setDimensions()を呼び出す。
	// 4. DIBの内容をint[] 配列にコピーした後、ImageConsumer.setPixels()を呼び出す
	// 5. ImageConsumer.imageComplete() を呼び出す
	
	HBITMAP hBitmap = (HBITMAP) bitmapHandle;
	HBITMAP hDIB = NULL;
	BITMAP bitmap;
	int* bits;	// イメージデータ
	jintArray intArray;
	jclass colorModel_class;
	jobject consumer, colorModel;
	BOOL srcIs32bbp = FALSE;

	// 転送元ファイルが32ビットカラーであるかを調べる
	if (! GetObject(hBitmap, sizeof(BITMAP), &bitmap)) {
		jclass clazz = (*env)->FindClass(env, "java/awt/AWTError");
		(*env)->ThrowNew(env, clazz, "GetObject() failed.");
		return;
	} else {
		// 1ピクセルあたり32ビットかを調べる
		if (bitmap.bmBitsPixel == 32 && bitmap.bmPlanes == 1 && bitmap.bmBits != NULL) {
			srcIs32bbp = TRUE;
			bits = bitmap.bmBits;
		}
	}

	
	// ColorModel.getRGBdefault()を呼び出し、デフォルトRGBカラーモデルを得る
	colorModel_class = (*env)->FindClass(env, "java/awt/image/ColorModel");
	if (colorModel_class) {
		// デフォルトのRGBカラーモデルを取得する
		jmethodID mid = (*env)->GetStaticMethodID(env, colorModel_class, "getRGBdefault", "()Ljava/awt/image/ColorModel;");
		if (! mid) {
			return;
		}
		colorModel = (*env)->CallStaticObjectMethod(env, colorModel_class, mid);
		if (! colorModel) {
			return;
		}
	} else {
		// エラーリターン
		return;
	}

	// ImageConsumerへの通知用int[]を作成する
	intArray = (*env)->NewIntArray(env, bitmap.bmWidth * bitmap.bmHeight);	
	if (! intArray) {
		// エラーリターン
		throw_AWTError(env, "Failed to allocate a data buffer.");
		return;
	}
	
	if (! srcIs32bbp) {
		HDC hdc, hdcSrc, hdcDest;
		HBITMAP hOldDestBitmap, hOldSrcBitmap;
		BITMAPINFO bitmapinfo = {0};

		// BITMAPINFO構造体を初期化する
		bitmapinfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
		bitmapinfo.bmiHeader.biWidth = bitmap.bmWidth;
		bitmapinfo.bmiHeader.biHeight = -bitmap.bmHeight;	// トップダウンDIBにする
		bitmapinfo.bmiHeader.biPlanes = 1;
		bitmapinfo.bmiHeader.biBitCount = 32;
		bitmapinfo.bmiHeader.biCompression = BI_RGB;


		// DIBを作成し、渡されたイメージの内容を描画する
		hDIB = CreateDIBSection(NULL,
								&bitmapinfo,
								DIB_RGB_COLORS,
								&bits,
								NULL,
								0);
		if (hDIB == NULL) {
			// throw new AWTException();
			return;
		}
		// 転送用のDCを作成する
		hdc = GetDC((HWND) windowHandle);
		hdcSrc = CreateCompatibleDC(hdc);
		hdcDest = CreateCompatibleDC(hdc);
		ReleaseDC((HWND) windowHandle, hdc);

		hOldSrcBitmap = (HBITMAP) SelectObject(hdcSrc, hBitmap);
		hOldDestBitmap = (HBITMAP) SelectObject(hdcDest, hDIB);

		// 転送する
		BitBlt(hdcDest,
			   0,
			   0,
			   bitmap.bmWidth,
			   bitmap.bmHeight,
			   hdcSrc,
			   0,
			   0,
			   SRCCOPY);

		// 後始末
		SelectObject(hdcSrc, hOldSrcBitmap);
		SelectObject(hdcDest, hOldDestBitmap);
		DeleteDC(hdcSrc);
		DeleteDC(hdcDest);
	}

	// DIB から intArray にコピーする
	(*env)->SetIntArrayRegion(env, intArray, 0, bitmap.bmWidth * bitmap.bmHeight, bits);

	// DIBを削除する
	if (hDIB) {
		DeleteObject(hDIB);
	}

	// ImageConsumerに通知する
	{
		int i;
		int num_consumers = (*env)->GetArrayLength(env, c);
		for (i = 0; i < num_consumers; ++i) {
			consumer = (*env)->GetObjectArrayElement(env, c, i);
			if (consumer) {		
				// setDimensions()を呼び出す
				(*env)->CallVoidMethod(env, consumer, g_setDimensions_id, bitmap.bmWidth, bitmap.bmHeight);

				if ((*env)->ExceptionCheck(env)) {
					break;
				}
			
				// setPixels()を呼び出す
				(*env)->CallVoidMethod(env,
									   consumer,
									   g_setPixels_id,
									   0,				// x
									   0,				// y
									   bitmap.bmWidth,	// width
									   bitmap.bmHeight,	// height
									   colorModel,		// ColorModel
									   intArray,		// pixels
									   0,				// offset
									   bitmap.bmWidth	// scanSice
									   );

				if ((*env)->ExceptionCheck(env)) {
					break;
				}
										
				// imageComlete()を呼び出す
				(*env)->CallVoidMethod(env, consumer, g_imageComplete_id, ImageConsumer_STATICIMAGEDONE);

				if ((*env)->ExceptionCheck(env)) {
					break;
				}
			}
		}
	}
}
