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

#define PREEDIT_STRLEN 15

static Bool
setup_local_preedit_ext(XicCommon ic)
{
  LocalPreeditExt *hook = (LocalPreeditExt *)(ic->local_icpart->preedit_ext);

  if (hook) return (True);

  hook = (LocalPreeditExt *)Xmalloc(sizeof(LocalPreeditExt));
  if(!hook)
    return (False);
  memset(hook, 0, sizeof(LocalPreeditExt));

  hook->preedit_text = Xmalloc(sizeof(char) * PREEDIT_STRLEN);
  if(!hook->preedit_text) {
    Xfree(hook);
    return (False);
  }
  hook->preedit_alloc_len = PREEDIT_STRLEN;
  hook->preedit_len = 0;
  ic->local_icpart->preedit_ext = (void *)hook;
  return(True);
}

/* public */
void
Ximp_Local_Preedit_Create(XicCommon ic) {
  setup_local_preedit_ext(ic);
  return;
}

void
Ximp_Local_Preedit_Start(XicCommon ic) {
  LocalPreeditExt *hook = (LocalPreeditExt *)(ic->local_icpart->preedit_ext);

  if (!hook) {
    if (!setup_local_preedit_ext(ic))
      return;
    hook = (LocalPreeditExt *)(ic->local_icpart->preedit_ext);
  }
  {
    XIMCallback *cb = &ic->core.preedit_attr.start_callback;
    int max_len = -1;
    if (cb->callback &&
	ic->core.input_style & XIMPreeditCallbacks)
      max_len = (*(int(*)())cb->callback)(ic, cb->client_data, NULL);
    else
      XIC_GUI(ic, change_preedit)((XIC)ic, PREEDIT_START, NULL);
  }
}

Bool
Ximp_Local_Preedit_Draw(XicCommon ic, KeySym keysym)
{
  XIMText cbtext;
  XIMPreeditDrawCallbackStruct call_data;
  XIMDrawTextStruct preedit_draw;
  LocalIMState *state = (LocalIMState *)(ic->local_icpart->imstate);
  LocalPreeditExt *hook = (LocalPreeditExt *)(ic->local_icpart->preedit_ext);
  int max_len;
  InputType mode;
  if (!state || !state->attr) return False;

  if (!hook) {
    Ximp_Local_Preedit_Start(ic);
    hook = (LocalPreeditExt *)(ic->local_icpart->preedit_ext);
    if (!hook) return False;
  }

  mode = state->attr->_attr_u.CIstruct.type_of_input;
  max_len = state->attr->_attr_u.CIstruct.max_input_len;

  memset(&call_data, 0, sizeof(XIMPreeditDrawCallbackStruct));
  memset(&cbtext, 0, sizeof(XIMText));

  if ( (keysym >= XK_0 && keysym <= XK_9) ||	/* 0 - 9 */
       (keysym >= XK_A && keysym <= XK_F) ||	/* A - F */
       (keysym >= XK_a && keysym <= XK_f) ) {	/* a - f */
    char *str = XKeysymToString(keysym);
    if (str &&
	(((mode == HEX) && strspn(str, "0123456789abcdefABCDEF")) ||
	 ((mode == OCTET) && strspn(str, "01234567")))) {
      XIMFeedback *p;
      /* append */
      size_t len = strlen(str);
      cbtext.length = len;
      cbtext.encoding_is_wchar = 0;
      cbtext.string.multi_byte = strdup(str);

      cbtext.feedback = (XIMFeedback*)Xmalloc(sizeof(XIMFeedback) * len);
      if (cbtext.feedback) {
	for (p = cbtext.feedback; p < &cbtext.feedback[len]; p++) {
	  *p = XIMReverse;
	}
      } else {
	return False;
      }
      call_data.caret = hook->preedit_len + len;
      call_data.chg_first = hook->preedit_len;
      call_data.chg_length = 0;
      call_data.text = &cbtext;

      if (hook->preedit_alloc_len < hook->preedit_len + len) {
	hook->preedit_alloc_len += 20;
	hook->preedit_text = Xrealloc(hook->preedit_text,
				      sizeof(char) * hook->preedit_alloc_len);
	if (!hook->preedit_text) return False;
      }
      if (hook->preedit_len) 
	strcat(hook->preedit_text, str);
      else
	strcpy(hook->preedit_text, str);
      hook->preedit_len += len;
    }
  } else if ((keysym == XK_Delete || keysym == XK_BackSpace) ) {
    /* delete 1 char */
    if (hook->preedit_len == 0) return False;

    hook->preedit_len--;
    call_data.caret = hook->preedit_len;
    call_data.chg_first = hook->preedit_len;
    call_data.chg_length = 1;
    call_data.text = 0;
    hook->preedit_text[hook->preedit_len] = '\0';
  }
  preedit_draw.call_data = (XPointer)&call_data;
  preedit_draw.feedback_list = 0;

  {
    XIMCallback *cb;
    cb = &ic->core.preedit_attr.draw_callback;
    if (cb->callback &&
	ic->core.input_style & XIMPreeditCallbacks)
      (*cb->callback)((XIC)ic, cb->client_data, (XPointer)&call_data);
    else
      XIC_GUI(ic, change_preedit)((XIC)ic, PREEDIT_DRAW,
				  (XPointer)&preedit_draw);
  }
  if (cbtext.feedback) Xfree(cbtext.feedback);
  if (cbtext.string.multi_byte) Xfree(cbtext.string.multi_byte);
  return True;
}

void
Ximp_Local_Preedit_Done(XicCommon ic) {
  LocalPreeditExt *hook = (LocalPreeditExt *)(ic->local_icpart->preedit_ext);

  if (!hook) return;

  /* delete preedit chars if any */
  if (hook->preedit_len) {
    XIMPreeditDrawCallbackStruct call_data;
    XIMDrawTextStruct preedit_draw;
    call_data.caret = 0;
    call_data.chg_first = 0;
    call_data.chg_length = hook->preedit_len;
    call_data.text = 0;
    preedit_draw.call_data = (XPointer)&call_data;
    preedit_draw.feedback_list = 0;

    {
      XIMCallback *cb;
      cb = &ic->core.preedit_attr.draw_callback;
      if (cb->callback &&
	  ic->core.input_style & XIMPreeditCallbacks)
	(*cb->callback)((XIC)ic, cb->client_data, (XPointer)&call_data);
      else
	XIC_GUI(ic, change_preedit)((XIC)ic, PREEDIT_DRAW,
				    (XPointer)&preedit_draw);
    }
  }
  {
    XIMCallback *cb;
    cb = &ic->core.preedit_attr.done_callback;
    if (cb->callback &&
	ic->core.input_style & XIMPreeditCallbacks)
      (*cb->callback)((XIC)ic, cb->client_data, NULL);
    else
      XIC_GUI(ic, change_preedit)((XIC)ic, PREEDIT_DONE, NULL);
  }

  Ximp_Local_Lookup_Done(ic);

  if (hook->preedit_text) Xfree(hook->preedit_text);
  hook->preedit_text = 0;
  hook->preedit_len = 0;
  hook->preedit_alloc_len = 0;
  Xfree(hook);
  ic->local_icpart->preedit_ext = 0;
  return;
}

#define LOCAL_MB_BUFSIZE 128

/* convert current input(code sequence) and commit */
void
Ximp_Local_Preedit_Conv(XicCommon ic, XEvent *ev) {
  LocalIMState *state = (LocalIMState *)(ic->local_icpart->imstate);
  LocalPreeditExt *hook = (LocalPreeditExt *)(ic->local_icpart->preedit_ext);
  char tmpstr[80], *ret;
  int twc[2];
  char local_mb_buf[LOCAL_MB_BUFSIZE];
  extern int errno;
  size_t len;
  InputType mode;
  Display *display = ic->core.im->core.display;
  XimCommon im = (XimCommon)ic->core.im;
  Bool useUnicode;

  if (!hook || !display || !state || !state->attr) return;

  mode = state->attr->_attr_u.CIstruct.type_of_input;

  if (mode == HEX)
    sprintf(tmpstr, "0X%s", hook->preedit_text);
  else
    sprintf(tmpstr, "0%s", hook->preedit_text);

  Ximp_Local_Preedit_Done(ic);

  twc[0] = (wchar_t)strtol(tmpstr, &ret, 0);
  if (twc[0] == 0 && errno == EINVAL) return;

  while (0xffff0000 &twc[0]) {
    if (HEX == mode) {
      twc[0] >>= 4;
    } else {
      twc[0] >>= 3;
    }
  }

  twc[1] = L'\0';

  useUnicode = (XIM_USE_UNICODE(im) &&
		NULL != ic->commit_string_callback.callback);

  /* private XIC extension */
  if (useUnicode) {
    XIMCallback *cb = &ic->commit_string_callback;
    XIMUnicodeText cbtext;
    memset(&cbtext, 0, sizeof(XIMUnicodeText));
    cbtext.string.utf16_char = (unsigned short*)&twc[0];
    cbtext.length = 1;
    (*cb->callback)((XIC)ic,
		    cb->client_data,
		    (XPointer)&cbtext);
  } else {
    len = IIimpWcstoMbs(im, (wchar_t*)twc, 1,
			local_mb_buf, LOCAL_MB_BUFSIZE - 1, NULL);
    if (len < 1) return;
    if (len <= LOCAL_MB_BUFSIZE) local_mb_buf[len] = '\0';

    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 = 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) {
      XFree(ic->local_icpart->composed);
      ic->local_icpart->composed = (DefTree *)NULL;
      return;
    }
    memset(ic->local_icpart->composed->mb, 0, len+1);
    bcopy(local_mb_buf, ic->local_icpart->composed->mb,
	  (len + 1) * sizeof(char));
    ic->local_icpart->composed->keysym_return = NoSymbol;

    /* return back to client KeyPressEvent keycode == 0 */
    ev->xkey.keycode = XIM_COMPOSE_KEYCODE;
    XPutBackEvent(display, ev);
  }
  return;
}

/* get candidates for current input(code sequence) */
void
Ximp_Local_Preedit_Lookup(XicCommon ic, XEvent *ev) {
  LocalIMState *state = (LocalIMState *)(ic->local_icpart->imstate);
  LocalPreeditExt *hook = (LocalPreeditExt *)(ic->local_icpart->preedit_ext);
  int chindex, zeropad;
  char tmpstr[80], format[80], *ret;
  int max_len;
  InputType mode;

  if (!hook || !state || !state->attr) return;

  mode = state->attr->_attr_u.CIstruct.type_of_input;
  max_len = state->attr->_attr_u.CIstruct.max_input_len;

  zeropad = max_len - strlen(hook->preedit_text);
  if (mode == HEX)
    sprintf(format, "0X%%s%%0%dd", zeropad);
  else
    sprintf(format, "0%%s%%0%dd", zeropad);

  sprintf(tmpstr, format, hook->preedit_text, 0);
  chindex = (int)strtol(tmpstr, &ret, 0);

  while (0xffff0000 & chindex) {
    if (HEX == mode) {
      chindex >>= 4;
    } else {
      chindex >>= 3;
    }
  }

  Ximp_Local_Lookup_Start(ic);

  if (chindex != -1 ) {
    LocalLookupExt *hook2 = (LocalLookupExt*)(ic->local_icpart->lookup_ext);
    if (!hook2) return;
    hook2->startindex = chindex;
    hook2->begin_range = chindex;
    hook2->crange = -1;
    hook2->end_range = -1;
    Ximp_Local_Lookup_Draw(ic);
  }
  return;
}

void
Ximp_Local_Preedit_Destroy(XicCommon ic) {
  LocalPreeditExt *hook = (LocalPreeditExt *)(ic->local_icpart->preedit_ext);

  if (!hook) return;

  if (hook->preedit_text) Xfree(hook->preedit_text);
  hook->preedit_text = 0;
  Xfree(hook);
  ic->local_icpart->preedit_ext = 0;
  return;
}
