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

*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>
#include <sys/types.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include "XIMPublic.hh"
#include "Xlcint.h"

#include <dlfcn.h>

static void *dl_module = 0;
static XIM (*im_openIM)(XLCd, Display*, XrmDatabase, char*, char*)
  = (XIM(*)(XLCd, Display*, XrmDatabase, char*, char*))0;

extern "C" {
  extern char *XSetIMValues(
#if NeedVarargsPrototypes
			    XIM /* im */, ...
#endif
			    );
	   }

#ifdef sun
#define XIIIMP_PATH     "/usr/openwin/lib/locale/common/xiiimp.so.2"
#else /* Linux */
#define XIIIMP_PATH     "/usr/lib/im/xiiimp.so.2"
#endif /* Linux */

#include <stdio.h>

void
XIMPublic::OpenIM() {
  char *tmpmodifiers;

  if (!dl_module) {
    dl_module = dlopen(XIIIMP_PATH, RTLD_LAZY);
    if (!dl_module) return;	// fatal error
    im_openIM =
      (XIM(*)(XLCd, Display*, XrmDatabase, char*, char*))dlsym(dl_module,
							       "_IIIMP_OpenIM");
    if (!im_openIM) return;	// fatal error
  }
  /* 
     Untidy hack.  When users set XMODIFIERS environment variable beforehand,
     XLC regard it as the modifier specification.   Therefore, if it specifies
     XIM-based IM, _IIIMP_OpenIM would fail to open IM because it could deal with
     only IIIMP-based IM.
  */

  tmpmodifiers = getenv("XMODIFIERS");
  unsetenv("XMODIFIERS");
  XSetLocaleModifiers("");
  XLCd lcd = _XlcCurrentLC();

  setenv("XMODIFIERS", tmpmodifiers, 1);
  XSetLocaleModifiers("");

  xim = (*im_openIM)(lcd, display, (XrmDatabase) NULL,
		     (char*)0, (char *)0);

  if (xim) {
    if (ifname.length())
      char *ret = XSetIMValues(xim,
			       "engineInterfaceName", (char*)ifname,
			       "applicationType", (char*)application_name,
			       0);
    else
      char *ret = XSetIMValues(xim,
			       "applicationType", (char*)application_name,
			       0);
    if (default_font_name.length())
      char *ret = XSetIMValues(xim,
			       "defaultFontName", (char*)default_font_name,
			       0);

    // create a root IC for X-AUX initialization
    root_xic =
      XCreateIC(xim,
		XNInputStyle, XIMPreeditCallbacks|XIMStatusCallbacks,
		0);
    if (root_xic)
      XSetICFocus(root_xic);
  }
  return;
}

XIM
XIMPublic::getXIM() {
  if (!xim) OpenIM();
  return xim;
}

void
XIMPublic::CloseIM() {
  if (root_xic) XDestroyIC(root_xic);
  if (xim) XCloseIM(xim);

  return;
}

const CompoundString&
XIMPublic::getIfName() const {
  return ifname;
}

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

  input_context_list.disable_reordering();

  xim = 0;
  root_xic = 0;
}

XIMPublic::
~XIMPublic() {
  delete start_keys.keylist;
  delete stop_keys.keylist;

  return;
}

int
XIMPublic::setSelectionOwner(Window im_window,
			     char *name, Atom *selection) {
  Window owner;
  *selection = XInternAtom(display, name, False);

  if ((owner = XGetSelectionOwner(display, *selection)) != im_window) {
    if (owner == None) {
      XSetSelectionOwner(display, *selection, im_window, CurrentTime);
      return True;
    } else {
      return False;
    }
  }
  return True;
}

int
XIMPublic::set_values(IMArg *args, int n) {
  if (n == 0) return 0;
  for (IMArg *argp = args; argp < &args[n]; argp++) {
    switch (argp->id) {
    case DisplayConnection:
      display = (Display*)argp->value; // extension 
      break;
    case IFName:
      ifname = (char*)argp->value; // extension 
      break;
    case AppName:
      application_name = (char*)argp->value; // extension 
      break;
    case DisableStatusArea:
      disable_status_area = (Bool)argp->value; // extension
      break;
    case DefaultFontName:
      default_font_name = (char*)argp->value; // extension
      break;
    default:
      (void)IMProtocol::set_values(argp, 1);
      break;
    }
  }
  return 0;
}

Bool
XIMPublic::isConversionKey(unsigned int kcode, unsigned int kstate,
			     int convOn) {
  int i;
  KeySym ksym = XKeycodeToKeysym(display, kcode, 0);
  XIMTriggerKey *ximp_keyp;

  if (convOn)
    ximp_keyp = stop_keys.keylist;
  else
    ximp_keyp = start_keys.keylist;

  for (i = 0; i < start_keys.count_keys; i++, ximp_keyp++) {
    if ((ximp_keyp->keysym == ksym) &&
	((kstate & ximp_keyp->modifier_mask) == ximp_keyp->modifier)) {
      return True;
    }
  }
  return False;
}

void
XIMPublic::select_destroy_emask(Window win) {
  XWindowAttributes win_attr;
  XGetWindowAttributes(display, win, &win_attr);
  XSelectInput(display, win,
	       (win_attr.your_event_mask | StructureNotifyMask));
  return;
}
void
XIMPublic::select_keypress_emask(Window win) {
  XWindowAttributes win_attr;
  XGetWindowAttributes(display, win, &win_attr);
  XSelectInput(display, win, (win_attr.your_event_mask | KeyPressMask));
  return;
}
void
XIMPublic::select_keyrelease_emask(Window win) {
  XWindowAttributes win_attr;
  XGetWindowAttributes(display, win, &win_attr);
  XSelectInput(display, win, (win_attr.your_event_mask | KeyReleaseMask));
  return;
}
void
XIMPublic::unselect_destroy_emask(Window win) {
  XWindowAttributes win_attr;
  XGetWindowAttributes(display, win, &win_attr);
  XSelectInput(display, win,
	       (win_attr.your_event_mask & ~StructureNotifyMask));
  return;
}
void
XIMPublic::unselect_keypress_emask(Window win) {
  XWindowAttributes win_attr;
  XGetWindowAttributes(display, win, &win_attr);
  XSelectInput(display, win,
	       (win_attr.your_event_mask & ~KeyPressMask));
  return;
}
void
XIMPublic::unselect_keyrelease_emask(Window win) {
  XWindowAttributes win_attr;
  XGetWindowAttributes(display, win, &win_attr);
  XSelectInput(display, win,
	       (win_attr.your_event_mask & ~KeyReleaseMask));
  return;
}
