/*
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.

*/

/* 
 * Copyright (c) 1996-2000 by Sun Microsystems, Inc.
 * All rights reserved.
 *
 * @(#)LookupAux.c	1.9 01/12/28
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <locale.h>
#include <X11/Xatom.h>
#include <X11/Intrinsic.h>
#include <X11/Shell.h>

#include <Xm/Xm.h>
#include <Xm/XmP.h>
#include <Xm/RepType.h>
#include <Xm/CascadeB.h>
#include <Xm/DialogS.h>
#include <Xm/DrawingA.h>
#include <Xm/Form.h>
#include <Xm/Frame.h>
#include <Xm/Label.h>
#include <Xm/MainW.h>
#include <Xm/PushB.h>
#include <Xm/PushBG.h>
#include <Xm/RowColumn.h>
#include <Xm/ScrollBar.h>
#include <Xm/ScrolledW.h>
#include <Xm/TextF.h>
#include <Xm/SeparatoG.h>
#include <Xm/List.h>
#include <Xm/ToggleBG.h>
#include <Xm/MwmUtil.h>

#include "TabBook.h"
#include "LookupAux.h"

extern int DrawSingleAndTwoBytes(Widget w, GC gc, int PageStart, int PageEnd);
extern int DrawFourBytes(Widget w, GC gc, int start, int PageStart, int PageEnd);
extern int DrawSubSet(Widget w, GC gc, int start, int PageStart, int PageEnd, SubSet *range, int mode);
extern int get_encodeid_from_locale(char *);
extern char *GetString(char *);

/* Font operation */
void append_font(char *name, int kind, char *tag); 
void setup_fontlist();

/* Callback Procs */
void Quit(Widget w, XtPointer data, XtPointer cbk);
void ShowAbout(Widget w, XtPointer data, XtPointer cbk);
void SelectChar(Widget w, XtPointer data, XtPointer cbk);
void DrawPageTitle(Widget w, XtPointer data, XtPointer cbk);
void Scrolling(Widget w, XtPointer data, XtPointer cbk);
void DrawCurrentPage(Widget w, XtPointer data, XtPointer cbk);
void PageDown(Widget w, XtPointer data, XtPointer cbk);
void PageUp(Widget w, XtPointer data, XtPointer cbk);
void Commit(Widget w, XtPointer data, XtPointer cbk);
void DrawSymbols(Widget w, XtPointer data, XtPointer cbk);

/* Other functions */
void DrawSelectedChar(Window win, int x, int y, char * str, int mode);
void CreateTableArea(Widget parent);
void CreateSymbolArea(Widget parent);
void CreateMainWindow(Widget parent);

/* Commit Selected Characters */
void CommitChar() ;

Display *display;
Screen *screen_ptr;
GC gc;
Widget pageup, pagedown, chartable, symboltable, scrollbar; 
Widget aboutdialog, rangestart, rangeend, character, symbol, subsetmenu;
char char_commit[8] = "", symbol_commit[8];

XmString RangeStart, RangeEnd;
XmFontList fontlist = NULL; 

int selectedx = -1, selectedy = -1;
int symbolx = -1, symboly = -1;
int CharWidth = 18, CharHeight = 18;
int LabelWidth = 65, PageHeight = 324;
int TableWidth = 357; 
int TableHeight = 500;

int PageStart = 0;
int PrimaryLocale, CurrentLocale;
int IsUTF8;
int FocusedPage;

int SymbolGroupNum;
int SelectedGroup;

LookupAuxData	gLookupData;
void LookupAux_Hide();
void LookupAux_Show();

void create_gc(Widget w) {
	XGCValues gcv;
	gcv.foreground = BlackPixelOfScreen(screen_ptr);
	XtVaGetValues(w, XmNbackground, &gcv.background, NULL);
	gc = XCreateGC(display, RootWindowOfScreen(screen_ptr), GCForeground | GCBackground, &gcv);
}

void append_font(char *name, int kind, char *tag) {
	XmFontListEntry entry;
	entry = XmFontListEntryLoad(display, name, kind, tag); 
	fontlist =XmFontListAppendEntry(fontlist, entry);
	XmFontListEntryFree(&entry); 
}

void setup_fontlist() {
	append_font(CS.fontname, XmFONT_IS_FONTSET, "Chinese");
}

/* Commit selected character */
void Commit(Widget w, XtPointer data, XtPointer cbk) {

	CommitChar();
	return;
}

void CommitChar() {
	char *commit;

	if(FocusedPage == CHARSET_PAGE) commit = char_commit;
	else commit = symbol_commit;

	if((is_valid_code(PrimaryLocale, commit, strlen(commit)) == 0) || (commit[0] < 0x80)) {
		DEBUG_printf("Commit string: %s\n", commit);
		LookupAux_Commit_String_Request(PrimaryLocale, commit);
	}
}

/* Quit */
void Quit(Widget w, XtPointer data, XtPointer cbk) {
	LookupAux_Hide();
	LookupAux_Change_Status_Request(0);
}

/* Show about dialog */
void ShowAbout(Widget w, XtPointer data, XtPointer cbk) {
	XtManageChild(aboutdialog);
}

void SelectSymbolGroup(Widget w, XtPointer data, XtPointer cbk) {
	XmListCallbackStruct *cbs = (XmListCallbackStruct *) cbk;
	
	if (cbs->reason == XmCR_BROWSE_SELECT)
	SelectedGroup = cbs->item_position - 1;
	symbolx = symboly = -1;
	DrawSymbols(symboltable, NULL, NULL);
}

void ChangeSubSet(Widget w, XtPointer data, XtPointer cbk) {
	int subsetid = (int) data;

	selectedx = selectedy = -1;
	XtVaSetValues(scrollbar, XmNvalue, 0, NULL);

	CS.selectedsubset = subsetid;

	DrawCurrentPage(chartable, (XtPointer)1, NULL);
}

void ChangeCharSet(Widget w, XtPointer data, XtPointer cbk) {
	if((int)data == 0) {
		CurrentLocale = PrimaryLocale;
		if(PrimaryLocale == ENCODE_GB18030) 
			XtManageChild(subsetmenu);
	}
	else {
		CurrentLocale = UNICODE;
		if(PrimaryLocale == ENCODE_GB18030) 
			XtUnmanageChild(subsetmenu);
	}

	selectedx = selectedy = -1;
	XtVaSetValues(scrollbar, XmNvalue, 0, NULL);
	DrawCurrentPage(chartable, (XtPointer)1, NULL);
}

/* Draw(XOR) selected characters */
void DrawSelectedChar(Window win, int x, int y, char *str, int mode) {
	static GC gc_hilight, gc_bg;
	static first = 1;
	XGCValues gcv;
	XmString string = XmStringCreateLocalized(str);
	
	if(first == 1) {
		gcv.foreground = BlackPixelOfScreen(screen_ptr);
		gcv.background = WhitePixelOfScreen(screen_ptr);
		gc_hilight = XCreateGC(display, win, GCForeground | GCBackground, &gcv);

		gcv.background = BlackPixelOfScreen(screen_ptr);
		gcv.foreground = WhitePixelOfScreen(screen_ptr);
		gc_bg = XCreateGC(display, win, GCForeground | GCBackground, &gcv);
		
		first = 0;
	}
	if(mode == 1) {
		XFillRectangle(display, win, gc_bg, x, y, CharWidth - 2, CharHeight - 2);
		XmStringDraw(display, win, fontlist, string, gc_hilight, x, y, CharWidth, 
			XmALIGNMENT_BEGINNING, 0, NULL);
	}
	else {
		XClearArea(display, win, x, y, CharWidth - 2, CharHeight - 2, False);
		XmStringDraw(display, win, fontlist, string, gc, x, y, CharWidth,
			XmALIGNMENT_BEGINNING, 0, NULL);
	}
	XmStringFree(string);
}

/* Draw selected symbol */
void SelectSymbol(Widget w, XtPointer data, XtPointer cbk) {
	Window win = XtWindow(w);
	XEvent *event = ((XmDrawingAreaCallbackStruct *)cbk)->event;
	char schar[16], cchar[16];
	static Time lasttime = 0, time;
	XmString xmstring;
	int old_x, old_y, lineno;

	char   outbuf[512], *tptr;
	const char *fptr;
	size_t inleft, outleft;

	if(event->xbutton.x < START_X) return;

	strcpy(schar, GetString("Selected:"));

	if(event->type == ButtonPress) {
		time = event->xbutton.time;
		old_x = symbolx;
		old_y = symboly;

		/* erase the last selected characters */
		if((symbolx != -1) && (symboly != -1))
			DrawSelectedChar(win, symbolx, symboly, symbol_commit, 0);

		/* draw the current selected characters */
		symbolx = (event->xbutton.x - START_X) / (CharWidth + CHAR_SPACE) * (CharWidth + CHAR_SPACE) + START_X;
		symboly = (event->xbutton.y - START_Y) / CharHeight * CharHeight + START_Y;

		lineno = symboly / CharHeight;
		strcpy(cchar, (char*)SymbolGroups[SelectedGroup].symbols[lineno * 10 + symbolx /CharWidth]);
                if(IsUTF8) {
                        inleft = strlen(cchar);
                        outleft = (size_t) 512;
                        fptr = (char *)cchar;
                        tptr = outbuf;
                        Convert_Native_To_UTF8(PrimaryLocale, (char *)fptr, inleft, &tptr, &outleft);
                        outbuf[512 - outleft] = 0;
                        strcat(schar, outbuf);
                        strcpy(symbol_commit, outbuf);
                }
		else {
			strcat(schar, cchar);
			strcpy(symbol_commit, cchar);
		}

		DrawSelectedChar(win, symbolx, symboly, symbol_commit, 1);

		xmstring = XmStringCreateLocalized(schar);
		XtVaSetValues(symbol, XmNlabelString, xmstring, NULL);
		XmStringFree(xmstring);

		if((time - lasttime <= DOUBLE_CLICK_TIME) && 
		   (old_x == symbolx) &&
		   (old_y == symboly)) CommitChar();
		lasttime = time;
	}
}

/* Draw selected characters */
void SelectChar(Widget w, XtPointer data, XtPointer cbk) {
	Window win = XtWindow(w);
	XEvent *event = ((XmDrawingAreaCallbackStruct *)cbk)->event;
	int i, low, hi, space, lineno, startcode;
	unsigned int base = 0, tmp;
	char schar[16], cchar[16];
	XmString xmstring;
	static Time lasttime = 0, time;
	int old_x, old_y;

	char   outbuf[512], *tptr;
	const char *fptr;
	size_t inleft, outleft;

	if(event->xbutton.x < LabelWidth) return;

	strcpy(schar, GetString("Selected:"));

	if(event->type == ButtonPress) {
		time = event->xbutton.time;
		old_x = selectedx;
		old_y = selectedy;

		/* draw the current selected characters */
		selectedx = (event->xbutton.x - LabelWidth) / (CharWidth + CHAR_SPACE) * (CharWidth + CHAR_SPACE) + LabelWidth;
		selectedy = (event->xbutton.y + PageStart - START_Y) / CharHeight * CharHeight + START_Y;

		strcpy(cchar, char_commit);
		DrawCurrentPage(chartable, 0, NULL);

		if(!strcmp(char_commit, cchar) && 
			((selectedx != old_x) || (selectedy != old_y))) {
			selectedx = old_x;
			selectedy = old_y;
			return;
		}

		if(IsUTF8) {
			inleft = strlen(cchar);
			outleft = (size_t) 512;
			fptr = (char *)cchar;
			tptr = outbuf;
			Convert_Native_To_UTF8(PrimaryLocale, (char *)fptr, inleft, &tptr, &outleft);
			outbuf[512 - outleft] = 0;
			strcat(schar, outbuf);
			strcpy(char_commit, outbuf);
		}
		else {
			strcat(schar, char_commit);
		}

		if((old_x != -1) && (old_y != -1))
			DrawSelectedChar(win, old_x, old_y - PageStart, cchar, 0);
		DrawSelectedChar(win, selectedx, selectedy - PageStart, char_commit, 1);

		xmstring = XmStringCreateLocalized(schar);
		XtVaSetValues(character, XmNlabelString, xmstring, NULL);
		XmStringFree(xmstring);

		/* if double-click on the character, then commit it. */
		if((time - lasttime <= DOUBLE_CLICK_TIME) && 
		   (old_x == selectedx) &&
		   (old_y == selectedy)) CommitChar();
		lasttime = time;
	}
}

/* Draw offset in each line */
void DrawPageTitle(Widget w, XtPointer data, XtPointer cbk) {
	Window win = XtWindow(w);
	int i;
	char offset[2];
	XmString xmstring;

	for(i = 0; i < 0x10; i ++) {
		sprintf(offset, "%1X", i);
		xmstring = XmStringCreateSimple((char *)offset);
		XmStringDraw(display, win, fontlist, xmstring, gc, 
		LabelWidth + 4 + (CharWidth + CHAR_SPACE) * i, 0, 0, 
		XmALIGNMENT_BEGINNING, XmSTRING_DIRECTION_L_TO_R, NULL);
	}
}
	
/* Scroll the character table */
void Scrolling(Widget w, XtPointer data, XtPointer cbk) {
	DrawCurrentPage(chartable, (XtPointer)1, cbk);
}

/* Draw current page of the characters */
void DrawCurrentPage(Widget w, XtPointer data, XtPointer cbk) {
	static int lastheight = -1;
	Window win = XtWindow(w);
	int pagestart, pageend, winheight;

	FocusedPage = CHARSET_PAGE;
	XtVaGetValues(scrollbar, XmNvalue, &PageStart, NULL);
	pagestart = PageStart;
	pageend = PageStart + PageHeight + CharHeight;

	if((int)data == 1)XClearWindow(display, win);

	winheight = DrawSubSet(w, gc, START_Y, pagestart, pageend, (CS.subsets + CS.selectedsubset), (int)data);

	if(((int)data == 1) && (selectedx != -1) && (selectedy != -1) &&
	   (selectedy >= pagestart) && (selectedy <= pageend))
		DrawSelectedChar(win, selectedx, selectedy - PageStart, char_commit, 1);

	if(lastheight != winheight) {
		lastheight = winheight;
		XtVaSetValues(scrollbar, XmNmaximum, winheight + 2 * START_Y, NULL);
	}
}

/* Draw selected symbol group */
void DrawSymbols(Widget w, XtPointer data, XtPointer cbk) {
	Window win = XtWindow(w);
	int i, j, offset = 0;
	int x = START_X, y = START_Y;
	char *ptr;
	XmString xmstring;
	XmFontList DrawingFontList = fontlist;

        char   outbuf[512], *tptr;
        const char *fptr;
        size_t inleft, outleft;
	
	FocusedPage = SYMBOLS_PAGE;
	XClearWindow(display, win);

	for(i = 0; i < SymbolGroups[SelectedGroup].number; i ++) {
		ptr = (char*)SymbolGroups[SelectedGroup].symbols[i];
		if(IsUTF8) {
			inleft = 2;
			outleft = (size_t)512;
			fptr = (char *)ptr;
			tptr = outbuf;
			Convert_Native_To_UTF8(PrimaryLocale, (char *)fptr, inleft, &tptr, &outleft);
			outbuf[512 - outleft] = 0;
			ptr = outbuf;
		}
		xmstring = XmStringCreateSimple((char*)ptr);
		XmStringDraw(display, win, DrawingFontList, xmstring, gc, 
			START_X + offset * CharWidth, y, 0, 
			XmALIGNMENT_BEGINNING, XmSTRING_DIRECTION_L_TO_R, NULL);
		XmStringFree(xmstring);
		if( offset % 10 == 9 ) {
			y += CharHeight;
			x = START_X;
			offset = 0;
		}
		else offset ++;
	}
	if((symbolx != -1) && (symboly != -1)) 
		DrawSelectedChar(win, symbolx, symboly, symbol_commit, 1);
}

/* Create about dialog */
void CreateDialog (Widget parent) {
	XmString msgstring, titlestring, okstring;
	Arg args[10];
	Widget cancelbtn, helpbtn;

	msgstring = XmStringCreateLocalized(GetString("Character Lookup Table Utility \nCopyright 1999, 2000 Sun Microsystems, Inc."));
	titlestring = XmStringCreateLocalized(GetString("About"));
	okstring = XmStringCreateLocalized(GetString("OK"));

	XtSetArg(args[0], XmNmessageString, msgstring);
	XtSetArg(args[1], XmNdialogTitle, titlestring);
	XtSetArg(args[2], XmNdefaultButtonType, XmDIALOG_OK_BUTTON);
	XtSetArg(args[3], XmNokLabelString, okstring);
	XtSetArg(args[4], XmNdialogStyle, XmDIALOG_APPLICATION_MODAL);
	XtSetArg(args[5], XmNmwmDecorations, MWM_DECOR_BORDER | MWM_DECOR_TITLE);

	aboutdialog = (Widget) XmCreateMessageDialog(parent, "About", args, 6);

	cancelbtn = (Widget) XmMessageBoxGetChild(aboutdialog, XmDIALOG_CANCEL_BUTTON);
	helpbtn = (Widget) XmMessageBoxGetChild(aboutdialog, XmDIALOG_HELP_BUTTON);

	XtUnmanageChild(cancelbtn);
	XtUnmanageChild(helpbtn);

	XmStringFree(msgstring);
	XmStringFree(titlestring);
	XmStringFree(okstring);
}

/* Create maing window */
void CreateMainWindow (Widget parent) {
	Widget mainwindow, panel, quitbtn, aboutbtn;
	Widget workform, tabBook, symbolbtn, charbtn, singlecharbtn;
	Widget page1, page2, page3;
	XmString quitstr, aboutstr;

	mainwindow = XtVaCreateManagedWidget("main_window",
		xmMainWindowWidgetClass, parent,
		XmNscrollingPolicy, XmAUTOMATIC,
		NULL);

	quitstr = XmStringCreateLocalized(GetString("Quit"));
/*
	aboutstr = XmStringCreateLocalized(GetString("About"));
*/

	workform = XtVaCreateManagedWidget("workform", xmFormWidgetClass, mainwindow,
		XmNmarginWidth, 10,
		XmNmarginHeight, 10,
		XmNhorizontalSpacing, 10,
		XmNverticalSpacing, 10,
		NULL);

	tabBook = XtVaCreateManagedWidget("Tab", xcgTabBookWidgetClass, workform,
		XmNtopAttachment, XmATTACH_FORM,
		XmNleftAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		XmNtopOffset, 15,
		NULL);

	panel = XtVaCreateManagedWidget("bar", xmFormWidgetClass, workform,
		XmNtopAttachment, XmATTACH_WIDGET,
		XmNtopWidget, tabBook,
		XmNtopOffset, 10,
		XmNleftAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		XmNbottomAttachment, XmATTACH_FORM,
		NULL);
	
	quitbtn = XtVaCreateManagedWidget("quit", xmPushButtonWidgetClass, panel,
		XmNtopAttachment, XmATTACH_FORM,
		XmNbottomAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		XmNrightOffset, -1,
		XmNlabelString, quitstr,
		XmNshadowThickness, 2,
		XmNwidth, 80,
		XmNheight, 27,
		XmNfontList, fontlist,
		NULL);

	XtAddCallback(quitbtn, XmNactivateCallback, Quit, NULL);

/*
	aboutbtn = XtVaCreateManagedWidget("about", xmPushButtonWidgetClass, panel,
		XmNtopAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		XmNrightOffset, -1,
		XmNbottomAttachment, XmATTACH_FORM,
		XmNlabelString, aboutstr,
		XmNshadowThickness, 2,
		XmNwidth, 80,
		XmNheight, 27,
		NULL);
	XtAddCallback(aboutbtn, XmNactivateCallback, ShowAbout, NULL);
	XmStringFree(aboutstr);
*/
	
	XmStringFree(quitstr);

	charbtn = XtVaCreateManagedWidget(GetString("Character Table"), xmPushButtonWidgetClass,
		tabBook, 
		XmNfontList, fontlist,
		NULL);

	symbolbtn = XtVaCreateManagedWidget(GetString("Symbol Table"), xmPushButtonWidgetClass,
		tabBook,
		XmNfontList, fontlist,
		NULL);

	page1 = XtVaCreateManagedWidget("Page1", xmFormWidgetClass, tabBook,
		XmNmarginWidth, 10,
		XmNmarginHeight, 10,
		NULL);

	page2 = XtVaCreateManagedWidget("Page2", xmFormWidgetClass, tabBook,
		XmNmarginWidth, 10,
		XmNmarginHeight, 10,
		NULL);

	CreateTableArea(page1);
	CreateSymbolArea(page2);
}

void CreateSymbolArea(Widget parent) {
	Widget tmpform, title, list, controlpanel;
	Widget scrollwin, confirmbtn;
	XmStringTable    str_list;
	char buf[64];
	int  i, n = SymbolGroupNum; /*XtNumber (symbols);*/

        char   outbuf[512], *tptr;
        const char *fptr;
        size_t inleft, outleft;

	title = XtVaCreateManagedWidget("title", xmLabelWidgetClass, parent,
		XmNtopAttachment, XmATTACH_FORM,
		XmNleftAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		XmNalignment, 	XmALIGNMENT_BEGINNING,
		XmNlabelString, XmStringCreateLocalized(GetString("Symbol Group")),
		XmNfontList, fontlist,
		NULL);

	tmpform = XtVaCreateManagedWidget("Form", xmFormWidgetClass, parent,
		XmNtopAttachment, XmATTACH_WIDGET,
		XmNtopWidget, title,
		XmNtopOffset, 10,
		XmNleftAttachment, XmATTACH_FORM,
		XmNleftOffset, 10,
		XmNbottomAttachment, XmATTACH_FORM,
		NULL);
	
	str_list = (XmStringTable) XtMalloc (n * sizeof (XmString *));
	for (i = 0; i < n; i++) {
		strcpy(buf, (char*)SymbolGroups[i].label);
		strcat(buf, "      ");
                if (IsUTF8) {
                        inleft = strlen(buf);
                        outleft = (size_t)512;
                        fptr = (char *)buf;
                        tptr = outbuf;
                        Convert_Native_To_UTF8(PrimaryLocale, (char *)fptr, inleft, &tptr, &outleft);
                        outbuf[512 - outleft] = 0;
			str_list[i] = XmStringCreateLocalized(outbuf);
                }
		else str_list[i] = XmStringCreateLocalized(buf);
	}

	list = XmCreateScrolledList(tmpform, "list", NULL, 0);
	XtVaSetValues(list,
		XmNscrollingPolicy, XmAUTOMATIC,
		XmNvisibleItemCount,   (n < 10) ? n : 10,
		XmNitemCount,          n,
		XmNitems,              str_list,
		XmNtopAttachment,	XmATTACH_FORM,
		XmNbottomAttachment,	XmATTACH_FORM,
		XmNleftAttachment,	XmATTACH_FORM,
		XmNleftOffset, 		10,
		XmNwidth,		100,
		XmNheight,		300,
		XmNlistSpacing,		5,
		XmNfontList, fontlist,
		NULL);
	XtManageChild(list);
	XmListSelectPos(list, 1, False);
	XtAddCallback (list, XmNbrowseSelectionCallback, SelectSymbolGroup, NULL);

	for (i = 0; i < n; i++) XmStringFree (str_list[i]);
	XtFree ((XtPointer) str_list);

	scrollwin = XtVaCreateManagedWidget("scrollwin", xmScrolledWindowWidgetClass, tmpform,
		XmNtopAttachment,	XmATTACH_FORM,
		XmNleftAttachment, XmATTACH_WIDGET,
		XmNleftWidget, list,
		XmNleftOffset, 20,
		XmNbottomAttachment,	XmATTACH_FORM,
		XmNrightAttachment,	XmATTACH_FORM,
		XmNscrollingPolicy, XmAUTOMATIC,
		XmNwidth, 210,
		XmNheight, 300,
		NULL);
		
	symboltable = XtVaCreateManagedWidget("symbols", xmDrawingAreaWidgetClass, scrollwin,
		XmNwidth, 180,
		XmNheight, 300,
		NULL);

	XtAddCallback(symboltable, XmNexposeCallback, DrawSymbols, NULL);
	XtAddCallback(symboltable, XmNinputCallback, SelectSymbol, NULL);

	XtVaSetValues(scrollwin, XmNworkWindow, symboltable, NULL);

	controlpanel = XtVaCreateManagedWidget("ControlPanel", xmRowColumnWidgetClass, parent,
		XmNtopAttachment, XmATTACH_WIDGET,
		XmNtopWidget, title,
		XmNtopOffset, 10,
		XmNbottomAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		XmNleftAttachment, XmATTACH_WIDGET,
		XmNleftWidget, tmpform,
		XmNleftOffset, 20,
		XmNorientation, XmVERTICAL,
		XmNpacking, XmPACK_COLUMN,
		XmNmarginHeight, 0,
		XmNmarginWidth, 0,
		XmNspacing, 10,
		XmNfontList, fontlist,
		NULL);

	symbol = XtVaCreateManagedWidget(GetString("Selected:"), xmLabelWidgetClass, controlpanel, 
		XmNfontList, fontlist,
		XmNmarginHeight, 0,
		XmNmarginWidth, 0,
		NULL);

	confirmbtn = XtVaCreateManagedWidget("Confirm", xmPushButtonWidgetClass, controlpanel,
		XmNalignment, XmALIGNMENT_CENTER,
		XmNfontList, fontlist,
		XmNlabelString, XmStringCreateLocalized(GetString("Confirm")),
		NULL);
	XtAddCallback(confirmbtn, XmNactivateCallback, Commit, NULL);
}

void CreateTableArea(Widget parent) {
	Widget workform, tabBook, symbolbtn, charbtn, singlecharbtn;
	Widget tmpform, tmpframe, tmplabel, tmprc, codepointtext, codepointlabel, codepoint; 
	Widget codeset, codesetmenu, pagerc, pagelabel;
	Widget title, charwindow, controlpanel, confirmbtn;
	Widget xmdisplay, rangerc;
	Widget pulldown, pb1, pb2;
	Widget native_toggle, unicode_toggle, menu, menuitem;
	XmString native, unicode, omlabel;
	char buf[32];
	int i;
	Arg	args[10];
	Cardinal n;

	tmpform = XtVaCreateManagedWidget("Form", xmFormWidgetClass, parent,
		XmNtopAttachment, XmATTACH_FORM,
		XmNbottomAttachment, XmATTACH_FORM,
		XmNleftAttachment, XmATTACH_FORM,
		NULL);

	title = XtVaCreateManagedWidget("Offset", xmDrawingAreaWidgetClass, tmpform,
		XmNtopAttachment, XmATTACH_FORM,
		XmNleftAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		XmNwidth, TableWidth,
		XmNheight, CharHeight,
		NULL);
	XtAddCallback(title, XmNexposeCallback, DrawPageTitle, NULL);

	charwindow = XtVaCreateManagedWidget("CharWindow", xmFormWidgetClass, tmpform,
		XmNwidth, TableWidth + 18,
		XmNheight, CharHeight * 18,
		XmNtopAttachment, XmATTACH_WIDGET,
		XmNtopWidget, title,
		XmNbottomAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		NULL);

	tmpframe = XtVaCreateManagedWidget("frame", xmFrameWidgetClass, charwindow,
		XmNwidth, TableWidth,
		XmNheight, TableHeight,
		XmNshadowType, XmSHADOW_IN,
		XmNtopAttachment, XmATTACH_FORM,
		XmNbottomAttachment, XmATTACH_FORM,
		XmNleftAttachment, XmATTACH_FORM,
		NULL);

	chartable = XtVaCreateManagedWidget("chartable", xmDrawingAreaWidgetClass, tmpframe,
		XmNwidth, TableWidth,
		XmNheight, TableHeight,
		XmNtopAttachment, XmATTACH_FORM,
		XmNbottomAttachment, XmATTACH_FORM,
		XmNleftAttachment, XmATTACH_FORM,
		NULL);

	XtAddCallback(chartable, XmNexposeCallback, DrawCurrentPage, (XtPointer)1);
	XtAddCallback(chartable, XmNinputCallback, SelectChar, NULL);

	scrollbar = XtVaCreateManagedWidget("scrollbar", xmScrollBarWidgetClass, charwindow,
		XmNincrement, CharHeight,
		XmNvalue, 0,
		XmNpageIncrement, PageHeight - CharHeight,
		XmNsliderSize, PageHeight,
		XmNmaximum, 500,
		XmNorientation, XmVERTICAL,
		XmNleftAttachment, XmATTACH_WIDGET,
		XmNleftWidget, tmpframe,
		XmNleftOffset, 5,
		XmNbottomAttachment, XmATTACH_FORM,
		XmNtopAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		NULL);
	XtAddCallback (scrollbar, XmNvalueChangedCallback, Scrolling, NULL);
	XtAddCallback (scrollbar, XmNdragCallback, Scrolling, NULL);
		
	controlpanel = XtVaCreateManagedWidget("ControlPanel", xmRowColumnWidgetClass, parent,
		XmNtopAttachment, XmATTACH_FORM,
		XmNbottomAttachment, XmATTACH_FORM,
		XmNrightAttachment, XmATTACH_FORM,
		XmNleftAttachment, XmATTACH_WIDGET,
		XmNleftWidget, tmpform,
		XmNtopOffset, 30,
		XmNleftOffset, 10,
		XmNorientation, XmVERTICAL,
		XmNpacking, XmPACK_TIGHT,
		XmNmarginHeight, 0,
		XmNmarginWidth, 0,
		XmNspacing, 10,
		XmNfontList, fontlist,
		NULL);

	sprintf(buf, "%s", CS.CharSetID);
	native = XmStringCreateLocalized(buf);
	sprintf(buf, "%s", ChineseCharSets[UNICODE].CharSetID);
	unicode = XmStringCreateLocalized(buf);

	codesetmenu = XmCreateRadioBox (controlpanel, "radio_box", NULL, 0);
	XtVaSetValues(codesetmenu,
		XmNmarginHeight, 0,
		XmNmarginWidth, 0,
		NULL);

	native_toggle = XtVaCreateManagedWidget ("native",
		xmToggleButtonGadgetClass, codesetmenu,
		XmNlabelString, native,
		XmNset, True,
		XmNfontList, fontlist,
		NULL);
	XtAddCallback(native_toggle, XmNvalueChangedCallback, ChangeCharSet, (XtPointer)0);

	unicode_toggle = XtVaCreateManagedWidget ("unicode",
		xmToggleButtonGadgetClass, codesetmenu,
		XmNlabelString, unicode,
		XmNfontList, fontlist,
		NULL);
	XtAddCallback(unicode_toggle, XmNvalueChangedCallback, ChangeCharSet, (XtPointer)1);

	XtManageChild(codesetmenu);
		
	XmStringFree(native);
	XmStringFree(unicode);

	character = XtVaCreateManagedWidget(GetString("Selected:"), xmLabelWidgetClass, controlpanel, 
		XmNfontList, fontlist,
		XmNmarginHeight, 0,
		XmNmarginWidth, 0,
		NULL);

	confirmbtn = XtVaCreateManagedWidget("Confirm", xmPushButtonWidgetClass, controlpanel,
		XmNalignment, XmALIGNMENT_CENTER,
		XmNfontList, fontlist,
		XmNlabelString, XmStringCreateLocalized(GetString("Confirm")),
		NULL);
	XtAddCallback(confirmbtn, XmNactivateCallback, Commit, NULL);


	if(CS.SubsetNum > 1) {
		menu = XmCreatePulldownMenu(controlpanel, "_pulldown", args, 0);
		n = 0;
		XtSetArg(args[n], XmNsubMenuId, menu); n ++;
		subsetmenu = XmCreateOptionMenu(controlpanel, "subset", args, n);

		for(i = 0; i < CS.SubsetNum; i ++) {
			menuitem = XtVaCreateManagedWidget(GetString((CS.subsets + i)->name), xmPushButtonGadgetClass, menu, NULL);
			XtVaSetValues(menuitem, XmNfontList, fontlist, NULL);
			XtAddCallback(menuitem, XmNactivateCallback, ChangeSubSet, (XtPointer) i);
		}
	    	XtManageChild(subsetmenu);
	}
			
/*
	tmplabel = XmOptionLabelGadget(codesetmenu);
	XtVaSetValues(tmplabel, XmNfontList, fontlist, NULL);

	XtVaGetValues(codesetmenu, XmNsubMenuId, &pulldown, NULL);

	if(pb1 = XtNameToWidget(pulldown, "button_0")) 
		XtVaSetValues(pb1, XmNfontList, fontlist, NULL);

	if(pb2 = XtNameToWidget(pulldown, "button_1"))
                XtVaSetValues(pb2, XmNfontList, fontlist, NULL);

	XtVaSetValues(codesetmenu,
		XmNmarginHeight, 0,
		XmNmarginWidth, 0,
		NULL);
*/
}

/* main function */
int main(int argc, char **argv) {
	Widget toplevel, dialog;
	XtAppContext app;
	char *locale, *tmp, *lpszTitle;
	XmString titlestr;
	Atom xa_ct;

	/* Enable Localisation of the Application */
	XtSetLanguageProc((XtAppContext) 0, (XtLanguageProc) 0, (XtPointer) 0) ;

	toplevel = XtVaAppInitialize(&app, "Characters Lookup Utility",
		NULL, 0,
		&argc, argv, NULL,
		XmNwidth,  575,
		XmNheight, 460,
		XmNallowResize, False,
		XmNinput, False,
		XmNmwmFunctions, MWM_FUNC_ALL | MWM_FUNC_CLOSE,
		NULL);

	locale = setlocale(LC_CTYPE, NULL);

	tmp = strstr(locale, "UTF-8");
	if(tmp != NULL) IsUTF8 = 1;
	else IsUTF8 = 0;

	PrimaryLocale = get_encodeid_from_locale(locale);
	if(PrimaryLocale == -1) exit(0);
	CurrentLocale = PrimaryLocale;

	/* zh.UTF-8 doesn't load GBK fonts */
	if((CurrentLocale == ENCODE_GBK) && (IsUTF8)) 
		PrimaryLocale = CurrentLocale = ENCODE_GB2312;

	xa_ct = XmInternAtom(XtDisplay(toplevel), "COMPOUND_TEXT", FALSE);
	titlestr = XmStringCreateLocalized(GetString("Character Table"));
	lpszTitle = XmCvtXmStringToCT(titlestr);
	XtVaSetValues(toplevel, XmNtitle, lpszTitle, XmNtitleEncoding, xa_ct, NULL);
	XmStringFree(titlestr);

	ReadSymbols();

	gLookupData.wdtShell = toplevel;

	display = XtDisplay(toplevel);
	screen_ptr = XtScreen(toplevel);

	setup_fontlist();
	create_gc(toplevel);

	CreateMainWindow(toplevel);
/*
	CreateDialog(toplevel);
*/
/*
	XtSetMappedWhenManaged(toplevel, FALSE);
*/

	XtRealizeWidget(toplevel);

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

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

	XtAppMainLoop(app);
}

void LookupAux_Show()
{
	Display *pDisplay = XtDisplay(gLookupData.wdtShell);
	Window window = XtWindow(gLookupData.wdtShell);

	DEBUG_printf("Show LookupAux\n");
	XtMapWidget(gLookupData.wdtShell);
	XRaiseWindow(pDisplay, window);
	XFlush(pDisplay);
}

void LookupAux_Hide()
{
	XtUnmapWidget(gLookupData.wdtShell);
}

