/*
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 <sys/types.h>
#include <netinet/in.h>		// for htonl
#include "IMProtocolStruct.h"
#include "XIMProtocol.hh"
#include "XIMPInputContext.hh"
#include "XIMProto.hh"
#include "Xfactory.hh"
#include <X11/Xutil.h>

/* ximp input styles */
static XIMStyle ximp_styles[] = {
  XIMPreeditCallbacks |XIMStatusCallbacks,
  XIMPreeditCallbacks | XIMStatusArea,
  XIMPreeditCallbacks | XIMStatusNothing,
  XIMPreeditPosition  | XIMStatusCallbacks,
  XIMPreeditPosition  | XIMStatusArea,
  XIMPreeditPosition  | XIMStatusNothing,
  XIMPreeditArea      | XIMStatusCallbacks,
  XIMPreeditArea      | XIMStatusArea,
  XIMPreeditArea      | XIMStatusNothing,
  XIMPreeditNothing   | XIMStatusCallbacks,
  XIMPreeditNothing   | XIMStatusArea,
  XIMPreeditNothing   | XIMStatusNothing,
  XIMPreeditCallbacks | XIMStatusNone,
  XIMPreeditPosition  | XIMStatusNone,
  XIMPreeditArea      | XIMStatusNone,
  XIMPreeditNothing   | XIMStatusNone,
  XIMPreeditNone      | XIMStatusCallbacks,
  XIMPreeditNone      | XIMStatusArea,
  XIMPreeditNone      | XIMStatusNothing,
  XIMPreeditNone      | XIMStatusNone
};

/* styles for disable_status_area */
static XIMStyle ximp_styles2[] = {
  XIMPreeditCallbacks | XIMStatusNone,
  XIMPreeditPosition  | XIMStatusNone,
  XIMPreeditArea      | XIMStatusNone,
  XIMPreeditNothing   | XIMStatusNone,
  XIMPreeditNone      | XIMStatusNone
};

XIMProtocol::
XIMProtocol(IMArg *args, int n) : XIMPublic(args, n) {

  input_context_list.disable_reordering();

  protocol_name = "XIMP4.0";

  ximp_version = "4.0";
  im_version = "4.0";

  ximp_type.num_of_types = 2;
  ximp_type.types = new unsigned long[2];

  ximp_type.types[0] = XIMP_FE_TYPE1;
  ximp_type.types[1] = XIMP_SYNC_BE_TYPE2;

  styles.count_styles = sizeof(ximp_styles)/sizeof(ximp_styles[0]);
  styles.supported_styles = &ximp_styles[0];

  atom_sequence = 0;

  thread = NULL;

}

XIMProtocol::
~XIMProtocol() {
  delete [] ximp_type.types;

  if (im_window)
    XDestroyWindow(display, im_window);

  delete start_keys.keylist;
  delete stop_keys.keylist;
  delete thread;

  return;
}

void
XIMProtocol::setProps() {
  Atom extensions[10];
  int ext_number;
  int i;

  /* IMS Window Property Name */
  const char *COMPOUND_TEXT = "COMPOUND_TEXT";
  const char *XIMP_VERSION = "_XIMP_VERSION";
  const char *XIMP_STYLE = "_XIMP_STYLE";
  const char *XIMP_TYPE = "_XIMP_TYPE";
  const char *XIMP_SERVERNAME = "_XIMP_SERVERNAME";
  const char *XIMP_SERVERVERSION = "_XIMP_SERVERVERSION";
  const char *XIMP_VENDORNAME = "_XIMP_VENDORNAME";
  const char *XIMP_KEYS = "_XIMP_KEYS";
  const char *XIMP_SPROC_STARTED_KEYS = "_XIMP_SPROC_STARTED_KEYS";
  const char *XIMP_SPROC_STOPPED_KEYS = "_XIMP_SPROC_STOPPED_KEYS";
  const char *XIMP_EXTENSIONS = "_XIMP_EXTENSIONS";
  const char *XIMP_PREEDITFONT = "_XIMP_PREEDITFONT";
  const char *XIMP_STATUSFONT = "_XIMP_STATUSFONT";

  /* Client Window Property Name */
  const char *XIMP_FOCUS = "_XIMP_FOCUS";
  const char *XIMP_PREEDIT = "_XIMP_PREEDIT";
  const char *XIMP_STATUS = "_XIMP_STATUS";

  const char *XIMP_EXT_XIMP_STATUSWINDOW = "_XIMP_EXT_XIMP_STATUSWINDOW";
  const char *XIMP_EXT_XIMP_BACK_FRONT = "_XIMP_EXT_XIMP_BACK_FRONT";
  const char *XIMP_EXT_XIMP_CONVERSION = "_XIMP_EXT_XIMP_CONVERSION";

  const char *XIMP_PREEDIT_DRAW_DATA = "_XIMP_PREEDIT_DRAW_DATA";
  const char *XIMP_FEEDBACKS = "_XIMP_FEEDBACKS";

#define INTERN(s) XInternAtom(display, s, False)
  atoms.ctext_type = INTERN(COMPOUND_TEXT);
  atoms.version = INTERN(XIMP_VERSION);
  atoms.supported_styles = INTERN(XIMP_STYLE);
  atoms.supported_types = INTERN(XIMP_TYPE);
  atoms.server_name = INTERN(XIMP_SERVERNAME);
  atoms.server_version = INTERN(XIMP_SERVERVERSION);
  atoms.vendor_name = INTERN(XIMP_VENDORNAME);
  atoms.keys = INTERN(XIMP_KEYS);
  atoms.sproc_started_keys = INTERN(XIMP_SPROC_STARTED_KEYS);
  atoms.sproc_stopped_keys = INTERN(XIMP_SPROC_STOPPED_KEYS);
  atoms.extensions = INTERN(XIMP_EXTENSIONS);

  atoms.focus = INTERN(XIMP_FOCUS);
  atoms.preedit = INTERN(XIMP_PREEDIT);
  atoms.status = INTERN(XIMP_STATUS);
  atoms.preedit_font = INTERN(XIMP_PREEDITFONT);
  atoms.status_font = INTERN(XIMP_STATUSFONT);

  atoms.ext_statuswin = INTERN(XIMP_EXT_XIMP_STATUSWINDOW);
  atoms.ext_backfront = INTERN(XIMP_EXT_XIMP_BACK_FRONT);
  atoms.ext_conversion = INTERN(XIMP_EXT_XIMP_CONVERSION);

  atoms.preedit_draw_data = INTERN(XIMP_PREEDIT_DRAW_DATA);
  atoms.feedbacks = INTERN(XIMP_FEEDBACKS);
#undef INTERN
  /* count supported extensions */
  ext_number = 0;

  ext_flag = 0;
  ext_flag |= EXT_CONV;		// default
  if (ext_flag & EXT_STATUS)
    extensions[ext_number++] = atoms.ext_statuswin;
  if (ext_flag & EXT_BACKFRONT)
    extensions[ext_number++] = atoms.ext_backfront;
  if (ext_flag & EXT_CONV)
    extensions[ext_number++] = atoms.ext_conversion;

  IMTriggerKey keyp;
  XIMTriggerKey *ximp_keyp;

  /* start keys */
  start_keys.count_keys = on_keys.count();
  start_keys.keylist = new XIMTriggerKey[start_keys.count_keys];
  ximp_keyp = start_keys.keylist;

  for (i = 0; i < start_keys.count_keys; i++, ximp_keyp++) {
    keyp = on_keys.getKey(i+1);
    ximp_keyp->modifier = keyp.get_modifier();
    ximp_keyp->modifier_mask = keyp.get_modifier_mask();
    ximp_keyp->keysym = keyp.get_keyCode();
  }

  /* stop keys */
  stop_keys.count_keys = off_keys.count();
  stop_keys.keylist = new XIMTriggerKey[stop_keys.count_keys];
  ximp_keyp = stop_keys.keylist;

  for (i = 0; i < stop_keys.count_keys; i++, ximp_keyp++) {
    keyp = off_keys.getKey(i+1);
    ximp_keyp->modifier = keyp.get_modifier();
    ximp_keyp->modifier_mask = keyp.get_modifier_mask();
    ximp_keyp->keysym = keyp.get_keyCode();
  }

  const char *xim_name = im_name; // evil, need to be fixed in CompoundString
  const char *xvendor_name = vendor_name;
  const char *xim_version = im_version;

  if (disable_status_area == True){
    styles.count_styles = sizeof(ximp_styles2)/sizeof(ximp_styles2[0]);
    styles.supported_styles = &ximp_styles2[0];
  }
    
#define SETPROPERTY(p, t, f, d, n) XChangeProperty(display, im_window, p, \
						   t, f, PropModeReplace, \
						   (unsigned char *)d, n)
  SETPROPERTY(atoms.version, XA_STRING, 8,
	      ximp_version, strlen(ximp_version));
  SETPROPERTY(atoms.supported_styles, atoms.supported_styles, 32,
	      styles.supported_styles, styles.count_styles);
  SETPROPERTY(atoms.supported_types, atoms.supported_types, 32,
	      ximp_type.types, ximp_type.num_of_types);
  SETPROPERTY(atoms.server_name, XA_STRING, 8, xim_name, strlen(xim_name));
  SETPROPERTY(atoms.server_version, XA_STRING, 8,
	      xim_version, strlen(xim_version));
  SETPROPERTY(atoms.vendor_name, XA_STRING, 8,
	      xvendor_name, strlen(xvendor_name));
  SETPROPERTY(atoms.keys, atoms.keys, 32,
	      start_keys.keylist, start_keys.count_keys * 3);
  SETPROPERTY(atoms.sproc_started_keys, atoms.sproc_started_keys, 32,
	      start_keys.keylist, start_keys.count_keys * 3);
  SETPROPERTY(atoms.sproc_stopped_keys, atoms.sproc_stopped_keys, 32,
	      stop_keys.keylist, stop_keys.count_keys * 3);
  SETPROPERTY(atoms.extensions, atoms.extensions, 32,
	      extensions, ext_number);
#undef SETPROPERTY
  return;
}

static char *
NextLocaleName(char **list) {
  char *p;
    
  for (p = *list; **list && **list != ','; (*list)++);
  if (**list == ',') {
    **list = '\0';
    (*list)++;
  } else if (p == *list) {
    p = (char *)NULL;
  }
  return(p);
}

#if 0
static Bool
_XimpWaitIMProtocol(Display *dpy, Window window, XEvent *ev,
		    XPointer client_data) {
#if 0
  XIMProtocol *ximp_protocol = (XIMProtocol*)client_data;
#endif
  return True;
}
#endif

int
XIMProtocol::run() {
  CompoundString locale_list = input_locale;
  char *locale_p;
  Bool found;
  char *p, *pp, im_shortname[64], im_longname[64];
  Atom selection;

  if (display == 0) {
    // nothing to do
    fprintf(stderr, "   Error - No XDisplay connection\n");
    fprintf(stderr, "       XIMP40 cannot be used\n");
    return -1;
  }

  (void)XSetErrorHandler(XFactory::xerror_handler);
#ifdef DEBUG
  (void)XSynchronize(display, True);
#endif
  if (display) {
    screen = DefaultScreen(display);
    im_window = XCreateSimpleWindow(display,
				    DefaultRootWindow(display),
				    0, 0, 1, 1, 1, 0, 0);
  }

  (void)setProps();

  found = False;
  locale_p = locale_list;
  for (p = NextLocaleName((char **)&locale_p); p != NULL;
       p = NextLocaleName((char **)&locale_p)) {
    /* short selection name */
    if (pp = strchr(p, '.')) *pp = (char)0;
    sprintf(im_shortname, "_XIMP_%s", p);
    if (setSelectionOwner(im_window, im_shortname, &selection) == True) {
      found = True;
    }
    /* long selection name */
    const char *xim_name = im_name;
    sprintf(im_longname, "%s@%s.%d", im_shortname, xim_name, screen);
    if (setSelectionOwner(im_window, im_longname, &selection) == True) {
      found = True;
    }
    // fix for 4134207&4260189
    for (int i = 0; i < ScreenCount(display); i++) {
      if (screen != i) {
	/* long selection name */
	sprintf(im_longname, "%s@%s.%d", im_shortname, xim_name, i);
	if (setSelectionOwner(im_window, im_longname, &selection) == True) {
	  found = True;
	}
      }
    }
  }
  if (!found) return -1;

  /* Property Name */
  const char *XIMP_PROTOCOL = "_XIMP_PROTOCOL";

  ximp_request = XInternAtom(display, XIMP_PROTOCOL, False);

  OpenIM();

  if (thread == NULL) {
    // start creating a thread
    thread = new IMThread(xevent_loop, this);
  }
  
  return 0;
}

Bool
XIMProtocol::get_protocol_version(Window win, char *&prop_ret) {
  Atom atom_ret = (Atom)0;
  int format_ret = 0;
  unsigned long nitems_ret = (unsigned long)0;
  unsigned long bytes_ret = (unsigned long)0;

  if (XGetWindowProperty(display, win, atoms.version, 0, 10000L, True,
			 XA_STRING, &atom_ret, &format_ret, &nitems_ret,
			 &bytes_ret, (unsigned char**)&prop_ret)
      != Success) return False;
  if (atom_ret == None || atom_ret != XA_STRING) {
    return False;
  }
  return True;
}

Bool
XIMProtocol::get_focus_window(Window win, Window &focus_win) {
  unsigned char *data;
  unsigned long len;

  if (!read_property(win, atoms.focus, XA_WINDOW, 32, &data, &len)) {
    return False;
  } else if (len != 1 && len != 2) {
    /* if len == 2, data[4-7] contains a event mask
       of the data[0-3] window. */
    XFree((char *)data);
    return False;
  }
  focus_win = *(Window *)data;
  XFree((char *)data);
  return True;
}

Bool
XIMProtocol::get_preedit_font(Window win, char **name) {
  unsigned char *data;
  unsigned long len;

  if (!read_property(win, atoms.preedit_font, XA_STRING, 8,
		     (unsigned char **)&data, &len)) {
    return False;
  }
  if (*name)
     delete []*name;
  char *t_name = new char[strlen((const char *)data)+1];
  *name = t_name;
  strcpy(t_name, (const char *)data);
  XFree(data);
  return True;
}

Bool
XIMProtocol::get_status_font(Window win, char **name) {
  unsigned char *data;
  unsigned long len;

  if (!read_property(win, atoms.status_font, XA_STRING, 8,
		     (unsigned char **)&data, &len)) {
    return False;
  }
  if (*name)
     delete []*name;
  char *t_name = new char[strlen((const char *)data)+1];
  *name = t_name;
  strcpy(t_name, (const char *)data);
  XFree(data);
  return True;
}

Bool
XIMProtocol::get_preedit4(Window win,
			  Ximp_PreeditPropRec4 &preedit_attr) {
  unsigned char *data;
  unsigned long len;

  if (!read_property(win, atoms.preedit, atoms.preedit, 32,
		     (unsigned char **)&data, &len)) {
    return False;
  }
  preedit_attr = *(Ximp_PreeditPropRec4*)data;
  XFree((char *)data);
  return True;
}

Bool
XIMProtocol::get_preedit3(Window win,
			  Ximp_PreeditPropRec3 &preedit_attr) {
  unsigned char *data;
  unsigned long len;

  if (!read_property(win, atoms.preedit, atoms.preedit, 32,
		     (unsigned char **)&data, &len)) {
    return False;
  }
  preedit_attr = *(Ximp_PreeditPropRec3*)data;
  XFree((char *)data);
  return True;
}

Bool
XIMProtocol::get_status4(Window win,
			 Ximp_StatusPropRec4 &status_attr) {
  unsigned char *data;
  unsigned long len;

  if (!read_property(win, atoms.status, atoms.status, 32,
		     (unsigned char **)&data, &len)) {
    return False;
  }
  status_attr = *(Ximp_StatusPropRec4*)data;
  XFree((char *)data);
  return True;
}

Bool
XIMProtocol::get_status3(Window win,
			 Ximp_StatusPropRec3 &status_attr) {
  unsigned char *data;
  unsigned long len;

  if (!read_property(win, atoms.status, atoms.status, 32,
		     (unsigned char **)&data, &len)) {
    return False;
  }
  status_attr = *(Ximp_StatusPropRec3*)data;
  XFree((char *)data);
  return True;
}

Bool
XIMProtocol::get_server_type4(Window win, unsigned long &type) {
  unsigned char *data;
  unsigned long len;

  if (!read_property(win, atoms.supported_types, atoms.supported_types,
		     32, &data, &len)) {
    return False;
  }
  type = *(unsigned long*)data;
  XFree((char*)data);
  return True;
}

Bool
XIMProtocol::set_focus_window(Window win, Window focus_win) {
  return write_property(win, atoms.focus,
			XA_WINDOW, 32,
			(unsigned char*)&focus_win, 1);
}

Bool
XIMProtocol::set_preedit_font(Window win, char *pre_font) {
  return write_property(win, atoms.preedit_font,
			XA_STRING, 8,
			(unsigned char *)pre_font,
			(CARD32)strlen(pre_font));
}

Bool
XIMProtocol::set_status_font(Window win, char *sts_font) {
  return write_property(win, atoms.status_font,
			XA_STRING, 8,
			(unsigned char *)sts_font,
			(CARD32)strlen(sts_font));
}

Bool
XIMProtocol::set_preedit4(Window win, Ximp_PreeditPropRec4 preedit_attr) {
  return write_property(win, atoms.preedit,
			atoms.preedit, 32,
			(unsigned char *)&preedit_attr,
			XIMP_PREEDIT_MAX_LONG4);
}

Bool
XIMProtocol::set_status4(Window win, Ximp_StatusPropRec4 status_attr) {
  return write_property(win, atoms.status,
			atoms.status, 32,
			(unsigned char *)&status_attr,
			XIMP_STATUS_MAX_LONG4);
}

Bool
XIMProtocol::set_preedit3(Window win, Ximp_PreeditPropRec3 preedit_attr) {
  return write_property(win, atoms.preedit,
			atoms.preedit, 32,
			(unsigned char *)&preedit_attr,
			XIMP_PREEDIT_MAX_LONG3);
}

Bool
XIMProtocol::set_status3(Window win, Ximp_StatusPropRec3 status_attr) {
  return write_property(win, atoms.status,
			atoms.status, 32,
			(unsigned char *)&status_attr,
			XIMP_STATUS_MAX_LONG3);
}

Bool
XIMProtocol::set_server_type4(Window win, unsigned long type) {
  return write_property(win, atoms.supported_types,
			atoms.supported_types, 32,
			(unsigned char *)&type, 1);
}

Bool
XIMProtocol::read_property(Window win, Atom prop, Atom type,
			   int format,
			   unsigned char **datapp, unsigned long *lenp) {
  Atom realtype;
  int realformat;
  unsigned long bytesafter;

  *datapp = NULL;
  if (XGetWindowProperty(display, win, prop, 0L, 1000000L, True, type,
			 &realtype, &realformat, lenp,
			 &bytesafter, datapp) != Success)
    return False;
  if (realtype == None) {
    return False;
  } else if (realtype != type) {
    return False;
  } else if (realformat != format) {
    if (*datapp != NULL) XFree((char *)*datapp);
    *datapp = NULL;
    return False;
  }
  return True;
}

Bool
XIMProtocol::write_property(Window win, Atom prop, Atom type,
			    int format,
			    const unsigned char *datap,
			    const unsigned long len) {
  (void)XChangeProperty(display, win, prop, type, format,
			PropModeReplace, datap, len);
  /* always return True */
  return True;
}

void*
XIMProtocol::xevent_loop(void* client_data) {
  XIMProtocol *ximp_protocol = (XIMProtocol*)client_data;

  for (;;) {
    XEvent event;
    XNextEvent(ximp_protocol->display, &event);
    if (DestroyNotify == event.type) {
      ximp_protocol->destroy_window(ximp_protocol,
				    event.xdestroywindow.window);
    }
    if (XFilterEvent(&event, 0) == True)
      continue;
    switch (event.type) {
    case KeyPress:
    case KeyRelease:
	  {
	    XIMPInputContext *ic =(XIMPInputContext *) ximp_protocol->getInputContextByFocusWindow(event.xkey.window);
	    if (ic)
	       ic->forward_xevent((XEvent*)&event);
	  }
	  break;
    case ClientMessage:
      if (event.xclient.message_type == ximp_protocol->ximp_request &&
	  event.xclient.window == ximp_protocol->im_window &&
	  event.xclient.format == 32) {
	switch ((int)event.xclient.data.l[0]) {
	case XIMP_KEYPRESS4:
	case XIMP_KEYPRESS3:
	  ximp_protocol->key_press((XClientMessageEvent*)&event);
	  break;
	case XIMP_KEYRELEASE4:
	  ximp_protocol->key_release((XClientMessageEvent*)&event);
	  break;
	case XIMP_CREATE4:
	case XIMP_CREATE3:
	  ximp_protocol->create_ic((XClientMessageEvent*)&event);
	  break;
	case XIMP_DESTROY4:
	case XIMP_DESTROY3:
	  ximp_protocol->destroy_ic((XClientMessageEvent*)&event);
	  break;
	case XIMP_REG_KEY_PRESSED4:
	case XIMP_BEGIN3:
	  ximp_protocol->start((XClientMessageEvent*)&event);
	  break;
	case XIMP_END3:
	  ximp_protocol->end((XClientMessageEvent*)&event);
	  break;
	case XIMP_SETFOCUS4:
	case XIMP_SETFOCUS3:
	  ximp_protocol->set_focus((XClientMessageEvent*)&event);
	  break;
	case XIMP_UNSETFOCUS4:
	case XIMP_UNSETFOCUS3:
	  ximp_protocol->unset_focus((XClientMessageEvent*)&event);
	  break;
	case XIMP_CLIENT_WINDOW4:
	  ximp_protocol->set_clientwin((XClientMessageEvent*)&event);
	  break;
	case XIMP_FOCUS_WINDOW4:
	  ximp_protocol->set_focuswin((XClientMessageEvent*)&event);
	  break;
	case XIMP_MOVE4:
	case XIMP_MOVE3:
	  ximp_protocol->move((XClientMessageEvent*)&event);
	  break;
	case XIMP_SETVALUE4:
	case XIMP_SETVALUE3:
	  ximp_protocol->set_icvalues((XClientMessageEvent*)&event);
	  break;
	case XIMP_GETVALUE4:
	case XIMP_GETVALUE3:
	  ximp_protocol->get_icvalues((XClientMessageEvent*)&event);
	  break;
	case XIMP_RESET4:
	case XIMP_RESET3:
	  ximp_protocol->reset((XClientMessageEvent*)&event);
	  break;
	case XIMP_EVENTMASK_NOTIFY4:
	  ximp_protocol->event_mask((XClientMessageEvent*)&event);
	  break;
	case XIMP_EXTENSION4:
	case XIMP_EXTENSION3:
	  ximp_protocol->extension((XClientMessageEvent*)&event);
	  break;
	case XIMP_PREEDITSTART_RETURN4:
	case XIMP_PREEDITSTART_RETURN3:
	  ximp_protocol->preedit_start_ret((XClientMessageEvent*)&event);
	  break;
	case XIMP_PREEDITCARET_RETURN4:
	case XIMP_PREEDITCARET_RETURN3:
	  ximp_protocol->preedit_caret_ret((XClientMessageEvent*)&event);
	  break;
	default:
	  break;	/* unknown ximp protocol */
	}
      }
    default:
      break;
    }
  }
  return 0;
}

InputContext *
XIMProtocol::getInputContextByFocusWindow(Window w) {
   XIMPInputContext *tmp_ic;
   tmp_ic = (XIMPInputContext *)&(input_context_list.getFirstItem());
   while (NULL != tmp_ic) {
     if ((NULL != tmp_ic) && (tmp_ic->focus_window() == w)) {
       return (InputContext *)tmp_ic;
     }
     tmp_ic = (XIMPInputContext *)&(input_context_list.getNextItem());
   }
   return NULL;
}

Bool
XIMProtocol::key_press(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));
  XEvent kev;
  if (!ic) return True;

  if (ic->checkAltKey(ev)) {
    if (ic->is_conv_state()) {
      ev->data.l[0] = XIMP_END3; // dummy
      end((XClientMessageEvent*)ev);
    } else {
      ev->data.l[0] = ic->is_version_40()?
	XIMP_REG_KEY_PRESSED4: XIMP_BEGIN3; // dummy
      start((XClientMessageEvent*)ev);
    }
    goto skip;
  }

  kev.xkey.type = KeyPress;
  kev.xkey.window = ic->focus_window();
  kev.xkey.display = display;
  kev.xkey.root = DefaultRootWindow(display);
  kev.xkey.x = 0;
  kev.xkey.y = 0;
  kev.xkey.x_root = 0;
  kev.xkey.y_root = 0;
  kev.xkey.keycode = ev->data.l[2];
  kev.xkey.state = ev->data.l[3];
  kev.xkey.time = (ic->is_version_40() ? ev->data.l[4] : 0);
  kev.xkey.same_screen = 1;

  if (!XFilterEvent((XEvent*)&kev, 0)) {
    // send back to client
    ic->forward_xevent((XEvent*)&kev);
  }

skip:
  if (ic->is_version_40() && ic->is_sync()) {
    ic->set_match(ev->data.l[2], ev->data.l[3]);
    send_client_message(ic->focus_window(),
			XIMP_KEYPRESS_RETURN4,
			input_context_id,
			0, 0, 0);
  }
  return True;
}

Bool
XIMProtocol::key_release(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));
  if (!ic) return True;

  if (ic->is_version_40() && ic->is_sync()) {
    ic->process_match(ev->data.l[2], ev->data.l[3]);
    send_client_message(ic->focus_window(),
			XIMP_KEYRELEASE_RETURN4,
			input_context_id,
			0, 0, 0);
    send_client_message(ic->focus_window(),
			XIMP_KEYRELEASE4,
			input_context_id,
			ev->data.l[2], ev->data.l[3], 0);
  }
  return True;
}

void
XIMProtocol::create_ic(XClientMessageEvent *ev) {
  XIMPInputContext *ic = new XIMPInputContext(this, ev);
  input_context_list.addItem(ic);
  int input_context_id = input_context_list.getIndex(ic);

  send_client_message(ic->focus_window(),
		      (ic->is_version_40() ?
		       XIMP_CREATE_RETURN4:
		       XIMP_CREATE_RETURN3),
		      input_context_id,
		      0, 0, 0);
  return;
}
void
XIMProtocol::destroy_ic(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));
  if (!ic) return;

  ic->destroy_xic();

  input_context_list.remove(ic);

  delete ic;

  return;
}

void
XIMProtocol::destroy_window(XIMProtocol *ximp_protocol,
			    Window destroy_win) {
  XIMPInputContext *ic;
  XClientMessageEvent xcme;

  ic = (XIMPInputContext *)&(ximp_protocol->input_context_list.getFirstItem());
  while (NULL != ic) {
    if (ic->client_window() == destroy_win) {
      /* in destroy_ic(), only data.i[1] is referred. */
      xcme.data.l[1] = ximp_protocol->input_context_list.getIndex(ic);
      ximp_protocol->destroy_ic(&xcme);
    }
    ic = (XIMPInputContext *)&(ximp_protocol->input_context_list.getNextItem());
  }

  return;
}

void
XIMProtocol::start(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));
  if (!ic) return;

  if (ic->is_conv_state()) return;

  ic->conversion_start();
  return;
}

void
XIMProtocol::end(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));
  if (!ic) return;

  if (!ic->is_conv_state()) return;

  ic->conversion_end();
  return;
}

void
XIMProtocol::set_focus(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItemMakeTop(input_context_id));
  if (!ic) return;

  ic->set_xicfocus();

  return;
}

void
XIMProtocol::unset_focus(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));

  if (!ic) return;
  ic->unset_xicfocus();

  return;
}

void
XIMProtocol::set_clientwin(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));
  if (!ic) return;

  ic->set_client_window(ev->data.l[2]);
  ic->set_fwin_select_mask(ev->data.l[3]);

  send_client_message(ic->focus_window(),
		      XIMP_CLIENT_WINDOW_RETURN4,
		      input_context_id,
		      0, 0, 0);
  return;
}

void
XIMProtocol::set_focuswin(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItemMakeTop(input_context_id));
  if (!ic) return;

  ic->set_focus_window(ev->data.l[2]);
  ic->set_fwin_select_mask(ev->data.l[3]);

  send_client_message(ic->focus_window(),
		      XIMP_FOCUS_WINDOW_RETURN4,
		      input_context_id,
		      0, 0, 0);
  return;
}

void
XIMProtocol::move(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));
  if (!ic) return;

  ic->set_preedit_spot_location(ev->data.l[2], ev->data.l[3]);

  return;
}

void
XIMProtocol::set_icvalues(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));

  if (!ic) return;

#if 0
  XIMProtocol *ximp_protocol = ic->ximp_protocol;
  IMArg args[1];
  int n = 0;
  // ximp_protocol->proto_handler->SetICValues((InputContext*)ic, args, n);
#endif

  ic->set_values(ev);

  return;
}

void
XIMProtocol::get_icvalues(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));

  if (!ic) return;

  ic->get_values(ev);

  send_client_message(ic->focus_window(),
		      (ic->is_version_40() ?
		       XIMP_GETVALUE_RETURN4 :
		       XIMP_GETVALUE_RETURN3),
		      input_context_id,
		      0, 0, 0);
  return;
}

//
// reset XIC
//
// note: the calling order of reset_xic, conversion_end, and
// 	 get_commit_string must not be changed so that
//	 implicit commit of XView applications should work well
void
XIMProtocol::reset(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));
  if (!ic) return;

#if 0
  XIMProtocol *ximp_protocol = ic->ximp_protocol;
  // IMText *text = ximp_protocol->proto_handler->ResetIC((InputContext*)ic);
#endif

  // 
  // Only XIMP4.0 supports sending reset string by cmsg.
  //
  Atom atom_ret = (Atom)0;
  XIC_RESET_FLAG flag = RESET_NOTHING;

  char *ctext = ic->reset_xic(); // ctext needs to be free
  Bool need_ctext_free = True;

  ic->conversion_end();		// must be called after reset_xic()

  if (ctext == 0 || *ctext == 0) {
    ctext = ic->get_commit_string();
    need_ctext_free = False;
  } else {
    (void)ic->get_commit_string(); // to clear xic's being_reset flag to 0
  }
  if (ic->is_version_40()) {
    if (ctext == 0 || *ctext == 0) {
      atom_ret = 0;
    } else {
      size_t length = strlen(ctext);
      if (length <= 250) {
	commit_by_client_message(ic->focus_window(),
				 input_context_id,
				 ctext,
				 length);
	flag = RESET_BY_CMSG;
      } else {
	atom_ret = replace_prop_pool((unsigned char*)ctext, length);
	flag = RESET_BY_PROP;
      }
    }
  } else {
    atom_ret = 0;
  }
  if (need_ctext_free && ctext) XFree(ctext);

  send_client_message(ic->focus_window(),
		      (ic->is_version_40() ?
		       XIMP_RESET_RETURN4 :
		       XIMP_RESET_RETURN3),
		      input_context_id,
		      (CARD32)flag, (CARD32)atom_ret, 0);

  return;
}

void
XIMProtocol::event_mask(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));
  if (!ic) return;

  ic->set_fwin_select_mask(ev->data.l[2]);

  send_client_message(ic->focus_window(),
		      XIMP_EVENTMASK_NOTIFY_RETURN4,
		      input_context_id,
		      0, 0, 0);
  return;
}

void
XIMProtocol::extension(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));
  if (!ic) return;
  unsigned int extension_type = ev->data.l[2];

  if (extension_type == atoms.ext_statuswin) {
    ;
  }
  if (extension_type == atoms.ext_backfront) {
    ;
  }
  if (extension_type == atoms.ext_conversion) {
    if (ev->data.l[3]) {
      // set conv_state
      if (ev->data.l[4])	// conv state
	ic->conversion_start();
      else
	ic->conversion_end();
    } else {
      // get conv_state
      int conv_state = ic->is_conv_state();
      send_client_message(ic->focus_window(),
			  (ic->is_version_40() ?
			   XIMP_EXTENSION4 : XIMP_EXTENSION3),
			  input_context_id,
			  atoms.ext_conversion,
			  conv_state,
			  0);
    }
  }
  return;
}

void
XIMProtocol::preedit_start_ret(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));
  if (!ic) return;

  ic->set_preedit_maxlen(ev->data.l[2]);

  return;
}

void
XIMProtocol::preedit_caret_ret(XClientMessageEvent *ev) {
  int input_context_id = ev->data.l[1];
  XIMPInputContext *ic = (XIMPInputContext*)&(input_context_list.getItem(input_context_id));
  if (!ic) return;

  ic->set_preedit_caret_position(ev->data.l[2]);

  return;
}

void
XIMProtocol::commit_by_client_message(Window focus_window,
				      int input_context_id,
				      const char *ctext, int length) {
  XClientMessageEvent event;
  int msglen = CM_DATA_ROOM;	/* default */
  char *ctptr = (char*)ctext;
  Ximp_CommitPropRec *msg = (Ximp_CommitPropRec*)&(event.data.l[0]);

  event.type = ClientMessage;
  event.display = display;
  event.message_type = ximp_request;
  event.window = focus_window;
  event.format = 8;

  while (length > 0) {
    memset(msg, 0, sizeof(Ximp_CommitPropRec));
    msg->icid = htonl((long)input_context_id);
    msg->size = length;
    if (length < CM_DATA_ROOM) msglen = length;

    memmove(msg->ctext, ctptr, msglen);
    XSendEvent(display,
	       focus_window,
	       False,
	       NoEventMask,
	       (XEvent*)&event);
    length -= CM_DATA_ROOM;
    ctptr += CM_DATA_ROOM;
  }
  XFlush(display);
  return;
}

Atom
XIMProtocol::replace_prop_pool(const unsigned char *data, int len) {
  char name[20];
  Atom type = atoms.feedbacks;
  Atom atom = XInternAtom(display, MakeNewAtom(name), False);

  XChangeProperty(display, im_window, atom, type, 32,
		  PropModeReplace, data, len);
  XFlush(display);
  return (atom);
}
  
Atom
XIMProtocol::set_preedit_draw_data_property(const unsigned char *data ,
					    int len) {
  char name[20];
  Atom atom = XInternAtom(display, MakeNewAtom(name), False);
  XChangeProperty(display, im_window, atom, atoms.preedit_draw_data,
		  32, PropModeReplace,
		  data, len);
  return atom;
}

Atom
XIMProtocol::set_ctext_property(const unsigned char *data, int len,
				int is_commit) {
  char name[20];
  Atom atom = XInternAtom(display, MakeNewAtom(name, is_commit), False);
  XChangeProperty(display, im_window, atom, atoms.ctext_type,
		  8, PropModeReplace,
		  data, len);
  return atom;
}

Atom
XIMProtocol::set_ctext_property(const unsigned char *data, int len) {
  return set_ctext_property(data, len, 0);
}

Atom
XIMProtocol::set_feedback_property(const unsigned char *data, int len) {
  char name[20];
  Atom atom = XInternAtom(display, MakeNewAtom(name), False);
  XChangeProperty(display, im_window, atom, atoms.feedbacks,
		  32, PropModeReplace,
		  data, len);
  return atom;
}

void
XIMProtocol::send_client_message(Window focus_window, int type,
				 unsigned long l1, unsigned long l2,
				 unsigned long l3, unsigned long l4) {
  XEvent event;

  memset(&event, 0, sizeof(event));
  event.xclient.type = ClientMessage;
  event.xclient.display = display;
  event.xclient.window = focus_window;
  event.xclient.message_type = ximp_request;
  event.xclient.format = 32;
  event.xclient.data.l[0] = type;
  event.xclient.data.l[1] = l1;
  event.xclient.data.l[2] = l2;
  event.xclient.data.l[3] = l3;
  event.xclient.data.l[4] = l4;

  XSendEvent(display, event.xclient.window,
	     False, NoEventMask, &event);
  XFlush(display);

}

char*
XIMProtocol::MakeNewAtom(char *atomName, int is_commit) {
  sprintf(atomName,
	  (is_commit ?
	   "_XIMP_NORMALPROP_%X" :
	   "_XIMP_CALLBACKS_%d"),
	  (atom_sequence > 40 ? (atom_sequence = 0) : atom_sequence));
  atom_sequence++;
  return atomName;
}

