/*
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.

*/

#include <stdio.h>

#include "le.h"
#include "encode.h"

#define IIIM_DRAW_PREEDIT_STYLE 1
#define IIIM_DRAW_LOOKUP_STYLE 1

/* UTF-8 string of [ Ӣ�� ] */
unsigned char English_Status_UTF[] = {
        0xe8, 0x8b, 0xb1, 0xe6, 0x96, 0x87, 0x0
/*
        0x5b, 0x20, 0xe8, 0x8b, 0xb1, 0xe6, 0x96, 0x87, 0x20, 0x5d, 0x0
*/
};

extern void le_draw_compositeaux_preedit_notify(iml_session_t *s, int encode_id, char* pretext, int caret, int deco_len, IMCharDecoration* predeco);
extern void le_draw_compositeaux_lookup_notify(iml_session_t *s, int encode_id, int nCand, int markType, char**candlist, int *deco_len, IMCharDecoration**canddecolist);


void ime_buffer_free(iml_session_t *s, IMEBuffer ime_buffer);
void le_free_ime_session_data(iml_session_t *s, IMEBuffer ime_buf);
void le_alloc_ime_session_data(iml_session_t *s, int engine_id, IMEBuffer ime_buf);
void le_clear_ime_session_data(iml_session_t *s, IMEBuffer ime_buf);

/* ============================================================== */
/*                   IME buffer for every session                 */
/* ============================================================== */
IMEBufferRec *ime_buffer_malloc(iml_session_t *s)
{
        int i;
        IMEBuffer ime_buffer;

        ime_buffer = (IMEBufferRec *)calloc(1, sizeof(IMEBufferRec));
        memset(ime_buffer, 0, sizeof(IMEBufferRec));
        ime_buffer->ime_session_data_engine = -1;

        ime_buffer->inputkey_buf = (char *)calloc(MAX_INPUT_KEY_NUM, sizeof(char));
        ime_buffer->preedit_buf = (unsigned char *)calloc(MAX_PREEDIT_CHAR_NUM, sizeof(char));
        ime_buffer->status_buf = (unsigned char *)calloc(MAX_STATUS_CHAR_NUM, sizeof(char));
        ime_buffer->commit_buf = (unsigned char *)calloc(MAX_COMMIT_CHAR_NUM, sizeof(char));

        ime_buffer->lookup_buf = (unsigned char **)calloc(MAX_CANDIDATES_NUM, sizeof(unsigned char *));
        ime_buffer->candidates_buf = (unsigned char **)calloc(MAX_CANDIDATES_NUM, sizeof(unsigned char *));
        ime_buffer->additions_buf = (unsigned char **)calloc(MAX_CANDIDATES_NUM, sizeof(unsigned char *));

        if (   	(ime_buffer == NULL) ||
                (ime_buffer->inputkey_buf == NULL) ||
                (ime_buffer->preedit_buf == NULL) ||
                (ime_buffer->status_buf == NULL) ||
                (ime_buffer->commit_buf == NULL) ||
                (ime_buffer->lookup_buf == NULL) ||
                (ime_buffer->candidates_buf == NULL) ||
                (ime_buffer->additions_buf == NULL) )
                goto Error;

        for (i =0; i<MAX_CANDIDATES_NUM; i++) {
                ime_buffer->lookup_buf[i] = (unsigned char *)calloc(MAX_CANDIDATE_CHAR_NUM, sizeof(char));
                ime_buffer->candidates_buf[i] = (unsigned char *)calloc(MAX_CANDIDATE_CHAR_NUM, sizeof(char));
                ime_buffer->additions_buf[i] = (unsigned char *)calloc(MAX_CANDIDATE_CHAR_NUM, sizeof(char));

                if ( 	(ime_buffer->lookup_buf[i] == NULL) ||
                        (ime_buffer->candidates_buf[i] == NULL) ||
                        (ime_buffer->additions_buf[i] == NULL) )
                        goto Error;
        }

        ime_buffer->preedit_deco = (IMCharDecoration *)calloc(MAX_PREEDIT_CHAR_NUM, sizeof(IMCharDecoration));
        ime_buffer->lookup_deco_len = (int *)calloc(MAX_CANDIDATES_NUM, sizeof(int));
        ime_buffer->lookup_deco =  (IMCharDecoration **)calloc(MAX_CANDIDATES_NUM, sizeof(IMCharDecoration*));
        if (ime_buffer->preedit_deco == NULL || ime_buffer->lookup_deco == NULL || ime_buffer->lookup_deco_len == NULL)
            goto Error;

        memset(ime_buffer->lookup_deco, 0, MAX_CANDIDATES_NUM*sizeof(IMCharDecoration*));
        for (i =0; i<MAX_CANDIDATES_NUM; i++) {
            ime_buffer->lookup_deco[i] =  (IMCharDecoration *)calloc(MAX_CANDIDATE_CHAR_NUM, sizeof(IMCharDecoration));
            if (ime_buffer->lookup_deco[i] == NULL)
                goto Error;
        }

        return(ime_buffer);

Error:
        ime_buffer_free(s, ime_buffer);
        return(NULL);
}

void ime_buffer_free(iml_session_t *s, IMEBuffer ime_buffer)
{
        int i;

        if (ime_buffer->preedit_deco)
            free(ime_buffer->preedit_deco);
        if (ime_buffer->lookup_deco_len)
            free(ime_buffer->lookup_deco_len);
        if (ime_buffer->lookup_deco) {
            for (i =0; i<MAX_CANDIDATES_NUM; i++)
                if (ime_buffer->lookup_deco[i])
                    free(ime_buffer->lookup_deco[i]);
            free(ime_buffer->lookup_deco);
        }

        if (ime_buffer->inputkey_buf) free(ime_buffer->inputkey_buf);
        if (ime_buffer->preedit_buf)  free(ime_buffer->preedit_buf);
        if (ime_buffer->status_buf)   free(ime_buffer->status_buf);
        if (ime_buffer->commit_buf)   free(ime_buffer->commit_buf);

        for (i =0; i<MAX_CANDIDATES_NUM; i++) {
            if (ime_buffer->lookup_buf[i])
                    free(ime_buffer->lookup_buf[i]);
            if (ime_buffer->candidates_buf[i])
                    free(ime_buffer->candidates_buf[i]);
            if (ime_buffer->additions_buf[i])
                    free(ime_buffer->additions_buf[i]);
        }

        if (ime_buffer->lookup_buf)
                free(ime_buffer->lookup_buf);
        if (ime_buffer->candidates_buf)
                free(ime_buffer->candidates_buf);
        if (ime_buffer->additions_buf)
                free(ime_buffer->additions_buf);

        le_free_ime_session_data(s, ime_buffer);
        free(ime_buffer);
}

/* ============================================================== */
/*           Change Language Engine Status Information            */
/* ============================================================== */
/* clear input method buffer */
void le_clear_ime_buffer(iml_session_t *s, IMEBuffer ime_buffer)
{
        int i ;

        le_clear_ime_session_data(s, ime_buffer);

        ime_buffer->lookup_num = 0;

        for (i =0; i<MAX_CANDIDATES_NUM; i++) {
            ime_buffer->lookup_deco_len[i] = 0;
        }

        if (IIIM_DRAW_LOOKUP_STYLE) {
            iml_lookup_enddraw(s);
        } else {
            le_hide_compositeaux_notify(s);
        }

        ime_buffer->inputkey_len = 0;
        ime_buffer->preedit_len = 0;
        ime_buffer->preedit_buf[0] = 0;
        ime_buffer->preedit_deco_len = 0;
        if (IIIM_DRAW_PREEDIT_STYLE) {
            iml_preedit_enddraw(s);
        } else {
            le_hide_compositeaux_notify(s);
        }
}

/* output input method buffer to system */
void le_output_ime_buffer(iml_session_t *s, IMEBuffer ime_buffer)
{

        int encode = ime_buffer->encode;
        int status = ime_buffer->return_status;
        int preedit_len = ime_buffer->preedit_len;
        int commit_len = ime_buffer->commit_len;
        int status_len = ime_buffer->status_len;
        int lookup_num = ime_buffer->lookup_num;
        int lookup_label_type = ime_buffer->lookup_label_type;
        int preedit_caretpos = ime_buffer->preedit_caretpos;
        unsigned char *preedit_buf = ime_buffer->preedit_buf;
        unsigned char *commit_buf  = ime_buffer->commit_buf;
        unsigned char *status_buf  = ime_buffer->status_buf;
        unsigned char **lookup_buf = ime_buffer->lookup_buf;

        if (status & IME_STATUS_AREA)
            encode_draw_status(s, encode, status_buf);

        if (status & IME_PREEDIT_AREA) {
            DEBUG_printf("preedit_len:%d\n", preedit_len);
            preedit_buf[preedit_len] = 0;
            if (IIIM_DRAW_PREEDIT_STYLE) {
                if (preedit_len <= 0) {
                    iml_preedit_enddraw(s);
                } else {
                    encode_draw_preedit(s, encode, preedit_buf, preedit_caretpos);
                }
            } else {
                le_draw_compositeaux_preedit_notify(s, encode, preedit_buf, preedit_caretpos, ime_buffer->preedit_deco_len, ime_buffer->preedit_deco);
            }
        }

        if (status & IME_LOOKUP_AREA) {
            DEBUG_printf("lookup_num:%d\n", lookup_num);
            if (IIIM_DRAW_LOOKUP_STYLE) {
                if (lookup_num <= 0) {
                    iml_lookup_enddraw(s);
                } else {
                    encode_draw_candidates(s, encode, lookup_buf, lookup_num, lookup_label_type);
                }
            } else {
                le_draw_compositeaux_lookup_notify(s, encode, lookup_num, lookup_label_type, (char**)lookup_buf, ime_buffer->lookup_deco_len, ime_buffer->lookup_deco);
            }
        }

        if ((status & IME_COMMIT) && (commit_len>0)) {
            commit_buf[commit_len] = 0;
            encode_commit(s, encode, commit_buf);
        }
}

void le_status_draw(iml_session_t *s)
{
        unsigned char status_str[256];
        MyDataPerSession *session_data = (MyDataPerSession *) s->specific_data;
	MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);
        int engine_id = session_data->paletteaux_status.engine_id;
        int on = session_data->paletteaux_status.on;

        if (!on || engine_id >= desktop_data->num_engine)
                encode_draw_status(s, ENCODE_UTF8, English_Status_UTF);
        else
        {
/*
                sprintf((char *)status_str, "[ %s ]", desktop_data->engine_info[engine_id]->core.baseinfo.cname);
*/
                sprintf((char *)status_str, "%s", desktop_data->engine_info[engine_id]->core.baseinfo.cname);
                encode_draw_status(s, desktop_data->engine_info[engine_id]->core.baseinfo.encode_id, status_str);
        }
}

void le_switch_engine(iml_session_t *s, int engine_id)
{
    int ret, original_engine;
    MyDataPerSession *session_data = (MyDataPerSession *) s->specific_data;
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);

    if (engine_id >= desktop_data->num_engine)
            engine_id = 0xff;

    if (engine_id > 0 && engine_id < desktop_data->num_engine &&
            desktop_data->engine_info[engine_id]->core.baseinfo.status == ENGINE_NOT_INSTALLED)
        engine_id = 0xff;

    if (engine_id != 0xff) {
        ret = desktop_data->engine_info[engine_id]->so_methods->IME_Open(
                                &desktop_data->engine_info[engine_id]->core,
                                session_data->ime_buffer);

        DEBUG_printf("start aux window and IME_Open return :%d\n", ret);
        if (ret == -1)
            engine_id = 0xff;
    }

    le_free_ime_session_data(s, session_data->ime_buffer);
    le_alloc_ime_session_data(s, engine_id, session_data->ime_buffer);

    session_data->paletteaux_status.engine_id = engine_id;
    le_status_draw(s);
    le_update_keymapinfo_notify(s, engine_id);
}

void le_free_ime_session_data(iml_session_t *s, IMEBuffer ime_buffer)
{
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);
    int original_engine = ime_buffer->ime_session_data_engine;

    if (original_engine >= 0 && original_engine < desktop_data->num_engine &&
                desktop_data->engine_info[original_engine]->core.baseinfo.status == ENGINE_INITIATED &&
                desktop_data->engine_info[original_engine]->so_methods->IME_FreeSessionData != NULL &&
                ime_buffer->ime_session_data != NULL) {

        desktop_data->engine_info[original_engine]->so_methods->IME_FreeSessionData(ime_buffer->ime_session_data);
        ime_buffer->ime_session_data = NULL;
    }
}

void le_alloc_ime_session_data(iml_session_t *s, int engine_id, IMEBuffer ime_buffer)
{
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);
    if (engine_id >= 0 && engine_id < desktop_data->num_engine &&
                desktop_data->engine_info[engine_id]->core.baseinfo.status == ENGINE_INITIATED &&
                desktop_data->engine_info[engine_id]->so_methods->IME_AllocSessionData != NULL) {

        ime_buffer->ime_session_data = desktop_data->engine_info[engine_id]->so_methods->IME_AllocSessionData(&desktop_data->engine_info[engine_id]->core);
        ime_buffer->ime_session_data_engine = engine_id;
    }
}

void le_clear_ime_session_data(iml_session_t *s, IMEBuffer ime_buffer)
{
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);
    int original_engine = ime_buffer->ime_session_data_engine;

    if (original_engine >= 0 && original_engine < desktop_data->num_engine &&
                desktop_data->engine_info[original_engine]->core.baseinfo.status == ENGINE_INITIATED &&
                desktop_data->engine_info[original_engine]->so_methods->IME_ClearSessionData != NULL &&
                ime_buffer->ime_session_data != NULL) {

        desktop_data->engine_info[original_engine]->so_methods->IME_ClearSessionData(ime_buffer->ime_session_data);
    }
}
