/*
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 <stdio.h>
#include "SunIM.h"
#include <EIMIL.h>

static char testEIMIL_class[] = "org.OpenI18N.testEIMIL";
static char testEIMIL_confdir[] = "../locale/common/testEIMIL";

Bool    if_testEIMIL_OpenIF();
Bool    if_testEIMIL_CloseIF();
Bool    if_testEIMIL_GetIFValue();
Bool    if_testEIMIL_SetIFValue();
Bool    if_testEIMIL_OpenDesktop();
Bool    if_testEIMIL_CloseDesktop();
Bool    if_testEIMIL_CreateSC();
Bool    if_testEIMIL_DestroySC();
Bool    if_testEIMIL_GetSCValue();
Bool    if_testEIMIL_SetSCValue();
IMText  *if_testEIMIL_ResetSC();
void    if_testEIMIL_SetSCFocus();
void    if_testEIMIL_UnsetSCFocus();
void    if_testEIMIL_SendEvent();

/* IF Method */
if_methods_t testEIMIL_method_table = {
    if_testEIMIL_OpenIF,
    if_testEIMIL_CloseIF,
    if_testEIMIL_GetIFValue,
    if_testEIMIL_SetIFValue,

    if_testEIMIL_OpenDesktop,
    if_testEIMIL_CloseDesktop,

    if_testEIMIL_CreateSC,
    if_testEIMIL_DestroySC,
    if_testEIMIL_GetSCValue,
    if_testEIMIL_SetSCValue,
    if_testEIMIL_ResetSC,
    if_testEIMIL_SetSCFocus,
    if_testEIMIL_UnsetSCFocus,
    if_testEIMIL_SendEvent,
};

UTFCHAR lename_string[] = {0x304B, 0x3093, 0x306A, 0x4C, 0x45, 0x0};
UTFCHAR jahrn_string[] = {0x65E5, 0x672C, 0x8A9E, 0x0};
UTFCHAR lookup_choice_title[] = {0x5019, 0x88DC, 0x9078, 0x629E, 0x0};

static IMLEName lename = {
    "testEIMIL", lename_string	/* LE id, HRN */
};

static IMLocale locales[] = {
    {"ja", jahrn_string},	/* locale id, HRN */
    NULL
};

/*
  Session data:
*/

typedef struct
{
    int conv_flag;
    int luc_start;
    int preedit_start;
    int status_start;
    EIMIL_handle eh;
} TestEIMILSession;

static TestEIMILSession*
testEIMIL_session_data(iml_session_t *s)
{
    return (TestEIMILSession*)(s->specific_data);
}

static EIMIL_handle
testEIMIL_handle(iml_session_t *s)
{
    return ((TestEIMILSession*)(s->specific_data))->eh;
}

static iml_session_t*
testEIMIL_session(EIMIL_handle eh)
{
    return (iml_session_t*) EIMIL_get_private(eh);
}

/*
  AUX Object:
*/

IMObjectDescriptorStruct *objects = NULL;
void init_objects()
{
}

/*
  IMText operations:
*/

static IMFeedbackList*
create_feedback(iml_session_t *s, int size)
{
    int i;
    IMFeedbackList *feedback, *fbl;
    IMFeedback *fb;
    
    if (!s) return NULL;

    feedback = ((IMFeedbackList *)
		s->If->m->iml_new(s, sizeof(IMFeedbackList) * size));
    for (i = 0; i < size; i++) {
        IMFeedbackList *fbl = &feedback[i];
        fbl->count_feedbacks = 1;
	fb = ((IMFeedback *) s->If->m->iml_new(s, sizeof(IMFeedback) * 4));
	fbl->feedbacks = fb;
        memset(fbl->feedbacks, 0, sizeof(IMFeedback) * 4);
    }
    return feedback;
}

static IMText*
create_IMText(iml_session_t *s, int len)
{
    int i;
    IMText *p;
    
    if (!s) return NULL;

    p = (IMText *) s->If->m->iml_new(s, sizeof(IMText));
    memset(p, 0, sizeof(IMText));
    p->encoding = UTF16_CODESET;
    p->text.utf_chars = ((UTFCHAR *)
			 s->If->m->iml_new(s, sizeof(UTFCHAR) * (len + 1)));
    p->char_length = len;
    p->feedback = create_feedback(s, len);

    return p;
}

static IMText*
UTFCHAR_to_IMText(iml_session_t *s, UTFCHAR *p)
{
    IMText *pit;
    UTFCHAR *p2 = p;
    int len;

    for (len = 0;*p2;p2++) len++;
    pit = create_IMText(s, len);
    if (!pit) return NULL;
    memcpy(pit->text.utf_chars, p, (len + 1) * sizeof(UTFCHAR));

    return pit;
}

static IMText*
ASCIZ_to_IMText(
    iml_session_t *s,
    unsigned char *p
)
{
    IMText *pit;
    UTFCHAR *pu;
    int len = strlen(p);

    pit = create_IMText(s, len);
    if (!pit) return NULL;

    pu = pit->text.utf_chars;
    for (;;) {
	*pu++ = *p++;
	if (!*p) break;
    }

    return pit;
}

/*
  Preedit
*/

static void
testEIMIL_preedit_draw(
    iml_session_t *s
)
{
    iml_inst *lp;
    iml_inst *rrv = NULL;
    IMText *p;
    TestEIMILSession *pes = testEIMIL_session_data(s);

    if (pes->preedit_start == False) {
        lp = s->If->m->iml_make_preedit_start_inst(s);
        s->If->m->iml_link_inst_tail(&rrv, lp);
        pes->preedit_start = True;
    }

    // TODO
    p = ASCIZ_to_IMText(s, "test");

    lp = s->If->m->iml_make_preedit_draw_inst(s, p);
    s->If->m->iml_link_inst_tail(&rrv, lp);
    s->If->m->iml_execute(s, &rrv);
}

static void
testEIMIL_preedit_done(iml_session_t *s)
{
    TestEIMILSession *pes = testEIMIL_session_data(s);
    if (pes->preedit_start == True) {
	iml_inst *lp;
        lp = s->If->m->iml_make_preedit_done_inst(s);
	s->If->m->iml_execute(s, &lp);
        pes->preedit_start = False;
    }
}

/*
  EIMIL handlers
 */

static int
testEIMIL_event_handler(
    EIMIL_handle eh,
    EIMIL_event *pevent
)
{
    iml_inst *lp;
    iml_session_t *s = testEIMIL_session(eh);
    IMInputEvent *piev;

    piev = EIMIL_convert_event_to_IMInputEvent(pevent);

    if (piev) {
	IMKeyListEvent *pimkev = (IMKeyListEvent*) piev;
	/* I don't process this keyevent.  Return it. */
	lp = s->If->m->iml_make_keypress_inst(s, ((IMKeyEventStruct *)
						  pimkev->keylist));
	s->If->m->iml_execute(s, &lp);
    }

    return 1;
}

static int
testEIMIL_uichange_handler(
    EIMIL_handle eh,
    EIMIL_value *pval,
    int uichange_flags
)
{
    iml_session_t *s = testEIMIL_session(eh);

    switch (uichange_flags) {
      case EIMIL_ENABLE_PREEDIT:
      case EIMIL_DISABLE_PREEDIT:
      case EIMIL_UPDATE_PREEDIT:
      case EIMIL_ENABLE_LOOKUP_CHOICE:
      case EIMIL_DISABLE_LOOKUP_CHOICE:
      case EIMIL_UPDATE_LOOKUP_CHOICE:
	;
    }

    return 1;
}


/*
  LEIF operations.
*/

static void
send_commit(
    iml_session_t *s,
    IMText *p,
    int executep
)
{
    iml_inst *lp;
    iml_inst *rrv = NULL;

    lp = s->If->m->iml_make_commit_inst(s, p);
    s->If->m->iml_link_inst_tail(&rrv, lp);
    if (executep) {
	s->If->m->iml_execute(s, &rrv);
    }
    return;
}

/*
  Initialization.
*/

static Bool
testEIMIL_register_class(
    char *if_path
)
{
    char *buf;
    int ipsize;

    ipsize = strlen(if_path);
    if (ipsize < 1) return False;
    buf = (char*) malloc((ipsize + 2) * sizeof(char)
			 + sizeof(testEIMIL_confdir));
    strcpy(buf, if_path);
    buf[ipsize] = '/';
    buf[ipsize + 1] = '\0';
    strcat(buf, testEIMIL_confdir);

    if (!EIMIL_register_class(testEIMIL_class, buf))
	return False;

    return True;
}

static EIMIL_handle eh_initial;

static Bool
testEIMIL_init(
    char *if_path
)
{
    unsigned char *pfile;
    if (eh_initial) return True;

    testEIMIL_register_class(if_path);
    pfile = EIMIL_find_file(testEIMIL_class, "default.xml");
    if (!pfile) return False;
    if (!EIMIL_parse_file(&eh_initial, pfile)) return False;
    EIMIL_register_handler(eh_initial,
			   testEIMIL_event_handler,
			   NULL, NULL);

    return True;
}

void
testEIMIL_status_draw(
    iml_session_t *s
)
{
    iml_inst *lp;
    iml_inst *rrv = NULL;
    IMText *p;
    TestEIMILSession *pes = testEIMIL_session_data(s);

    if (pes->conv_flag) {
	p = ASCIZ_to_IMText(s, "ON");
    } else {
	p = ASCIZ_to_IMText(s, "OFF");
    }
    if (!p) return;

    if (pes->status_start == False) {
        lp = s->If->m->iml_make_status_start_inst(s);
        s->If->m->iml_link_inst_tail(&rrv, lp);
        pes->status_start = True;
    }

    lp = s->If->m->iml_make_status_draw_inst(s, p);
    s->If->m->iml_link_inst_tail(&rrv, lp);
    
    s->If->m->iml_execute(s, &rrv);
}

void
testEIMIL_start_lookup_choice(
    iml_session_t *s,
    iml_inst **prrv,
    int num
)
{
    TestEIMILSession *pes = testEIMIL_session_data(s);
    if (pes->luc_start == False) {
	iml_inst *lp;
	IMLookupStartCallbackStruct *start;
        start = ((IMLookupStartCallbackStruct *)
		 s->If->m->iml_new(s, sizeof(IMLookupStartCallbackStruct)));
	start->whoIsMaster = IMIsMaster;
        start->IMPreference = (LayoutInfo *) s->If->m->iml_new(s, sizeof(LayoutInfo));
	memset(start->IMPreference, 0, sizeof(LayoutInfo));

        start->IMPreference->choice_per_window = num;
        start->IMPreference->ncolumns = 1;
        start->IMPreference->nrows = num;
        start->IMPreference->drawUpDirection = DrawUpHorizontally;
        start->IMPreference->whoOwnsLabel = IMOwnsLabel;
        start->CBPreference = NULL;

        lp = s->If->m->iml_make_lookup_start_inst(s, start);
	s->If->m->iml_link_inst_tail(prrv, lp);
        pes->luc_start = True;
    }
}

void
testEIMIL_show_lookup_choice(
    iml_session_t *s
)
{
    int num;
    iml_inst *lp;
    iml_inst *rrv = NULL;
    IMText *p;
    IMLookupDrawCallbackStruct *draw;
    TestEIMILSession *pes = testEIMIL_session_data(s);

    draw = ((IMLookupDrawCallbackStruct *)
	    s->If->m->iml_new(s, sizeof(IMLookupDrawCallbackStruct)));
    memset(draw, 0, sizeof(IMLookupDrawCallbackStruct));
    draw->title = UTFCHAR_to_IMText(s, lookup_choice_title);

    /* set choices */
    {
	/* TODO */
#if 0
	fprintf(stderr, "draw->index_of_first_candidate=%x\n",
		draw->index_of_first_candidate);
	fprintf(stderr, "draw->index_of_last_candidate=%x\n",
		draw->index_of_last_candidate);
	fprintf(stderr, "draw->n_choices=%x\n",
		draw->n_choices);
	fprintf(stderr, "draw->choices=%x\n",
		draw->choices);
	fprintf(stderr, "draw->choices->label=%x\n",
		draw->choices->label);
	fprintf(stderr, "draw->max_len=%x\n", max_len);
	fprintf(stderr, "draw->index_of_current_candidate=%x\n",
		draw->index_of_current_candidate);
#endif
    }
    testEIMIL_start_lookup_choice(s, &rrv, num);
    lp = s->If->m->iml_make_lookup_draw_inst(s, draw);
    s->If->m->iml_link_inst_tail(&rrv, lp);
    s->If->m->iml_execute(s, &rrv);
}

void
testEIMIL_lookup_choice_done(iml_session_t *s)
{
    TestEIMILSession *pes = testEIMIL_session_data(s);
    if (pes->luc_start == True) {
	iml_inst *lp;
        lp = s->If->m->iml_make_lookup_done_inst(s);
	s->If->m->iml_execute(s, &lp);
        pes->luc_start = False;
    }
}

void
testEIMIL_make_conversion_off(
    iml_session_t *s
)
{
    TestEIMILSession *pes = testEIMIL_session_data(s);

    pes->conv_flag = 0;
    testEIMIL_status_draw(s);
    testEIMIL_lookup_choice_done(s);
    testEIMIL_preedit_done(s);
}

void
testEIMIL_make_conversion_on(
    iml_session_t  *s
)
{
    TestEIMILSession *pes = testEIMIL_session_data(s);

    pes->conv_flag = 1;
    testEIMIL_status_draw(s);
}

/*
  IF offer.
*/

void
if_GetIfInfo(IMArgList args, int num_args)
{
    int i;
    init_objects();
    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) &testEIMIL_method_table;
	   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;
	}
    }
}

/*
  IFs
*/

Bool
if_testEIMIL_OpenIF(
    iml_if_t *If
)
{
    return testEIMIL_init(If->ifpath_name);
}

Bool
if_testEIMIL_CloseIF(
    iml_if_t *If
)
{
    EIMIL_free_handle(eh_initial);
    return True;
}

Bool
if_testEIMIL_GetIFValue(
    iml_if_t *If,
    IMArgList args,
    int num_args
)
{
    return True;
}

Bool
if_testEIMIL_SetIFValue(
    iml_if_t *If,
    IMArgList args,
    int num_args
)
{
    return True;
}

Bool
if_testEIMIL_OpenDesktop(
    iml_desktop_t * desktop,
    IMArgList args,
    int num_args
)
{
    return True;
}

Bool
if_testEIMIL_CloseDesktop(
    iml_desktop_t * desktop
)
{
    return True;
}

Bool
if_testEIMIL_CreateSC(
    iml_session_t *s,
    IMArgList args,
    int num_args
)
{
    EIMIL_handle eh;
    TestEIMILSession *pes = (TestEIMILSession*) malloc(sizeof(TestEIMILSession));

    if (!pes) return False;

    if (!EIMIL_duplicate_handle(&eh, eh_initial)) return False;
    EIMIL_set_private(eh, s);

    pes->eh = eh;
    s->specific_data = (void*) pes;

    return True;
}

Bool
if_testEIMIL_DestroySC(
    iml_session_t *s
)
{
    EIMIL_free_handle(testEIMIL_handle(s));

    return True;
}

IMText*
if_testEIMIL_ResetSC(
    iml_session_t *s
)
{
    iml_inst *lp;
    TestEIMILSession *pes = testEIMIL_session_data(s);

    EIMIL_free_handle(testEIMIL_handle(s));
    EIMIL_duplicate_handle(pes->eh, eh_initial);

    /* erase preedit. */
    lp = s->If->m->iml_make_preedit_erase_inst(s);
    s->If->m->iml_execute(s, &lp);

    return (IMText*) NULL;
}

Bool
if_testEIMIL_SetSCValue(
    iml_session_t *s,
    IMArgList args,
    int num
)
{
    int i;
    IMArg *p = args;

    for (i = 0; i < num; i++, p++) {
        switch (p->id) {
	case SC_TRIGGER_ON_NOTIFY:
	    testEIMIL_make_conversion_on(s);
	    break;
	case SC_TRIGGER_OFF_NOTIFY:
	    testEIMIL_make_conversion_off(s);
	    break;
	case SC_REALIZE:
	    /* currently do nothing. */
	    break;
	case SC_LOOKUP_LABELTYPE:
	    break;
	default:
	    break;
	}
    }

    return True;
}

Bool
if_testEIMIL_GetSCValue(iml_session_t *s, IMArgList args, int num_args)
{
    int i;
    IMArg *p = args;

    /* Canna uses at least LATIN, HIRAGANA, KATAKANA,
       and KANJI scripts.
       That's all to it? */
    static int charsubset[] = {
        67,			/* LATIN */
        47,			/* HIRAGANA */
        48,			/* KATAKANA */
        71,			/* KANJI */
        0
    };

    for (i = 0; i < num_args; i++, p++) {
        switch (p->id) {
            case SC_SUPPORTED_CHARACTER_SUBSETS:
                /* specify CHARACTER_SUBSETS */
                p->value = (IMArgVal) charsubset;
                break;
            default:
                break;
            }
    }
    return True;
}

void
if_testEIMIL_SetSCFocus(iml_session_t *s)
{
    testEIMIL_status_draw(s);
}

void
if_testEIMIL_UnsetSCFocus(iml_session_t *s)
{
    /* do nothing. */
}

void
if_testEIMIL_SendEvent(iml_session_t *s, IMInputEvent *ev)
{
    int n;
    EIMIL_value **ppevs;
    EIMIL_handle eh = testEIMIL_handle(s);

    n = EIMIL_construct_events_from_IMInputEvent(ev, &ppevs);
    for (; n > 0; n--, ppevs++) {
	if (ppevs) EIMIL_send_event(eh, *ppevs);
    }
    return;
}

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