#define		STRICT
#include	<windows.h>
#include	<windowsx.h>
#include	"kedit.h"

#define		IDM_FEPOK			(41260)
#define		IDM_FEPCHAR			(41263)
#define		IDM_ACTIVATE_HWND	(41264)
#define		IDM_FEPGETMODE		(41265)
#define		IDM_FEPSETMODE		(41266)

#define		FEP_ISSENDING		(WM_USER+0x0100)


BOOL			g_fKanji = FALSE ;
TCHAR			g_szFepName[ MAX_PATH ] = TEXT("KANJIIN") ;
TCHAR			g_szFepProgram[ MAX_PATH ] = TEXT("KANJIIN.EXE") ;
static WNDPROC	g_pfnEditProc = 0 ;

/*
 * FEPを起動する
 */
static	void
FepExecute( HWND hWndMain )
{
	HWND	hWnd ;

	hWnd = FindWindow( NULL, g_szFepName ) ;
	if ( hWnd ) {
		/* FEPがあった場合は現在の逆の状態にする */
		g_fKanji = SendMessage( hWnd, WM_COMMAND, IDM_FEPGETMODE, 0 ) ;
		SendMessage( hWnd, WM_COMMAND, IDM_FEPSETMODE, g_fKanji ? 0 : 1 ) ;
#ifdef	_WIN32_WCE
	} else {
		/* FEPがなかった場合 */
		PROCESS_INFORMATION	pi ;
		TCHAR				param[ 20 ] ;
		wsprintf( param, TEXT("%d"), hWndMain ) ;
		g_fKanji = CreateProcess( g_szFepProgram, param,
						NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi ) ;
#endif	/* _WIN32_WCE */
	}
}

/*
 * FEPを通じた入力を行う
 */
static	BOOL
FepChar( HWND hWndMain, TCHAR chCharCode )
{
	HWND	hWndFep ;

	if ( chCharCode <= TEXT(' ') ) {
		return FALSE ;
	}
	hWndFep = FindWindow( NULL, g_szFepName ) ;
	if ( hWndFep ) {
		g_fKanji = SendMessage( hWndFep, WM_COMMAND, IDM_FEPGETMODE, 0 ) ? FALSE : TRUE ;
	} else {
		g_fKanji = FALSE ;
	}
	if ( g_fKanji && (chCharCode != TEXT(' ')) ) {
		SendMessage( hWndFep, WM_COMMAND, MAKEWPARAM( IDM_ACTIVATE_HWND, chCharCode ), (LPARAM) hWndMain ) ;
		return TRUE ;
	}
	return FALSE ;
}

static	LRESULT CALLBACK
KEditWndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
	switch ( message ) {
	case WM_CHAR:
		if ( FepChar( hWnd, (TCHAR) wParam ) ) {
			return 1 ;
		}
		break ;
	case WM_SYSCHAR:
		if ( (TCHAR) wParam == TEXT(' ') ) {
			if ( lParam & 0x20000000 ) {
				/* ALT+SPACEが押された場合 */
				FepExecute( hWnd ) ;
				return 1 ;
			}
		}
		break ;
	case WM_COMMAND:
		switch ( GET_WM_COMMAND_ID( wParam, lParam ) ) {
		case IDM_FEPOK:
			return IDM_FEPCHAR ;
		case IDM_FEPCHAR:
			message = WM_CHAR ;
			wParam = (TCHAR) lParam ;
			lParam = 0 ;
			break ;
		}
		break ;
	}
	return CallWindowProc( g_pfnEditProc, hWnd, message, wParam, lParam ) ;
}

void
SubclassToKEdit( HWND hWnd )
{
	if ( !g_pfnEditProc ) {
		g_pfnEditProc = (WNDPROC) GetWindowLong( hWnd, GWL_WNDPROC ) ;
	}
	SetWindowLong( hWnd, GWL_WNDPROC, (LONG) KEditWndProc ) ;
}
