/*
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.
 *
 * @(#)LookupImpl.c	1.4 01/09/28
 *
 */

#include <stdio.h>
#include <iconv.h>
#include <stdlib.h>
#include <locale.h>
#include <X11/Intrinsic.h>
#include <Xm/Xm.h>
#include <Xm/XmP.h>

#include "LookupAux.h"

extern Display *display;
extern int CharWidth, CharHeight, LabelWidth;
extern int TableWidth;
extern int CurrentLocale;
extern int PrimaryLocale;
extern int SymbolGroupNum;
extern int selectedx, selectedy;

extern XmString RangeStart, RangeEnd;
extern int IsUTF8;
extern XmFontList fontlist;
extern char char_commit[];

int SearchMessage(char *);
char* GetString(char *);
void SetSymbols(SymbolGroup *group, char *line);

int DrawSingleByte(Widget w, GC gc, int position, int pagestart, int pageend, 
		unsigned int startcode, unsigned int endcode, int mode) {

	Window win = XtWindow(w);
	XmString xmstring;
	unsigned char labelstr[10], charstr[6];
	int i, j, numberperline = 0x10;
	int x, y = position;

	if(endcode < startcode) return 0;

	startcode &= 0xF0;

	for(i = startcode; i <= endcode; i += 0x10) {
		charstr[0] = i & 0xFF;
		charstr[1] = 0;

		if((y >= pagestart - CharHeight) && (y <= pageend)) {
			for(j = 0; j < numberperline; j ++) {

				/* draw label */
				if(j == 0) {
					if(CurrentLocale == UNICODE) sprintf((char *)labelstr, "%04X ", i);
					else sprintf((char *)labelstr, "%02X ", i);
					xmstring = XmStringCreateSimple((char *)labelstr);
					XmStringDraw(display, win, fontlist, xmstring, gc, START_X, y - pagestart, 0, 
						XmALIGNMENT_BEGINNING, XmSTRING_DIRECTION_L_TO_R, NULL);
					XmStringFree(xmstring);
				}
				/* draw characters */
				x = LabelWidth + (CharWidth + CHAR_SPACE) * j;
				if((selectedx == x) && (selectedy == y)) {
					strcpy(char_commit, (const char*)charstr);
				}

				if(mode == 1) {
					xmstring = XmStringCreateSimple((char *)charstr);
					XmStringDraw(display, win, fontlist, xmstring, gc, 
						LabelWidth + (CharWidth + CHAR_SPACE) * j, y - pagestart, 0,
						XmALIGNMENT_BEGINNING, XmSTRING_DIRECTION_L_TO_R, NULL);
					XmStringFree(xmstring);
				}
				charstr[0] ++;
			}
		}
		y += CharHeight;
	}
	return y - position;
}

int DrawDoubleBytes(Widget w, GC gc, int position, int pagestart, int pageend,
		unsigned int startcode, unsigned int endcode, int mode) {

	Window win = XtWindow(w);
	XmString xmstring;
	int firstbegin, firstend, secondbegin, secondend, singlebegin, singleend;
	unsigned char labelstr[10], charstr[6];
	unsigned int tmp, i;
	int j, k, numberperline = 0x10;
	int x, y = position;

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

	if(endcode < startcode) return position;

/*
	firstbegin  = CS.HighByteBegin;
	firstend    = CS.HighByteEnd;
	secondbegin = CS.LowByteBegin;
	secondend   = CS.LowByteEnd;
*/
	firstbegin  = startcode >> 8;
	firstend    = endcode >> 8;
	secondbegin = startcode & 0xFF;
	secondend   = endcode & 0xFF;

	numberperline = 0x10;

	startcode &= 0xFFF0;

	for(i = startcode; i <= endcode; i += 0x10) {
		charstr[0] = (i >> 8) & 0xFF;
		charstr[1] = i & 0xFF;
		charstr[2] = 0;
		
		if((CS.Include8090 == 0) &&
		  ((charstr[1] == 0x80) || (charstr[1] == 0x90))) {
			continue;
		}

		if((y >= pagestart - CharHeight) && (y <= pageend)) {
			for(j = 0; j < numberperline; j ++) {

				/* draw label */
				if(j == 0) {
					sprintf((char *)labelstr, "%04X ", i);
					xmstring = XmStringCreateSimple((char *)labelstr);
					XmStringDraw(display, win, fontlist, xmstring, gc,
						START_X, y - pagestart, 0,
						XmALIGNMENT_BEGINNING, XmSTRING_DIRECTION_L_TO_R, NULL);
					XmStringFree(xmstring);
				}

				/* draw characters */
				if((charstr[1] < secondbegin) || (charstr[1] > secondend)) {
					charstr[1] ++;
					continue;
				}

				else if (CurrentLocale == UNICODE) {
					tmpbuf[0] = charstr[0];
					tmpbuf[1] = charstr[1];
					tmpbuf[2] = 0;

					inleft = 2;
					outleft = (size_t)512;
					fptr = (char *)tmpbuf;
					tptr = outbuf;
					Convert_UTF16_To_Native(PrimaryLocale, fptr, inleft, &tptr, &outleft);

					outbuf[512 - outleft] = 0;
					if(is_valid_code(PrimaryLocale, outbuf, 512 - outleft) == 0)
						for(k = 0; k <= 512 - outleft; k ++) tmpbuf[k] = outbuf[k];
					else tmpbuf[0] = 0;
				}
				else strcpy((char*) tmpbuf, (char*) charstr);

				if(IsUTF8 && (tmpbuf[0] != 0)) {
					inleft = 2;
					outleft = (size_t)512;
					fptr = (char *)tmpbuf;
					tptr = outbuf;
					Convert_Native_To_UTF8(PrimaryLocale, (char *)fptr, inleft, &tptr, &outleft);
					outbuf[512 - outleft] = 0;
					strcpy(tmpbuf, outbuf);
				}

				if((tmpbuf[0] != 0) && is_valid_code(PrimaryLocale, tmpbuf, strlen(tmpbuf)) == 0) {

					x = LabelWidth + (CharWidth + CHAR_SPACE) * j;
					if((selectedx == x) && (selectedy == y)) 
						strcpy(char_commit, (const char*)tmpbuf);

					if(mode == 1) {
						xmstring = XmStringCreateSimple((char *)tmpbuf);
						XmStringDraw(display, win, fontlist, xmstring, gc,
							x, y - pagestart, 0,
							XmALIGNMENT_BEGINNING, XmSTRING_DIRECTION_L_TO_R, NULL);
						XmStringFree(xmstring);
					}
				}

				charstr[1] ++;
			}
		}

		/* jump to next area */
		tmp = i;
		if( (tmp & 0xF0) >= (secondend & 0xF0)) {
			tmp &= 0xFF00;
			tmp += 0x100 + (secondbegin & 0xF0);
		}
		if( ((tmp >> 8) & 0xFF) > firstend ) {
			tmp &= 0x00FF;
			tmp += 0x10000 + (firstbegin << 8);
		}
		if (i != tmp) i = tmp - 0x10;

		y += CharHeight;
	}

	return y - position;
}

int DrawFourBytes(Widget w, GC gc, int position, int pagestart, int pageend, 
		unsigned int startcode, unsigned int endcode, int mode) {

	Window win = XtWindow(w);
	XmString xmstring;
	int firstbegin, firstend, secondbegin, secondend;
	int thirdbegin, thirdend, forthbegin, forthend;
	unsigned char labelstr[12], charstr[32];
	unsigned int i, tmp;
	int j, numberperline;
	int x, y = position;

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

	if(endcode < startcode) return position;

	startcode &= 0xFFFFFFF0;

	firstbegin  = CS.FirstByteBegin;
	firstend    = CS.FirstByteEnd;
	secondbegin = CS.SecondByteBegin;
	secondend   = CS.SecondByteEnd;
	thirdbegin  = CS.ThirdByteBegin;
	thirdend    = CS.ThirdByteEnd;
	forthbegin  = CS.ForthByteBegin;
	forthend    = CS.ForthByteEnd;

	for(i = startcode; i <= endcode; i += 0x0010) {
		charstr[0] = (i >> 24) & 0x000000FF;
		charstr[1] = (i >> 16) & 0x000000FF;
		charstr[2] = (i >> 8) & 0x000000FF;
		charstr[3] = i & 0x000000FF;
		charstr[4] = 0;

		if(CurrentLocale == ENCODE_GB18030) numberperline = 0x0a;
		else numberperline = 0x10;

		if((y >= pagestart - CharHeight) && (y <= pageend)) {
			for(j = 0; j < numberperline; j ++) {

				/* draw label */
				if(j == 0) {
					sprintf((char *)labelstr, "%8X ", i);
					xmstring = XmStringCreateSimple((char *)labelstr);
					XmStringDraw(display, win, fontlist, xmstring, gc, 
						START_X, y - pagestart, 0, 
						XmALIGNMENT_BEGINNING, XmSTRING_DIRECTION_L_TO_R, NULL);
					XmStringFree(xmstring);
				}

				/* draw characters */
				if((charstr[3] < forthbegin) || (charstr[3] > forthend)) {
					charstr[3] ++;
					continue;
				}

				if(IsUTF8) {
					inleft = 4;
					outleft = (size_t)512;
					fptr = (char *)charstr;
					tptr = outbuf;
					Convert_Native_To_UTF8(PrimaryLocale, (char *)fptr, inleft, &tptr, &outleft);
					outbuf[512 - outleft] = 0;

					xmstring = XmStringCreateSimple((char *)outbuf);
					XmStringDraw(display, win, fontlist, xmstring, gc, 
			       			LabelWidth + (CharWidth + CHAR_SPACE) * j, y - pagestart, 0, 
						XmALIGNMENT_BEGINNING, XmSTRING_DIRECTION_L_TO_R, NULL);
					XmStringFree(xmstring);

					charstr[3] ++;
					continue;
				}

				x = LabelWidth + (CharWidth + CHAR_SPACE) * j;
				if((selectedx == x) && (selectedy == y))
					strcpy(char_commit, (const char*)charstr);

				if(mode == 1) {
					xmstring = XmStringCreateSimple((char *)charstr);
					XmStringDraw(display, win, fontlist, xmstring, gc, 
						x, y - pagestart, 0,
						XmALIGNMENT_BEGINNING, XmSTRING_DIRECTION_L_TO_R, NULL);
					XmStringFree(xmstring);
				}
				charstr[3] ++;
			}
		}

		/* jump to next area */	
		tmp = i;
		if( (tmp & 0xF0) >= (forthend & 0xF0)) {
			tmp &= 0xFFFFFF00;  
			tmp += 0x100 + (forthbegin & 0xF0);
		}
		if( ((tmp >> 8) & 0xFF) > thirdend ) {
			tmp &= 0xFFFF00FF;
			tmp += 0x10000 + (thirdbegin << 8);
		}
		if( ((tmp >> 16) & 0xFF) > secondend ) {
			tmp &= 0xFF00FFFF;
			tmp += 0x1000000 + (secondbegin << 16);
		}
		if (i != tmp) i = tmp - 0x10;

		y += CharHeight;
	}

	/* return the height of the drawing area for the page */
	return y - position;
}
				
int DrawSubSet(Widget w, GC gc, int position, int pagestart, int pageend, SubSet *subset, int mode) {
	unsigned int startcode, endcode, i;
	int y = position;

	if(subset == NULL) return position;
	for(i = 0; i < XtNumber(subset->range); i ++) {
		startcode = subset->range[i];
		endcode = subset->range[++i];
		
		if((startcode == 0) && (endcode == 0)) break;
		if(endcode < startcode) continue;

		/* draw single byte chars */
		if(endcode < 0x100) 
			y += DrawSingleByte(w, gc, position, pagestart, pageend, startcode, endcode, mode);

		/* draw double bytes chars */
		else if(endcode < 0x10000) 
			y += DrawDoubleBytes(w, gc, y, pagestart, pageend, startcode, endcode, mode);

		/* draw four bytes chars */
		else y+= DrawFourBytes(w, gc, y, pagestart, pageend, startcode, endcode, mode);
	}

	return y - position;
}

static char   outbuf[512];

char* GetString(char *utf8str) {
	char   *tptr;
	const char *fptr;
	size_t inleft, outleft;
	int msgid;

	msgid = SearchMessage(utf8str);

	if(msgid == -1) fptr = (char *) utf8str;
	else if(PrimaryLocale < 3) fptr = msg[msgid].sch;
	else fptr = msg[msgid].tch;

	if(IsUTF8) {
		strcpy(outbuf, fptr);
		return(outbuf);
	}

	inleft = (size_t)strlen((char *)fptr);
	outleft = (size_t)512;
	tptr = outbuf;

	Convert_UTF8_To_Native(PrimaryLocale, (char *)fptr, inleft, &tptr, &outleft);
	outbuf[512 - outleft] = 0;

	return outbuf;
}

int SearchMessage(char *utf8str) {
	int i;

	for(i = 0; i < XtNumber(msg); i ++) {
		if(!strcmp(msg[i].id, utf8str)) break;
	}
	if (i == XtNumber(msg)) return -1;
	else return i;
}

void get_one_line(FILE *fd, char *line)
{
        int line_ptr;
        char line_buf[256], *ptr;

        line_ptr = 0;
        line[0] = '\0';

        /* get line with no space */
        while(fgets(line_buf, 255, fd) != NULL) {
                ptr = line_buf;

                /* skip space keys */
                while(*ptr && isspace(*ptr)) ptr++;

                /* if is space line, get new line */
                if (*ptr == '\n' || *ptr == '\0')
                        continue;

                while(*ptr != '\n' && *ptr != '\0' && line_ptr < MAX_LINE_LEN)
                        line[line_ptr++] = *ptr++;

                /* trim right space */
                while (isspace(line[line_ptr-1])) line_ptr--;
                line[line_ptr] = '\0';

                /* if the line end with '\', then continue read the next line */
                if (line[line_ptr-1] == '\\') {
                        line_ptr--;
                        line[line_ptr] = '\0';
                        continue;
                }

                break;
        }
}

void ReadSymbols() {
	char *sLocaleName, *lang_name, path_name[64];
	int i, j, ret;

	sLocaleName = setlocale(LC_ALL, NULL);
	lang_name = (char *)get_langname_from_locale(sLocaleName);

	sprintf(path_name, "/usr/lib/im/locale/%s", lang_name);
	ret = read_keyboard_config_file(path_name, DEFAULT_SYMBOLS_CONFIG_FILE);
}

int read_keyboard_config_file(char *path_name, char *file_name) {
	char    line[MAX_LINE_LEN], sFileName[256];
	char    *ptr, *ename_str;
	FILE    *fd;
	int     locale_flag = ENCODE_ERROR;
	int     have_matched = 0;
	int     len;

	sprintf(sFileName, "%s/%s", path_name, file_name);
	DEBUG_printf("File Name:%s\n", sFileName);
	fd = fopen(sFileName, "r");
	if (!fd) {
		DEBUG_printf("Can not open the file:%s.\n", sFileName);
		return(-1);
	}

	do {
		get_one_line(fd, line);

		if (line[0] == '\0') break;
		if (line[0] == '#') continue;

		len = strlen(line);
		if (line[0] == '[' && line[len-1] == ']') {

			if (have_matched == 1) break;

			/* Check the previous item is a formal item */
			/* get english name of the item */
			ptr = line + 1;
			while(isspace(*ptr)) ptr++;
			ename_str = ptr;

			ptr = line + len - 2;
			while(isspace(*ptr)) ptr--;
			*(ptr+1) = '\0';

			DEBUG_printf("read_config_file: locale_name:%s\n", ename_str);
			if (*ename_str) {
				locale_flag = get_encodeid_from_locale(ename_str);
			}
			continue;
		}

		if (locale_flag == ENCODE_ERROR || locale_flag != CurrentLocale) continue;

		have_matched = 1;

		/* read the layout file */
		read_symbol_file(path_name, line);

	} while (1);

	fclose(fd);
	/* if no entry for the locale, read the default layout file. */
	if (have_matched == 0)
		return(-1);

	return(0);
}

int read_symbol_file(char *path_name, char *file_name) {
        char    line[MAX_LINE_LEN], sFileName[256];
        char    *ptr, *ename_str;
        FILE    *fd;
        int     i, len, need_alloc_new_item;
        int     list_begin = 0, groupnum = -1;

        sprintf(sFileName, "%s/%s", path_name, file_name);
        DEBUG_printf("File Name:%s\n", sFileName);
        fd = fopen(sFileName, "r");
        if (!fd) {
                DEBUG_printf("Can not open the file:%s\n", sFileName);
		sprintf(sFileName, "%s/%s", path_name, DEFAULT_SYMBOLS_FILE);
		fd = fopen(sFileName, "r");
		if(!fd) {
			DEBUG_printf("Can not open the default file!");
			return(-1);
		}
        }

        do {
                if (groupnum >= MAX_GROUPS) break;

                get_one_line(fd, line);

                if (line[0] == '\0') break;
                if (line[0] == '#') continue;

		len = strlen(line);
		if(line[0] == '[' && line[len-1] == ']') {
			groupnum ++;
			SymbolGroups[groupnum].number = 0;
			continue;
		}

                if (!(strncasecmp(line, LABEL_STR, strlen(LABEL_STR)))) {
                        ptr = line + strlen(LABEL_STR);
                        while(*ptr && isspace(*ptr)) ptr++;
                        if (*ptr) {
				strcpy((char*)SymbolGroups[groupnum].label, ptr);
                        }
                        continue;
                }
/*
                if (!(strncasecmp(line, ENCODE_STR, strlen(ENCODE_STR)))) {
                        ptr = line + strlen(ENCODE_STR);
                        while(*ptr && isspace(*ptr)) ptr++;
                        if (*ptr) {
                                set_keyboard_encode(pVKB, ptr);
                                DEBUG_printf("encode:%s\n", ptr);
                        }
                        continue;
                }

                if (!(strncasecmp(line, TYPE_STR, strlen(TYPE_STR)))) {
                        ptr = line + strlen(TYPE_STR);
                        while(*ptr && isspace(*ptr)) ptr++;
                        if (*ptr) {
                                DEBUG_printf("TYPE: %s\n", ptr);
                                if (!(strncasecmp(ptr, KEY_TYPE_STR, strlen(KEY_TYPE_STR)))) {
                                        pVKB->type = KEYBOARD_KEY_TYPE;
                                } else {
                                        pVKB->type = KEYBOARD_STRING_TYPE;
                                }
                        }
                        continue;
                }
*/
                if (!(strncasecmp(line, LIST_BEGIN_STR, strlen(LIST_BEGIN_STR)))) {
                        list_begin = 1;
                        continue;
                }

                if (!(strncasecmp(line, LIST_END_STR, strlen(LIST_END_STR)))) {
                        list_begin = 0;
                        continue;
                }

                if (list_begin == 1) {
                        SetSymbols(&(SymbolGroups[groupnum]), line);
                }

        } while (1);
	SymbolGroupNum = groupnum + 1;

        fclose(fd);
        return(0);
}

void SetSymbols(SymbolGroup *group, char *line) {
	int i, index, len;
	char *ptr;

	/* skip spaces */
        ptr = line;
        while (*ptr && isspace(*ptr)) ptr++;
	len = strlen(ptr);

	for(i = 0, index = 0; i < len; i += 2, index ++) {
		group->symbols[index][0] = *(ptr + i);
		group->symbols[index][1] = *(ptr + i + 1);
		group->symbols[index][2] = 0;
		if(index >= MAX_SYMBOLS) break;
	}
	group->number = index;
}

