/*
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 "commonIM.h"
#include "XimpIm.h"
#include "switchIM.h"
#include "iiimpIM.h"
#include "composeIM.h"
#include "iiimpIC.h"
#include "status.h"
#include "iiimpSwitcher.h"
#include "iiimpAuxP.h"

static int SwitchCloseIM(XIM);

extern char* IIIMP_SetIMValues(XIM, XIMArg*);
extern char* IIIMP_GetIMValues(XIM, XIMArg*);

static XIC SwitchCreateIC(XIM, XIMArg*);
extern int _Ximp_ctstombs(XIM, char*, int, char*, int, Status*);
extern int _Ximp_ctstowcs(XIM, char*, int, wchar_t*, int, Status*);

static XIMMethods
get_switch_im_methods()
{
    static XIMMethodsRec imm;

    if (!imm.close) {
	imm.close = SwitchCloseIM;
	imm.set_values = IIIMP_SetIMValues;
	imm.get_values = IIIMP_GetIMValues;
	imm.create_ic = SwitchCreateIC;
	imm.ctstombs = _Ximp_ctstombs;
	imm.ctstowcs = _Ximp_ctstowcs;
    }
    return &imm;
}


static void DestroyIC(XIC);
static void SetFocus(XIC);
static void UnSetFocus(XIC);
static char *MbReset(XIC);
static wchar_t *WcReset(XIC);
extern char *IIIMP_SetICValues(XIC, XIMArg *);
extern char *IIIMP_GetICValues(XIC, XIMArg *);
static int MbLookupString(XIC, XKeyEvent *,
			  char *, int,
			  KeySym *, Status *);
static int WcLookupString(XIC, XKeyEvent *,
			  wchar_t *, int,
			  KeySym *, Status *);

static XICMethods
get_switch_ic_methods()
{
    static XICMethodsRec icm;

    if (!icm.destroy) {
	icm.destroy = DestroyIC;
	icm.set_focus = SetFocus;
	icm.unset_focus = UnSetFocus;
	icm.set_values = IIIMP_SetICValues;
	icm.get_values = IIIMP_GetICValues;
	icm.mb_reset = MbReset;
	icm.wc_reset = WcReset;
	icm.mb_lookup_string = MbLookupString;
	icm.wc_lookup_string = WcLookupString;
    }
    return &icm;
}

XIM
_SwitchOpenIM(
    XLCd lcd,
    Display *dpy,
    XrmDatabase rdb,
    char *res_name,
    char *res_class
)
{
    XimCommon im = 0;
    char *disableMultiScriptIM = getenv("DISABLE_MULTI_SCRIPT_IM");

    if (disableMultiScriptIM &&
	!strcmp("true", disableMultiScriptIM)) return 0; /* hidden feature */

    im = Xmalloc(sizeof(XimCommonRec));
    if (!im) goto Error;
    memset(im, 0, sizeof(XimCommonRec));

    if (!CommonOpenIM((XIM)im, lcd, dpy, rdb, res_name, res_class))
	goto Error;

    im->methods = get_switch_im_methods();

    if (!im_switcher_active(im))
      if (!COMPOSE_OpenIM_SWITCH((XIM)im, lcd)) goto Error;

    if (!IIIMP_OpenIM_SWITCH((XIM)im, lcd, dpy)) goto Error;

    return (XIM)im;

Error:
    if (im) Xfree(im);
    return 0;
}

static Status
SwitchCloseIM(
    XIM xim
)
{
    XimCommon im = (XimCommon)xim;

    XIM_COMPOSE(im, switch_methods)->close(xim);
    XIM_IIIMP(im, switch_methods)->close(xim);

    CommonCloseIM((XIM)im);

    return True;
}

void
RegisterSwitchFilter(
    XicCommon ic, 
    SwitchKeyEventProc is_switch_key,
    XFilterEventProc key_filter,
    XICMethods ic_methods
)
{
    SwitchFilterEventRec *rec;

    rec = (SwitchFilterEventList)Xmalloc(sizeof(SwitchFilterEventRec));
    if (!rec)
	return;
    rec->is_switch_key = is_switch_key;
    rec->key_filter = key_filter;
    rec->ic_methods = ic_methods;
    rec->next = ic->switch_filters;
    ic->switch_filters = rec;
    return;
}

void
UnRegisterSwitchFilter(
    XicCommon ic, 
    SwitchKeyEventProc is_switch_key,
    XFilterEventProc key_filter,
    XICMethods ic_methods
)
{
    SwitchFilterEventList *prev, fl;

    for (prev = &ic->switch_filters; (fl = *prev) != NULL; ) {
	if (fl->is_switch_key == is_switch_key &&
	    fl->key_filter == key_filter && fl->ic_methods == ic_methods) {
	    *prev = fl->next;
	    Xfree((char *)fl);
	} else
	    prev = &fl->next;
    }
    return;
}

void
ResetSwitchFilter(
    XicCommon ic
)
{
    extern Bool Ximp_Local_KeyFilter(Display *, Window, XEvent*, XPointer);

    ic->active_filter = Ximp_Local_KeyFilter; /* default */
    ic->active_methods = get_local_ic_methods();
    return;
}

/*
  ALLOW_SWITCH_FROM_REMOTE_TO_LOCAL is a bad idea, but for now as
  a quick solution to disable switching from a remote language engine
  to a local input mode, I have to put these codes..
  (by toshi with deepest regrets)
*/
  
static Bool
Switch_KeyFilter(
    Display *d /*unused*/,
    Window w /* unused */,
    XEvent *ev,
    XPointer client_data
)
{
    XicCommon ic = (XicCommon)client_data;
    SwitchFilterEventList filter;
    SwitchMode mode;
#ifndef ALLOW_SWITCH_FROM_REMOTE_TO_LOCAL
    Bool IIIMP_Local_KeyFilter(Display *d /*unused*/,
			       Window w /* unused */,
			       XEvent *ev, XPointer client_data);
#endif

    if (im_switcher_active((XimCommon)ic->core.im))
      return IIIMP_Local_KeyFilter (d, w, ev, client_data);

    for (filter = ic->switch_filters; filter; filter = filter->next) {
	if (ev->type == KeyPress)
	    mode = filter->is_switch_key(ic, ev);
	else
	    mode = Switch_NOP;
	switch (mode) {
	  case Switch_ON:
	   if (filter->next && filter->next->is_switch_key(ic, ev) == Switch_ON) {
	       /* If this key is used for the next filter too, give way 
		  to the next */
	       ic->active_filter = filter->next->key_filter;
	       ic->active_methods = filter->next->ic_methods;
	   } else {
	       ic->active_filter = filter->key_filter;
	       ic->active_methods = filter->ic_methods;
	   }
	   goto call_filter;
	  case Switch_OFF:
	   if (ic->active_filter) {
	       /* Before turn off active filter, pass the event to the
		  handler because it may need to process the event to
		  finalize operations.  */
	       ic->active_filter(d, w, ev, client_data);
	   }
	   ResetSwitchFilter(ic);
	   goto call_filter;
	  case Switch_NOP:
	  default:
#ifndef ALLOW_SWITCH_FROM_REMOTE_TO_LOCAL
	   if (ic->active_filter == IIIMP_Local_KeyFilter)
	       goto call_filter;
#endif
	   break;
	}
    }
call_filter:
    if (!ic->active_filter) {
	ResetSwitchFilter(ic);
    }
    return ic->active_filter(d, w, ev, client_data);
}

static XIC
SwitchCreateIC(
    XIM xim,
    XIMArg * arg
)
{
    XicCommon ic = 0;
    ic = Xmalloc(sizeof(XicCommonRec));
    if (!ic) goto Error;;
    memset(ic, 0, sizeof(XicCommonRec));

    ic->core.im = xim;
    ic->methods = get_switch_ic_methods();

    if (!CommonCreateIC((XIC)ic, arg)) goto Error;
    
    if (!im_switcher_active((XimCommon)ic->core.im))
      if (!COMPOSE_CreateIC_SWITCH((XIC)ic, arg)) goto Error;
    if (!IIIMP_CreateIC_SWITCH((XIC)ic, arg)) goto Error;

    ic->core.filter_events = KeyPressMask;

    ResetSwitchFilter(ic);

    return (XIC)ic;
Error:
    if (ic) Xfree(ic);
    return 0;
}

static void
DestroyIC(
    XIC xic
)
{
    XicCommon ic = (XicCommon)xic;

    _XUnregisterFilter(ic->core.im->core.display, ic->core.focus_window,
		       Switch_KeyFilter, (XPointer)ic);

    IIimpDestroryAuxData(ic);

    if (ic->local_icpart)
      XIC_COMPOSE(ic, switch_methods)->destroy(xic);
    XIC_IIIMP(ic, switch_methods)->destroy(xic);

    CommonDestroyIC(xic);

    return;
}

static void
SetFocus(
    XIC xic
)
{
    XicCommon ic = (XicCommon)xic;

    _XRegisterFilterByType(ic->core.im->core.display, ic->core.focus_window,
			   KeyPress, KeyRelease,
			   Switch_KeyFilter, (XPointer)ic);
    ic->active_methods->set_focus(xic);
  
    return;
}

static void
UnSetFocus(
    XIC xic
)
{
    XicCommon ic = (XicCommon)xic;

    ic->active_methods->unset_focus(xic);
  
    return;
}

static char*
MbReset(
    XIC xic
)
{
    XicCommon ic = (XicCommon)xic;

    _XUnregisterFilter(ic->core.im->core.display, ic->core.focus_window,
		       Switch_KeyFilter, (XPointer)ic);
    return ic->active_methods->mb_reset(xic);
}

static wchar_t*
WcReset(
    XIC xic
)
{
    XicCommon ic = (XicCommon)xic;

    _XUnregisterFilter(ic->core.im->core.display, ic->core.focus_window,
		       Switch_KeyFilter, (XPointer)ic);
    return ic->active_methods->wc_reset(xic);
}

static int
MbLookupString(
    XIC xic,
    XKeyEvent *ev,
    char * buffer,
    int bytes,
    KeySym *keysym,
    Status *status
)
{
    XicCommon ic = (XicCommon)xic;
    int ret;

    ret = IIIMP_MbLookupString_SWITCH(xic, ev, buffer, bytes, keysym, status);
    if (0 < ret) {
	return ret;
    }

    return ic->active_methods->mb_lookup_string(xic,
						ev, buffer,
						bytes, keysym,
						status);
}

static int
WcLookupString(
    XIC xic,
    XKeyEvent *ev,
    wchar_t * buffer, 
    int wlen,
    KeySym *keysym,
    Status *status
)
{
    XicCommon ic = (XicCommon)xic;
    int ret;
    ret = IIIMP_WcLookupString_SWITCH(xic, ev, buffer, wlen, keysym, status);
    if (0 < ret) {
	return ret;
    }
    return ic->active_methods->wc_lookup_string(xic,
						ev, buffer,
						wlen, keysym,
						status);
}
      
void
SwitchUpdateStatus(
    XicCommon ic
)
{
    if (XIM_IS_SWITCH(ic->core.im) &&
	(ic->active_methods == get_local_ic_methods()) &&
	(None != ic->core.client_window)) {
	Ximp_Local_Status_Set(ic);
	Ximp_Local_Status_Start(ic);
	Ximp_Local_Status_Draw(ic);
    }
    return;
}

void
SwitchKeyEventFilter(
    XicCommon ic,
    Window old_focus
)
{
    _XUnregisterFilter(ic->core.im->core.display, old_focus,
		       Switch_KeyFilter, (XPointer)ic);
    _XRegisterFilterByType(ic->core.im->core.display, ic->core.focus_window,
			   KeyPress, KeyRelease,
			   Switch_KeyFilter, (XPointer)ic);
    return;
}

/* Local Variables: */
/* c-file-style: "iiim-project" */
/* End: */
