/*
Copyright 1990-2003 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/

#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Xmd.h>
#include <Xm/Xm.h>
#include <signal.h>
#include <wait.h>
#include <unistd.h>
#include <sys/types.h>

#include "xaux_common.h"
#include "xaux_ext_common.h"
#include "thai_aux.h"
#include "thai_common.h"
#include "thai_protocol.h"

#include "PaletteAux.h"
#include "OptionConfig.h"

/* Define Aux class */
xaux_class_t *xc_ = 0;
int im_ = 0;
int ic_ = 0;

/* Define Aux class */
xaux_class_t xaux_class = {
	XAUX_PALETTE_CLASS_NAME, 1,
	NULL,
	(Window)0, (Window)0,
	(Atom)0, (Atom)0, (Atom)0,
	{ (Atom)0 }, ATOM_NUM_PALETTEAUX, 0,
	{ (Atom)0 }, ATOM_NUM_PALETTEAUX, 0,
	NULL,
};

/*  Auxiliary Window User Input Method Information  */
extern PaletteAuxData 	gPAData;
extern Display 	*gDisplay;
extern char 	gLocaleID;

void xaux_ext_event_handler(Widget, XtPointer, XEvent *, Boolean *);

void PaletteAux_Connect_To_LE_Request();
void PaletteAux_Lost_Focus_Request();
void PaletteAux_Proc_LE_Notify();
void PaletteAux_Set_Selection_Owner();
void PaletteAux_Proc_LE_Change_Focus_Notify(aux_ext_data_t *aux_ext_data);
void PaletteAux_Proc_LE_Switch_Mode_Notify(aux_ext_data_t *aux_ext_data);
void PaletteAux_Proc_LE_ModeName_List_Notify(aux_ext_data_t *aux_ext_data);
void PaletteAux_Set_Default_Request();

void ActionAux_SigChld_Handler(int sig, siginfo_t * info, void * ucontext);
/*   
	Event Handler 
*/
void xaux_ext_event_handler(Widget w, XtPointer client_data, XEvent * event, Boolean * b)
{
	switch (event->type) {
		case ClientMessage:
			xaux_ext_process_client_message(XtDisplay(w),
				(XClientMessageEvent *) event);
			break;
		case SelectionClear:
			PaletteAux_Lost_Focus_Request();
			break;
	}
	return;
}

/*
	xaux_ext_init_classes(): Initialize the Atom of Auxiliary Window.
	It is in ../xaux_common/xaux_ext_common.c
*/
int xaux_ext_register_classes(Widget shell)
{
	/* Register aux class */
	if (xaux_ext_init_classes(XtDisplay(shell), &xaux_class, XtWindow(shell)) == False)
		return(-1);

	/* Register event handler */
	XtAddEventHandler(shell, PropertyChangeMask, False,
		xaux_ext_event_handler, NULL);
	XtAddEventHandler(shell, NoEventMask, True,
		xaux_ext_event_handler, NULL);

	return(0);
}

/* 
Note:
     xaux_ext_Start(), xaux_ext_Draw(), xaux_ext_Done() 
     These three functions are all called by xaux_ext_process_client_message()

     xaux_ext_SetValue() will send auxiliary window information to language engine;
*/

/* Method - Start */
Bool xaux_ext_Start(xaux_class_t *xc, aux_ext_data_t *aux_ext_data)
{
	DEBUG_printf("ext_Start: im:%d, ic:%d\n", aux_ext_data->im, aux_ext_data->ic);
	im_ = aux_ext_data->im;
	ic_ = aux_ext_data->ic;
	xc_ = xc;

	/* inform Language Engine that PaletteAux has started. */
	PaletteAux_Connect_To_LE_Request(gLocaleID);
	PaletteAux_Set_Default_Request();

	return True;
}

/* Method - Draw */
Bool xaux_ext_Draw(xaux_class_t *xc, aux_ext_data_t *aux_ext_data)
{
	DEBUG_printf("ext_Draw == im:0x%x, ic:0x%x\n",aux_ext_data->im, aux_ext_data->ic);
	im_ = aux_ext_data->im;
	ic_ = aux_ext_data->ic;
	xc_ = xc;

        PaletteAux_Proc_LE_Notify(aux_ext_data);
	return True;
}

/* Method - Done */
Bool xaux_ext_Done(xaux_class_t *xc, aux_ext_data_t *aux_ext_data)
{
	DEBUG_printf("ext_Done im:0x%x, ic_id:0x%x\n", aux_ext_data->im, aux_ext_data->ic);
	return True;
}


/* ================================================================= */
/*       Process Notify information From Language Engine             */
/* ================================================================= */
void PaletteAux_Proc_LE_Notify(aux_ext_data_t *aux_ext_data)
{
	int nIntegerCount, notifyType;

	nIntegerCount = aux_ext_data->integer_count;
	if (nIntegerCount <= 0) return;

	notifyType = aux_ext_data->integer_list[0];

	switch (notifyType) {
		case COMMONAUX_CHANGE_FOCUS_NOTIFY:
			DEBUG_printf("COMMONAUX_CHANGE_FOCUS_NOTIFY Notify Received\n");
			PaletteAux_Proc_LE_Change_Focus_Notify(aux_ext_data);
			break;
		case PALETTEAUX_SWITCH_ISC_MODE_NOTIFY:
			DEBUG_printf("PALETTEAUX_SWITCH_ISC_MODE_NOTIFY Notify Received\n");
			PaletteAux_Proc_LE_Switch_Mode_Notify(aux_ext_data);
			break;
		case COMMONAUX_MODE_NAME_NOTIFY:
			DEBUG_printf("COMMONAUX_MODE_NAME_NOTIFY Notify Received\n");
			PaletteAux_Proc_LE_ModeName_List_Notify(aux_ext_data);
			break;
	}
}

void PaletteAux_Set_Selection_Owner()
{
	Widget shell = gPAData.wdtShell;
	Atom aux_atom = XInternAtom(XtDisplay(shell), "CH_PALETTEAUX_MODULE_ATOM", False);

	XSetSelectionOwner(XtDisplay(shell), aux_atom, XtWindow(shell), CurrentTime);
}

void PaletteAux_Proc_LE_Change_Focus_Notify(aux_ext_data_t *aux_ext_data)
{
        gPAData.x       = aux_ext_data->integer_list[1];
        gPAData.y       = aux_ext_data->integer_list[2];
        gPAData.on      = aux_ext_data->integer_list[3];
        gPAData.mode_id       = aux_ext_data->integer_list[4];

        if (gPAData.on)
                PaletteAux_Set_Selection_Owner();

        PaletteAux_UpdateStatus();
}

void PaletteAux_Proc_LE_Switch_Mode_Notify(aux_ext_data_t *aux_ext_data)
{
	int mode_id = aux_ext_data->integer_list[1];
	PaletteAux_ChangeMode(mode_id, FALSE);
}

void PaletteAux_Proc_LE_ModeName_List_Notify(aux_ext_data_t *aux_ext_data)
{
	int nMode_Num = aux_ext_data->integer_list[1];
	int i;

	DEBUG_printf("nMode_Num: %d\n", nMode_Num);
	if (nMode_Num <= 0)
		return;

	if (gPAData.ppArrModeName != NULL) {
		for (i = 0; i < gPAData.nMode_Num; i ++) {
			if (gPAData.ppArrModeName[i]) free((char *)gPAData.ppArrModeName[i]);
		}
		free((char *)gPAData.ppArrModeName);
	}

	gPAData.nMode_Num = nMode_Num;
	gPAData.ppArrModeName = (char **)calloc(nMode_Num, sizeof(char *));
	for (i = 0; i < nMode_Num; i ++) {
		gPAData.ppArrModeName[i] = (char *)strdup((char *)aux_ext_data->string_list[i].ptr);
/*
		printf("Mode[%d],  th_name:%s\n", i, 
			aux_ext_data->string_list[i].ptr);
*/
	}

	PaletteAux_CreateModeListMenu();
}

/* ================================================================= */
/*             Send information to Language Engine                   */
/* ================================================================= */
void PaletteAux_Connect_To_LE_Request(int locale_id)
{
	int nIntegerCount, pIntegerList[2];

	nIntegerCount = 2;
	pIntegerList[0] = PALETTEAUX_CONNECT;
	pIntegerList[1] = locale_id;
	NotifyIntegerListDataToLanguageEngine(gDisplay, nIntegerCount, pIntegerList);
}

void PaletteAux_Change_LE_Position_Request(int x, int y)
{
	int nIntegerCount, pIntegerList[3];

	nIntegerCount = 3;
	pIntegerList[0] = PALETTEAUX_CHANGE_POSITION;
	pIntegerList[1] = x;
	pIntegerList[2] = y;
	NotifyIntegerListDataToLanguageEngine(gDisplay, nIntegerCount, pIntegerList);
}

void PaletteAux_Switch_LE_Mode_Request(int mode_id)
{
	int nIntegerCount, pIntegerList[2];

	nIntegerCount = 2;
	pIntegerList[0] = PALETTEAUX_SWITCH_ISC_MODE;
	pIntegerList[1] = mode_id;
	NotifyIntegerListDataToLanguageEngine(gDisplay, nIntegerCount, pIntegerList);
}

void PaletteAux_Show_KeyboardAux_Request(int nKeyboardID)
{
	int nIntegerCount, pIntegerList[2];

	nIntegerCount = 2;
	pIntegerList[0] = PALETTEAUX_SHOW_KEYBOARDAUX;
	pIntegerList[1] = nKeyboardID;
	NotifyIntegerListDataToLanguageEngine(gDisplay, nIntegerCount, pIntegerList);
}

void PaletteAux_Show_OptionAux_Request()
{
	int nIntegerCount, pIntegerList[1];

	nIntegerCount = 1;
	pIntegerList[0] = PALETTEAUX_SHOW_OPTIONAUX;
	NotifyIntegerListDataToLanguageEngine(gDisplay, nIntegerCount, pIntegerList);
}

void ActionAux_Register_SigChld_Handler()
{
	struct sigaction act;

	act.sa_handler = NULL;
	act.sa_sigaction = ActionAux_SigChld_Handler;
	sigfillset(&act.sa_mask);
	act.sa_flags = SA_SIGINFO;

	sigaction(SIGCHLD, &act, NULL);
}

void ActionAux_SigChld_Handler(int sig, siginfo_t * info, void * ucontext)
{
	pid_t   pid;
	int     status;

	while ((pid = waitpid(info->si_pid, &status, WNOHANG|WUNTRACED)) > 0) {
		DEBUG_printf("pid %d: die\n", pid);
	}
}

void PaletteAux_StartAction_Request(char *command)
{
	static bSIGInited = 0;
	int pid;
	
	if (bSIGInited == 0) 
		ActionAux_Register_SigChld_Handler();

	pid = fork();
	if (pid < 0) {
		return;
	} else if (pid == 0) {
		/* in child process */
		execl("/bin/sh", "sh", "-c", command, (char *)0);

		/* Exec failed. */
		fprintf (stderr, "Error: Could not exec %s!\n", command);
		_exit(1);
	}
}

void PaletteAux_Lost_Focus_Request()
{
	int nIntegerCount, pIntegerList[1];

	nIntegerCount = 1;
	pIntegerList[0] = COMMONAUX_LOST_FOCUS;
	NotifyIntegerListDataToLanguageEngine(gDisplay, nIntegerCount, pIntegerList);
}

void PaletteAux_Set_Default_Request()
{
	int nIntegerCount, pIntegerList[3];

	TThaiOptions aThaiOptions;

	Get_ThaiOptions_From_Profile(&aThaiOptions);

	nIntegerCount = 3;
	pIntegerList[0] = COMMONAUX_SET_DEFAULT_VALUE;
	pIntegerList[1] = aThaiOptions.isc_mode_id;
	pIntegerList[2] = aThaiOptions.keyboard_id;

	NotifyIntegerListDataToLanguageEngine(gDisplay, nIntegerCount, pIntegerList);
}

NotifyIntegerListDataToLanguageEngine(Display *display, 
int nIntegerCount, int *pIntegerList)
{
	aux_ext_data_t aux_ext_data;

	DEBUG_printf("im_:%d, ic_:%d\n", im_, ic_);

	if (!im_ || !ic_ || !xc_)
		return;

	aux_ext_data.im = im_;
	aux_ext_data.ic = ic_;
	aux_ext_data.integer_count = nIntegerCount;
	aux_ext_data.integer_list = pIntegerList;
	aux_ext_data.string_count = 0;
	aux_ext_data.string_list = NULL;
	aux_ext_data.string_ptr = NULL;
	aux_ext_data.point.x = 0;
	aux_ext_data.point.y = 0;

	xaux_ext_SetValue(display, xc_, &aux_ext_data);
	XFlush(display);
}

NotifyStringListDataToLanguageEngine(Display *display, 
int nIntegerCount, int *pIntegerList,
int nStringCount,  int *pStringLen,
char **pStringList)
{
	int i;

	aux_ext_data_t aux_ext_data;
	aux_ext_string_t *p;

	DEBUG_printf("im_:%d, ic_:%d\n", im_, ic_);

	if (!im_ || !ic_ || !xc_)
		return;

	aux_ext_data.im = im_;
	aux_ext_data.ic = ic_;
	aux_ext_data.integer_count = nIntegerCount;
	aux_ext_data.integer_list = pIntegerList;
	aux_ext_data.point.x = 0;
	aux_ext_data.point.y = 0;

	aux_ext_data.string_count = nStringCount;
	aux_ext_data.string_ptr = NULL;

	if (nStringCount > 0) {
		aux_ext_data.string_list = (aux_ext_string_t *) calloc(nStringCount, sizeof(aux_ext_string_t));
		for (i = 0; i < nStringCount; i++) {
			aux_ext_string_t *p = &aux_ext_data.string_list[i];
			p->length = pStringLen[i];
			p->ptr = (unsigned char *) (pStringList[i]);
		}
	}

	xaux_ext_SetValue(display, xc_, &aux_ext_data);
	XFlush(display);

	free(aux_ext_data.string_list);
}

