/*
Copyright 1985, 1986, 1987, 1991, 1998  The Open Group

Portions Copyright 2000 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

#ifndef __XLIBINT_HH
#define __XLIBINT_HH
#include <X11/Xlibint.h>
#endif /* __XLIBINT_HH */
#include "Xlcint.h"
#include "XIM.h"
#include "switchIM.h"
#include "iiimpIM.h"
#include "genutil.h"
#include <locale.h>
#include <langinfo.h>

static int
getXIMArg(XIMArg *arg,
	  char *name, void *value) {
  XIMArg *p;

  for (p = arg; p->name != 0; p++) {
    if (!strcmp(p->name, XNMultiLingualInput)) {
      *((Bool*)value) = (Bool)p->value;
      return 0;
    }
  }
  return -1;
}

#define NAME_LEN 20
XIM
__XOpenIM(Display *display, XrmDatabase rdb,
	  char *res_name, char *res_class,
	  XIMArg *arg) {
  Bool isMultilingual = False;
  XIM xim = (XIM)0;
  XOpenIMProc open_im;
  XLCd lcd = 0;
  char *current_locale = 0;

  (void)getXIMArg(arg,
		  XNMultiLingualInput, &isMultilingual);
  open_im = isMultilingual? _SwitchOpenIM : _IIIMP_OpenIM ;
  if (isMultilingual)
    putenv("DISABLE_MULTI_SCRIPT_IM=false"); /* hidden feature */

  current_locale = (char*)strdup(setlocale(LC_CTYPE, NULL));

  lcd = _XOpenLC((char*)NULL);

  /* try first with the current locale */
  if (strcmp(nl_langinfo(CODESET), "UTF-8") == 0) {
    if (lcd) {
      xim = open_im((XLCd)lcd, display, rdb, res_name, res_class);
      if (xim) {
	((XimCommon)xim)->isUnicode = isMultilingual;
	goto Ret;
      }
    }
  }

  /* pick an UTF-8 locale best matching for the lang part of
     the current locale */
  if (lcd) {
    char new_locale[NAME_LEN];
    char *language, *territory;
    char *codeset;
    XLCd new_lcd;

    _XGetLCValues(lcd, XlcNLanguage,  &language,
		  XlcNTerritory, &territory,
		  XlcNCodeset,   &codeset,
		  (char*)NULL);
    _genutil_strlcpy(new_locale, language, NAME_LEN);

    if (territory && *territory) {
      _genutil_strlcat(new_locale, "_", NAME_LEN);
      _genutil_strlcat(new_locale, territory, NAME_LEN);
    }
    _genutil_strlcat(new_locale, ".UTF-8", NAME_LEN);
    new_lcd = _XOpenLC(new_locale);
    if (new_lcd) {
      xim = open_im((XLCd)new_lcd, display, rdb, res_name, res_class);
      if (xim) {
	_XCloseLC(lcd);		/* no more need */
	((XimCommon)xim)->isUnicode = isMultilingual;
	goto Ret;
      }
      _XCloseLC(new_lcd);
      new_lcd = 0;
    }
    if (!territory || !*territory) {
      /* get territory name from current locale */
      char *p = index(current_locale, '_');
      if (p &&strlen(p) >= 2) {
	territory = p + 1; territory[2] = 0;

	_genutil_strlcpy(new_locale, language, NAME_LEN);
	_genutil_strlcat(new_locale, "_", NAME_LEN);
	_genutil_strlcat(new_locale, territory, NAME_LEN);
	_genutil_strlcat(new_locale, ".UTF-8", NAME_LEN);

	new_lcd = _XOpenLC(new_locale);
	if (new_lcd) {
	  xim = open_im((XLCd)new_lcd, display, rdb, res_name, res_class);
	  if (xim) {
	    _XCloseLC(lcd);	/* no more need */
	    ((XimCommon)xim)->isUnicode = isMultilingual;
	    goto Ret;
	  }
	  _XCloseLC(new_lcd);
	  new_lcd = 0;
	}
      }
    }
  }

Ret:
  Xfree(current_locale);
  return xim;
}

/********************************************************************************
                              XIM callback
 ********************************************************************************/
/******************************************************************

           Copyright 1993, 1994 by Sony Corporation

Permission to use, copy, modify, distribute, and sell this software
and its documentation for any purpose is hereby granted without fee,
provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear
in supporting documentation, and that the name of Sony Corporation
 not be used in advertising or publicity pertaining to distribution
 of the software without specific, written prior permission.
Sony Corporation makes no representations about the suitability of
 this software for any purpose. It is provided "as is" without
 express or implied warranty.

SONY CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL SONY CORPORATION BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

  Author:   Makoto Wakamatsu   Sony Corporation
                               makoto@sm.sony.co.jp

******************************************************************/

typedef struct _XimInstCallback {
    Bool			 call;
    Bool			 destroy;
    Display			*display;
    XLCd			 lcd;
    char			 name[NAME_LEN];
    char			*modifiers;
    XrmDatabase			 rdb;
    char			*res_name;
    char			*res_class;
    XIDProc			 callback;
    XPointer			 client_data;
    struct _XimInstCallback	*next;
} XimInstCallbackRec, *XimInstCallback;


static XimInstCallback	callback_list	= NULL;
static Bool		lock		= False;


static void
MakeLocale(XLCd lcd, char locale[])
{
  char	*language, *territory, *codeset;

  _XGetLCValues(lcd, XlcNLanguage, &language,
		XlcNTerritory, &territory,
		XlcNCodeset, &codeset, NULL);

  _genutil_strlcpy(locale, language, NAME_LEN);
  if (territory && *territory) {
    _genutil_strlcat(locale, "_", NAME_LEN);
    _genutil_strlcat(locale, territory, NAME_LEN);
  }
  if (codeset && *codeset) {
    _genutil_strlcat(locale, ".", NAME_LEN);
    _genutil_strlcat(locale, codeset, NAME_LEN);
  }
}


static Bool
_XimFilterPropertyNotify(Display *display,
			 Window window,
			 XEvent *event,
			 XPointer client_data)
{
#if 0
    Atom		ims, actual_type, *atoms;
    int			actual_format;
    unsigned long	nitems, bytes_after;
    Window		ims_window;
    int			ii;
    XIM			xim;
    Bool		flag = False;
    XimInstCallback	icb, picb, tmp;

    if( (ims = XInternAtom( display, XIM_SERVERS, True )) == None  ||
	event->xproperty.atom != ims  ||
	event->xproperty.state == PropertyDelete )
	return( False );

    if( XGetWindowProperty( display, RootWindow(display, 0), ims, 0L, 1000000L,
			    False, XA_ATOM, &actual_type, &actual_format,
			    &nitems, &bytes_after, (unsigned char **)&atoms )
	    != Success ) {
	return( False );
    }
    if( actual_type != XA_ATOM  ||  actual_format != 32 ) {
	XFree( atoms );
	return( False );
    }

    lock = True;
    for( ii = 0; ii < nitems; ii++, atoms ) {
	if((ims_window = XGetSelectionOwner (display, atoms[ii]))) {
	    for( icb = callback_list; icb; icb = icb->next ) {
		if( !icb->call  &&  !icb->destroy ) {
		    xim = (*icb->lcd->methods->open_im)( icb->lcd, display,
							 icb->rdb,
							 icb->res_name,
							 icb->res_class );
		    if( xim ) {
			xim->methods->close( (XIM)xim );
			flag = True;
			icb->call = True;
			icb->callback( icb->display, icb->client_data, NULL );
		    }
		}
	    }
	    break;
	}
    }
    XFree( atoms );

    for( icb = callback_list, picb = NULL; icb; ) {
	if( icb->destroy ) {
	    if( picb )
		picb->next = icb->next;
	    else
		callback_list = icb->next;
	    tmp = icb;
	    icb = icb->next;
	    XFree( tmp );
	}
	else {
	    picb = icb;
	    icb = icb->next;
	}
    }
    lock = False;

    return( flag );
#else
    return False;
#endif
}


Bool
_XimRegisterIMInstantiateCallback(
    XLCd	 lcd,
    Display	*display,
    XrmDatabase	 rdb,
    char	*res_name,
    char	*res_class,
    XIDProc	 callback,
    XPointer	 client_data)
{
    XimInstCallback	icb, tmp;
    XIM			xim;
    Window		root;
    XWindowAttributes	attr;

    if( lock )
	return( False );

    icb = (XimInstCallback)Xmalloc(sizeof(XimInstCallbackRec));
    if( !icb )
	return( False );
    icb->call = icb->destroy = False;
    icb->display = display;
    icb->lcd = lcd;
    MakeLocale( lcd, icb->name );
    icb->modifiers = lcd->core->modifiers;	/* XXXXX */
    icb->rdb = rdb;
    icb->res_name = res_name;
    icb->res_class = res_class;
    icb->callback = callback;
    icb->client_data = client_data;
    icb->next = NULL;

    if( !callback_list )
	callback_list = icb;
    else {
	for( tmp = callback_list; tmp->next; tmp = tmp->next );
	tmp->next = icb;
    }

    xim = (*lcd->methods->open_im)( lcd, display, rdb, res_name, res_class );

    if( icb == callback_list ) {
	root = RootWindow( display, 0 );
	XGetWindowAttributes( display, root, &attr );
	_XRegisterFilterByType( display, root, PropertyNotify, PropertyNotify,
				_XimFilterPropertyNotify, (XPointer)NULL );
	XSelectInput( display, root,
		      attr.your_event_mask | PropertyChangeMask );
    }

    if( xim ) {
	lock = True;
	xim->methods->close( (XIM)xim );
	lock = False;
	icb->call = True;
	callback( display, client_data, NULL );
    }

    return( True );
}


Bool
_XimUnRegisterIMInstantiateCallback(
    XLCd	 lcd,
    Display	*display,
    XrmDatabase	 rdb,
    char	*res_name,
    char	*res_class,
    XIDProc	 callback,
    XPointer	 client_data)
{
    char locale[NAME_LEN];
    XimInstCallback	icb, picb;

    if (!callback_list)
	return False;

    MakeLocale( lcd, locale );

    for( icb = callback_list, picb = NULL; icb; picb = icb, icb = icb->next ) {
	if( !strcmp( locale, icb->name )  &&
	    (lcd->core->modifiers == icb->modifiers  ||		/* XXXXX */
	     (lcd->core->modifiers  &&  icb->modifiers  &&
	      !strcmp( lcd->core->modifiers, icb->modifiers )))  &&
	    rdb == icb->rdb  &&					/* XXXXX */
	    ((res_name == NULL  &&  icb->res_name == NULL)  ||
	     (res_name != NULL  &&  icb->res_name != NULL  &&
	      !strcmp( res_name, icb->res_name )))  &&
	    ((res_class == NULL  &&  icb->res_class == NULL)  ||
	     (res_class != NULL  &&  icb->res_class != NULL  &&
	      !strcmp( res_class, icb->res_class )))  &&
	    callback == icb->callback  &&
	    client_data  ==  icb->client_data  &&		/* XXXXX */
	    !icb->destroy ) {
	    if( lock )
		icb->destroy = True;
	    else {
		if( !picb ) {
		    callback_list = icb->next;
		    _XUnregisterFilter( display, RootWindow(display, 0),
					_XimFilterPropertyNotify,
					(XPointer)NULL );
		    XSelectInput( display, RootWindow(display, 0),
				  NoEventMask );
		}
		else
		    picb->next = icb->next;
		_XCloseLC( icb->lcd );
		XFree( icb );
	    }
	    return( True );
	}
    }
    return( False );
}

void
_XimResetIMInstantiateCallback(XIM xim)
{
    char		 locale[NAME_LEN];
    XimInstCallback	 icb;
    XLCd	 	 lcd = xim->core.lcd;

    if( !callback_list  &&  lock )
	return;

    MakeLocale( lcd, locale );

    for( icb = callback_list; icb; icb = icb->next )
	if( !strcmp( locale, icb->name )  &&
	    (lcd->core->modifiers == icb->modifiers  ||
	     (lcd->core->modifiers  &&  icb->modifiers  &&
	      !strcmp( lcd->core->modifiers, icb->modifiers ))) )
	    icb->call = False;
}
