/*
  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 <stdlib.h>
#include <ctype.h>
#include <limits.h>

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

Bool if_le_OpenIF(iml_if_t *);
Bool if_le_CloseIF(iml_if_t *);
Bool if_le_GetIFValue(iml_if_t *, IMArgList, int);
Bool if_le_SetIFValue(iml_if_t *, IMArgList, int);
Bool if_le_OpenDesktop(iml_desktop_t *, IMArgList, int);
Bool if_le_CloseDesktop(iml_desktop_t *);
Bool if_le_CreateSC(iml_session_t *, IMArgList, int);
Bool if_le_DestroySC(iml_session_t *);
Bool if_le_GetSCValue(iml_session_t *, IMArgList, int);
Bool if_le_SetSCValue(iml_session_t *, IMArgList, int);
IMText *if_le_ResetSC(iml_session_t *);
void if_le_SetSCFocus(iml_session_t *);
void if_le_UnsetSCFocus(iml_session_t *);
void if_le_SendEvent(iml_session_t *, IMInputEvent * ev);
int get_list_of_supported_locales();
unit_desktop_t *create_unit_desktop();
void add_unit_desktop(unit_desktop_t *udp);
unit_desktop_t * find_unit_desktop_by_sc(iml_session_t *);
int CpyUTFCHAR(char *src, UTFCHAR *dest);
IMHotkeyProfileStruct *get_hkp_from_hkm(int);

/* IF Method */
if_methods_t le_methods = {
	if_le_OpenIF,
	if_le_CloseIF,
	if_le_GetIFValue,
	if_le_SetIFValue,
	if_le_OpenDesktop,
	if_le_CloseDesktop,
	if_le_CreateSC,
	if_le_DestroySC,
	if_le_GetSCValue,
	if_le_SetSCValue,
	if_le_ResetSC,
	if_le_SetSCFocus,
	if_le_UnsetSCFocus,
	if_le_SendEvent
};

extern char lename_string[];
extern UTFCHAR lename_utf_string[];
extern char default_locale_id;
extern void get_line(char *buf, int size, char **curptr, char *line);
extern void unit_desktop_init(unit_desktop_t *udp);
extern int unit_desktop_add_listener(unit_desktop_t *udp, iml_session_t *s);
extern int unit_desktop_load_engines(unit_desktop_t *udp, iml_desktop_t *desktop);
extern void unit_desktop_set_curr_profile_id(unit_desktop_t *udp, int profile_id);
extern int unit_desktop_get_curr_profile_id(unit_desktop_t *udp);
extern void unit_desktop_switch_hotkey_profile(unit_desktop_t *udp, iml_desktop_t *desktop);
extern void unit_desktop_done(unit_desktop_t *udp);

extern IMEBufferRec *ime_buffer_malloc();
extern void ime_buffer_free(IMEBuffer);
extern void proc_key_event(unit_desktop_t *, iml_session_t *, IMKeyListEvent *);
extern void process_hotkey_event(unit_desktop_t *, iml_session_t *, IMKeyListEvent *);
extern void proc_key_switch_conversion_event(unit_desktop_t *, iml_session_t *, int, char *);
extern IMHotkeyManagerStruct *parse_hotkey_config_file(IMLEName *, char *);
extern void printHotkeyManager(IMHotkeyManagerStruct *);

IMLEName lename = {lename_string, lename_utf_string };
static IMObjectDescriptorStruct *objects = NULL;

static IMHotkeyManagerStruct *g_hkms = NULL;

static Bool add_listener_flag = False;
IMLocale locales[MAX_SUPPORTED_LOCALES];
int n_Supported_Locales;
unit_if_t *UIf;

/* htt_server get the IF information when start htt_server */

/* if_GetHotKeyInfo:
   returns Unit L/E specific hotkey profile struct
   a_le_name : this should match to unit's lename which was
   previously set as IF_LE_NAME in If_GetIfInfo().
*/

IMHotkeyManagerStruct *
if_GetHotKeyInfo (
    IMLEName *a_le_name
)
{
    char file_name[PATH_MAX];

    snprintf(file_name, sizeof(file_name),"%s/%s/%s", 
                 DEFAULT_ENGINE_PATH, XAUX_LOCALE_NAME, HOTKEY_CONFIG_FILE);

    log_f("if_GetHotkeyInfo: file_name [%s]\n", file_name);

    g_hkms = parse_hotkey_config_file(a_le_name, file_name);

    /*
     * printHotkeyManager(g_hkms);
     */

    return g_hkms;
}

void 
if_GetIfInfo(
    IMArgList args, 
    int num_args
)
{
    int i;

    log_f("if_GetIfInfo == num_args:%d\n", num_args);

    n_Supported_Locales =  get_list_of_supported_locales();
    log_f("n_Supported_Locales [%d]\n",n_Supported_Locales);

    for (i = 0; i < num_args; i++, args++) {
	switch (args->id) {
	  case IF_VERSION:
	   args->value = (IMArgVal) "1.2";
	   break;
	  case IF_METHOD_TABLE:
	   args->value = (IMArgVal) & le_methods;
	   break;
	  case IF_LE_NAME:
	   args->value = (IMArgVal) & lename;
	   break;
	  case IF_SUPPORTED_LOCALES:
	   args->value = (IMArgVal) & locales;
	   break;
	  case IF_SUPPORTED_OBJECTS:
	   args->value = (IMArgVal) objects; 
	   break;
	  case IF_NEED_THREAD_LOCK:
	   args->value = (IMArgVal) True;
	   break;
	  default:
	   break;
	}
    }
}

/* Open the IF interface */
Bool 
if_le_OpenIF(
    iml_if_t * If
)
{
    log_f("if_le_OpenIF ====\n");

    UIf = 0;

    return True;
}

/* Close the IF interface */
Bool 
if_le_CloseIF(
    iml_if_t * If
)
{
    int i;

    log_f("if_le_CloseIF === \n");

    for (i=0 ; i<n_Supported_Locales ; i++){
	if (locales[i].id != NULL) {
	    free(locales[i].id);
	    locales[i].id = NULL;
	}
	if (locales[i].name != NULL) {
	    free(locales[i].name);
	    locales[i].name = NULL;
	}
    }

    if (UIf)
	free(UIf);

    /*
      Free the allocated memory for hotkey profile under UNIT
    */

    if (g_hkms) {
	if (g_hkms->hkps) {
	    for (i=0; i<g_hkms->num_hotkey_profiles; i++) {
		if (g_hkms->hkps[i].hks)
		    free(g_hkms->hkps[i].hks);
	    }
	    free(g_hkms->hkps);
	}
	free(g_hkms);
    }

    return True;
}

Bool 
if_le_GetIFValue(
    iml_if_t * If, 
    IMArgList args, 
    int num_args
)
{
    log_f("if_le_GetIFValue()\n");
    return True;
}

Bool 
if_le_SetIFValue(
    iml_if_t * If, 
    IMArgList args, 
    int num_args
)
{
    log_f("if_le_SetIFValue()\n");
    return True;
}

unit_if_t *
unit_if() 
{
    if (!UIf) {
	UIf = (unit_if_t *)calloc(1, sizeof(unit_if_t));
	UIf->create_unit_desktop = create_unit_desktop;
	UIf->add_unit_desktop = add_unit_desktop;
	UIf->find_unit_desktop_by_sc = find_unit_desktop_by_sc;
	UIf->ud_count = 0;
    } 
    if (!UIf) 
	log_f("calloc/realloc error in unit_if() \n");

    return UIf;
}

unit_desktop_t *
create_unit_desktop() 
{
    unit_desktop_t *udp = (unit_desktop_t *) calloc(1, sizeof(unit_desktop_t));
    udp->next = unit_if()->ud_list;
    return udp;
}

void 
add_unit_desktop(
    unit_desktop_t *udp
) 
{
    udp->unit_desktop_init = unit_desktop_init;
    udp->unit_desktop_add_listener = unit_desktop_add_listener;
    udp->unit_desktop_load_engines = unit_desktop_load_engines;
    udp->unit_desktop_set_curr_profile_id = unit_desktop_set_curr_profile_id;
    udp->unit_desktop_get_curr_profile_id = unit_desktop_get_curr_profile_id;
    udp->unit_desktop_switch_hotkey_profile = unit_desktop_switch_hotkey_profile;
    udp->unit_desktop_done = unit_desktop_done;
    unit_if()->ud_list = udp;
    unit_if()->ud_count++;
    return;
}

unit_desktop_t *
find_unit_desktop_by_sc(
    iml_session_t *s
) 
{
    unit_desktop_list udl, *prev;

    if (UIf->ud_list == NULL) {
	return (unit_desktop_t *) NULL; 
    }
    for (prev = &UIf->ud_list; (udl = *prev) != 0; prev = &udl->next) {
        if (udl->s) {
	    if (udl->s->desktop == s->desktop)
		return udl;
        } else if ((udl->s == 0) && (udl->next == NULL)) {
	    return udl;
	}
    }
    return (unit_desktop_t *) NULL; 
}

Bool 
if_le_OpenDesktop(
    iml_desktop_t * desktop, 
    IMArgList args, 
    int num_args
)
{
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)calloc(1,sizeof(MyDataPerDesktop));
    unit_desktop_t *udp = (unit_desktop_t *) 0;

    udp = unit_if()->create_unit_desktop();
    unit_if()->add_unit_desktop(udp);
    udp->unit_desktop_init(udp); 
    log_f("if_le_OpenDesktop: udp [0x%x]\n", (unsigned int) udp);
    udp->unit_desktop_load_engines(udp, desktop);

    desktop_data->current_session = 0;
    desktop_data->root_session = 0;
    desktop_data->aux_locale_id = default_locale_id;
    desktop_data->udp = udp;

    desktop->specific_data = (void *) desktop_data;

    add_listener_flag = False;

    return True;
}

Bool 
if_le_CloseDesktop(
    iml_desktop_t * desktop
)
{
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *) desktop->specific_data;
    unit_desktop_t *temp, *prev;
    int i;

    log_f("if_le_CloseDesktop: udp [0x%x] \n", (unsigned int) desktop_data->udp);
    for (i=0; i<MAX_ENGINE_NUM; i++) {
	if (desktop_data->ime_args[i] != (IMEArgList) NULL)
	    free((char *)desktop_data->ime_args[i]);
    }
    if (UIf && (UIf->ud_count > 0)) {
	temp = desktop_data->udp;
	prev = UIf->ud_list; /* Starting of the node */
        if (temp == prev) {
	    if (temp->next == NULL) {
		unit_desktop_done(temp);
		UIf->ud_count--;
		free(temp);
	    } else if (temp->next != NULL) {
		prev = temp->next;
		unit_desktop_done(temp);
		UIf->ud_count--;
		free(temp);
		UIf->ud_list = prev;
	    }
	} else {
	    while ((prev->next != temp) && (prev->next != NULL)) {
		prev = prev->next;
	    }
	    prev->next = temp->next;
	    if (temp->next == NULL)
		temp->next = prev;
	    unit_desktop_done(temp);
	    UIf->ud_count--;
	    free(temp);
	}
    }
    free(desktop_data);

    return True;
}

Bool 
if_le_CreateSC(
    iml_session_t *s, 
    IMArgList args, 
    int num_args
)
{
    int i;
    iml_desktop_t *desktop = s->desktop;
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *) desktop->specific_data;
    MyDataPerSession *p = (MyDataPerSession *) calloc(1, sizeof(MyDataPerSession));
    log_f("if_le_CreateSC: udp [0x%x] \n", (unsigned int) desktop_data->udp);

    desktop_data->current_session = 0;
    p->paletteaux_status.engine_id = 0xff;
    desktop_data->udp->s = 0;
    
    /* Allocate memory for input method session context */
    p->ime_buffer = (IMEBuffer)ime_buffer_malloc();
    p->locale = NULL;

    s->specific_data = (void*) p;

    /* set aux proxy data */
    p->protocol_type = UNKNOWN_IMP;
    p->client_type = UNKNOWN_CLIENT;
    for (i = 0; i < num_args; i++, args++) {
	switch (args->id) {
	  case UI_PROTOCOL_TYPE:
	   if (args->value) {
	       log_f("UI_PROTOCOL_TYPE: value: %s\n", args->value);
	       if (!strcmp (UI_PROTOCOL_TYPE_XIMP, args->value))
		   p->protocol_type = XIMP;
	   }
	   break;
	  case UI_CLIENT_TYPE:
	   if (args->value) {
	       log_f("UI_CLIENT_TYPE: value: %s\n", args->value);
	       if (!strcmp (UI_CLIENT_TYPE_X, args->value))
		   p->client_type = X11_CLIENT;
	   }
	   break;
	}
    }
    if (p->protocol_type == XIMP && p->client_type == X11_CLIENT)
	if (desktop_data->root_session == 0)
	    desktop_data->root_session = s;

    return True;
}

Bool 
if_le_DestroySC(
    iml_session_t * s
)
{
    iml_desktop_t *desktop = s->desktop;
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *) desktop->specific_data;
    MyDataPerSession *p = (MyDataPerSession *) s->specific_data;

    log_f("if_le_DestroySC: udp [0x%x] \n", (unsigned int) desktop_data->udp);

    desktop_data->current_session = 0;
    desktop_data->udp->s = 0;

    if (p->locale != NULL) {
	free((char *)p->locale);
	p->locale = NULL;
    }

    ime_buffer_free(p->ime_buffer);
    free((char *) p);

    if (s == desktop_data->root_session)
	desktop_data->root_session = 0;

    return True;
}

Bool 
if_le_GetSCValue(
    iml_session_t * s, 
    IMArgList args, 
    int num_args
)
{
    log_f("if_le_GetSCValue(s=%x)\n\n", (unsigned int) s);
    return True;
}

Bool 
if_le_SetSCValue(
    iml_session_t * s, 
    IMArgList args, 
    int num_args
)
{
    int i;
    IMArg *p = args;
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);
    MyDataPerSession *session_data = (MyDataPerSession *) s->specific_data;
    unit_desktop_t *udp = desktop_data->udp;

    log_f("if_le_SetSCValue: udp [0x%x]\n", (unsigned int) desktop_data->udp);

    desktop_data->current_session = s;
    desktop_data->udp->s = s;

    for (i = 0; i < num_args; i++, p++) {
	switch (p->id) {
	  case SC_CLIENT_LOCALE:
	   log_f("if_le_SetSCValue(): SC_CLIENT_LOCALE: [%s]\n",p->value);
	   if (session_data->locale != NULL) {
	       free((char *)session_data->locale);
	       session_data->locale = NULL;
	   }
	   session_data->locale = (char *)strdup(p->value);
	   break;
	  case SC_TRIGGER_ON_NOTIFY:
	   proc_key_switch_conversion_event(udp, s, CONVERSION_ON, (char *)session_data->locale);
           udp->unit_desktop_switch_hotkey_profile(udp, s->desktop);
	   break;
                
	  case SC_TRIGGER_OFF_NOTIFY:
	   log_f("SC_TRIGGER_OFF_NOTIFY\n");
	   proc_key_switch_conversion_event(udp, s, CONVERSION_OFF, (char *)NULL);
	   break;
                
	  case SC_REALIZE:
	   break;

	  default:
	   break;
	}
    }
  
    return True;
}

IMText *
if_le_ResetSC(
    iml_session_t * s
)
{
    log_f("if_le_ResetSC(s=%x)\n\n", (unsigned int) s);
    return (IMText *) NULL;
}

void 
if_le_SetSCFocus(
    iml_session_t * s
)
{
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);
    unit_desktop_t *udp = desktop_data->udp;

    log_f("if_le_SetSCFocus() s:%x, current_session:%x, udp:0x%x\n", (unsigned int)s, (unsigned int)desktop_data->current_session, (unsigned int)desktop_data->udp);

    desktop_data->current_session = s;
    desktop_data->udp->s = s;
    le_status_draw(udp, s);
    udp->unit_desktop_switch_hotkey_profile(udp, s->desktop);
    /*
      if (s->desktop->session_count == 1) {
      if (!add_listener_flag) {
      log_f("if_le_SetSCFocus() : Loading Engines ...\n");
      udp = unit_if()->ud_list;
      udp->unit_desktop_add_listener(udp, s); 
      add_listener_flag = True;
      }
      }
    */
    return;
}

void 
if_le_UnsetSCFocus(
    iml_session_t * s
)
{
    log_f("if_le_UnsetSCFocus() s:%x\n", (unsigned int) s);
}

void 
if_le_SendEvent(
    iml_session_t * s, 
    IMInputEvent * ev
)
{
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);
    unit_desktop_t *udp = desktop_data->udp;

    log_f("if_le_SendEvent session=%x\n", (unsigned int) s);
    if (ev) {
	if (ev->type == IM_EventKeyList) {
	    log_f("Keyboard Event\n");
	    proc_key_event(udp, s, (IMKeyListEvent *)ev);
	} else if (ev->type == IM_HotkeyEvent) {
	    log_f("Hotkey Event\n");
	    process_hotkey_event(udp, s, (IMKeyListEvent *)ev);
        }
    }
}

int 
get_list_of_supported_locales()
{
    char	file_name[PATH_MAX], line[MAX_LINE_LEN]; 
    char        *file_buf, *curr_ptr;
    char	keyCodeName[NAME_MAX], modifierName[NAME_MAX];
    char	locale_name[NAME_MAX], *kptr, *ptr;
    
    int	len, n, nfread, fsize, fd;
    int	locale_flag = ENCODE_ERROR;
    int	generic_flag = 0;
    int	switch_to_next_locale_flag = 0;
    int	switch_to_prev_locale_flag = 0;
    int	switch_layout_flag = 0;
    FILE	*fp;
    struct stat buf;

    n = 0;

    memset((char *)keyCodeName,'\0',sizeof(keyCodeName));
    memset((char *)modifierName,'\0',sizeof(modifierName));

    snprintf(file_name, sizeof(file_name), "%s/%s/%s",  DEFAULT_ENGINE_PATH, 
	     XAUX_LOCALE_NAME, 
	     SYSTEM_PROFILE_NAME);

    log_f("get_list_of_supported_locales: file name :%s\n",file_name);
    fp = fopen(file_name, "r");
    if (! fp)
	return (-1);

    fd = fileno((FILE *)fp);
    if (fstat(fd, &buf) < 0) {
        return -1;
    }
    fsize = buf.st_size;
    log_f("get_list_of_supported_locales: fsize [%d]\n",fsize);
    file_buf = (char *)calloc(fsize, sizeof(char));
    nfread = fread(file_buf, fsize, 1, fp);
    log_f("get_list_of_supported_locales: nfread [%d]\n",nfread);

    curr_ptr = 0;

    do {
        get_line(file_buf, fsize, &curr_ptr, line);

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

	len = strlen(line);
	if (line[0] == '[' && line[len-1] == ']') {
	    /* compute locale_flag */
	    ptr = line + 1;
	    while(isspace(*ptr)) ptr++;

	    memset((char *)locale_name,'\0',sizeof(locale_name));
	    /* get locale section name */
	    kptr = locale_name;
	    while (*ptr && !isspace(*ptr) && *ptr!=']') 
		*(kptr++) = *(ptr++);
	    *kptr = '\0';

	    /* get locale section name */
	    if (!strcasecmp(locale_name, COMMON_ENGINE_PATH))
		locale_flag = ENCODES_NUM;
	    else if(!strcasecmp(locale_name, GENERIC_IM_TABLE_NAME)){
		generic_flag = 1;
		continue;
	    }else if(!strcasecmp(locale_name, SWITCH_TO_NEXT_LOCALE)){
                switch_to_next_locale_flag = 1;
		continue;
	    }else if(!strcasecmp(locale_name, SWITCH_TO_PREV_LOCALE)){
		switch_to_prev_locale_flag = 1;
		continue;
	    }else if(!strcasecmp(locale_name, SWITCH_LAYOUT_NAME)){
		switch_layout_flag = 1;
		continue;
	    } 

	    if(!generic_flag)
		locale_flag = get_encodeid_from_locale(locale_name);
	    else{
		locale_flag = ENCODES_NUM;

		locales[n].id = (char *)strdup(locale_name);
		locales[n].name = (UTFCHAR *)calloc(strlen(locale_name)+1,sizeof(UTFCHAR));
		CpyUTFCHAR(locale_name, locales[n].name);
		n++;
	    }
	    continue;
	}else
	    continue;
    } while (1);
    locales[n].id = (char *)NULL;
    locales[n].name = (UTFCHAR *)NULL;
    fclose(fp);
    return(n);
}

int 
CpyUTFCHAR(
    char *src, 
    UTFCHAR *dest
)
{
    int i;

    for(i=0;*src;i++){
	*dest++ = *src++;
    }
    *dest = 0;
    return i;
}

IMHotkeyProfileStruct *
get_hkp_from_hkm(
    int profile_id
)
{
    int i;
    IMHotkeyProfileStruct *hkp = NULL;

    if (g_hkms) {
	if (g_hkms->hkps) {
	    for (i=0; i<g_hkms->num_hotkey_profiles; i++) {
		if (g_hkms->hkps[i].profile_id == profile_id) {
                  hkp = (IMHotkeyProfileStruct *) calloc(1, sizeof(IMHotkeyProfileStruct));
                  hkp->profile_id = g_hkms->hkps[i].profile_id;
                  hkp->scope = g_hkms->hkps[i].scope;
                  hkp->name = g_hkms->hkps[i].name;
                  hkp->num_hotkeys = g_hkms->hkps[i].num_hotkeys;
                  hkp->hks = g_hkms->hkps[i].hks;
                  return hkp;
                }
	    }
	}
    }
    return hkp;
}

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