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

*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif

#include "SunIM.h"
#include "unit_input.h"

/* general functions */
IMFeedbackList *create_feedback(iml_session_t *s, int size)
{
  int i;
  IMFeedbackList *feedback, *fbl;
    
  if (s) {
    feedback = (IMFeedbackList *) s->If->m->iml_new(s, sizeof(IMFeedbackList) * size);
    memset(feedback, 0, sizeof(IMFeedbackList) * size);
  } else {
    feedback = (IMFeedbackList *) calloc(1, sizeof(IMFeedbackList) * size);
  }
  for (i = 0; i < size; i++) {
    fbl = &feedback[i];
    fbl->count_feedbacks = 1;
    if (s) {
      fbl->feedbacks = (IMFeedback *) s->If->m->iml_new(s, sizeof(IMFeedback));
      memset(fbl->feedbacks, 0, sizeof(IMFeedback));
    } else {
      fbl->feedbacks = (IMFeedback *) calloc(1, sizeof(IMFeedback));
    }
  }
  return feedback;
}

void free_feedback(iml_session_t *s, IMFeedbackList *feedback, int size)
{
  int i;
  IMFeedbackList *fbl;

  if ((s!= NULL) || (feedback == NULL)) return;

  for (i = 0; i < size; i++) {
    fbl = &feedback[i];
    if (fbl->feedbacks != NULL)
      free(fbl->feedbacks);
  }
  free(feedback);
}

int get_feedback(IMFeedbackList * fbl)
{
  IMFeedback *fb = &fbl->feedbacks[0];
  return IM_FEEDBACK_VALUE(fb);
}

void set_feedback(IMFeedbackList * fbl, int value)
{
  IMFeedback *fb = &fbl->feedbacks[0];
  IM_FEEDBACK_TYPE(fb)=IM_DECORATION_FEEDBACK;
  IM_FEEDBACK_VALUE(fb)=value;
}

void set_feedback_private(IMFeedbackList * fbl, int normalfeedback, int fg, int bg, int underline)
{
  int count = 0;
  IMFeedback *fb;
	
  fb = &fbl->feedbacks[count];
  IM_FEEDBACK_TYPE(fb) = IM_DECORATION_FEEDBACK;
  IM_FEEDBACK_VALUE(fb) = normalfeedback;
  count++;

  if (fg != -1) {
    fb = &fbl->feedbacks[count];
    IM_FEEDBACK_TYPE(fb) = IM_FOREGROUND_RGB_FEEDBACK;
    IM_FEEDBACK_VALUE(fb) = fg;
    count++;
  }
  if (bg != -1) {
    fb = &fbl->feedbacks[count];
    IM_FEEDBACK_TYPE(fb) = IM_BACKGROUND_RGB_FEEDBACK;
    IM_FEEDBACK_VALUE(fb) = bg;
    count++;
  }
  if (underline != -1) {
    fb = &fbl->feedbacks[count];
    IM_FEEDBACK_TYPE(fb) = IM_UNDERLINE_RGB_FEEDBACK;
    IM_FEEDBACK_VALUE(fb) = underline;
    count++;
  }
  IM_FEEDBACK_COUNT(fbl) = count;
}

/* UTF16 string handle functions */
int UTFCHARCat(UTFCHAR *dest, UTFCHAR *str1, UTFCHAR *str2)
{
  int i;
  for (i = 0; *str1; i++) {
    *dest++ = *str1++;
  }
  for (i = 0; *str2; i++) {
    *dest++ = *str2++;
  }
  *dest = 0;
  return i;
}

int UTFCHARCpy(UTFCHAR * dest, UTFCHAR * original)
{
  int i;
  for (i = 0; *original; i++) {
    *dest++ = *original++;
  }
  *dest = 0;
  return i;
}

int UTFCHARLen(UTFCHAR * p)
{
  int i;
  for (i = 0; *p; i++)
    p++;
  return i;
}

IMText *make_imtext(iml_session_t * s, UTFCHAR * p)
{
  int i, len;
  IMText *text = (IMText *) s->If->m->iml_new(s, sizeof(IMText));

  memset(text, 0, sizeof(IMText));

  len = UTFCHARLen(p);

  text->encoding = UTF16_CODESET;

  text->text.utf_chars = (UTFCHAR *) s->If->m->iml_new(s, sizeof(UTFCHAR) * (len + 1));
  UTFCHARCpy(text->text.utf_chars, p);
  /*

  Notes:  Can not use memcpy to copy UTFCHAR data. 

  log_f("before memcpy: len:%d\n", len);
  memcpy(text->text.utf_chars, p, sizeof(UTFCHAR) * len);
  log_f("After memcpy: len:%d\n", len);
  */
  text->char_length = len;

  text->feedback = create_feedback(s, len);

  for (i = 0; i < len; i++) {
    set_feedback_private(&text->feedback[i], IMReverse, -1, -1, -1);
  }

  return text;
}

/* Send a Unicode string to the system */
void iml_commit(iml_session_t * s, UTFCHAR *commit_buf)
{
  int len;
  iml_inst *lp;
  IMText *im_text;
    
  len = UTFCHARLen(commit_buf);
  if (len == 0) return;

  im_text = make_imtext(s, commit_buf);
  lp = (iml_inst *)s->If->m->iml_make_commit_inst(s, im_text);
  s->If->m->iml_execute(s, &lp);
}

/* Send a KeyPress Event to system */
void iml_sendback_key(iml_session_t *s, IMKeyEventStruct *key)
{
  iml_inst *lp;

  lp = (iml_inst *)s->If->m->iml_make_keypress_inst(s, key);
  s->If->m->iml_execute(s, &lp);
}

/* Begin catch the system Key Event */
void iml_conversion_on(iml_session_t * s)
{
  iml_inst *lp;
    
  lp = (iml_inst *)s->If->m->iml_make_start_conversion_inst(s);
  lp = s->If->m->iml_execute(s, &lp);
}

/* Do not catch the system Key Event */
void iml_conversion_off(iml_session_t * s)
{
  iml_inst *lp;
  iml_inst *rrv = NULL;
    
  lp = (iml_inst *)s->If->m->iml_make_preedit_done_inst(s);
  s->If->m->iml_link_inst_tail(&rrv, lp);
  lp = (iml_inst *)s->If->m->iml_make_end_conversion_inst(s);
  s->If->m->iml_link_inst_tail(&rrv, lp);
  s->If->m->iml_execute(s, &rrv);
}

/* Start Status Area Information */
void iml_status_start(iml_session_t * s)
{
  iml_inst *lp;
    
  lp = (iml_inst *)s->If->m->iml_make_status_start_inst(s);
  s->If->m->iml_execute (s, &lp);
}

/* Destroy Status Area Information */
void iml_status_enddraw(iml_session_t * s)
{
  iml_inst *lp;
    
  lp = (iml_inst *)s->If->m->iml_make_status_done_inst(s);
  s->If->m->iml_execute(s, &lp);
}

/* Draw Status line information */
void iml_status_draw(iml_session_t * s, UTFCHAR *status_str)
{
  iml_inst *lp;
  iml_inst *rrv = NULL;
  IMText  *im_text;

  iml_status_start(s);

  im_text = make_imtext(s, status_str);
  lp = (iml_inst *)s->If->m->iml_make_status_draw_inst(s, im_text);
  s->If->m->iml_link_inst_tail(&rrv, lp);
  s->If->m->iml_execute(s, &rrv);
}

void iml_preedit_start(iml_session_t * s)
{
  iml_inst *lp;
  iml_inst *rrv = NULL;
    
  lp = (iml_inst *)s->If->m->iml_make_preedit_start_inst(s);
  s->If->m->iml_link_inst_tail(&rrv, lp);
}

/* Destroy Pre_edit Area Information */
void iml_preedit_enddraw(iml_session_t * s)
{
  iml_inst *lp;
    
  lp = (iml_inst *)s->If->m->iml_make_preedit_erase_inst(s);
  s->If->m->iml_execute(s, &lp);
}

/* Draw Pre_edit Area Information */
void iml_preedit_draw(iml_session_t * s, UTFCHAR *preedit_buf, int caret_pos)
{
  int i, len;
  iml_inst *lp;
  iml_inst *rrv = NULL;
  IMText *im_text;
    
  iml_preedit_start(s);

  len = UTFCHARLen(preedit_buf);
  log_f("len:%d, caret_pos:%d\n", len, caret_pos);

  if(len == 0) {
    lp = (iml_inst *)s->If->m->iml_make_preedit_erase_inst(s);
    s->If->m->iml_link_inst_tail(&rrv, lp);
    s->If->m->iml_execute(s, &rrv);
    return;
  }

  im_text = make_imtext(s, preedit_buf);

  if (caret_pos>len) caret_pos = len;
  for(i = 0; i < caret_pos; i ++) {
    set_feedback(&(im_text->feedback[i]), IMReverse);
  }
  for(i = caret_pos; i < len; i ++) {
    set_feedback(&(im_text->feedback[i]), IMUnderline);
  }
  /*
    set_feedback(&(im_text->feedback[caret_pos - 1]), IMNormal);
  */

  lp = (iml_inst *)s->If->m->iml_make_preedit_draw_inst(s, im_text);
  s->If->m->iml_link_inst_tail(&rrv, lp);
    
  if(caret_pos != -1) {
    lp = (iml_inst *)s->If->m->iml_make_preedit_caret_inst(s, caret_pos); 
    s->If->m->iml_link_inst_tail(&rrv, lp);
  }
  s->If->m->iml_execute(s, &rrv);
}

void iml_lookup_start(iml_session_t * s)
{
  iml_inst *lp;
  IMLookupStartCallbackStruct *start;
    
  start = (IMLookupStartCallbackStruct *) s->If->m->iml_new(s, sizeof(IMLookupStartCallbackStruct));
  memset(start, 0, sizeof(IMLookupStartCallbackStruct));

  start->IMPreference = (LayoutInfo *) s->If->m->iml_new(s, sizeof(LayoutInfo));
  memset(start->IMPreference, 0, sizeof(LayoutInfo));

  start->IMPreference->choice_per_window = 7;
  start->IMPreference->ncolumns = 1;
  start->IMPreference->nrows = 10;
  start->IMPreference->drawUpDirection = DrawUpHorizontally;
  start->IMPreference->whoOwnsLabel = IMOwnsLabel;

  start->CBPreference = NULL;
  start->whoIsMaster = IMIsMaster;

  lp = (iml_inst *)s->If->m->iml_make_lookup_start_inst(s, start);
  s->If->m->iml_execute(s, &lp);
}

/* Destroy Candidate Selection Area */
void iml_lookup_enddraw(iml_session_t *s)
{
  iml_inst *lp;

  lp = (iml_inst*)s->If->m->iml_make_lookup_done_inst(s);
  s->If->m->iml_execute(s, &lp);
}

/* Draw Candidate Selection Area */
void iml_lookup_draw(iml_session_t * s, UTFCHAR ** luc_tmp, int luc_num, int label_type)
{
  int i, char_len;
  char begin_char;
  int max_len = 0;
  iml_inst *lp;
  IMText **candidates, **labels;
  IMLookupDrawCallbackStruct *draw;
    
  if (luc_num <= 0) return;

  iml_lookup_start(s);

  if (luc_num > MAX_CANDIDATES_NUM) 
    luc_num = MAX_CANDIDATES_NUM;

  /* Set candidate data */
  candidates = (IMText **) s->If->m->iml_new(s, luc_num * sizeof(IMText *));
  memset(candidates, 0, luc_num * sizeof(IMText *));
  for (i = 0; i < luc_num; i++) {
    candidates[i] = (IMText *) s->If->m->iml_new(s, sizeof(IMText));
    memset(candidates[i], 0, sizeof(IMText));
    candidates[i]->encoding = UTF16_CODESET;
    candidates[i]->count_annotations = 0;
    candidates[i]->annotations = NULL;
    char_len = UTFCHARLen(luc_tmp[i]);
    candidates[i]->char_length = char_len;
    candidates[i]->text.utf_chars = (UTFCHAR *)s->If->m->iml_new(s, sizeof(UTFCHAR) * char_len);
    UTFCHARCpy(candidates[i]->text.utf_chars, luc_tmp[i]);
    /*
      memcpy(candidates[i]->text.utf_chars, luc_tmp[i], sizeof(UTFCHAR) * char_len);
    */
    candidates[i]->feedback = create_feedback(s, char_len);
  }

  /* Set Label data */
  switch(label_type) {
  case NUMERIC_LABEL:
    begin_char = '1';
    break;
  case LOWER_LABEL:
    begin_char = 'a';
    break;
  case UPPER_LABEL:
    begin_char = 'A';
    break;
  default:
    begin_char = '1';
  }

  labels = (IMText **) s->If->m->iml_new(s, luc_num  * sizeof(IMText *));
  memset(labels, 0, luc_num * sizeof(IMText *));
  for (i = 0; i < luc_num; i++) {
    labels[i] = (IMText *) s->If->m->iml_new(s, sizeof(IMText));
    memset(labels[i], 0, sizeof(IMText));
    labels[i]->encoding = UTF16_CODESET;
    labels[i]->count_annotations = 0;
    labels[i]->annotations = NULL;
    char_len = 2;
    labels[i]->char_length = char_len;
    labels[i]->text.utf_chars = (UTFCHAR *) s->If->m->iml_new(s, sizeof(UTFCHAR) * char_len);
    labels[i]->text.utf_chars[0] = (UTFCHAR) (begin_char + i);
    labels[i]->text.utf_chars[1] = (UTFCHAR) ('.');
    labels[i]->feedback = create_feedback(s, char_len);
  }

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

  draw->title = (IMText *) s->If->m->iml_new(s, sizeof(IMText));
  memset(draw->title, 0, sizeof(IMText));
 
  draw->n_choices = luc_num ;
  draw->index_of_first_candidate = 0;
  draw->index_of_last_candidate = luc_num - 1;
  draw->index_of_current_candidate = -1;
    
  /* Set choices data */
  draw->choices = (IMChoiceObject *) s->If->m->iml_new(s, luc_num * sizeof(IMChoiceObject));
  memset(draw->choices, 0, luc_num * sizeof(IMChoiceObject));
    
  for (i = 0; i < luc_num; i++) {
    IMText *vt;		/* for value */
    IMText *lt;		/* for label */

    vt = draw->choices[i].value = candidates[i];
    lt = draw->choices[i].label = labels[i];
        
    if (max_len < vt->char_length)
      max_len = vt->char_length;
  }

  draw->max_len = max_len;
    
  lp = (iml_inst *)s->If->m->iml_make_lookup_draw_inst(s, draw);
  s->If->m->iml_execute(s, &lp);
}

/* Start An Auxiliary Window */
void iml_aux_start(iml_session_t * s, char *classname)
{
  iml_inst *lp;
  IMAuxStartCallbackStruct *aux;

  aux = (IMAuxStartCallbackStruct *) s->If->m->iml_new(s, sizeof(IMAuxStartCallbackStruct));
  memset(aux, 0, sizeof(IMAuxStartCallbackStruct));
  aux->aux_name = classname;

  lp = (iml_inst *)s->If->m->iml_make_aux_start_inst(s, aux);
  s->If->m->iml_execute(s, &lp);

  log_f("iml_aux_start ----- auxwin name :%s \n", classname);
}

/* Close the Auxiliary Window */
void iml_aux_done(iml_session_t * s, char *classname)
{
  iml_inst *lp;
  IMAuxDoneCallbackStruct *aux;

  aux = (IMAuxDoneCallbackStruct *)s->If->m->iml_new(s, sizeof(IMAuxDoneCallbackStruct));
  memset(aux, 0, sizeof(IMAuxDoneCallbackStruct));
  aux->aux_name = classname;

  lp = (iml_inst *)s->If->m->iml_make_aux_done_inst(s, aux);
  s->If->m->iml_execute(s, &lp);

  log_f("iml_aux_done -------------------------------- end \n");
}

/* Draw the Auxiliary Window Items */
void iml_aux_draw(iml_session_t *s, char *classname, 
		  int count_integers,  int *integers,
		  int count_strings,   int *len_strings,
                  unsigned char **strings)
{
  iml_inst *lp;
  IMText *lt;
  IMAuxDrawCallbackStruct *aux;
  int i, len;

  aux = (IMAuxDrawCallbackStruct *) s->If->m->iml_new(s, sizeof(IMAuxDrawCallbackStruct));
  memset(aux, 0, sizeof(IMAuxDrawCallbackStruct));
  aux->aux_name = classname;

  aux->count_integer_values = count_integers;
  if (count_integers) {
    aux->integer_values = (int *) s->If->m->iml_new(s, sizeof(int) * count_integers);
    memset(aux->integer_values, 0, sizeof(int) * count_integers);

    for (i = 0; i < count_integers; i++) {
      aux->integer_values[i] = integers[i];
    }
  }

  aux->count_string_values = count_strings;
  if (count_strings) {
    aux->string_values = (IMText *) s->If->m->iml_new(s, sizeof(IMText) * count_strings);
    memset(aux->string_values, 0, sizeof(IMText) * count_strings);

    aux->string_values->encoding = UTF16_CODESET;
    for (i = 0, lt = aux->string_values; i < count_strings; i++, lt++) {
      len = len_strings[i];
      lt->text.utf_chars = (UTFCHAR *) s->If->m->iml_new(s, len+1);
      lt->char_length = len;
      memcpy(lt->text.utf_chars, strings[i], len);
    }
  }

  lp = (iml_inst *)s->If->m->iml_make_aux_draw_inst(s, aux);
  s->If->m->iml_execute(s, &lp);

  log_f("iml_aux_draw -------------------------------- end \n");
}


