/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2006)
  
	Adresse mèl :
	BILLARD, non joignable par mèl ;
	CALISTE, damien P caliste AT cea P fr.

	Ce logiciel est un programme informatique servant à visualiser des
	structures atomiques dans un rendu pseudo-3D. 

	Ce logiciel est régi par la licence CeCILL soumise au droit français et
	respectant les principes de diffusion des logiciels libres. Vous pouvez
	utiliser, modifier et/ou redistribuer ce programme sous les conditions
	de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA 
	sur le site "http://www.cecill.info".

	Le fait que vous puissiez accéder à cet en-tête signifie que vous avez 
	pris connaissance de la licence CeCILL, et que vous en avez accepté les
	termes (cf. le fichier Documentation/licence.fr.txt fourni avec ce logiciel).
*/

/*   LICENCE SUM UP
	Copyright CEA, contributors : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2006)

	E-mail address:
	BILLARD, not reachable any more ;
	CALISTE, damien P caliste AT cea P fr.

	This software is a computer program whose purpose is to visualize atomic
	configurations in 3D.

	This software is governed by the CeCILL  license under French law and
	abiding by the rules of distribution of free software.  You can  use, 
	modify and/ or redistribute the software under the terms of the CeCILL
	license as circulated by CEA, CNRS and INRIA at the following URL
	"http://www.cecill.info". 

	The fact that you are presently reading this means that you have had
	knowledge of the CeCILL license and that you accept its terms. You can
	find a copy of this licence shipped with this software at Documentation/licence.en.txt.
*/
#include "visu_windowInterface.h"

#define  __USE_BSD

#include <unistd.h>

#include <X11/Xlib.h>
#include <X11/cursorfont.h>
#include <X11/keysym.h>
#include <X11/xpm.h>

#include <stdio.h>
#include <stdlib.h>

#include <pixmaps/icone-observe.xpm>
#include "visu_tools.h"
#include <OSOpenGL/visu_OSInterface.h>
#include <OSOpenGL/visu_X11.h>

Cursor cursorRotate;
Cursor cursorWatch;
Cursor cursorPointer;
Cursor cursorPirate;
Cursor *currentCursor;

static long currentWindowEventMask;
static guint XeventCallbackFunc;

CallbackFunctions standardCallback;


gboolean XTestEvent(gpointer data)
{
  CallbackFunctions *callbacks;
  SimplifiedEvents ev;
  XEvent report;
  int action;
  Window root, child;
  int root_x, root_y, pos_x, pos_y;
  unsigned int keys_buttons;
  KeySym keysym;

  callbacks = (CallbackFunctions*)data;
  if (!callbacks)
    {
      fprintf(stderr, "INTERNAL ERROR! 'XTestEvent' has been called"
	      " with a null data parameter.\n");
      return FALSE;
    }
  
  if (!XPending(dpy))
    {
      usleep(10000);
      return TRUE;
    }
  
  (void)XDefineCursor(dpy, *window, cursorWatch);
  (void)XFlush(dpy);
  (void)XNextEvent(dpy, &report);
  action = 0;
  ev.button = 0;
  ev.motion = 0;
  ev.letter = '\0';
  switch(report.type)
    {
    case ButtonPress:
      ev.x = report.xbutton.x;
      ev.y = report.xbutton.y;
      ev.button = report.xbutton.button;
      ev.shiftMod = report.xbutton.state & ShiftMask;
      ev.controlMod = report.xbutton.state & ControlMask;
      action = 1;
      break;
    case MotionNotify:
      if(!XQueryPointer(dpy, report.xmotion.window,
			&root, &child, &root_x, &root_y,
			&pos_x, &pos_y, &keys_buttons)) break;
      ev.x = report.xmotion.x;
      ev.y = report.xmotion.y;
      if (report.xmotion.state & Button1Mask)
	ev.button = 1;
      else if (report.xmotion.state & Button2Mask)
	ev.button = 2;
      else if (report.xmotion.state & Button3Mask)
	ev.button = 3;
      ev.shiftMod = report.xmotion.state & ShiftMask;
      ev.controlMod = report.xmotion.state & ControlMask;
      ev.motion = 1;
      action = 1;
      break;
    case KeyRelease:
      keysym = XKeycodeToKeysym(dpy, report.xkey.keycode, 0);
      if(keysym == XK_r || keysym == XK_R)
	ev.letter = 'r';
      action = 1;
      break;
    default:
      action = 0;
    }
  if (action)
    {
      if (callbacks->action(&ev) && callbacks->stop)
	callbacks->stop((gpointer)0);
    }

  (void)XDefineCursor(dpy, *window, *currentCursor);
  (void)XFlush(dpy);

  return TRUE;
}

gboolean checkForXEvent(gpointer data)
{
  XEvent report;

  if (!XPending(dpy))
    return TRUE;

  /* Bouffe la pile pour éviter de faire 15 000 reDraw
     inutiles. */
  while (XPending(dpy))
    (void)XNextEvent(dpy, &report);
  switch(report.type)
    {
    case Expose:
      if (report.xexpose.count == 0 && standardCallback.action)
	standardCallback.action((SimplifiedEvents*)0);
      break;
/*     case ResizeRequest: */
/*       if (setNewWindowSize(report.xresizerequest.width, */
/* 			   report.xresizerequest.height)) */
/* 	reDraw((GObject*)0, (gpointer)1); */
/*       break; */
    }
  
  return TRUE;
}


GList* setObserveEventListener(CallbackFunctions *userCallbacks)
{
  GList *listId;
  guint *idEve;

  (void)XDefineCursor(dpy, *window, cursorRotate);
  (void)XSelectInput(dpy, *window,
		     KeyReleaseMask| 
		     ButtonPressMask|ButtonReleaseMask|
		     ButtonMotionMask|PointerMotionHintMask);
  (void)XFlush(dpy);
  currentCursor = &cursorRotate;

  listId = (GList*)0;

  idEve = malloc(sizeof(guint));
  if (!idEve)
    {
      allocationProblems();
      exit(1);
    }
  *idEve = g_idle_add_full(G_PRIORITY_HIGH_IDLE + 20,
			   XTestEvent, (gpointer)userCallbacks,
			   userCallbacks->stop);
  listId = g_list_append(listId, (gpointer)idEve);

  return listId;
}

GList* setPickEventListener(CallbackFunctions *userCallbacks)
{
  GList *listId;
  guint *idEve;

  (void)XDefineCursor(dpy, *window, cursorPointer);
  (void)XSelectInput(dpy, *window, ButtonPressMask);
  (void)XFlush(dpy);
  currentCursor = &cursorPointer;

  listId = (GList*)0;

  idEve = malloc(sizeof(guint));
  if (!idEve)
    {
      allocationProblems();
      exit(1);
    }
  *idEve = g_idle_add_full(G_PRIORITY_HIGH_IDLE + 20,
			   XTestEvent, (gpointer)userCallbacks,
			   userCallbacks->stop);
  listId = g_list_append(listId, (gpointer)idEve);

  return listId;
}

void removeEventListener(GList *listId)
{
  GList* ptList;

  ptList = listId;
  while (ptList)
    {
      if (*(guint*)ptList->data)
	g_source_remove(*(guint*)ptList->data);
      free(ptList->data);
      ptList = g_list_next(ptList);
    }
  if (listId)
    g_list_free(listId);
  listId = (GList*)0;
}

void restoreStandardEventListener()
{
  (void)XSelectInput(dpy, *window, currentWindowEventMask);
  (void)XDefineCursor(dpy, *window, cursorPirate);
  (void)XFlush(dpy);
  if (currentWindowEventMask)
    {
      DBG_fprintf(stderr, "Visu OpenGl : adding timer.\n");
      XeventCallbackFunc = g_timeout_add(50, checkForXEvent, (gpointer)0);
    }
}
void stopStandardEventListener()
{
  if (XeventCallbackFunc)
    g_source_remove(XeventCallbackFunc);
  XeventCallbackFunc = 0;
}

void addExposureEvent(ActionFunc action)
{
  currentWindowEventMask = currentWindowEventMask | ExposureMask;
  (void)XSelectInput(dpy, *window, currentWindowEventMask);
  XFlush(dpy);
  standardCallback.action = action;
  if (!XeventCallbackFunc)
    XeventCallbackFunc = g_timeout_add(50, checkForXEvent, (gpointer)0);
}
void removeExposureEvent()
{
  currentWindowEventMask = currentWindowEventMask ^ ExposureMask;
  (void)XSelectInput(dpy, *window, currentWindowEventMask);
  XFlush(dpy);
  standardCallback.action = (ActionFunc)0;
  if (!currentWindowEventMask)
    g_source_remove(XeventCallbackFunc);
  XeventCallbackFunc = 0;
}


int initRenderingWindow(char* windowRef, char* iconRef, char* window_name,
			char* class_name, int width, int height)
{
  int d_depth;
  Colormap cmap;
  XSetWindowAttributes wattrs;
  /* window manager : WMProperties */
  XTextProperty window_name_txt, icon_name_txt;
  XSizeHints shints;
  XWMHints whints;
  XClassHint chints;
  XEvent event;
  Atom wm_delete_window;
  XpmAttributes	attributes;
  int res;

  res = initDisplay();
   
  res = initOpenGLContext() || res;

  if (!res)
    return 0;
    
  cmap = XCreateColormap(dpy, RootWindow(dpy, vinfo->screen),
			 vinfo->visual, AllocNone);
    
  wattrs.backing_store = 0;
  wattrs.background_pixel =  
    wattrs.border_pixel = BlackPixel(dpy, DefaultScreen(dpy)); 
  wattrs.event_mask = ExposureMask ;
  wattrs.colormap = cmap; 

  window = malloc(sizeof(Window));
  if (!window)
    {
      allocationProblems();
      exit(1);
    }
  *window = XCreateWindow(dpy, RootWindow(dpy, vinfo->screen),
			  0, 0, width, height, 0,
			  vinfo->depth, InputOutput, vinfo->visual,
			  CWBackingStore|CWBackPixel|CWBorderPixel|CWEventMask|CWColormap,
			  &wattrs);
   
  (void)XStringListToTextProperty(&windowRef, 1, &window_name_txt);  
  (void)XStringListToTextProperty(&iconRef, 1, &icon_name_txt);
    
  shints.x = 0; shints.y = 0;
  shints.width  = shints.min_aspect.x = shints.max_aspect.x = width;
  shints.height = shints.min_aspect.y = shints.max_aspect.y = height;  
  shints.flags = PSize | PAspect;

  d_depth = DefaultDepth(dpy,DefaultScreen(dpy) );
  whints.initial_state = NormalState;
/*   whints.icon_pixmap = XCreateBitmapFromData(dpy, *window, (char *)visu_btmp_bits,  */
/* 					     visu_btmp_width, visu_btmp_height);   */
  whints.icon_pixmap = XCreatePixmap(dpy, *window, 16, 16, d_depth);
  attributes.valuemask = (XpmReturnPixels | XpmReturnExtensions);
  XpmCreatePixmapFromData(dpy, *window, icone_observe_xpm, &whints.icon_pixmap, NULL, &attributes);
  XCreatePixmapFromBitmapData(dpy, *window, (char *)icone_observe_xpm, 16, 16, 0, 128, d_depth);
  whints.flags = StateHint | IconPixmapHint;
  
  chints.res_name = window_name; 
  chints.res_class = class_name;

  (void)XSetWMProperties (dpy, *window,
			  &window_name_txt, &icon_name_txt,
			  NULL, 0,
			  &shints, &whints, &chints);
   
  wm_delete_window = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
  (void)XSetWMProtocols(dpy, *window, &wm_delete_window, 1);
    
  (void)XMapWindow(dpy, *window);
  event.type = 0;
  while (event.type != Expose)  (void)XNextEvent(dpy, &event);


  currentWindowEventMask = 0;
  cursorPirate = XCreateFontCursor(dpy, XC_pirate);
  cursorRotate = XCreateFontCursor(dpy, XC_box_spiral);
  cursorWatch = XCreateFontCursor(dpy, XC_watch);
  cursorPointer = XCreateFontCursor(dpy, XC_dotbox);

  (void)XDefineCursor(dpy, *window, cursorPirate); 
  (void)XSelectInput(dpy, *window, currentWindowEventMask);
  (void)XFlush(dpy);
   
  res = setWindowHandler(window);

/*   attachOpenGlContext((gpointer)window, TRUE, FALSE); */

  /* Now that the glx tunnel has been added, we need
     to specify again that we want a backing store because until now
     the backing store is only for the X window (and thus is black)
     but not for the glx screen. */
  startBackingStore();

  /* The automatic resize is not working... */
/*   XeventCallbackFunc = g_timeout_add(50, checkForXEvent, (gpointer)0); */
  XeventCallbackFunc = 0;

  return 1;
}

void checkWindowSize(unsigned int *width, unsigned int *height)
{
  Window root; int xu, yu; unsigned int bdr, dpth; /* not used */
   
  if(!XGetGeometry(dpy, *window, &root, &xu, &yu,
		   width, height, &bdr, &dpth))
    {
      DBG_fprintf(stderr, "INTERNAL ERROR! XGetGeometry failed!\n");
      exit(1);
    }
}

gpointer getWindowHandler()
{
  return (gpointer)window;
}


void raiseRenderWindow()
{
  XRaiseWindow(dpy, *window);
  XFlush(dpy);
}

void rename_window(char *nom)
{
    char *window_name_L[1];
    XTextProperty window_name_txt;
    
    window_name_L[0] = nom;
    
    (void)XStringListToTextProperty(window_name_L, 1, &window_name_txt);  
    (void)XSetWMName (dpy, *window, &window_name_txt);
    (void)XFlush(dpy);
}

void visuRenderigWindowGet_backgroundColor(float rgb[3])
{
  rgb[0] = 0.5;
  rgb[1] = 0.5;
  rgb[2] = 0.5;
}
gpointer visuRenderigWindowGet_backgroundImage(guchar **rowData, gboolean *hasAlphaChannel,
					       int *width, int *height)
{
  return (gpointer)0;
}
void visuRenderigWindowFree_backgroundImage(gpointer image)
{
}
