/*
  Copyright 2002-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 <string.h>

#include "le.h"
#include "encode.h"
#include "xaux_locale.h"
#include "logf.h"
#include "iml.h"
#include "le_proc.h"

void switch_to_prev_lang(iml_session_t *s, unit_desktop_t *udp, int engine_id);
void switch_to_next_lang(iml_session_t *s, unit_desktop_t *udp, int engine_id);
int map_keyevent_to_immkey(unit_desktop_t *udp, IMKeyEventStruct *key_event);
void proc_key_round_switch_ime_event(unit_desktop_t *udp, iml_session_t *s);
void proc_key_switch_conversion_event(unit_desktop_t *udp, iml_session_t *s, int on, char *to_locale);
void proc_hotkey_conversion_event(unit_desktop_t *udp, iml_session_t *s, int on, char *to_locale);
void proc_key_select_switch_ime_event(unit_desktop_t *udp, iml_session_t *s, int ime_id);
void proc_key_output(unit_desktop_t *udp, iml_session_t *s, IMKeyEventStruct *key_event);
extern IMHotkeyProfileStruct *get_hkp_from_hkm(int);
extern int unit_desktop_get_curr_profile_id(unit_desktop_t *udp);

/* process the keyboard event */
void 
proc_key_event(
    unit_desktop_t *udp,
    iml_session_t *s,
    IMKeyListEvent *keylistevent
)
{
    MyDataPerSession *session_data = (MyDataPerSession *) s->specific_data;
    IMKeyEventStruct *key_event = (IMKeyEventStruct *) keylistevent->keylist;
    char *cur_locale_string;
    char *cur_engine_string;
    int i,  key_ret, engine_id;
    int feid = 0, leid = 0;
    int keyCode, Modifier, keyChar;

    keyCode = key_event->keyCode;
    keyChar = key_event->keyChar;
    Modifier = key_event->modifier;

    cur_locale_string = (char *)alloca(256 * sizeof(char));
    cur_engine_string = (char *)alloca(256 * sizeof(char));

    (void) memset((char *)cur_locale_string,'\0',256);
    (void) memset((char *)cur_engine_string,'\0',256);

    /* if no input methods in language engine. */
    if (udp->gEngine_Num <=0) {
	log_f("udp->gEngine_Num is zero \n");
	iml_sendback_key(s, key_event);
	return;
    }

    key_ret = map_keyevent_to_immkey(udp, key_event);
    engine_id = session_data->paletteaux_status.engine_id;

    switch (key_ret) {
	/* English status <----> Non-English status */
      case ENGLISH_NONENGLISH_SWITCH_KEY:
       proc_key_switch_conversion_event(udp, s, CONVERSION_OFF, (char *)NULL);
       return;

       /* Bound Switching between Input Methods */
      case ROUND_SWITCH_KEY:
       proc_key_round_switch_ime_event(udp, s);
       return;

    }

    if ((keyCode == udp->nextLocaleKeycode) && (Modifier == udp->nextLocaleModifier)) {
       switch_to_next_lang(s, udp, engine_id);
       return;
    }

    if ((keyCode == udp->prevLocaleKeycode) && (Modifier == udp->prevLocaleModifier)) {
       switch_to_prev_lang(s, udp, engine_id);
       return;
    }

    if((keyCode == udp->layoutNameKeyCode) && (Modifier == udp->layoutNameModifier)){ 
	/*  Changing keyboard layout Name */
	log_f("Changing Layout: engine_id [%d]\n",engine_id);
	(void) strncpy((char *)cur_locale_string, udp->modeList[engine_id]->locale_name, strlen( udp->modeList[engine_id]->locale_name));
	log_f("Changing Layout: cur_locale_string [%s]\n",cur_locale_string);
	(void) strncpy((char *)cur_engine_string, udp->modeList[engine_id]->engine_name, strlen(udp->modeList[engine_id]->engine_name));
	log_f("Changing Layout: engine_name [%s]\n",cur_engine_string);

	for(i=0; i< udp->locale_Num; i++){
	    if(!strcmp(cur_locale_string, udp->localeList[i].locale_name)){
		feid = udp->localeList[i].firstEngineId;
		leid = udp->localeList[i].lastEngineId;
	    }
	}
	log_f("Changing Layout: feid [%d] leid [%d]\n",feid, leid);
	for (i = engine_id; i<= udp->gEngine_Num; i++) {
	    if(!strcmp(cur_locale_string, udp->modeList[i]->locale_name)){
		if(!strcmp(cur_engine_string, udp->modeList[i]->engine_name)){
		    log_f("Engine EQUAL <%s>\n",udp->modeList[i]->engine_name);
		    if(engine_id == leid){
			log_f("engine_id == leid \n");
			le_switch_engine(udp, s, feid, True);
			break;
		    }
		}else{
		    log_f("Engine NOT EQUAL engine_name <%s>\n",udp->modeList[i]->engine_name);
		    log_f("NOT EQUAL engine_id <%d>\n",udp->modeList[i]->engine_id);
		    le_switch_engine(udp, s, udp->modeList[i]->engine_id, True);
		    break;
		}
	    }
	}
	return;
    }
    proc_key_output(udp, s, key_event);
}

void process_hotkey_event(
    unit_desktop_t *udp,
    iml_session_t *s, 
    IMKeyListEvent *keylistevent
)
{
    MyDataPerSession *session_data = (MyDataPerSession *) s->specific_data;
    IMKeyEventStruct *key_event = (IMKeyEventStruct *) keylistevent->keylist;
    int key_ret;
    int keyCode, Modifier, keyChar;
    int on = session_data->paletteaux_status.on;

    keyCode = key_event->keyCode;
    keyChar = key_event->keyChar;
    Modifier = key_event->modifier;

    /* Incase of Hotkey Event, keylistEvent->n_operation holds the Hotkey_ID and   */ 
    /* keylistEvent->n_key holds the Index of KEYEVENT in LISTofKEYEVENT in HOTKEY */

    log_f("process_hotkey_event: session [%x], udp [0x%x], Hotkey ID [%d], Index [%d] \n", s, udp, keylistevent->n_operation, keylistevent->n_key);

    /* if no input methods in language engine. */
    if (udp->gEngine_Num <=0) {
	log_f("udp->gEngine_Num is zero \n");
	iml_sendback_key(s, key_event);
	return;
    }

    key_ret = map_keyevent_to_immkey(udp, key_event);

    switch (key_ret) {
	/* If the incoming key is Hotkey (deadkey) and                  */
	/* 1. If Client conversion mode is turned OFF, then             */
	/*    - turn ON the conversion and set hotkey_flag as          */
	/*      IME_HOTKEY_START (this flag will be changed by Xctim    */
	/*      to IME_HOTKEY_END after completing the deadkey          */
	/*      composition and committing it)                          */
	/*    - session_data->ime_buffer->conv_flag helps restore       */
	/*      the original CONVERSION MODE of the client              */
	/*    - In this case, since conv_flag = CONVERSION_OFF,         */
	/*      once the deadkey operation is completed, conversion     */
	/*      will be turned OFF                                      */
	/* 2. If Client conversion mode is turned ON, then              */
	/*    - In this case, since conv_flag = CONVERSION_ON,          */
	/*      once the deadkey operation is completed, conversion     */
	/*      will still be turned ON.                                */
	/*    - process the key input                                   */

      case IME_DEADKEY_AS_HOTKEY:
      {
        if (!on) {
	   session_data->paletteaux_status.engine_id = 0xff;
	   proc_key_switch_conversion_event(udp, s, CONVERSION_ON, (char *)"en");
	   session_data->ime_buffer->hotkey_flag = IME_HOTKEY_START;
	   session_data->ime_buffer->conv_flag = CONVERSION_OFF;
        } else {
	   session_data->ime_buffer->conv_flag = CONVERSION_ON;
        }
        proc_key_output(udp, s, key_event);
        return;
      }

      case IME_COMPOSE_KEY_AS_HOTKEY:
      {
        if (!on) {
	   session_data->paletteaux_status.engine_id = 0xff;
	   proc_key_switch_conversion_event(udp, s, CONVERSION_ON, (char *)"en");
	   session_data->ime_buffer->hotkey_flag = IME_HOTKEY_START;
	   session_data->ime_buffer->conv_flag = CONVERSION_OFF;
        } else {
	   session_data->ime_buffer->conv_flag = CONVERSION_ON;
        }
        key_event->keyCode = IM_VK_T;
        key_event->keyChar = IM_VK_T;
        key_event->modifier = IM_CTRL_MASK|IM_SHIFT_MASK ;

        proc_key_output(udp, s, key_event);
        return;
      }

      case IME_EURO_KEY_AS_HOTKEY:
      {
	session_data->ime_buffer->hotkey_flag = IME_HOTKEY_COMMIT;
        if (!on) {
	   session_data->paletteaux_status.engine_id = 0xff;
           proc_hotkey_conversion_event(udp, s, CONVERSION_ON, (char *)"en");
	   session_data->ime_buffer->conv_flag = CONVERSION_OFF;
        } else {
	   session_data->ime_buffer->conv_flag = CONVERSION_ON;
        }
        proc_key_output(udp, s, key_event);
        return;
      }
    }
    proc_key_output(udp, s, key_event);
}

/* filter keys that used by Input Methods Manager */
int 
map_keyevent_to_immkey(
    unit_desktop_t *udp,
    IMKeyEventStruct *key_event
) 
{
    int keycode, modifier, keychar;
    int i, j;

    keycode = key_event->keyCode;
    keychar = key_event->keyChar;
    modifier = key_event->modifier;
    int profile_id;
    IMHotkeyProfileStruct *hkp = NULL;

    log_f("Dec: keycode: %d, keychar: %d, status: %d\n",keycode, keychar, modifier);
    log_f("Hex: keycode: %x, keychar: %x, modifier: %x\n",keycode, keychar, modifier);

    /*  Control status */
    if (modifier & IM_CTRL_MASK) {
	switch(keycode) {
	  case IM_VK_ESCAPE:	return(ROUND_SWITCH_KEY);
	  case IM_VK_SPACE:	return(ENGLISH_NONENGLISH_SWITCH_KEY);
	}
    } else if (modifier & IM_ALT_GRAPH_MASK) {
	switch(keycode) {
	  case IM_VK_E:
	  case IM_VK_4:	
	  case IM_VK_5:	
           return (IME_EURO_KEY_AS_HOTKEY);
	}
    }

    /* Check if it is DEAD_KEY */
    switch(keycode) {
      case IM_VK_DEAD_ACUTE:
      case IM_VK_DEAD_GRAVE:
      case IM_VK_DEAD_CIRCUMFLEX:
      case IM_VK_DEAD_TILDE:
      case IM_VK_DEAD_MACRON:
      case IM_VK_DEAD_BREVE:
      case IM_VK_DEAD_ABOVEDOT:
      case IM_VK_DEAD_DIAERESIS:
      case IM_VK_DEAD_ABOVERING:
      case IM_VK_DEAD_DOUBLEACUTE:
      case IM_VK_DEAD_CARON:
      case IM_VK_DEAD_CEDILLA:
      case IM_VK_DEAD_OGONEK:
      case IM_VK_DEAD_IOTA:
      case IM_VK_DEAD_VOICED_SOUND:
      case IM_VK_DEAD_SEMIVOICED_SOUND:
       return(IME_DEADKEY_AS_HOTKEY);
    }

    /* Check if it is COMPOSE_KEY */
    profile_id = unit_desktop_get_curr_profile_id(udp);

    if (profile_id < 0) 
      return (IMM_NOT_USED_KEY);

    hkp = get_hkp_from_hkm(profile_id);

    if (hkp) {
      for (i=0; i<hkp->num_hotkeys; i++) {
        for (j=0; j<hkp->hks[i].nkeys; j++) {
          if ((keycode == hkp->hks[i].keys[j].keyCode) && (modifier == hkp->hks[i].keys[j].modifier)) {
            free(hkp);
            return(IME_COMPOSE_KEY_AS_HOTKEY);
          }
        }
      }
    }
    return (IMM_NOT_USED_KEY);
}

void 
proc_hotkey_conversion_event(
    unit_desktop_t *udp,
    iml_session_t *s,
    int on,
    char *to_locale
)
{
    MyDataPerSession *session_data = (MyDataPerSession *) s->specific_data;
    int i, engine_id;

    session_data->paletteaux_status.on = on;
    engine_id = session_data->paletteaux_status.engine_id;
    log_f("proc_hotkey_conversion_event: engine_id <%d>\n", engine_id);

    if (engine_id != 0xff) {
      le_switch_engine(udp, s, engine_id, False);
    }

    for (i = 0; i< udp->gEngine_Num; i++) {
       if (!strcmp(to_locale, udp->modeList[i]->locale_name)){
         engine_id = i;
         break;
       }
    }

    log_f("proc_hotkey_conversion_event:engine_id [%d]\n", engine_id);
    le_switch_engine(udp, s, engine_id, False);
}

void 
proc_key_switch_conversion_event(
    unit_desktop_t *udp,
    iml_session_t *s,
    int on,
    char *to_locale
)
{
    MyDataPerSession *session_data = (MyDataPerSession *) s->specific_data;
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);
    int engine_id, i;
    char locale_id, system_locale_id;

    log_f("ENGLISH_NONENGLISH SWITCH IME KEY, on:%d\n", on);

    le_clear_ime_buffer(s, session_data->ime_buffer);

    session_data->paletteaux_status.on = on;
    engine_id = session_data->paletteaux_status.engine_id;
    log_f("proc_key_switch_conversion_event: engine_id <%d>\n", engine_id);
    if (on == CONVERSION_OFF) {
	log_f("Inside CONVERSION_OFF \n");
	le_status_draw(udp, s);
	iml_conversion_off(s);
    } else {
	log_f("Inside CONVERSION_ON \n");
	iml_conversion_on(s);
	if (engine_id != 0xff) {
	    log_f("engine_id != 0xff \n");
	    le_switch_engine(udp, s, engine_id, True);
	}
    }

    if (on == CONVERSION_ON && engine_id == 0xff) {
	if (to_locale == NULL || to_locale[0] == '\0'){
	    log_f("key_event: to_locale is NULL \n");
	    system_locale_id = desktop_data->aux_locale_id;
	    log_f("keyevent.c: system_locale_id <%d>\n",system_locale_id);
	    engine_id = 0;
	    for (i = 0; i< udp->gEngine_Num; i++) {
		locale_id = udp->gEngine_Info[i]->core.baseinfo.locale_id;
		log_f("keyevent.c: system_locale_id <%d> locale_id <%d>\n",system_locale_id,locale_id);
		if (locale_id == system_locale_id || locale_id == ENCODES_NUM) {
		    engine_id = i;
		    break;
		}
	    }
	}else{
	    log_f("key_event: to_locale is Not NULL \n");
	    for (i = 0; i< udp->gEngine_Num; i++) {
		if(!strcmp(to_locale, udp->modeList[i]->locale_name)){
		    engine_id = i;
		    break;
		}
	    }
	}
	log_f("engine_id:%d\n", engine_id);
	le_switch_engine(udp, s, engine_id, True);
    }
}

void 
proc_key_round_switch_ime_event(
    unit_desktop_t *udp,
    iml_session_t *s
)
{
    MyDataPerSession *session_data = (MyDataPerSession *) s->specific_data;
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);
    int engine_id, i;
    char locale_id, system_locale_id;

    log_f("ROUND SWITCH IME KEY\n");

    system_locale_id = desktop_data->aux_locale_id;
    engine_id = session_data->paletteaux_status.engine_id;
    for (i = engine_id; i< udp->gEngine_Num; i++) {
	engine_id = (engine_id + udp->localeList[engine_id].nEngineId) % (udp->gEngine_Num);
	locale_id = udp->gEngine_Info[engine_id]->core.baseinfo.locale_id;
	if (locale_id == system_locale_id || locale_id == ENCODES_NUM) {
	    break;
	}
    }
    log_f("engine_id:%d\n", engine_id);

    le_clear_ime_buffer(s, session_data->ime_buffer);
    le_switch_engine(udp, s, engine_id, True);
}

void
switch_to_prev_lang(
    iml_session_t *s,
    unit_desktop_t *udp,
    int engine_id
)
{
   int i, j, n;
   MyDataPerSession *session_data = (MyDataPerSession *) s->specific_data;

   n = udp->locale_Num;
   if (!engine_id) {
      log_f("Prev engine to switch [%d]\n", udp->localeList[n-1].firstEngineId);
      engine_id = udp->localeList[n-1].firstEngineId;
   } else {
      for (i=0, j=i+1; j<udp->locale_Num; i++, j++){
         if ((engine_id >= udp->localeList[j].firstEngineId) &&
             (engine_id <= udp->localeList[j].lastEngineId)) {
           engine_id = udp->localeList[i].firstEngineId;
           break;
         }
      }
   }
   le_clear_ime_buffer(s, session_data->ime_buffer);
   le_switch_engine(udp, s, engine_id, True);
}

void
switch_to_next_lang(
    iml_session_t *s,
    unit_desktop_t *udp,
    int engine_id
)
{
   int i, j, n;
   MyDataPerSession *session_data = (MyDataPerSession *) s->specific_data;

   n = udp->locale_Num;
   if (engine_id == udp->localeList[n-1].firstEngineId) {
      log_f("Next engine to switch [%d]\n", udp->localeList[n-1].firstEngineId);
      engine_id = 0;
   } else {
      for (i=0, j=i+1; j<udp->locale_Num; i++, j++){
         if (udp->localeList[i].firstEngineId == engine_id) {
           engine_id = udp->localeList[j].firstEngineId;
           break;
         }
      }
   }
   le_clear_ime_buffer(s, session_data->ime_buffer);
   le_switch_engine(udp, s, engine_id, True);
}

void 
proc_key_select_switch_ime_event(
    unit_desktop_t *udp,
    iml_session_t *s,
    int ime_id
)
{
    MyDataPerSession *session_data = (MyDataPerSession *) s->specific_data;
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);
    int engine_id, engine_num, i;
    char locale_id, system_locale_id;

    log_f("SELECT SWITCH IME KEY\n");
    log_f("selected ime_id:%d\n", ime_id);

    system_locale_id = desktop_data->aux_locale_id;
    engine_num = 0;
    engine_id = 0;
    for (i = 0; i< udp->gEngine_Num; i++) {
	locale_id = udp->gEngine_Info[i]->core.baseinfo.locale_id;
	if (locale_id == system_locale_id || locale_id == ENCODES_NUM) {
	    if (engine_num >= ime_id) {
		engine_id = i;
		break;
	    }
	    engine_num ++;
	}
    }

    log_f("engine_id:%d\n", engine_id);
    le_clear_ime_buffer(s, session_data->ime_buffer);
    le_switch_engine(udp, s, engine_id, True);
}

void 
proc_key_output(
    unit_desktop_t *udp,
    iml_session_t *s,
    IMKeyEventStruct *key_event
)
{
    MyDataPerSession *session_data = (MyDataPerSession *) s->specific_data;
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);
    IMEKeyRec  ime_keyevent;
    IMEArgList ime_args;
    int ret, cur_engine_id;

    cur_engine_id = session_data->paletteaux_status.engine_id;
    log_f("cur_engine_id:%d\n", cur_engine_id);
    if (cur_engine_id == 0xff) {
	iml_sendback_key(s, key_event);
	return;
    }

    ime_keyevent.keyCode = key_event->keyCode;
    ime_keyevent.keyChar = key_event->keyChar;
    ime_keyevent.modifier = key_event->modifier;

    /* get user defined arguments */
    ime_args = desktop_data->ime_args[cur_engine_id];
    udp->gEngine_Info[cur_engine_id]->core.envinfo.output_encode_id = desktop_data->aux_locale_id;
    ret = udp->gEngine_Info[cur_engine_id]->so_methods->IME_Filter(&udp->gEngine_Info[cur_engine_id]->core,
								   &ime_keyevent, ime_args, 
								   session_data->ime_buffer);

    if (ret == IME_NOT_USED_KEY)
	iml_sendback_key(s, key_event);
    else if (ret == RETURN_KEY) {
	key_event->keyCode = IM_VK_ENTER;
	key_event->keyChar = 0;
	key_event->modifier = 0;
	le_output_ime_buffer(s, session_data->ime_buffer);
	iml_sendback_key(s, key_event);
    } 

    if ((session_data->ime_buffer->hotkey_flag == IME_HOTKEY_END) && !session_data->ime_buffer->conv_flag) {
      proc_key_switch_conversion_event(udp, s, CONVERSION_OFF, (char *)NULL);
      le_output_ime_buffer(s, session_data->ime_buffer);
    } else if (session_data->ime_buffer->hotkey_flag == IME_HOTKEY_COMMIT) {
      if (!session_data->ime_buffer->conv_flag)
        proc_key_switch_conversion_event(udp, s, CONVERSION_OFF, (char *)NULL);
        le_commit_euro(s, session_data->ime_buffer);
    } else
        le_output_ime_buffer(s, session_data->ime_buffer);
}

/* Local Variables: */
/* c-file-style: "iiim-project" */
/* End: */
