/*
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 "guiIMSts.h"
#include "XimpIm.h"
#include "iiimpIM.h"
#include "xfactory.h"
#include "trace_message.h"

static XicCommon Focussed_IC = 0;
static StatusWin Focussed_STATUS = 0;

static void set_window(XicCommon ic, XPointer call_data);

static Bool
track_client_window_move (Display *d, Window w,
			  XEvent *ev, XPointer client_data)
{
  XicCommon ic = (XicCommon)client_data;

  if (ic && ic->gui_icpart)
    set_window(ic, 0);
  else
    _XUnregisterFilter(d, w, track_client_window_move, (XPointer)ic);

  return False;
}

/* ChangeStatus Methods */
static void
create(XicCommon ic, XPointer call_data) {
  StatusWin status = (StatusWin)(ic->gui_icpart->status);
  Display *display = ic->core.im->core.display;
  XWindowAttributes attr;

#ifdef DISABLE_IMSTATUS_FOR_NON_UTF8_LOCALES
  char *client_type = XIM_IIIMP(ic->core.im, client_type);
  if (client_type && strcmp(client_type, "Htt XIM Server") == 0)
    return;
#endif

  if (!(ic->ximp_icpart->value_mask & XIMP_CLIENT_WIN)) return;

  if (!status) {
    SetupStatusExt(ic);
    status = (StatusWin)(ic->gui_icpart->status);
  }

  if (status->parent != 0) {
    /* status window is already created  */
    return;
  }
  XGetWindowAttributes(display, 
		       ic->core.client_window,
		       &attr);
  SetupStatusWindow(ic, RootWindow(display,
				   XScreenNumberOfScreen(attr.screen)));

  {
    Window client_toplevel = None;
    client_toplevel = XFactoryGetToplevelWindow(display,
						ic->core.client_window);
    if (client_toplevel) {
      XimCommon im = (XimCommon)ic->core.im;
      if (XIM_IS_IIIMP(im)) {
	char *client_type = XIM_IIIMP(im, client_type);
	if (client_type && strcmp(client_type, "Htt XIM Server") == 0) {
	  XSelectInput(display, client_toplevel,
		       attr.your_event_mask | StructureNotifyMask);
	}
      }
      _XRegisterFilterByType(display, client_toplevel,
			     ConfigureNotify, ConfigureNotify,
			     track_client_window_move, (XPointer)ic);
    }
  }
  return;
}

static void
set_window(XicCommon ic, XPointer call_data) {
  StatusWin status = (StatusWin)(ic->gui_icpart->status);
  Display *display = ic->core.im->core.display;

  TRACE_MESSAGE('s', ("iiimp_set_window: status=0x%08x window=0x%08x\n",
		      status, status ? status->window : 0));
  if (!status) {
    create(ic, NULL);
    status = (StatusWin)(ic->gui_icpart->status);
    if (!status) return;
  }

  if (!Focussed_IC) {
    Focussed_IC = (XicCommon)ic;
    Focussed_STATUS = (StatusWin)status;
  }
  if (XIMP_CHK_FOCUSWINMASK(ic) && (ic != Focussed_IC)) {
    if (Focussed_STATUS->window) {
      XWindowAttributes tswin_att;
      if (XGetWindowAttributes(display,Focussed_STATUS->window,&tswin_att) > 0) {
	if (tswin_att.map_state != IsUnmapped) {
	  XUnmapWindow(display,Focussed_STATUS->window);
          Focussed_IC = (XicCommon)ic;
          Focussed_STATUS = (StatusWin)status;	
	}
      }
    }
  }

  if (status->window) {
    XWindowAttributes win_att;
    Window frame_window;
    int x_margin, y_margin;

    frame_window = XFactoryGetFrameWindow(display,
					  ic->core.client_window);

    if (XGetWindowAttributes(display, frame_window,
			     &win_att) > 0) {
      int x, y, width = 0, height = 0;
      XSizeHints  hints;
      XWMHints wm_hints;
      CacheRec *status_cache = (CacheRec*)&(status->status_cache);
      char * status_string;
      int len;
      extern char * MergeStatus(XicCommon ic);

      x = win_att.x;
      y = win_att.y;
      y += win_att.height;

      if (!status->fontset)
	SetStatusFont(ic, NULL);

      if (!status->fontset)
	return;

      status_string = MergeStatus(ic);
      len = ((NULL == status_string) ? 0 : strlen(status_string));
      if (0 < len) {
	XFontSetExtents *fse;
	fse = XExtentsOfFontSet(status->fontset);
	width = XmbTextEscapement(status->fontset,
				  status_string,
				  len);
	height = fse->max_logical_extent.height;
      }
      Xfree(status_string);
      /* avoid creating 0 width/height or too large status window */
      if (width == 0 || width > 1000) width = 100;
      if (height == 0 || height > 1000) height = 15;

      /* calculate margin */
      x_margin = 0;
      y_margin = height/5;

      width += x_margin * 2;

      status_cache = (CacheRec*)&(status->status_cache);
      if (status_cache->win_x == x &&
	  status_cache->win_y == y &&
	  status_cache->win_width == width &&
	  status_cache->win_height == height) {
	return;
      }

      status->x = x_margin;
      status->y = height - y_margin;

      hints.flags = PSize | PPosition;
      hints.x = x;
      hints.y = y;
      hints.width  = width;
      hints.height = height;
      XSetWMNormalHints(display, status->window, &hints);
      wm_hints.flags = InputHint;
      wm_hints.input = False;
      XSetWMHints(display, status->window, &wm_hints);
      XFactoryValidateCoordinates(ic->core.im->core.display,
				  status->window,
				  &x, &y);
      XMoveResizeWindow(ic->core.im->core.display,
			status->window,
			x, y, width, height);
      /* data cache */
      status_cache->win_x = x;
      status_cache->win_y = y;
      status_cache->win_width = width;
      status_cache->win_height = height;
    }
  }
  return;
}

static void
HideStatus(XicCommon ic, XPointer call_data) {
  StatusWin status;

  if (!ic->gui_icpart) return;

  status = (StatusWin)(ic->gui_icpart->status);

  if (!status) return;

#ifndef	linux
 {
   XWindowAttributes cwin_att;
   if (XGetWindowAttributes(ic->core.im->core.display,
                            ic->core.client_window,
                            &cwin_att)) {
     if (cwin_att.map_state != IsUnmapped) return;
   }
 }
#endif

  if (XIMP_CHK_FOCUSWINMASK(ic)){
    XUnmapWindow(ic->core.im->core.display, status->window);
  }
}

static StatusCB status_nothing_methods[] = {
  create,			/* STATUS_CREATE */
  set_window,			/* STATUS_WIN */
  SetStatusForeground,		/* STATUS_FG */
  SetStatusBackground,		/* STATUS_BG */
  SetStatusFont,		/* STATUS_FONT */
  StatusStart,			/* STATUS_START */
  StatusDrawText,		/* STATUS_DRAW */
  StatusDone,			/* STATUS_DONE */
  DestroyStatus,		/* STATUS_DESTROY */
  HideStatus			/* STATUS_HIDE */
};

/* Public function */
void
ChangeStatusNothing(XIC xic, StatusAttr reason, XPointer call_data) {
  XicCommon ic = (XicCommon)xic;

#ifdef	linux
  if(getenv("HTT_DISABLE_STATUS_WINDOW")){
    return;
  }
#endif

  if (reason == STATUS_DESTROY) {
    Focussed_IC=(XicCommon)NULL;
    Focussed_STATUS = (StatusWin)NULL;
  }

  if (reason > STATUS_HIDE) return;

  status_nothing_methods[reason](ic, call_data);
  return;
}

