/*
Copyright 1990-2001 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 <stdlib.h>
#include <stdio.h>
#include <fcntl.h>

#include "CodeTable.h"
#include "UDEngine.h"
#include "IMKeyMap.h"

engine_info **im;

int     maximum_cans = 7;

im_data *im_commit();
void    clear_buffer();

struct im_buffer      *buffer[MAX_SESSION];
im_data     *current;

im_data * IM_sendEvent(int, int, int, int);

int IM_open(char * ct_file_path) {
	int i;

	char ** ct_list;
	char ct_path[200];

	strcpy(ct_path, ct_file_path);
	ct_list = (char **) get_list_of_codetable(ct_path);

	if(ct_list == NULL) {

#ifndef WIN32
		strcat(ct_path, "/../locale/zh_CN/ude/data");
#else
		strcat(ct_path, "\\..\\locale\\zh_CN\\ude\\data");
#endif
		ct_list = (char **) get_list_of_codetable(ct_path);
	}

	im = (engine_info **)malloc( sizeof(engine_info*) * 100);
	for(i =0; i < 100; i++) {
		if(ct_list[i] == NULL) break;

		im[i] = (engine_info *)malloc( sizeof(engine_info));
		strcpy(im[i]->name, "udim");
		strcpy(im[i]->locale, "zh");
		im[i]->next_choice = '.';
		im[i]->prev_choice = ',';
		im[i]->del_pe_char = 8;
		im[i]->del_pe_str = 27;
		im[i]->wild_char = -1;
		im[i]->symbol = 0;
		strcpy(im[i]->status_native, "udim");
		strcpy(im[i]->ct_file, ct_list[i]);
		im[i]->c_tab = NULL;
		im[i]->data = NULL;
		printf("read codetable %d\n", read_code_table(i));
		free(ct_list[i]);
	}
	free(ct_list);
	return i ;
}

void IM_close(int codetable_number) {
	int i;
	for(i = 0; i < codetable_number; i ++) {
		free(im[i]->data);
		free(im[i]->c_tab);
		free(im[i]);
	}
	free(im);
}

void IM_createSession(int session_id) {
	int i;

	if(current == NULL) { /* malloc struct datasun for sessions */
		current = (im_data *)malloc(sizeof(im_data));
		if(current == NULL) {
			printf("can malloc i2x\n");
		}
	}

	if(buffer[session_id] == NULL) { /* malloc struct im_buffer for this session */
		buffer[session_id] = (struct im_buffer *)malloc(sizeof(struct im_buffer));
		if(buffer[session_id] == NULL) {
			printf("can malloc input buffer\n");
		}
		clear_buffer(buffer[session_id]);
		buffer[session_id]->input_method = 0;
		Quanjiao = QUANJIAO_ON;
		strcpy(IM_Status, im[buffer[session_id]->input_method]->name);

		strcat(IM_Status, QUANJIAO_STR);

		for(i = 0; i < MAX_CANDIDATE; i ++) {
			Candidate[i] = (char *) malloc(21);
		}
	}
}

void IM_resetSession(int session_id) {
	clear_buffer(buffer[session_id]);
}

void IM_destroySession(int session_id) {
	if(buffer[session_id]) free(buffer[session_id]);
}

im_data * IM_setAuxValue(int session_id, int arg, int value) {
	/*clear_buffer(buffer[session_id]);*/
	if((arg == SOFTKEYBOARD_LAYOUT) && (Input_Method != value)) {
		Input_Method = value;
		return (im_data *)IM_sendEvent(session_id, IMXK_Mode_switch, 0xff, 0);
	}
	else if((arg == PUNCTUATION_STATUS) && (Quanjiao!= value)) {
		strcpy(IM_Status, im[buffer[session_id]->input_method]->name);
		Quanjiao = value;
		if(Quanjiao == QUANJIAO_ON) strcat(IM_Status, QUANJIAO_STR);
		else strcat(IM_Status, BANJIAO_STR);
	}
	return NULL;
}

void IM_getValue(int session_id, int arg, char * value) {
	if(arg == IM_STATUS) {
		strcpy((char*)value, IM_Status);
	}
}

im_data * IM_sendEvent(session_id , keycode, keychar, state)
int session_id;
int keycode;
int keychar;
int state;
{
	int     i, k;
	char    c, basestr[20];
	int	key;
	int	number;

#ifdef DEBUG
	printf("keycode = %d keychar = %d\n", keycode, keychar);
#endif

	if((0x0 <= keychar) && (keychar <= 0x7f))  key = keychar;
	else key = keycode & 0xff;

	if (key == im[Input_Method]->del_pe_char) { /* Back Space */
		if (Preedit_Len == 0) {
			Commit_Buf[0] = key;
			Commit_Buf[1] = '\0';
			clear_buffer(buffer[session_id]);
			This_Operation = CIM_COMMIT;
			return (im_data *) im_commit(current, buffer[session_id]);
		}

		/* Delete characters in pre-edit region */
		if ((Preedit_Len > 0) && (Preedit_Buf[Preedit_Len - 1] == im[Input_Method]->wild_char)) {
			if(WildChar_Pos == Preedit_Len - 1) WildChar_Pos = -1;
			Preedit_Len --;
			Inbuf_Len --;
			Preedit_Buf[Preedit_Len] = '\0';
			Inbuf[Inbuf_Len] = '\0';
		}
		else {
			Inbuf_Len --;
			/* c = Inbuf[Inbuf_Len]; */
			Inbuf[Inbuf_Len] = '\0';
			/*
			for (k = 0; im[Input_Method]->tab_idx[idx(c)].pe_text[k] != '\0' && k < MAX_CHAR_PE; k++);
			*/
			Preedit_Len --;
			Preedit_Buf[Preedit_Len] = '\0';
		}

		if (Inbuf_Len == 0) {
			clear_buffer(buffer[session_id]);
		}

		if (Inbuf_Len > 0) {
			if(WildChar_Pos != -1) {
				strncpy(basestr, Inbuf, WildChar_Pos);
				basestr[WildChar_Pos] = '\0';
			}
			else strcpy(basestr, Inbuf);

			find_candidate(Input_Method, basestr, &First_Candidate, &Last_Candidate);
			S_Pointer = First_Candidate;
			S_Direction = 1;
			LUC_Number = make_selections(Input_Method, Candidate, &S_Pointer, Last_Candidate, 
					S_Direction, WildChar_Pos + 1, Preedit_Buf, maximum_cans);
			if(LUC_Number >= 1) Mode = LOOKUP_CHOICE;
		}
		Commit_Buf[0] = '\0';
		This_Operation = CIM_INTERM;
		return (im_data *) im_commit(current, buffer[session_id]);
	}

	else if(keycode == IMXK_Mode_switch){
		clear_buffer(buffer[session_id]);
		Commit_Buf[0] = '\0';
		strcpy(IM_Status, im[Input_Method]->name);

		if(Quanjiao == QUANJIAO_ON) strcat(IM_Status, QUANJIAO_STR);
		else strcat(IM_Status, BANJIAO_STR);

		This_Operation = CIM_STATUS;
		return (im_data *) im_commit(current, buffer[session_id]);
	}

	else if(key == im[Input_Method]->del_pe_str) { /* Esc , clear preedit, lookup choice pointer, and so on */
		clear_buffer(buffer[session_id]);
		Commit_Buf[0] = '\0';
		This_Operation = CIM_INTERM;
		return (im_data *) im_commit(current, buffer[session_id]);
	}

	else if((key == im[Input_Method]->wild_char) &&
		!is_preedit_char(Input_Method, key)) {

		if(WildChar_Pos == -1) WildChar_Pos = Preedit_Len;

		Preedit_Buf[Preedit_Len] = Inbuf[Inbuf_Len] = key;
		Inbuf_Len ++; Preedit_Len ++;
		Preedit_Buf[Preedit_Len] = Inbuf[Inbuf_Len] = '\0';

		S_Pointer = First_Candidate;
		S_Direction = 1;
		LUC_Number = make_selections(Input_Method, Candidate, &S_Pointer, Last_Candidate, 
			S_Direction, WildChar_Pos + 1, Preedit_Buf, maximum_cans);

		if ( LUC_Number >= 1) {
			Mode = LOOKUP_CHOICE;
			Commit_Buf[0] = '\0';
			This_Operation = CIM_INTERM;
			return (im_data *) im_commit(current, buffer[session_id]);
		}
		else { 
			Preedit_Len --;
			Inbuf_Len --;
			Inbuf[Inbuf_Len] = Preedit_Buf[Preedit_Len] = '\0';
			WildChar_Pos = -1;
			printf("\007");
			Commit_Buf[0] = '\0';
			This_Operation = CIM_INTERM;
			return (im_data *) im_commit(current, buffer[session_id]);
		}
	}

	else if(is_preedit_char(Input_Method, key)) { /* search for candidate */
		Inbuf[Inbuf_Len] = key;
		Inbuf_Len ++;
		Inbuf[Inbuf_Len] = '\0';

		if(WildChar_Pos != -1) {
			strncpy(basestr, Inbuf, WildChar_Pos);
			basestr[WildChar_Pos] = '\0';
		}
		else strcpy(basestr, Inbuf);

		find_candidate(Input_Method, basestr, &First_Candidate, &Last_Candidate);
		if(First_Candidate > Last_Candidate) { /* no candidate, then delete this key */
			Inbuf_Len --;
			Inbuf[Inbuf_Len] = '\0';
			if (Inbuf_Len == 0) {
				Commit_Buf[0] = key;
				Commit_Buf[1] = '\0';
				clear_buffer(buffer[session_id]);
				This_Operation = CIM_COMMIT;
				return (im_data *) im_commit(current, buffer[session_id]);
			}
			printf("\007");
			find_candidate(Input_Method, Inbuf, &First_Candidate, &Last_Candidate);
		}
		else {
			Preedit_Buf[Preedit_Len] = key;
			Preedit_Len ++;
			Preedit_Buf[Preedit_Len] = '\0';
		}

		S_Pointer = First_Candidate;
		S_Direction = 1;

		LUC_Number = make_selections(Input_Method, Candidate, &S_Pointer, Last_Candidate, 
				S_Direction, WildChar_Pos + 1, Preedit_Buf, maximum_cans);

		if ( LUC_Number > 1) {
			Mode = LOOKUP_CHOICE;
			Commit_Buf[0] = '\0';
			This_Operation = CIM_INTERM;
			return (im_data *) im_commit(current, buffer[session_id]);
		}
		else if(LUC_Number == 1) {
			strcpy(Commit_Buf , Candidate[0]);
			clear_buffer(buffer[session_id]);
			Mode = PRE_EDIT;
			This_Operation = CIM_COMMIT;
			return (im_data *) im_commit(current, buffer[session_id]);
		}
		else { /* some error occurs when make_selections(), then delete this key */
			Preedit_Len --;
			Inbuf_Len --;
			Inbuf[Inbuf_Len] = Preedit_Buf[Preedit_Len] = '\0';
			printf("\007");
			Commit_Buf[0] = '\0';
			This_Operation = CIM_INTERM;
			return (im_data *) im_commit(current, buffer[session_id]);
		}
	}

	else if(key == 32) { /* space : commit the first one in lookup choice region */

		if( Mode == PRE_EDIT) {
			change_symbol(key,Quanjiao,Commit_Buf);
		}
		else {
			strcpy(Commit_Buf , Candidate[0]);
		}
		clear_buffer(buffer[session_id]);
		This_Operation = CIM_COMMIT;
		return (im_data *) im_commit(current, buffer[session_id]);
	}

	else if((key >= '0') && (key <= '9')) { /* select from candidata */
		/* here should see whether there is enough candidates */
		if(( Mode == PRE_EDIT) || ((key - '1') > (LUC_Number - 1))) {
			change_symbol(key,Quanjiao,Commit_Buf);
		}
		else {
			if (key > '0')
				strcpy(Commit_Buf , Candidate[key - '1']);
			else 
				strcpy(Commit_Buf , Candidate[9]);
		}
		clear_buffer(buffer[session_id]);
		This_Operation = CIM_COMMIT;
		return (im_data *) im_commit(current, buffer[session_id]);
	}

	else if((key == CTRL_N) || (key == im[Input_Method]->next_choice)) { /* page down */
		if( Mode == PRE_EDIT) {
			change_symbol(key,Quanjiao,Commit_Buf);
			clear_buffer(buffer[session_id]);
			This_Operation = CIM_COMMIT;
			return (im_data *) im_commit(current, buffer[session_id]);
		}
		else {
			if(S_Direction == -1) {
				S_Pointer ++;
				S_Direction = 1;
				if(S_Pointer <= Last_Candidate)
					make_selections(Input_Method, Candidate, &S_Pointer, Last_Candidate,
						S_Direction, WildChar_Pos + 1, Preedit_Buf, LUC_Number);
			}
			if(S_Pointer <= Last_Candidate)
				LUC_Number = make_selections(Input_Method, Candidate, &S_Pointer, Last_Candidate, 
					S_Direction, WildChar_Pos + 1, Preedit_Buf, maximum_cans);
			This_Operation = CIM_INTERM;
			return (im_data *) im_commit(current, buffer[session_id]);
		}
	}

	else if((key == CTRL_P) || (key == im[Input_Method]->prev_choice)) { /* page up */

		if( Mode == PRE_EDIT) {
			change_symbol(key,Quanjiao,Commit_Buf);
			clear_buffer(buffer[session_id]);
			This_Operation = CIM_COMMIT;
			return (im_data *) im_commit(current, buffer[session_id]);
		}
		else {
			if(S_Direction == 1) {
				S_Pointer --;
				S_Direction = -1;
				if(S_Pointer >= First_Candidate)
					make_selections(Input_Method, Candidate, &S_Pointer, First_Candidate, 
						S_Direction, WildChar_Pos + 1, Preedit_Buf, LUC_Number);
			}
			if(S_Pointer >= First_Candidate) 
				LUC_Number = make_selections(Input_Method, Candidate, &S_Pointer, First_Candidate, 
					S_Direction, WildChar_Pos + 1, Preedit_Buf, maximum_cans);
/*
			if(number <= 0) return (im_data *) im_commit(current, buffer[session_id]);
			LUC_Number = number;
*/
			This_Operation = CIM_INTERM;
			return (im_data *) im_commit(current, buffer[session_id]);
		}
	}

	else { /* need not handle here , commit it or bounce it */
		if(!change_symbol(key,Quanjiao,Commit_Buf)) This_Operation = CIM_COMMIT;
		else This_Operation = CIM_BOUNCEKEY;
		clear_buffer(buffer[session_id]);
		return (im_data *) im_commit(current, buffer[session_id]);
	}
}

change_symbol(str,flag,ch_str)
char str;
int flag;
unsigned char *ch_str;
{
	unsigned int chinese_symbol;

	if(str == 0) return 1;
	if(flag == QUANJIAO_ON) {
		chinese_symbol = to_Chinese_symbols(str);
		if (chinese_symbol & 0xff00) {
			*ch_str = (chinese_symbol & 0xff00) >> 8;
			*(ch_str + 1) = (chinese_symbol & 0xff);
			*(ch_str + 2) = '\0';
			return 0;
		}
	}
	*ch_str = str;
	*(ch_str + 1) = '\0';
	return 0;
}

void clear_buffer(buffer)
struct im_buffer        * buffer;
{
	buffer->preedit[0] = buffer->inbuf[0] = '\0';
	buffer->preedit_len = buffer->inbuf_len  = 0;
	buffer->wildchar_pos = -1;
	buffer->candidate_low = 1;
	buffer->candidate_high = 0;
	buffer->lookupchoice_low = 1;
	buffer->lookupchoice_high = 0;
	buffer->lookupchoice_number = 0;
	buffer->search_pointer = 1;
	buffer->search_direction = 1;
	buffer->mode = PRE_EDIT;
}

im_data *
im_commit(i2x,buffer)
im_data     * i2x;
struct im_buffer    * buffer;
{
	int i=0;
	int number = buffer->lookupchoice_number;

	strcpy(i2x->pre_str, buffer->preedit);
	i2x->caret_pos = 0;
	for(i = 0; i < number; i ++) strcpy(i2x->luc_str[i] , buffer->candidate[i]);
	sscanf(buffer->commit, "%s", i2x->commit_str);
	i2x->luc_num = number;
	strcpy(i2x->status_str, buffer->status);
	i2x->operation = buffer->this_operation;
	i2x->labeltype = NUMERIC_LABEL;
	return i2x;
}

to_Chinese_symbols(eng_c)
char            eng_c;
{
	unsigned        symbol;
	symbol = 0;
	switch (eng_c) {
	case ' ':
		symbol = DSPACE;
		break;
	case '.':
		symbol = PERIOD;
		break;
	case ',':
		symbol = COMMAM;
		break;
	case '!':
		symbol = EXCLMM;
		break;
	case ':':
		symbol = COLONM;
		break;
	case '-':
		symbol = HYPHEN;
		break;
	case '^':
		symbol = CARETM;
		break;
	case '(':
		symbol = LPARNT;
		break;
	case '{':
		symbol = LCUBRT;
		break;
	case '`':
		symbol = ACCENT;
		break;
	case '[':
		symbol = LSQBRT;
		break;
	case '<':
		symbol = LESSTH;
		break;
	case '@':
		symbol = COMMAT;
		break;

	case '/':
		symbol = SOLDUS;
		break;
	case ';':
		symbol = SEMCLN;
		break;
	case '?':
		symbol = QUESTM;
		break;
	case '&':
		symbol = AMPERS;
		break;
	case ')':
		symbol = RPARNT;
		break;
	case '}':
		symbol = RCUBRT;
		break;
	case '\'':
		symbol = SNGQUO;
		break;
	case '"':
		symbol = DBLQUO;
		break;
	case ']':
		symbol = RSQBRT;
		break;
	case '>':
		symbol = GREATH;
		break;
	case '|':
		symbol = VERBAR;
		break;
	case '=':
		symbol = EQUALS;
		break;
	case '#':
		symbol = SGNNUM;
		break;
	case '$':
		symbol = DALLAR;
		break;
	case '%':
		symbol = PERCNT;
		break;
	case '*':
		symbol = SGNSTR;
		break;
	case '_':
		symbol = UNDSCR;
		break;
	case '\\':
		symbol = BCKSLH;
		break;
	case '~':
		symbol = STILDE;
		break;
	case '+':
		symbol = SGNADD;
		break;
	case '0':
	case '1':
	case '2':
	case '3':
	case '4':
	case '5':
	case '6':
	case '7':
	case '8':
	case '9':
		symbol = DIGITS + eng_c - 0x30;
		break;

	case 'A':
	case 'B':
	case 'C':
	case 'D':
	case 'E':
	case 'F':
	case 'G':
	case 'H':
	case 'I':
	case 'J':
	case 'K':
	case 'L':
	case 'M':
	case 'N':
	case 'O':
	case 'P':
	case 'Q':
	case 'R':
	case 'S':
	case 'T':
	case 'U':
	case 'V':
	case 'W':
	case 'X':
	case 'Y':
	case 'Z':
		symbol = UPPERS + eng_c - 0x41;
		break;
	case 'a':
	case 'b':
	case 'c':
	case 'd':
	case 'e':
	case 'f':
	case 'g':
	case 'h':
	case 'i':
	case 'j':
	case 'k':
	case 'l':
	case 'm':
	case 'n':
	case 'o':
	case 'p':
	case 'q':
	case 'r':
	case 's':
	case 't':
	case 'u':
	case 'v':
	case 'w':
	case 'x':
	case 'y':
	case 'z':
		symbol = LOWERS + eng_c - 0x61;
		break;
	default:
		symbol = (eng_c & 0xff);
		break;
	};

	return (symbol);
}

