/*
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 <X11/keysym.h>
#include "xiiimp.h"
#include "iiimpIM.h"
#include "guiIM.h"
#include "composeIM.h"
#include "codeinput.h"
#include "lookup.h"

#define MAX_LABEL_SIZE 0x5e
#define LABEL_OFF 0x21

static XIMFeedback no_feedback[] = {
  0, 0
};

static Bool
DefillLookup(LocalLookupExt *luext, int start_index, int n_choices) {
  XIMText *p;
  XIMChoiceObject2 *LUTable = (XIMChoiceObject2*)luext->LUTable;
  int i;
  if (!LUTable) return True;

  p = LUTable->label;
  if (!p) return True;
  for (i = 0; p < &LUTable->label[n_choices]; p++, i++) {
    if (p->string.multi_byte) {
      Xfree(p->string.multi_byte);
      p->string.multi_byte = NULL;
    } else
      break;
  }
  if (LUTable->label) {
    Xfree(LUTable->label);
    LUTable->label = 0;
  }
  p = LUTable->value;
  if (!p) return True;
  for (i = 0; p < &LUTable->value[n_choices]; p++, i++) {
    if (p->string.multi_byte) {
      Xfree(p->string.multi_byte);
      p->string.multi_byte = NULL;
    } else
      break;
  }
  if (LUTable->value) {
    Xfree(LUTable->value);
    LUTable->value = 0;
  }
  return True;
}

static Bool
FillLookup(XicCommon ic, LocalLookupExt *luext,
	   int start_index, int n_choices) {
  XIMChoiceObject2 *LUTable;
  XIMText *p;
  int i;
  wchar_t wstr[2];
  XimCommon im = (XimCommon)ic->core.im;
  size_t mb_len;

  if (!luext->LUTable) {
    LUTable = Xmalloc(sizeof(XIMChoiceObject2));
    memset(LUTable, 0, sizeof(XIMChoiceObject2));
  } else {
    LUTable = (XIMChoiceObject2*)luext->LUTable;
  }
  if (!LUTable) return False;

  LUTable->label_decoration = BRACKET_DECORATION;

  LUTable->label = Xmalloc(sizeof(XIMText) * n_choices);
  LUTable->value = Xmalloc(sizeof(XIMText) * n_choices);

  if (!LUTable->label || !LUTable->value) {
    /* something is wrong */
    return False;
  }
  memset(LUTable->label, 0, sizeof(XIMText) * n_choices);
  memset(LUTable->value, 0, sizeof(XIMText) * n_choices);

  p = LUTable->label;
  for (i = 0; p < &LUTable->label[n_choices]; p++, i++) {
    p->length = 1;
    p->feedback = no_feedback;
    p->encoding_is_wchar = False;

    wstr[0] = (wchar_t)(i + LABEL_OFF);
    wstr[1] = (wchar_t)0;

    mb_len = XLC_PUBLIC(im->core.lcd, mb_cur_max);
    p->string.multi_byte = Xmalloc(mb_len + 1);
    if (p->string.multi_byte) {
      if ((mb_len = IIimpWcstoMbs(im, wstr, 1,
				  p->string.multi_byte, mb_len, NULL)) < 0) {
	return False;
      }
      p->string.multi_byte[mb_len] = 0;
    } else {
      goto error;
    }
  }
  p = LUTable->value;
  for (i = 0; p < &LUTable->value[n_choices]; p++, i++) {
    p->length = 1;
    p->feedback = no_feedback;
    p->encoding_is_wchar = False;

    wstr[0] = (wchar_t)(start_index + i);
    wstr[1] = (wchar_t)0;

    mb_len = XLC_PUBLIC(im->core.lcd, mb_cur_max);
    p->string.multi_byte = Xmalloc(mb_len + 1);
    if (p->string.multi_byte) {
      if ((mb_len = IIimpWcstoMbs(im, wstr, 1,
				  p->string.multi_byte, mb_len, NULL)) < 0) {
	return False;
      }
      p->string.multi_byte[mb_len] = 0;
    } else {
      goto error;
    }
  }
  luext->LUTable = (XPointer)LUTable;
  return True;
 error:
  /* memory clean up */
  DefillLookup(luext, start_index, n_choices);
  return False;
}

static Bool
setup_local_lookup_ext(XicCommon ic) {
  LocalLookupExt *hook = (LocalLookupExt*)(ic->local_icpart->lookup_ext);

  if (hook) return False;

  hook = (LocalLookupExt *)Xmalloc(sizeof(LocalLookupExt));
  if (!hook) return False;

  memset(hook, 0, sizeof(LocalLookupExt));
  ic->local_icpart->lookup_ext = hook;
  return True;
}

#define XIMIsMaster 1

/* public */
void
Ximp_Local_Lookup_Create(XicCommon ic) {
  setup_local_lookup_ext(ic);
  return;
}

void
Ximp_Local_Lookup_Start(XicCommon ic) {
  LocalLookupExt *hook = (LocalLookupExt*)(ic->local_icpart->lookup_ext);
  LocalIMState *state = (LocalIMState *)(ic->local_icpart->imstate);
  XIMLookupStartCallbackStruct2 cbdata;

  if (!hook) {
    if (!setup_local_lookup_ext(ic))
      return;
    hook = (LocalLookupExt*)(ic->local_icpart->lookup_ext);
    if (!hook) return;
  }

  memset(&cbdata, 0, sizeof(XIMLookupStartCallbackStruct2));
  cbdata.which_is_master = XIMIsMaster;
  if (state->attr && state->type == LookupState) {
    cbdata.nrows = state->attr->_attr_u.LUstruct.num_of_rows;
    cbdata.ncolumns = state->attr->_attr_u.LUstruct.num_of_cols;
    cbdata.choice_per_window = state->attr->_attr_u.LUstruct.num_of_cands;
  } else {
    cbdata.nrows = 6;
    cbdata.ncolumns = 16;
    cbdata.choice_per_window = 80;
  }
  hook->choice_per_window = cbdata.choice_per_window; /* for drawing */
  hook->nrows = cbdata.nrows; /* for drawing */
  hook->ncolumns = cbdata.ncolumns; /* for drawing */
  cbdata.who_owns_label = XIMOwnsLabel;

  XIC_GUI(ic, change_lookup)((XIC)ic, LOOKUP_START,
			     (XPointer)&cbdata);
  return;
}

void
Ximp_Local_Lookup_Draw(XicCommon ic) {
  LocalLookupExt *hook = (LocalLookupExt*)(ic->local_icpart->lookup_ext);
  XIMLookupDrawCallbackStruct2 cbdata;
  XIMText title_text;
  char stitle[80];
  size_t tlen;
  int startindex, endindex;

  if (!hook) {
    Ximp_Local_Lookup_Start(ic);
    hook = (LocalLookupExt *)(ic->local_icpart->lookup_ext);
    if (!hook) return;
  }
  DefillLookup(hook, hook->startindex, hook->n_choices);

  startindex = hook->startindex;

  endindex = startindex + ((hook->end_range == -1) ? 
			   hook->choice_per_window : hook->end_range);

  if (endindex < startindex) return;

  if (0xffff0000 & endindex) {
    endindex = 0x0000ffff;
  }

  memset(&cbdata, 0, sizeof(XIMLookupDrawCallbackStruct2));
  cbdata.n_choices =
    ((endindex - startindex) + 1 > hook->choice_per_window) ?
    hook->choice_per_window : (endindex - startindex) + 1;
  hook->n_choices = cbdata.n_choices;
  cbdata.first_index = 0;
  cbdata.current_index = hook->currentindex;
  cbdata.last_index = cbdata.n_choices - 1;

  if (!FillLookup(ic, hook, startindex, cbdata.n_choices)) return;

  cbdata.choices = (XIMChoiceObject2*)hook->LUTable;

  if (hook->crange != -1) {
    sprintf(stitle, "%s:  0x%04x to 0x%04x",
	    hook->range[hook->crange].RangeName+3, startindex, 
	    (startindex + (cbdata.n_choices - 1)));
  } else {
    sprintf(stitle, "UNICODE Lookup:  0x%04x to 0x%04x",
	    startindex, (startindex +(cbdata.n_choices - 1)));
  }
  tlen = strlen(stitle);

  cbdata.title = &title_text;
  memset((char *)cbdata.title, 0, sizeof(XIMText));
  cbdata.title->length = tlen;
  cbdata.title->feedback = (XIMFeedback*)Xmalloc(sizeof(XIMFeedback) * tlen);
  if (cbdata.title->feedback) {
    XIMFeedback *p;
    for (p = cbdata.title->feedback; p < &cbdata.title->feedback[tlen]; p++) {
      *p = 0;
    }
  } else {
    return;
  }

  cbdata.title->encoding_is_wchar = False;
  cbdata.title->string.multi_byte = stitle;

  XIC_GUI(ic, change_lookup)((XIC)ic, LOOKUP_DRAW, (XPointer)&cbdata);
  hook->mapped = LOOKUP_MAPPED;

  if (cbdata.title->feedback) {
    Xfree(cbdata.title->feedback);
  }
  return;
}

void
Ximp_Local_Lookup_Done(XicCommon ic) {
  LocalLookupExt *hook = (LocalLookupExt*)(ic->local_icpart->lookup_ext);
  if (!hook) return;
  DefillLookup(hook, hook->startindex, hook->n_choices);
  XIC_GUI(ic, change_lookup)((XIC)ic, LOOKUP_DONE, NULL);
  hook->mapped = LOOKUP_UNMAPPED;
}

static void
lookup_commit(XicCommon ic, char *mb, XEvent *ev) {
  Display *display = ic->core.im->core.display;
  size_t len = strlen(mb);
  XimCommon im = (XimCommon)ic->core.im;
  Bool useUnicode;

  if (!display) {
    return;
  }

  useUnicode = (XIM_USE_UNICODE(im) &&
		NULL != ic->commit_string_callback.callback);
  /* private XIC extension */
  if (useUnicode) {
    XIMCallback *cb = &ic->commit_string_callback;
    XIMUnicodeText cbtext;
    size_t len_utf16 = 256;	/* enough */
    char buffer[256];
    memset(&cbtext, 0, sizeof(XIMUnicodeText));
    cbtext.string.multi_byte = buffer;
    cbtext.length = len_utf16;
    IMConvertFromUTF8ToUTF16(mb, len,
			     (char**)&cbtext.string.utf16_char,
			     &len_utf16);
    cbtext.length -= len_utf16;
    cbtext.length /= sizeof(unsigned short);
    (*cb->callback)(ic, cb->client_data, (XPointer)&cbtext);
  } else {
    if (ic->local_icpart->composed != (DefTree *)NULL ) {
      if (ic->local_icpart->composed->mb != NULL )
	Xfree(ic->local_icpart->composed->mb);
      ic->local_icpart->composed->mb = (char *)NULL;
      Xfree(ic->local_icpart->composed);
      ic->local_icpart->composed = (DefTree *)NULL;
    }
    if ((ic->local_icpart->composed =
	 (DefTree *)Xmalloc(sizeof(DefTree))) == NULL)
      return;
    memset(ic->local_icpart->composed, 0, sizeof(DefTree));

    if ((ic->local_icpart->composed->mb = (char *)
	 Xmalloc((len + 1) * sizeof(char))) == (char *)NULL) {
      return;
    }
    strncpy(ic->local_icpart->composed->mb, mb, len);
    ic->local_icpart->composed->mb[len] = 0;
    ic->local_icpart->composed->keysym_return = NoSymbol;
    /* return back to client KeyPressEvent keycode == 0 */
    ev->type = KeyPress;
    ev->xkey.keycode = XIM_COMPOSE_KEYCODE;
    ev->xkey.window = ic->core.focus_window;
    XPutBackEvent(display, ev);
  }

  Ximp_Local_Preedit_Done(ic);

  return;
}

Bool
Ximp_Local_Lookup_Button_Filter(XicCommon ic,
				int index, XEvent *ev) {
  LocalLookupExt *hook = (LocalLookupExt*)(ic->local_icpart->lookup_ext);
  XIMChoiceObject2 *LUTable;
  XIMText *p;

  if (!hook) return False;
  LUTable = (XIMChoiceObject2*)hook->LUTable;
  p = &LUTable->value[index];
  lookup_commit(ic, p->string.multi_byte, ev);
  return True;
}

Bool
Ximp_Local_Lookup_Input_Filter(XicCommon ic, char *input, XEvent *ev) {
  LocalLookupExt *hook = (LocalLookupExt *)(ic->local_icpart->lookup_ext);
  int i;
  XIMChoiceObject2 *LUTable;
  XIMText *p;
  LUTable = (XIMChoiceObject2*)hook->LUTable;
  if (!LUTable) return False;
  p = LUTable->label;
  if (!p) return False;
  /* if given input matches to a label, commit it */
  for (i = 0; p < &LUTable->label[hook->n_choices]; p++, i++) {
    if (!strcmp(p->string.multi_byte, input)) {
      Ximp_Local_Lookup_Button_Filter(ic, i, ev);
      return True;		/* filtered */
    }
  }
  return False;			/* not filtered */
}

Bool
Ximp_Local_Lookup_Action_Filter(XicCommon ic, ActionType action,
				XEvent *ev) {
  LocalLookupExt *hook = (LocalLookupExt*)(ic->local_icpart->lookup_ext);
  int startindex, endindex;

  if (!hook) return False;
  switch (action) {
  case TopPage:
    /* top page */
    startindex = hook->begin_range;
    if (hook->startindex == startindex) {
      /* already at top */
      return False;
    }
    hook->startindex = startindex;
    Ximp_Local_Lookup_Draw(ic);
    break;
  case LastPage:
    /* last page */
    endindex = hook->end_range == -1 ? 0xffff : hook->end_range;
    if (hook->startindex + hook->choice_per_window - 1 == endindex) {
      /* already at last */
      return False;
    }
    startindex = endindex - hook->choice_per_window + 1;
    hook->startindex = startindex;
    Ximp_Local_Lookup_Draw(ic);
    break;
  case NextPage:
    /* next page */
    endindex = hook->end_range == -1 ? 0xffff : hook->end_range;
    if (hook->startindex + hook->choice_per_window - 1 == endindex) {
      /* already at last */
      return False;
    }
    startindex = hook->startindex + hook->choice_per_window;
    if (startindex + hook->choice_per_window > endindex) {
      startindex = endindex - hook->choice_per_window + 1;
    }
    hook->startindex = startindex;
    Ximp_Local_Lookup_Draw(ic);
    break;
  case PrevPage:
    /* prev page */
    startindex = hook->begin_range;
    if (hook->startindex == startindex) {
      /* already at top */
      return False;
    }
    startindex = hook->startindex - hook->choice_per_window;
    if (startindex < hook->begin_range) {
      startindex = hook->begin_range;
    }
    hook->startindex = startindex;
    Ximp_Local_Lookup_Draw(ic);
    break;
  case NextCand:
    /* move focus to next cand */
    if (hook->currentindex == hook->choice_per_window - 1) {
      /* move to top */
      hook->currentindex = 0;
    } else {
      hook->currentindex++;
    }
    Ximp_Local_Lookup_Draw(ic);
    break;
  case PrevCand:
    /* move focus to prev cand */
    if (hook->currentindex == 0) {
      /* move to last */
      hook->currentindex = hook->choice_per_window - 1;
    } else {
      hook->currentindex--;
    }
    Ximp_Local_Lookup_Draw(ic);
    break;
  case UpCand:
    /* move focus to up cand */
    hook->currentindex -= hook->ncolumns;
    if (hook->currentindex < 0) {
      hook->currentindex += hook->choice_per_window;
    }
    Ximp_Local_Lookup_Draw(ic);
    break;
  case DownCand:
    /* move focus to down cand */
    hook->currentindex += hook->ncolumns;
    if (hook->currentindex >= hook->choice_per_window) {
      hook->currentindex -= hook->choice_per_window;
    }
    Ximp_Local_Lookup_Draw(ic);
    break;
  case SelectCand:
    {
      /* select cand at currentindex */
      XIMText *p;
      XIMChoiceObject2 *LUTable;
      LUTable = (XIMChoiceObject2*)hook->LUTable;
      p = &LUTable->value[hook->currentindex];
      lookup_commit(ic, p->string.multi_byte, ev);
    }
    break;
  default:
    break;
  }
  return True;
}

void
Ximp_Local_Lookup_Destroy(XicCommon ic) {
  LocalLookupExt *hook = (LocalLookupExt *)(ic->local_icpart->lookup_ext);

  if (!hook) return;

  if (hook->LUTable) {
    DefillLookup(hook, hook->startindex, hook->n_choices);
    Xfree(hook->LUTable);
  }
  Xfree(hook);
  ic->local_icpart->lookup_ext = 0;
  return;
}
