/*
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 "xiiimp.h"
#include "guiIM.h"
#include "composeIM.h"
#include "tableinput.h"
#include "lookup.h"
#include "xfactory.h"

static int
findLUIndex(LuRange *range, int size, int ch) {
  int i;

  for (i = 0; i < size; i++) {
    if (range[i].RangeName[0] == ch) {
      return(i);
    }
  }
  return -1;
}

static Bool
selectLURange(XicCommon ic, int idx) {
  LocalTableExt *hook = (LocalTableExt *)(ic->local_icpart->table_ext);
  LocalLookupExt *hook2;

  if (idx < 0 || idx > hook->nrange) return False;

  Ximp_Local_Lookup_Start(ic);
  hook2 = (LocalLookupExt*)(ic->local_icpart->lookup_ext);
  hook2->range = hook->range;
  hook2->begin_range = hook->range[idx].start_range;
  hook2->startindex = hook->range[idx].start_range;
  hook2->end_range = hook->range[idx].end_range;
  hook2->crange = idx;
  hook2->currentindex = 0;
  Ximp_Local_Lookup_Draw(ic);

  XUnmapWindow(ic->core.im->core.display, hook->window);
  return True;
}

static Bool
FilterKeyPress(Display *d, Window w, XEvent *ev, XPointer client_data) {
  XicCommon ic = (XicCommon)client_data;
  LocalTableExt *hook = (LocalTableExt *)(ic->local_icpart->table_ext);
  KeySym ks;
  int idx;

  if (ev->type != KeyPress) return False;
  if (!hook || !hook->window ||
      !hook->range || !hook->fontset || !hook->gc) return False;
  
  ks = XKeycodeToKeysym(d, ev->xkey.keycode, 0);
  idx = findLUIndex(hook->range, hook->nrange, (int)ks);

  return selectLURange(ic, idx);
}
static Bool
RepaintTable(Display *d, Window w, XEvent *ev, XPointer client_data) {
  XicCommon ic = (XicCommon)client_data;
  LocalTableExt *hook = (LocalTableExt *)(ic->local_icpart->table_ext);
  int i, ypos;

  if (!hook || !hook->range || !hook->fontset || !hook->gc) return False;

  for (i = 0; i < hook->nrange; i++) {
    ypos = (i+1) * hook->theight;
    XmbDrawString(d, w, hook->fontset, hook->gc, 0, ypos,
		  hook->range[i].RangeName,
		  strlen(hook->range[i].RangeName));
  }
  return(True);
}

#define xMargin 4
#define yMargin 4
static Bool
FilterMotionNotify(Display *d, Window w, XEvent *ev, XPointer client_data) {
  XicCommon ic = (XicCommon)client_data;
  LocalTableExt *hook = (LocalTableExt *)(ic->local_icpart->table_ext);
  int y;
  static int oy = -1;

  if (ev->type != MotionNotify) return False;

  if (!hook || !hook->window ||
      !hook->range || !hook->fontset || !hook->gc) return False;

  y = (int)((int)(ev->xmotion.y/hook->theight)*hook->theight);
  if (y != oy) {
    if (oy != -1) {
      y += yMargin;
      XDrawRectangle(d, w, hook->rgc, 0, oy, hook->rect.width, hook->theight);
    }
    XDrawRectangle(d, w, hook->gc, 0, y, hook->rect.width, hook->theight);
    oy = y;
  }
  return True;
}

static Bool
FilterButtonRelease(Display *d, Window w, XEvent *ev, XPointer client_data) {
  XicCommon ic = (XicCommon)client_data;
  LocalTableExt *hook = (LocalTableExt *)(ic->local_icpart->table_ext);
  int idx;

  if (ev->type != ButtonRelease) return False;

  if (!hook || !hook->window ||
      !hook->range || !hook->fontset || !hook->gc) return False;

  if (ev->xbutton.x < 0 || ev->xbutton.x > hook->rect.width ||
      ev->xbutton.y < 0 || ev->xbutton.y > hook->rect.height)
    return False;

  idx = (int)(ev->xbutton.y/hook->theight);

  return selectLURange(ic, idx);
}

static Window
setup_table_window(XicCommon ic) {
  LocalTableExt *hook = (LocalTableExt *)(ic->local_icpart->table_ext);
  XWindowAttributes attr;
  Display *display = ic->core.im->core.display;
  Window parent, win;
  unsigned long fg, bg;
  unsigned long val_mask;
  XGCValues gcval;
  XIMFilterRec filters[4];
  short x, y;
  unsigned short width, height;

  XGetWindowAttributes(display, 
		       ic->core.client_window,
		       &attr);
  parent = RootWindow(display, XScreenNumberOfScreen(attr.screen));

  if (XIMP_CHK_PREBGMASK(ic)) 
    bg = ic->core.preedit_attr.background;
  else
    bg = WhitePixel(display, XScreenNumberOfScreen(attr.screen));

  if (XIMP_CHK_PREFGMASK(ic))
    fg = ic->core.preedit_attr.foreground;
  else
    fg = BlackPixel(display, XScreenNumberOfScreen(attr.screen));

  filters[0].type = KeyPress;
  filters[0].filter = FilterKeyPress;
  filters[0].client_data = (XPointer)ic;
  filters[1].type = Expose;
  filters[1].filter = RepaintTable;
  filters[1].client_data = (XPointer)ic;
  filters[2].type = MotionNotify;
  filters[2].filter = FilterMotionNotify;
  filters[2].client_data = (XPointer)ic;
  filters[3].type = ButtonRelease;
  filters[3].filter = FilterButtonRelease;
  filters[3].client_data = (XPointer)ic;

  x = y = 0;			/* default position */
  width = height = 10;		/* default size */
  win = XFactoryCreateIMWindow(display, parent,
			       ic->core.client_window,
			       x, y, width, height,
			       bg,
			       KeyPressMask|ExposureMask|
			       ButtonPressMask |PointerMotionMask|
			       ButtonReleaseMask |
			       StructureNotifyMask,
			       filters, 4);
  if (!win) return 0;

  val_mask = GCForeground | GCBackground;
  gcval.foreground = fg;
  gcval.background = bg;
  hook->gc = XCreateGC(display, win, val_mask, &gcval);
  gcval.foreground = bg;
  gcval.background = fg;
  hook->rgc = XCreateGC(display, win, val_mask, &gcval);

  /* fontset */
  hook->need_free_fontset = False;
  if (ic->core.status_attr.fontset) {
    hook->fontset = ic->core.status_attr.fontset;
  }
  if (ic->core.preedit_attr.fontset) {
    hook->fontset = ic->core.preedit_attr.fontset;
  }
  if (!hook->fontset) {
    char *base_font_name = DEFAULT_FONT_NAME;
    char **missing_list;
    int missing_count;
    char *def_string;
    hook->fontset = XCreateFontSet(display,
				   base_font_name, &missing_list,
				   &missing_count, &def_string);
    hook->need_free_fontset = True;
  }
  return win;
}

static void
move_table_window(XicCommon ic) {
  LocalTableExt *hook = (LocalTableExt *)(ic->local_icpart->table_ext);
  XPoint point;
  int x = 0, y = 0;	/* default */

  point.x = point.y = 0;	/* default */
  if (XIMP_CHK_PREAREAMASK(ic)) {
    x = ic->core.preedit_attr.area.x;
    y = ic->core.preedit_attr.area.y;
    XFactoryGetLocationOnScreen(ic->core.im->core.display,
				ic->core.client_window, x, y, &point);
  }
  if (XIMP_CHK_PRESPOTLMASK(ic)) {
    point.x = -1;
    point.y = -1;
    if ((-1 == point.x) && (-1 == point.y)) {
      XFontSetExtents *fse;
      fse = XExtentsOfFontSet(hook->fontset);

      x = ic->core.preedit_attr.spot_location.x;
      y = ic->core.preedit_attr.spot_location.y;
      y += (fse->max_logical_extent.height + fse->max_logical_extent.y);
      y += yMargin;
    
      XFactoryGetLocationOnScreen(ic->core.im->core.display,
				  ic->core.focus_window, x, y, &point);
    }
  }

#if 0
  if (hook->fontset) {
    XFontSetExtents *fse;
    fse = XExtentsOfFontSet(hook->fontset);
    if (fse) {
      int height = fse->max_logical_extent.height;
      hook->column_height = height;
    }
  }
#endif
  x = point.x;
  y = point.y;
  XFactoryAdjustPlacementInsideScreen(ic->core.im->core.display,
				      hook->window,
				      point.x, point.y,
				      hook->rect.width + (2 * xMargin),
				      hook->rect.height + (2 * yMargin),
				      &x, &y);
  XMoveWindow(ic->core.im->core.display, hook->window, x, y);
  hook->rect.x = point.x;
  hook->rect.y = point.y;
  return;
}

static void
set_table_window_size(XicCommon ic) {
  LocalTableExt *hook = (LocalTableExt *)(ic->local_icpart->table_ext);
  int i, slen, sheight;
  XRectangle ink, logic;

  slen = 0;
  sheight = 0;
  for (i = 0; i < hook->nrange; i++) {
    XmbTextExtents(hook->fontset,
		   hook->range[i].RangeName,
		   strlen(hook->range[i].RangeName),
		   &ink, &logic);
    if (slen < logic.width) slen = logic.width;
    if (sheight < logic.height) sheight = logic.height;
  }
  hook->rect.width = slen;
  hook->rect.height = sheight * hook->nrange + yMargin;
  hook->theight = sheight;
  return;
}

static Bool
setup_local_table_ext(XicCommon ic) {
  LocalIMState *state = (LocalIMState *)(ic->local_icpart->imstate);
  LocalTableExt *hook = (LocalTableExt *)(ic->local_icpart->table_ext);

  if (hook) return (True);

  hook = (LocalTableExt *)Xmalloc(sizeof(LocalTableExt));
  if (!hook)
    return (False);
  memset(hook, 0, sizeof(LocalTableExt));

  hook->range = (LuRange*)Xmalloc(sizeof(LuRange) * state->attr->_attr_u.LUstruct.nrange);
  memcpy(hook->range, state->attr->_attr_u.LUstruct.range,
	 sizeof(LuRange)*state->attr->_attr_u.LUstruct.nrange);
  hook->nrange = state->attr->_attr_u.LUstruct.nrange;

  ic->local_icpart->table_ext = (void *)hook;
  return(True);
}

/* public */
void
Ximp_Local_Table_Create(XicCommon ic) {
  LocalIMState *state = (LocalIMState *)(ic->local_icpart->imstate);
  LocalTableExt *hook = (LocalTableExt *)(ic->local_icpart->table_ext);
  Display *display = ic->core.im->core.display;

  if (!display || !state || !state->attr) return;

  if (!(XIMP_CHK_FOCUSWINMASK(ic))) {
    return;  /* Client's not ready, Let's do it later */
  }
  if (!hook) {
    if (!setup_local_table_ext(ic))
      return;
    hook = (LocalTableExt *)(ic->local_icpart->table_ext);
  }
  if (!hook->window) {
    hook->window = setup_table_window(ic);
    if (!hook->window) return;
    set_table_window_size(ic);
  }
  return;
}

void
Ximp_Local_Table_Start(XicCommon ic) {
  LocalTableExt *hook = (LocalTableExt *)(ic->local_icpart->table_ext);
  Display *display = ic->core.im->core.display;
  XSizeHints hints;

  if (!hook) {
    Ximp_Local_Table_Create(ic);
    hook = (LocalTableExt *)(ic->local_icpart->table_ext);
    if (!hook) return;
  }
  hints.flags = PSize | PMinSize | PMaxSize;
  hints.width = hook->rect.x;
  hints.min_width = hook->rect.width;
  hints.max_width = hook->rect.width;
  hints.height = hook->rect.height;
  hints.min_height = hook->rect.height;
  hints.max_height = hook->rect.height;
  XSetWMNormalHints(display, hook->window, &hints);
  move_table_window(ic);
  XMapWindow(display, hook->window);
  return;
}

void
Ximp_Local_Table_Draw(XicCommon ic) {
}

void
Ximp_Local_Table_Done(XicCommon ic) {
  LocalTableExt *hook = (LocalTableExt *)(ic->local_icpart->table_ext);
  Display *display = ic->core.im->core.display;
  Ximp_Local_Lookup_Done(ic);
  if (hook && display)
    XUnmapWindow(display, hook->window);
  return;
}

void
Ximp_Local_Table_Destroy(XicCommon ic) {
  LocalTableExt *hook = (LocalTableExt *)(ic->local_icpart->table_ext);
  Display *display = ic->core.im->core.display;
  if (!hook || !display) return;

  if (hook->window) {
    XDestroyWindow(display, hook->window);
    _XUnregisterFilter(display, hook->window,
		       RepaintTable, (XPointer)ic);
    _XUnregisterFilter(display, hook->window,
		       FilterKeyPress, (XPointer)ic);
    _XUnregisterFilter(display, hook->window,
		       FilterMotionNotify, (XPointer)ic);
    _XUnregisterFilter(display, hook->window,
		       FilterButtonRelease, (XPointer)ic);
    hook->window = 0;
  }
  if (hook->gc) XFreeGC(display, hook->gc);
  if (hook->rgc) XFreeGC(display, hook->rgc);

  if (hook->need_free_fontset && hook->fontset) {
    XFreeFontSet(display, hook->fontset);
    hook->need_free_fontset = False;
  }
  if (hook->range) Xfree(hook->range);
  Xfree(hook);
  
  ic->local_icpart->table_ext = 0;
}
