/*
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 <X11/Xlib.h>
#include <X11/Xatom.h>		/* Required for XA_ATOM */
#ifndef linux
#include <Xm/MwmUtil.h>
#endif
#include "guiIM.h"
#include "xfactory.h"

#define PROP_WM_STATE_ELEMENTS 2

typedef struct _PropWMState {
    unsigned long state;
    unsigned long ion;

} PropWMState;

static Bool
GetWMState(Display *display, Window window) {
    int ret_val;
    PropWMState *property = NULL;
    Atom actual_type;
    int actual_format;
    unsigned long nitems;
    unsigned long leftover;
    Atom wm_state = XInternAtom(display, "WM_STATE", True);

    ret_val = XGetWindowProperty(display, window, wm_state,
				 0L, PROP_WM_STATE_ELEMENTS,
				 False, wm_state,
				 &actual_type, &actual_format,
				 &nitems, &leftover,
				 (unsigned char **)&property);
    if (!((ret_val == Success) && (actual_type == wm_state) &&
	  (nitems == PROP_WM_STATE_ELEMENTS))) {
	/*
	 * The property could not be retrieved or is not correctly set up.
	 */
	if (property) {
	    XFree((char *)property);
	}
	return False;
    }
    if (property) {
	XFree((char *)property);
    }
    return True;
}

/* Refer to /usr/dt/include/Xm/MwmUtil.h */
static Atom mwm_del_atom = (Atom)0;

/* Refer to OlClients.h */
static Atom ol_del_atom = (Atom)0;
static Atom ol_del_atom_list[3];
static int ol_atom_inx = 0;

static void getAtoms(Display *display) {
    if (!mwm_del_atom) {
	mwm_del_atom = XInternAtom(display, "_MOTIF_WM_HINTS", True);
    }
    if (!ol_del_atom) {
        ol_atom_inx = 0;
	ol_del_atom = XInternAtom(display, "_OL_DECOR_DEL", True);
	ol_del_atom_list[ol_atom_inx++] =
	    XInternAtom(display, "_OL_DECOR_RESIZE", True);
	ol_del_atom_list[ol_atom_inx++] =
	    XInternAtom(display, "_OL_DECOR_HEADER", True);
    }
}

static void
remove_decoration(Display * display, Window window,
		  int decoration)
{
    struct _mwmhints {
	unsigned long flags, func, deco;
	long    input_mode;
	unsigned long status;
    } mwm_del_hints;
    
    getAtoms(display);

    if (mwm_del_atom != None) {
	mwm_del_hints.flags = 1L << 1; /* flags for decoration */
	mwm_del_hints.deco = decoration;
	XChangeProperty(display, window,
			mwm_del_atom, mwm_del_atom, 32,
			PropModeReplace,
			(unsigned char *)&mwm_del_hints, 5);
    }
    if (ol_del_atom != None) {
        XChangeProperty(display, window, ol_del_atom, XA_ATOM, 32,
			PropModeReplace, (unsigned char*)ol_del_atom_list,
			ol_atom_inx);
    }

    {
      /* 4344419 */
      /* window title is attached while using enlightenment on linux */
      /* need to disable [x] (dismiss window) function */
      Atom wm_window_protocols[1];
      Atom wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
      wm_window_protocols[0] = wm_delete_window;
      XSetWMProtocols(display, window, wm_window_protocols, 1);
    }
    {
      /* 4390729 */
      /* window should not grab any input focus */
      XWMHints wm_hints;
      wm_hints.flags = InputHint;
      wm_hints.input = False;
      XSetWMHints(display, window, &wm_hints);
    }
    {
      Atom net_wm_state = XInternAtom(display, "_NET_WM_STATE", False);
      Atom net_wm_state_skip_taskbar = XInternAtom(display, "_NET_WM_STATE_SKIP_TASKBAR", False);
      Atom net_wm_state_prop[1];

      net_wm_state_prop[0] = net_wm_state_skip_taskbar;
      XChangeProperty(display, window, net_wm_state, XA_ATOM, 32,
		      PropModeReplace, (unsigned char *) net_wm_state_prop, 1);
    }
}

/*
#define MWM_DECOR_ALL		(1L << 0)
#define MWM_DECOR_BORDER	(1L << 1)
#define MWM_DECOR_RESIZEH	(1L << 2)
#define MWM_DECOR_TITLE		(1L << 3)
#define MWM_DECOR_MENU		(1L << 4)
#define MWM_DECOR_MINIMIZE	(1L << 5)
#define MWM_DECOR_MAXIMIZE	(1L << 6)
*/

void
XFactoryRemoveDecoration(Display *display, Window window) {
  remove_decoration(display, window, 1L << 1); /* set Border only */
  return;
}

void
XFactoryRemoveDecorationExceptTitle(Display *display, Window window) {
  remove_decoration(display, window, 1L << 1 | 1L << 3); /* set Border only */
  return;
}

void
XFactoryRemoveAllDecoration(Display *display, Window window) {
  remove_decoration(display, window, 0); /* set nothing */
  return;
}

void
XFactoryRemoveMenu(Display *display, Window window) {
  remove_decoration(display, window, 1L << 1 | 1L << 3);
  return;
}

void
XFactoryRemoveBorder(Display *display, Window window) {
  /* set all the flags other than border */
  remove_decoration(display, window,
		    1L << 2 | 1L << 3 | 1L << 4 | 1L << 5 | 1L << 6);
  return;
}

Window
XFactoryGetFrameWindow(Display *display, Window window) {
    Window top_win;
    Window current_window = window;

    for (;;) {
        Window root_return, parent_return, *child_return = NULL;
        unsigned int nchild_return;
        top_win = current_window;
        if (XQueryTree(display, current_window,
                       &root_return, &parent_return,
                       &child_return, &nchild_return) == 0) {
            if (child_return) XFree(child_return);
            break;
        }
        if (child_return) XFree(child_return);
        current_window = parent_return;
        if (parent_return == root_return) break;
    }
    return top_win;
}

Window
XFactoryGetToplevelWindow(Display *display, Window window) {
    Window root_return, parent_return, *child_return = NULL, current_window;
    unsigned int nchild_return;

    if (GetWMState(display, window)) return window;

    current_window = window;
    for (;;) {
	if (XQueryTree(display, current_window,
		       &root_return, &parent_return,
		       &child_return, &nchild_return) == 0) {
	    if (child_return) XFree(child_return);
	    break;
	}
	if (child_return) XFree(child_return);
	if (GetWMState(display, parent_return)) {
	    return parent_return;
	}
	if (parent_return == root_return) {
	    return current_window;
	}
	current_window = parent_return;
    }
    /* error */
    return window;
}

void
XFactoryGetLocationOnScreen(Display *display, Window window,
			    int x, int y, XPoint *point) {
  XWindowAttributes attr;
  Window child;
  int new_x, new_y;

  if (XGetWindowAttributes(display, window, &attr) > 0) {
    XTranslateCoordinates(display, window,
			  RootWindow(display,
				     XScreenNumberOfScreen(attr.screen)),
			  x, y,
			  &new_x, &new_y, &child);

    point->x = new_x;
    point->y = new_y;
  }
  return;
}

Window
XFactoryCreateIMWindow(Display *display, Window parent,
		       Window transient_win,
		       int x, int y,
		       unsigned int width, unsigned int height,
		       unsigned long bg, long event_mask,
		       XIMFilter filters, int count) {
  Window win;
  int i;
  Window top_win;

  if (width <= 0) width = 1;
  if (height <= 0) height = 1;

  win = XCreateSimpleWindow(display, parent,
			    x, y, width, height,
			    0,	/* border width: who cares? */
			    0,	/* border color */
			    bg);
  if (!win) return 0;

  XFactoryRemoveDecoration(display, win);

  /* query toplevel window */
  top_win = XFactoryGetToplevelWindow(display, transient_win);
  XSetTransientForHint(display, win, top_win);

  XSelectInput(display, win, event_mask);

  for (i = 0; i < count; i++) {
    _XRegisterFilterByType(display, win,
			   filters[i].type, filters[i].type,
			   filters[i].filter,
			   (XPointer)filters[i].client_data);
  }
  return win;
}

void
XFactoryAdjustPlacementInsideScreen(Display * dpy, Window win,
				    int x, int y,
				    int width, int height,
				    int * ret_x, int * ret_y) {
  XWindowAttributes attr;
  int dpy_width;
  int dpy_height;
  int screen_num;

  width += 20;
  height += 20;

  if (XGetWindowAttributes(dpy, win, &attr) > 0) {
    screen_num = XScreenNumberOfScreen(attr.screen);
  } else {
    screen_num = 0;
  }

  dpy_width = DisplayWidth(dpy, screen_num);
  dpy_height = DisplayHeight(dpy, screen_num);

  if (dpy_width < (x + width)) {
    if (width <= dpy_width) {
      *ret_x = (dpy_width - width);
    } else {
      *ret_x = 0;
    }
  } else {
    *ret_x = x;
  }

  if (dpy_height < (y + height)) {
    if (height <= dpy_height) {
      *ret_y = (dpy_height - height);
    } else {
      *ret_y = 0;
    }
  } else {
    *ret_y = y;
  }
}

int
XFactoryResizeWindowInsideScreen(Display * display, Window w,
				 unsigned int width, unsigned int height) {
  XWindowAttributes attr;
  int x;
  int y;

  if (XGetWindowAttributes(display, w, &attr) > 0) {
    XFactoryAdjustPlacementInsideScreen(display, w, attr.x, attr.y,
					width, height, &x, &y);
    if ((attr.x == x) && (attr.y == y)) {
      XResizeWindow(display, w, width, height);
    } else {
      XMoveResizeWindow(display, w, x, y, width, height);
    }
  }
  return 0;
}

int
XFactoryMoveResizeWindowInsideScreen(Display * display, Window w,
				     int x, int y,
				     unsigned int width, unsigned int height) {
  XFactoryAdjustPlacementInsideScreen(display, w, x, y,
				      width, height, &x, &y);
  XMoveResizeWindow(display, w, x, y, width, height);

  return 0;
}

int
XFactoryMoveWindowInsideScreen(Display * display, Window w,
			       int x, int y) {
  XWindowAttributes attr;

  if (XGetWindowAttributes(display, w, &attr) > 0) {
    XFactoryAdjustPlacementInsideScreen(display, w, x, y,
					attr.width, attr.height,
					&x, &y);
    XMoveWindow(display, w, x, y);
  }

  return 0;
}

int 
XFactoryValidateCoordinates(Display * display, Window w,
                               int *x, int *y) {
  XWindowAttributes attr;
  int newx, newy;
  if (XGetWindowAttributes(display, w, &attr) > 0) {
    XFactoryAdjustPlacementInsideScreen(display, w, *x, *y,
                                        attr.width, attr.height,
                                        &newx, &newy);
    *x = newx;
    *y = newy;
  }
  return 0;
}

/* 4378199: Linux Htt: can not operate after WMDoc client is
                              closed on VineLinux2.0

   Need to check client_window is valid or not before creating
   status, preedit and lookup
*/
Bool
XFactoryCheckIMWindow(Display* display, Window window) {
  Window root;
  int ax, ay;
  unsigned int awidth, aheight, aborder, adepth;
  int s;

  if (!window) return False;

  s = XGetGeometry(display, window, &root, &ax, &ay,
                &awidth, &aheight, &aborder, &adepth);

  return s;
}

static XFontSet default_fontset = (XFontSet)0;
static int ref_count = 0;

XFontSet
XFactoryCreateDefaultFontSet (Display *display, char *default_fontname)
{
  char **missing_list;
  int missing_count;
  char *def_string;
  char *base_font_name;

  ref_count++;

  if (default_fontset)
    return default_fontset;

  if (default_fontname && default_fontname[0])
    {
      base_font_name = default_fontname;
      default_fontset = XCreateFontSet (display,
					base_font_name, &missing_list,
					&missing_count, &def_string);
    }
  if (default_fontset)
    return default_fontset;

  base_font_name = DEFAULT_FONT_NAME_CDE;
  default_fontset = XCreateFontSet (display,
				    base_font_name, &missing_list,
				    &missing_count, &def_string);
  if (default_fontset)
    return default_fontset;

  base_font_name = DEFAULT_FONT_NAME;
  default_fontset = XCreateFontSet (display,
				    base_font_name, &missing_list,
				    &missing_count, &def_string);
  return default_fontset;
}

void
XFactoryFreeDefaultFontSet(Display *display)
{
  if (--ref_count == 0)
    {
      if (default_fontset)
	XFreeFontSet (display, default_fontset);
      default_fontset = 0;
    }
  return;
}
