/*
Copyright 1999-2004 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.

*/

/* my_stpcpy is a copy of g_stpcpy() from glib-2, hence
   glib-2 copyright is included here.
   	Commentted by Hidetoshi Tajima <hidetoshi.tajima@sun.com>
 */

/* GLIB - Library of useful routines for C programming
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/*
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
 * file for a list of people on the GLib Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GLib at ftp://ftp.gtk.org/pub/gtk/. 
 */

#include "iiimpIM.h"
#include "iiimpSwitcher.h"

struct _SwitcherInfo
{
  Window switcher_window;
  Atom  selection_atom;
  Atom  set_current_input_language_atom;
  Atom  set_current_client_atom;
  Atom  set_status_text_atom;
  Atom  set_input_language_list_atom;
  Atom  set_conversion_mode_atom;
};

/* A listener window for input method switcher */
struct _SwitcherContext
{
  Window invisible;
};

static Atom selection = None;

/**
 * my_stpcpy: 
 * @dest: destination buffer.
 * @src: source string.
 * 
 * Copies a nul-terminated string into the dest buffer, include the
 * trailing nul, and return a pointer to the trailing nul byte.
 * This is useful for concatenating multiple strings together
 * without having to repeatedly scan for the end.
 * 
 * Return value: a pointer to trailing nul byte.
 **/
char *
my_stpcpy (char *dest, const char *src)
{
  if (dest == NULL || src == NULL)
    return NULL;
#ifdef HAVE_STPCPY
  return stpcpy (dest, src);
#else
  register char *d = dest;
  register const char *s = src;

  do
    *d++ = *s;
  while (*s++ != '\0');

  return d - 1;
#endif
}

Bool
im_switcher_active (XimCommon im)
{
  SwitcherInfo *sw_info = im->switcher_info;

  return (sw_info && (sw_info->switcher_window));
}

static Bool
filter_destroy_event(Display *d, Window w, XEvent *ev,
		     XPointer client_data)
{
  XimCommon im = (XimCommon)client_data;
  SwitcherInfo *sw_info = im->switcher_info;

  if (sw_info && sw_info->switcher_window == w)
    {
      sw_info->switcher_window = None;
      Xfree (sw_info);
      im->switcher_info = NULL;
      return True;
    }
  return False;
}

Bool
im_switcher_new (XimCommon im)
{
  Display *display = im->core.display;
  SwitcherInfo *sw_info = im->switcher_info;
  Window owner = None;

  if (sw_info == NULL)
    {
      sw_info = Xmalloc (sizeof(SwitcherInfo));
      if (sw_info == NULL)
	return False;
      memset(sw_info, 0, sizeof(SwitcherInfo));
      im->switcher_info = sw_info;
    }

  if (selection == None)
    selection  = XInternAtom (display, "_IIIM_SWITCHER", False);

  sw_info->selection_atom = selection;

  owner = XGetSelectionOwner (display, selection);
  if (owner == None)
    return False;

  sw_info->switcher_window = owner;

  _XRegisterFilterByType (display, owner,
			  DestroyNotify, DestroyNotify,
			  filter_destroy_event, (XPointer)im);

  XSelectInput (display, owner, StructureNotifyMask);

  sw_info->set_current_input_language_atom
    = XInternAtom (display, "_IIIM_SWITCHER_CURRENT_INPUT_LANGUAGE", False);

  sw_info->set_current_client_atom =
    XInternAtom (display, "_IIIM_SWITCHER_CURRENT_CLIENT", False);

  sw_info->set_status_text_atom =
    XInternAtom (display, "_IIIM_SWITCHER_STATUS_TEXT", False);

  sw_info->set_input_language_list_atom =
    XInternAtom (display, "_IIIM_SWITCHER_INPUT_LANGUAGE_LIST", False);

  sw_info->set_conversion_mode_atom = 
    XInternAtom (display, "_IIIM_SWITCHER_SET_CONVERSION_MODE", False);

  return True;
}

void
im_switcher_shutdown (XimCommon im)
{
  SwitcherInfo *sw_info = im->switcher_info;
  Display *display = im->core.display;

  if (sw_info && sw_info->switcher_window)
    _XUnregisterFilter (display, sw_info->switcher_window,
			filter_destroy_event, (XPointer)im);
}

static Bool
property_notify_switcher_window(Display *d, Window w, XEvent *ev,
				XPointer client_data)
{
  XicCommon ic = (XicCommon)client_data;
  XimCommon im = (XimCommon)ic->core.im;
  Atom type;
  unsigned char *data = NULL;
  int format;
  unsigned long length = 0, bytes_after;
  Display *display = ic->core.im->core.display;
  SwitcherInfo *sw_info = im->switcher_info;

  if (ev->xproperty.atom == sw_info->set_current_input_language_atom)
    {
      XGetWindowProperty(display, w, ev->xproperty.atom, 0L, 1000000L,
			 False, AnyPropertyType, &type, &format,
			 &length, &bytes_after, (unsigned char **)&data);
      ic_initialize_with_input_language (ic, data);
      Xfree (data);
      return True;
    }
  if (ev->xproperty.atom == sw_info->set_conversion_mode_atom)
    {
      XGetWindowProperty(display, w, ev->xproperty.atom, 0L, 1000000L,
			 False, AnyPropertyType, &type, &format,
			 &length, &bytes_after, (unsigned char **)&data);
      ic_change_conversion_mode (ic, data);
      Xfree (data);
      return True;
    }
  return False;
}

static Bool
destroy_switcher_window(Display *d, Window window, XEvent *ev,
			XPointer client_data)
{
  XicCommon ic = (XicCommon)client_data;
  SwitcherContext *w = ic->switcher_context;

  if (!w)
    return False;
  XDestroyWindow (d, w->invisible);
  Xfree (w);
  ic->switcher_context = NULL;
  return False;
}

void
ic_switcher_new (XicCommon ic)
{
  SwitcherContext *w = Xmalloc(sizeof(SwitcherContext));
  XimCommon im = (XimCommon)ic->core.im;
  Display *display = im->core.display;

  if (w == NULL)
    return;

  memset(w, 0, sizeof(SwitcherContext));

  w->invisible = XCreateSimpleWindow(display, DefaultRootWindow(display),
				     0, 0, 1, 1, 0, 0, 0);
  XSelectInput(display, w->invisible,
	       PropertyChangeMask| StructureNotifyMask);

  _XRegisterFilterByType(display, w->invisible,
			 PropertyNotify, PropertyNotify,
			 property_notify_switcher_window, (XPointer)ic);
  _XRegisterFilterByType(display, w->invisible,
			 DestroyNotify, DestroyNotify,
			 destroy_switcher_window, (XPointer)ic);
  ic->switcher_context = w;
}

void
ic_switcher_finalize (XicCommon ic)
{
  SwitcherContext *w = ic->switcher_context;
  XimCommon im = (XimCommon)ic->core.im;
  Display *display = im->core.display;

  if (w == NULL)
    return;

  _XUnregisterFilter(display, w->invisible,
		     property_notify_switcher_window, (XPointer)ic);
  _XUnregisterFilter(display, w->invisible,
		     destroy_switcher_window, (XPointer)ic);

  XDestroyWindow (display, w->invisible);

  Xfree (w);
  ic->switcher_context = NULL;
  return;

}

void
ic_switcher_set_language_list (XicCommon ic,
			       IIIMCF_language *lang_list,
			       int n_lang)
{
  Display *display = ic->core.im->core.display;
  XimCommon im = (XimCommon)ic->core.im;
  SwitcherInfo *sw_info = im->switcher_info;
  char *languages;
  char *ptr;
  IIIMF_status st;
  char *langid;
  int i;
  size_t len;
  const char *separator = ";";
  size_t separator_len;

  if (sw_info == NULL)
    return;

  if (lang_list == NULL || n_lang == 0)
    return;

  if (sw_info->switcher_window == None)
    return;

  /* First part, getting length */
  st = iiimcf_get_language_id (lang_list[0],
			       (const char **) &langid);
  if (st != IIIMF_STATUS_SUCCESS)
    return;

  separator_len = strlen (separator);
  len = strlen (langid);
  for (i = 1; i < n_lang; i++)
    {
      st = iiimcf_get_language_id (lang_list[i],
				   (const char **) &langid);
      if (st != IIIMF_STATUS_SUCCESS)
	continue;
      len += strlen (langid);
    }
  len += separator_len * (i - 1);

  /* Second part, building string */
  languages = Xmalloc (sizeof(char) * (len + 1));
  if (languages == NULL)
    return;
  memset(languages, 0, sizeof(char) * (len + 1));

  st = iiimcf_get_language_id (lang_list[0],
			       (const char **) &langid);
  ptr = my_stpcpy (languages, langid);
  for (i = 1; i < n_lang; i++)
    {
      ptr = my_stpcpy (ptr, separator);
      st = iiimcf_get_language_id (lang_list[i],
				   (const char **) &langid);
      if (st != IIIMF_STATUS_SUCCESS)
	continue;
      ptr = my_stpcpy (ptr, langid);
    }

  XChangeProperty (display, sw_info->switcher_window,
		   sw_info->set_input_language_list_atom,
		   sw_info->set_input_language_list_atom,
		   8,
		   PropModeReplace,
		   (unsigned char*)languages, len);
  Xfree (languages);
}

void
ic_switcher_set_status_text (XicCommon ic, char *utf8)
{
  Display *display = ic->core.im->core.display;
  XimCommon im = (XimCommon)ic->core.im;
  SwitcherInfo *sw_info = im->switcher_info;

  if (sw_info == NULL || sw_info->switcher_window == None ||
      utf8 == NULL)
    return;

  XChangeProperty (display,
		   sw_info->switcher_window,
		   sw_info->set_status_text_atom,
		   sw_info->set_status_text_atom,
		   8,
		   PropModeReplace,
		   (unsigned char *)utf8,
		   strlen (utf8));
}

void
ic_switcher_set_focus (XicCommon ic)
{
  Display *display = ic->core.im->core.display;
  XimCommon im = (XimCommon)ic->core.im;
  SwitcherInfo *sw_info;
  SwitcherContext *w;

  if (!im_switcher_active (im))
    {
      im_switcher_new (im);
      if (!im_switcher_active (im))
	return;
    }

  if (ic->switcher_context == NULL)
    ic_switcher_new (ic);

  w = ic->switcher_context;
  sw_info = im->switcher_info;

  if (w && w->invisible)
    XConvertSelection (display,
		       sw_info->selection_atom,
		       sw_info->set_current_client_atom,
		       sw_info->set_current_client_atom,
		       w->invisible,
		       CurrentTime);
}

void
ic_switcher_set_input_language (XicCommon ic, char *input_lang)
{
  Display *display = ic->core.im->core.display;
  XimCommon im = (XimCommon)ic->core.im;
  SwitcherInfo *sw_info = im->switcher_info;

  if (sw_info == NULL)
    return;

  if (input_lang == NULL)
    input_lang = ic->current_language;

  if (input_lang == NULL)
    return;

  XChangeProperty (display,
		   sw_info->switcher_window,
		   sw_info->set_current_input_language_atom,
		   sw_info->set_current_input_language_atom,
		   8,
		   PropModeReplace,
		   (unsigned char *)input_lang,
		   strlen (input_lang));
}

void
ic_switcher_set_conversion_mode (XicCommon ic)
{
  Display *display = ic->core.im->core.display;
  XimCommon im = (XimCommon)ic->core.im;
  SwitcherInfo *sw_info = im->switcher_info;
  IIIMF_status st;
  int conversion_mode = CONV_OFF;

  if (sw_info == NULL || sw_info->switcher_window == None)
    return;

  st = iiimcf_get_current_conversion_mode (XIC_IIIMP(ic, context),
					   &conversion_mode);
  XChangeProperty (display,
		   sw_info->switcher_window,
		   sw_info->set_conversion_mode_atom,
		   sw_info->set_conversion_mode_atom,
		   32,
		   PropModeReplace,
		   (unsigned char *)&conversion_mode,
		   1);
}
