/*
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 "Xfactory.hh"
#include <X11/Xlib.h>
#include <X11/Xatom.h>		/* Required for XA_ATOM */
#ifdef DEBUG
#include <stdio.h>
#endif
#include <stdlib.h>
#include <string.h>

extern "C" {
  extern void _XRegisterFilterByType(Display*, Window, int, int,
			      XIMFilter, XPointer);
  extern void _XUnregisterFilter(Display*, Window, XIMFilter, XPointer);
	   }

/* 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_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);
  }
}


void
XFactory::remove_decoration(Display *display, Window window) {
  const int decoration = (1L << 1);	/* set border only */
  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);
  }
  return;
}

void
XFactory::register_filter(Display *display, Window window,
			  int start_type, int end_type,
			  XIMFilter filter, XPointer call_data) {
  _XRegisterFilterByType(display, window, start_type,
			 end_type, filter, call_data);
  return;
}

void
XFactory::unregister_filter(Display *display, Window window,
			    XIMFilter filter, XPointer call_data) {
  _XUnregisterFilter(display, window, filter, call_data);
  return;
}

FsSet XFactory::fs_list;

XFontSet
XFactory::create_fontset(Display *display, const char *name) {
  CompoundString font_name(name);

  FsSet fsp = fs_list;
  while (fsp) {
    if (fsp->fs_name.length() == font_name.length() &&
	fsp->fs_name == font_name) {
      fsp->ref_count++;
      return(fsp->fs);
    }
    fsp = fsp->next;
  }
  // not found
  char **missing_list;
  int missing_count;
  char *def_string;
  int fallback_flag = 0;
  XFontSet font_set = XCreateFontSet(display, (char*)font_name,
				     &missing_list, &missing_count,
				     &def_string);
  if (font_set == 0) {
    fallback_flag = 1;
  }
  if (missing_count > 0) {
    int list_ret;
    XFontStruct **struct_list = NULL;
    char **name_list = NULL;
    const char *cur_str = NULL;
    int i;
    list_ret = XFontsOfFontSet(font_set,
			       &struct_list, &name_list);
    cur_str = name;
    for (i = 0; i < list_ret && cur_str != NULL; ++i) {
      char *tmp_str;
      if (strncmp(cur_str, (const char*)name_list[i],
		  strlen(name_list[i])) != 0) {
	break;
      };
      tmp_str = (char *)strchr(cur_str, ',');
      if (tmp_str != NULL && strlen(tmp_str) > 1) {
	++tmp_str;
      }
      else {
	tmp_str = NULL;
      }
      cur_str = (const char*)tmp_str;
    }
    if (i != list_ret || cur_str != NULL) {
#ifdef DEBUG
      fprintf(stderr, "Warning\n");
      fprintf(stderr, " - FontSet creation partically failed due to missing character sets\n");
#endif
      fallback_flag = 1;
    }
    XFreeStringList(missing_list);
  }
  if (fallback_flag == 1) {
    const char default_name[] = "-*-*-medium-r-normal-*-16-*-*-*-*-*-*-*";

    font_name = CompoundString(default_name);
    fsp = fs_list;
    while (fsp) {
      if (fsp->fs_name.length() == font_name.length() &&
	  fsp->fs_name == font_name) {
	fsp->ref_count++;
	return(fsp->fs);
      }
      fsp = fsp->next;
    }
    font_set = XCreateFontSet(display, (char*)font_name,
			      &missing_list, &missing_count,
			      &def_string);
    if (font_set == 0) {
#ifdef DEBUG
    fprintf(stderr, "Error\n");
    fprintf(stderr, " - Fallback FontSet creation failes\n");
#endif
      return (XFontSet)0;
    }
    if (missing_count > 0) {
#ifdef DEBUG
      fprintf(stderr, "Warning\n");
      fprintf(stderr, " - FontSet creation partically failed due to missing character sets\n");
#endif
      XFreeStringList(missing_list);
    }
  }
  fsp = fs_list;
  while (fsp) {
    if (fsp->fs == 0 && fsp->ref_count == 0) break;
    fsp = fsp->next;
  }
  FsSet newfsp;
  if (fsp) {
    newfsp = fsp;	// found one
  } else {
    // create new list
    newfsp = new FsSetRec;
    if (!fs_list) {
      newfsp->next = (FsSet)0;
      fs_list = newfsp;
    } else {
      newfsp->next = fs_list;
      fs_list = newfsp;
    }
  }
  newfsp->fs = font_set;
  newfsp->fs_name = font_name;
  newfsp->ref_count = 1;

  return(newfsp->fs);
}

void
XFactory::free_fontset(Display *display, XFontSet font_set) {

  if (!fs_list) return;

  FsSet fsp = fs_list;
  while (fsp) {
    if (font_set == fsp->fs)
      break;
    fsp = fsp->next;
  }

  if (!fsp || fsp->ref_count == 0) return;

  if (--(fsp->ref_count) > 0)   /* somebody else is still using */
    return;

  if (fsp->fs) {
    XFreeFontSet(display, fsp->fs);
    fsp->fs = 0;	//
  }
  return;
}

void
XFactory::getLocationOnScreen(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;
}

#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;
}

Window
XFactory::getToplevelWindow(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;
}

Window
XFactory::getFrameWindow(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;
}

int
XFactory::xerror_handler(Display *display, XErrorEvent *ev) {
  char errmsg[80];
  Bool print_xerror = True;

  if (getenv("NOPRINT_XERROR")) print_xerror = False;

  if (print_xerror) {
    XGetErrorText(display, ev->error_code, errmsg, 80);
#ifdef DEBUG
    fprintf(stderr, "Warning (X Error) -  %s\n", errmsg);
#endif
  }
  return 0;
}
