/*
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 <Xm/Xm.h>
#include <Xm/ScrolledW.h>
#include <Xm/RowColumn.h>
#include <Xm/ToggleBG.h>
#include <Xm/List.h>
#include <Xm/PushB.h>
#include <Xm/PushBG.h>
#include <Xm/SeparatoG.h>
#include <Xm/LabelG.h>
#include <Xm/Form.h>
#include <Xm/MwmUtil.h>
#include <locale.h>

#include "hzinput.h"
#include "OptionConfig.h"

typedef struct _OptionAuxData {
	Widget 	wdtShell;
	Widget 	wdtSelectedList;
	Widget 	wdtOptionsArea;
	Widget 	wdtOptionsList[MAX_ENGINE_NUM];

	int 	nIME_id;

} OptionAuxData;

OptionAuxData 	gOptData;
char		gLocaleID;
Display		*gDisplay;

extern int 		gIMEOptionsNum;
extern IMEOption_Item	*gIMEOptions[MAX_ENGINE_NUM];
 		
void OptionAux_Hide();
void OptionAux_Show();
void OptionAux_InitObjects();
void OptionAux_DestroyProc(Widget widget, XtPointer pClientData, XtPointer pCallData);
void OptionAux_OK_cb(Widget widget, XtPointer pClientData, XtPointer pCallData);
void OptionAux_Apply_cb(Widget widget, XtPointer pClientData, XtPointer pCallData);
void OptionAux_Reset_cb(Widget widget, XtPointer pClientData, XtPointer pCallData);
void OptionAux_Cancel_cb(Widget widget, XtPointer pClientData, XtPointer pCallData);
void OptionAux_Argument_Display_cb(Widget w, XtPointer data, XtPointer cbk);
void OptionAux_Argument_Changed_cb(Widget w, XtPointer client_data, XtPointer call_data);
void OptionAux_OptionValue_Changed_cb(Widget w, XtPointer client_data, XtPointer call_data);

int main(int argc, char **argv)
{
	XtAppContext    app;

	Widget shell, form, scrolllist_w, scroll_w, separator;
	Widget rowcol, sel_label, togglebutton;
	Widget ok_button, apply_button, reset_button, cancel_button;
	XmString xmstr;
	Atom xa_ct;
	int nXPos, nYPos, nWidth, nHeight;
	int nFrameWidth, nFrameHeight, nScrollWidth, nScrollHeight;
	int nListWidth, nListHeight;
	int nButtonWidth, nYListWidget, nYLabelWidget;
	int i, nRows, nYDelta, nSpacing;

	/* creates all of the widgets in the dialog box. */
	Arg arrArg[24];
	int nArg;

	char *msg, *lpszTitle;
	char *locale_name = NULL;

	gOptData.nIME_id = 0;

	nFrameWidth = 500;
	nFrameHeight = 530;
	nListWidth = 28;
	nListHeight = 55;
	nScrollWidth = 52;
	nScrollHeight = nListHeight;
	nButtonWidth = 16;
	nYDelta = 8;
	nSpacing = 8;
	nYLabelWidget = 6;
	nYListWidget  = 16;

	XtSetLanguageProc((XtAppContext)0, (XtLanguageProc)0, (XtPointer)0) ;

	/* create but do NOT manage the container dialog. */
	nArg = 0;
	XtSetArg(arrArg[nArg], XmNx, 620); nArg++;
	XtSetArg(arrArg[nArg], XmNy, 420); nArg++;
	XtSetArg(arrArg[nArg], XmNinput, FALSE); nArg++;
	XtSetArg(arrArg[nArg], XmNdefaultPosition, FALSE); nArg++;
	XtSetArg(arrArg[nArg], XmNheight, nFrameHeight); nArg++;
	XtSetArg(arrArg[nArg], XmNwidth, nFrameWidth); nArg++;
	XtSetArg(arrArg[nArg], XmNmwmFunctions, MWM_FUNC_ALL | MWM_FUNC_CLOSE); nArg++;
	shell = XtAppInitialize(&app, "OptionAux", NULL, 0, &argc, argv, NULL, arrArg, nArg);

	locale_name = setlocale(LC_CTYPE, NULL);
	if (locale_name == NULL) return;
	locale_name = (char *) strdup(locale_name);
	gLocaleID = get_encodeid_from_locale(locale_name);
	Msg_Init(locale_name);
	free(locale_name);

	XtAddCallback(shell, XmNdestroyCallback, OptionAux_DestroyProc, NULL);
	gOptData.wdtShell = shell;
	gDisplay = XtDisplay(shell);

	/* Set the window title */
	msg = (char *)get_msg_by_msgid(0, "IME Options Setting");
	xa_ct = XmInternAtom(XtDisplay(shell), "COMPOUND_TEXT", FALSE);
	xmstr = XmStringCreateLocalized(msg);
	lpszTitle = XmCvtXmStringToCT(xmstr);
	XtVaSetValues(shell, XmNtitle, lpszTitle, XmNtitleEncoding, xa_ct, NULL);
	XmStringFree(xmstr);
	free(msg);

	form = XtVaCreateManagedWidget("Form", xmFormWidgetClass, shell, NULL);

	/* create hint label indicate which IM not added */
	nXPos = 8;
	nYPos = nYLabelWidget;
	msg = (char *)get_msg_by_msgid(1, "Selected input methods:");
	xmstr = XmStringCreateLtoR(msg, XmSTRING_DEFAULT_CHARSET);
	free(msg);
	sel_label = XtVaCreateManagedWidget ("label", 
		xmLabelGadgetClass,  form, 
		XmNleftAttachment, XmATTACH_POSITION,
		XmNleftPosition, nXPos,
		XmNtopAttachment, XmATTACH_POSITION,
		XmNtopPosition, nYPos,
		XmNlabelString, xmstr,
		NULL);
	XmStringFree(xmstr);
		
	nYPos = nYListWidget;
	nArg=0;
	XtSetArg(arrArg[nArg],XmNselectionPolicy, XmBROWSE_SELECT); nArg++;
	XtSetArg(arrArg[nArg],XmNrecomputeSize, FALSE); nArg++;
	XtSetArg(arrArg[nArg],XmNresizable, FALSE); nArg++;
	XtSetArg(arrArg[nArg],XmNleftAttachment, XmATTACH_POSITION); nArg++;
	XtSetArg(arrArg[nArg],XmNleftPosition, nXPos); nArg++;
	XtSetArg(arrArg[nArg],XmNrightAttachment, XmATTACH_POSITION); nArg++;
	XtSetArg(arrArg[nArg],XmNrightPosition, nXPos+nListWidth); nArg++;
	XtSetArg(arrArg[nArg],XmNtopAttachment, XmATTACH_POSITION); nArg++;
	XtSetArg(arrArg[nArg],XmNtopPosition, nYPos); nArg++;
	XtSetArg(arrArg[nArg],XmNbottomAttachment, XmATTACH_POSITION); nArg++;
	XtSetArg(arrArg[nArg],XmNbottomPosition, nYPos+nListHeight); nArg++;
	scrolllist_w = XmCreateScrolledList(form, "scroll_list1", arrArg, nArg);
	XtManageChild(scrolllist_w);
	XtAddCallback (scrolllist_w, XmNbrowseSelectionCallback, OptionAux_Argument_Display_cb, NULL);
	gOptData.wdtSelectedList = scrolllist_w;

	/* create hint label indicate which IM have been added */
	nXPos += nListWidth + 6;
	nYPos = nYLabelWidget;
	msg = (char *)get_msg_by_msgid(2, "IME Options:");
	xmstr = XmStringCreateLtoR(msg, XmSTRING_DEFAULT_CHARSET);
	free(msg);
	sel_label = XtVaCreateManagedWidget ("label", 
		xmLabelGadgetClass,  form, 
		XmNleftAttachment, XmATTACH_POSITION,
		XmNleftPosition, nXPos,
		XmNtopAttachment, XmATTACH_POSITION,
		XmNtopPosition, nYPos,
		XmNlabelString, xmstr,
		NULL);
	XmStringFree(xmstr);
		
	nYPos = nYListWidget;
	scroll_w = XtVaCreateManagedWidget ("scrolled_w",
		xmScrolledWindowWidgetClass, form,
		XmNscrollingPolicy, XmAUTOMATIC,
		XmNleftAttachment, XmATTACH_POSITION,
		XmNleftPosition, nXPos,
		XmNrightAttachment, XmATTACH_POSITION,
		XmNrightPosition, nXPos+nScrollWidth,
		XmNtopAttachment, XmATTACH_POSITION,
		XmNtopPosition, nYPos,
		XmNbottomAttachment, XmATTACH_POSITION,
		XmNbottomPosition, nYPos+nScrollHeight,
		NULL);

	gOptData.wdtOptionsArea = scroll_w;

	for (i=0; i<MAX_ARGS_NUM; i++)
		gOptData.wdtOptionsList[i] = 0;

	/* Create separator line */
	nYPos = nYListWidget + nScrollHeight + nYDelta;
	separator = XtVaCreateManagedWidget ("separator",
		xmSeparatorGadgetClass, form,
		XmNleftAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		XmNtopAttachment, XmATTACH_POSITION,
		XmNtopPosition, nYPos,
		NULL);
	
	/* Create 4 Buttons: OK/Apply/Reset/Cancel */
	nXPos = (100 - 3 * nSpacing - 4 * nButtonWidth) / 2;
	nYPos += nYDelta;
	msg = (char *)get_msg_by_msgid(3, "OK");
	xmstr = XmStringCreateLtoR(msg, XmSTRING_DEFAULT_CHARSET);
	free(msg);
	ok_button = XtVaCreateWidget ("OK",
		xmPushButtonWidgetClass, form,
		XmNrecomputeSize, True,
		XmNlabelString, xmstr,
		XmNleftAttachment, XmATTACH_POSITION,
		XmNleftPosition, nXPos,
		XmNtopAttachment, XmATTACH_POSITION,
		XmNtopPosition, nYPos,
		XmNrightAttachment, XmATTACH_POSITION,
		XmNrightPosition, nXPos+nButtonWidth,
		NULL);
	XtManageChild(ok_button);
	XtAddCallback(ok_button, XmNactivateCallback, OptionAux_OK_cb, 0);
	XmStringFree(xmstr);

	nXPos += nSpacing + nButtonWidth;
	msg = (char *)get_msg_by_msgid(4, "Apply");
	xmstr = XmStringCreateLtoR(msg, XmSTRING_DEFAULT_CHARSET);
	free(msg);
	apply_button = XtVaCreateWidget ("rowcol",
		xmPushButtonWidgetClass, form,
		XmNrecomputeSize, True,
		XmNlabelString, xmstr,
		XmNleftAttachment, XmATTACH_POSITION,
		XmNleftPosition, nXPos,
		XmNtopAttachment, XmATTACH_POSITION,
		XmNtopPosition, nYPos,
		XmNrightAttachment, XmATTACH_POSITION,
		XmNrightPosition, nXPos+nButtonWidth,
		NULL);
	XtManageChild(apply_button);
	XtAddCallback(apply_button, XmNactivateCallback, OptionAux_Apply_cb, 0);
	XmStringFree(xmstr);

	nXPos += nSpacing + nButtonWidth;
	msg = (char *)get_msg_by_msgid(5, "Reset");
	xmstr = XmStringCreateLtoR(msg, XmSTRING_DEFAULT_CHARSET);
	free(msg);
	reset_button = XtVaCreateWidget ("Reset",
		xmPushButtonWidgetClass, form,
		XmNrecomputeSize, True,
		XmNlabelString, xmstr,
		XmNleftAttachment, XmATTACH_POSITION,
		XmNleftPosition, nXPos,
		XmNtopAttachment, XmATTACH_POSITION,
		XmNtopPosition, nYPos,
		XmNrightAttachment, XmATTACH_POSITION,
		XmNrightPosition, nXPos+nButtonWidth,
		NULL);
	XtManageChild(reset_button);
	XtAddCallback(reset_button, XmNactivateCallback, OptionAux_Reset_cb, 0);
	XmStringFree(xmstr);

	nXPos += nSpacing + nButtonWidth;
	msg = (char *)get_msg_by_msgid(6, "Cancel");
	xmstr = XmStringCreateLtoR(msg, XmSTRING_DEFAULT_CHARSET);
	free(msg);
	cancel_button = XtVaCreateWidget ("Cancel",
		xmPushButtonWidgetClass, form,
		XmNrecomputeSize, True,
		XmNlabelString, xmstr,
		XmNleftAttachment, XmATTACH_POSITION,
		XmNleftPosition, nXPos,
		XmNtopAttachment, XmATTACH_POSITION,
		XmNtopPosition, nYPos,
		XmNrightAttachment, XmATTACH_POSITION,
		XmNrightPosition, nXPos+nButtonWidth,
		NULL);
	XtManageChild(cancel_button);
	XtAddCallback(cancel_button, XmNactivateCallback, OptionAux_Cancel_cb, 0);
	XmStringFree(xmstr);

	XtSetMappedWhenManaged(shell, FALSE);
	XtRealizeWidget(shell);

	/* Make dtsession do not save the geometry information */
	XSetCommand(XtDisplay(shell), XtWindow(shell), NULL, 0);

	OptionAux_InitObjects();

	/* Register aux class */
	if (xaux_ext_register_classes(shell) == -1) {
		return(-1);
	}

	XtAppMainLoop(app);
}
	
void OptionAux_InitObjects()
{
}

void OptionAux_FreeObjects()
{
	Msg_Done();
}

void OptionAux_DestroyProc(Widget widget, XtPointer pClientData, XtPointer pCallData)
{
	OptionAux_FreeObjects();
}

void OptionAux_Reset_OptionsList()
{
	int i, nRows;
	XmStringTable str_list;

	if (gIMEOptionsNum <= 0) return;

	nRows = gIMEOptionsNum;
	str_list = (XmStringTable)XtMalloc(nRows * sizeof (XmString *));
	for ( i = 0; i < nRows; i++ ) {
		str_list[i] = XmStringCreateLocalized((char *)gIMEOptions[i]->ime_cname);
	}

	XtVaSetValues(gOptData.wdtSelectedList,
		XmNitemCount, nRows,
		XmNitems, str_list,
		NULL);
	XtManageChild(gOptData.wdtSelectedList);

	for (i = 0; i < nRows; i++ )
		XmStringFree(str_list[i]);
	XtFree((char *)str_list);
}

Widget MyCreateOptionMenu(Widget parent, char *arg_name, int arg_id, int arg_value)
{
	Widget menu, cascade, widget, default_widget;
	XmString xmstr;
	int i, item_id, item_value;
	char item_str[512], menu_title[64];
	char *ptr;

	menu = XmCreatePulldownMenu (parent, "_pulldown", NULL, 0);
	XtVaSetValues (menu, XmNtearOffModel, XmTEAR_OFF_ENABLED, NULL);

	default_widget = 0;
	ptr = arg_name;

	/* get menu title */
	i = 0;
	while(*ptr && *ptr != ';' && i<63) {
		menu_title[i] = *ptr;
		i++, ptr++;
	}
	menu_title[i] = 0;

	/* Now add the menu items */
	item_id = 0;
	while(*ptr) {
		/* skip the characters that exceed 512 */
		while(*ptr && *ptr != ';') ptr++;
		if (*ptr == 0) break;

		/* get option items */
		ptr++;
		i = 0;
		while(*ptr && *ptr != ';' && i<511) {
			item_str[i] = *ptr;
			i++, ptr++;
		}
		item_str[i] = 0;

		if (i>0) {
			widget = XtVaCreateManagedWidget (item_str,
				xmPushButtonGadgetClass, menu,
				NULL);

			item_value = 0;
			item_value |= ((arg_id & 0x00ff) << 8);
			item_value |= (item_id & 0x00ff);
			XtAddCallback(widget, XmNactivateCallback, 
				OptionAux_OptionValue_Changed_cb, (XtPointer)item_value);

			if (item_id == arg_value) default_widget = widget;
			item_id++;
		}
	}

	cascade = 0;
	if (menu_title[0]) {
		Arg args[3];

		xmstr = XmStringCreateLocalized (menu_title);
		XtSetArg (args[0], XmNsubMenuId, menu); 
		XtSetArg (args[1], XmNlabelString, xmstr); 
		XtSetArg (args[2], XmNmenuHistory, default_widget); 
		cascade = XmCreateOptionMenu (parent, menu_title, args, 3);

		XmStringFree (xmstr);
	}

	return cascade;
}

void OptionAux_Display_IME_Arguments(int nIME_id)
{
	int i, arg_value, arg_type;
	char *arg_name;
	Widget rowcol;
	XmString xmstr;
	
	DEBUG_printf("OptionAux_Display_IME_Arguments ====IME No:%d\n", nIME_id);
	if (gIMEOptionsNum <= 0) return;

	if (nIME_id < 0 || nIME_id >= gIMEOptionsNum) 
		nIME_id = 0;

/*
	if (gOptData.nIME_id == nIME_id && gOptData.wdtOptionsList[nIME_id] != 0) 
		return;
*/

	gOptData.nIME_id = nIME_id;

	for (i = 0; i < gIMEOptionsNum; i++) {
		if (gOptData.wdtOptionsList[i])
			XtUnmanageChild(gOptData.wdtOptionsList[i]);
	}

	if (gOptData.wdtOptionsList[nIME_id] != 0) {
		XtManageChild(gOptData.wdtOptionsList[nIME_id]);
		return;
	}

	rowcol = XtVaCreateWidget ("rowcol",
		xmRowColumnWidgetClass, gOptData.wdtOptionsArea,
		XmNorientation, XmVERTICAL,
		XmNpacking, XmPACK_COLUMN,
		NULL);
	gOptData.wdtOptionsList[nIME_id] = rowcol;
	XtManageChild (rowcol);

	for (i = 0; i < gIMEOptions[nIME_id]->args_list->args_num; i++) {
		arg_name = (char *)gIMEOptions[nIME_id]->args_list->args[i].name;
		arg_value = gIMEOptions[nIME_id]->args_list->args[i].value;
		arg_type  = gIMEOptions[nIME_id]->args_list->args[i].type;

		DEBUG_printf("argname:%s, value:%d, type: %d\n", arg_name, arg_value, arg_type);

		if (arg_name == NULL) continue;

		if (arg_type <= 1) {
			Widget togglebutton;
		
			xmstr = XmStringCreateLtoR(arg_name, XmSTRING_DEFAULT_CHARSET);
			togglebutton = XtVaCreateManagedWidget("Arguments",
				xmToggleButtonGadgetClass, rowcol,
				XmNset, (arg_value ? 1:0),
				XmNlabelString, xmstr,
				NULL);

			XtAddCallback (togglebutton, XmNvalueChangedCallback, 
					OptionAux_Argument_Changed_cb, (XtPointer)i);
			XtManageChild(togglebutton);
		} else {
			Widget option_menu;
			int arg_id = i;

			option_menu = MyCreateOptionMenu(rowcol, arg_name, arg_id, arg_value);

			XtManageChild (option_menu);
		}
	}
}

void OptionAux_Argument_Changed_cb(Widget w, XtPointer client_data, XtPointer call_data)
{
	int nIME_id = gOptData.nIME_id;
	int nArg_id = (int) client_data;

	XmToggleButtonCallbackStruct *toggle_data =
		(XmToggleButtonCallbackStruct *) call_data;

	if (toggle_data->set) {
		gIMEOptions[nIME_id]->args_list->args[nArg_id].value = 1;
	} else {
		gIMEOptions[nIME_id]->args_list->args[nArg_id].value = 0;
	}
}

void OptionAux_OptionValue_Changed_cb(Widget w, XtPointer client_data, XtPointer call_data)
{
	int arg_data = (int) client_data;

	int nIME_id = gOptData.nIME_id;
	int nArg_id = (arg_data >> 8) & 0x00ff;
	int nArg_value = arg_data & 0x00ff;

	gIMEOptions[nIME_id]->args_list->args[nArg_id].value = nArg_value;
}

void OptionAux_Argument_Display_cb(Widget w, XtPointer client_data, XtPointer call_data) 
{
	XmListCallbackStruct *cbs = (XmListCallbackStruct *) call_data;
	int nIME_id = 0;

	if (cbs->reason == XmCR_BROWSE_SELECT)
		nIME_id = cbs->item_position - 1;

	if (nIME_id < 0) nIME_id = 0;

	DEBUG_printf("OptionAux_Argument_Display_cb: Select IME: %d\n", nIME_id);
	OptionAux_Display_IME_Arguments(nIME_id);
}

void OptionAux_OK_cb(Widget widget, XtPointer pClientData, XtPointer pCallData)
{
	int i;

	DEBUG_printf(" OptionAux_OK_cb ===\n");
	OptionAux_Hide();
	OptionAux_Change_Status_Request(0);

	for (i=0; i<gIMEOptionsNum; i++) {
		Set_OptionValue_From_ArgList(gIMEOptions[i]);
	};

	OptionAux_Update_OptionInfo_Request();
	Save_OptionsList_To_Profile();
}

void OptionAux_Apply_cb(Widget widget, XtPointer pClientData, XtPointer pCallData)
{
	int i;

	DEBUG_printf(" OptionAux_Apply_cb ===\n");

	for (i=0; i<gIMEOptionsNum; i++) {
		Set_OptionValue_From_ArgList(gIMEOptions[i]);
	};

	OptionAux_Update_OptionInfo_Request();
	Save_OptionsList_To_Profile();
}

void OptionAux_Reset_cb(Widget widget, XtPointer pClientData, XtPointer pCallData)
{
	DEBUG_printf(" OptionAux_Reset_cb ===\n");

	Set_ArgList_From_OptionValue(gIMEOptions[gOptData.nIME_id]);
	OptionAux_Display_IME_Arguments(gOptData.nIME_id);
}

void OptionAux_Cancel_cb(Widget widget, XtPointer pClientData, XtPointer pCallData)
{
	DEBUG_printf(" OptionAux_Cancel_cb ===\n");
	OptionAux_Hide();
	OptionAux_Change_Status_Request(0);
}

void OptionAux_Show()
{
	Display *pDisplay = XtDisplay(gOptData.wdtShell);
	Window window = XtWindow(gOptData.wdtShell);

	if (gIMEOptionsNum <= 0) return;

	XmListSelectPos(gOptData.wdtSelectedList, gOptData.nIME_id + 1, False);
	OptionAux_Display_IME_Arguments(gOptData.nIME_id);

	XtMapWidget(gOptData.wdtShell);
	XRaiseWindow(pDisplay, window);
	XFlush(pDisplay);
}

void OptionAux_Hide()
{
	XtUnmapWidget(gOptData.wdtShell);
}

