/*   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 "gtk_observePick.h"
#include "callbacks.h"
#include "gtk_main.h"

#include "visu_pickMesure.h"
#include "gtk_renderingWindowWidget.h"
#include "renderingBackend/visu_windowInterface.h"
#include "extraGtkFunctions/gtk_numericalEntryWidget.h"
#include "openGLFunctions/interactive.h"

/* Possibe actions. */
typedef enum
  {
    action_observe,
    action_pick,
    action_move,
    action_mark
  } GtkPickObserveActionId;
static GtkPickObserveActionId currentAction;

/* Callbacks. */
void visuDataChanged(GObject *obj, VisuData *dataObj, gpointer bool);
void visuElementRenderChanged(VisuData *dataObj, VisuElement *element, gpointer data);
void translationChanged(GtkSpinButton* button, gpointer data);
void translationChecked(GtkToggleButton* button, gpointer data);
void observeMethodChanged(GtkToggleButton* button, gpointer data);
void applyTranslationsOnVisuDataChanged(GObject *obj, VisuData* visuData, gpointer data);
gboolean onKillObserveEvent(GtkWidget *widget, GdkEvent *event, gpointer user_data);
static void radioObserveToggled(GtkToggleButton *togglebutton, gpointer user_data);
static void radioPickToggled(GtkToggleButton *togglebutton, gpointer user_data);
static void radioMoveToggled(GtkToggleButton *togglebutton, gpointer user_data);
static void radioMarkToggled(GtkToggleButton *togglebutton, gpointer user_data);
void onCloseButtonClicked(GtkButton *button, gpointer user_data);
void onDrawDistanceChecked(GtkToggleButton* button, gpointer data);
void onEraseDistanceClicked(GtkButton *button, gpointer user_data);
static void refreshCameraSpinValues(VisuData *obj, OpenGLView *view, gpointer data);
static void refreshMoveAxesValues(VisuData *obj, OpenGLView *view, gpointer data);
static void onMovePositionChanged(NumericalEntry *entry, double value, gpointer data);
static void onMoveToOriginalClicked(GtkButton *button, gpointer data);
static void onTabActionChanged(GtkNotebook *book, GtkNotebookPage *page,
			       guint num, gpointer data);
static void onEraseMarksClicked(GtkButton *button, gpointer user_data);

/* Local methods. */
static void setSensitiveActionSensitive(GtkPickObserveActionId id);



/* Pick informations hook */
static PickMesure *pickMesure;
static VisuNode *movedNode;
static float moveNodeOrigin[3];

/* Widgets */
static GtkWidget *entryMoveX, *entryMoveY, *entryMoveZ;
static GtkWidget *labelOriginX, *labelOriginY, *labelOriginZ;
static GtkWidget *labelScreenX[3], *labelScreenY[3];

/* Values of the translation */
float initialTranslation[3];
float currentUserTranslation[3];

/* Help message used in the help area. */
#define GTK_PICKOBSERVE_OBSERVE_INFO _("left-button : rotations\nControl-left-button : rotation of the camera\nShift-left-button : translations\nmiddle-button (along Y) or wheel : size\nShift-middle-button (along Y) or shift-wheel : perspective\nkey 'r' : reset\nright-button : switch to current tabbed action")
#define GTK_PICKOBSERVE_PICK_INFO _("left-button  : standard pick\nmiddle-button: pick (1st) reference\n   Shift-middle-button: pick 2nd reference\nright-button : switch to observe")
#define GTK_PICKOBSERVE_MOVE_INFO _("left-button: drag node in the screen plane\nShift-left-button: drag node along x or y axis\nControl-left-button: drag node along z axis\nright-button : switch to observe")
#define GTK_PICKOBSERVE_MARK_INFO _("left-button: select (unselect) a node\nright-button : switch to observe")
char *markupObserveHelp, *markupPickHelp, *markupMoveHelp, *markupMarkHelp;

#define GTK_PICKOBSERVE_NO_NODE _("<i>none</i>")

/* Flag used to block callbacks when changing are done. */
gboolean flagDisableChangePickObserve;


/* Initialise the observe/pick window, connect the
   signals, give names to widgets... */
void initObserveAndPickWindow()
{
  observeWindow = (GtkWidget*)0;
  disableCallbacks = 0;
}

void gtkObservePickBuild_window()
{
  int i;
  GtkWidget *labelHelp;
  RenderingWindow *window;
  VisuData *data;
 
  window = visuRenderingWindowGet_current();
  g_return_if_fail(window);
  data = renderingWindowGet_visuData(window);
  g_return_if_fail(data);

  DBG_fprintf(stderr, "Gtk observePick : creating the window.\n");
  observeWindow = create_observeDialog();
  gtk_window_set_type_hint(GTK_WINDOW(observeWindow), GDK_WINDOW_TYPE_HINT_NORMAL);
  setNamesGtkWidgetObservePick();
  /* Create and Set the help text. */
  markupObserveHelp = g_markup_printf_escaped("<span size=\"smaller\">%s</span>",
					      GTK_PICKOBSERVE_OBSERVE_INFO);
  markupPickHelp = g_markup_printf_escaped("<span size=\"smaller\">%s</span>",
					    GTK_PICKOBSERVE_PICK_INFO);
  markupMoveHelp = g_markup_printf_escaped("<span size=\"smaller\">%s</span>",
					    GTK_PICKOBSERVE_MOVE_INFO);
  markupMarkHelp = g_markup_printf_escaped("<span size=\"smaller\">%s</span>",
					    GTK_PICKOBSERVE_MARK_INFO);
  labelHelp = lookup_widget(observeWindow, "labelInfoObservePick");
  gtk_label_set_markup(GTK_LABEL(labelHelp), markupObserveHelp);
  currentAction = action_observe;
  /* connect the signals to the spins. */
  connectSignalsObservePick();
  /* set the initial periodic stuff */
  DBG_fprintf(stderr, "Gtk observePick : force initial periodic stuff to initialize.\n");
  visuDataChanged((GObject*)0, data, (gpointer)0);
  /* set the initial values for the spins. */
  refreshCameraSpinValues((VisuData*)0, visuDataGet_openGLView(data), (gpointer)0);
}

/* Methods dealing with observe & pick session. */
void stopPickObserveGtk()
{
  GtkWidget *wd;
  gint id;

  if (flagDisableChangePickObserve)
    return;

  wd = (GtkWidget*)0;
  if (currentAction == action_observe)
    {
      wd = lookup_widget(observeWindow, "notebookAction");
      id = gtk_notebook_get_current_page(GTK_NOTEBOOK(wd));
      switch (id + 1)
	{
	case action_pick:
	  wd = lookup_widget(observeWindow, "radioPick");
	  break;
	case action_move:
	  wd = lookup_widget(observeWindow, "radioMove");
	  break;
	case action_mark:
	  wd = lookup_widget(observeWindow, "radioSelect");
	  break;
	default:
	  wd = (GtkWidget*)0;
	};
    }
  else
    wd = lookup_widget(observeWindow, "radioObserve");

  if (wd)
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(wd), TRUE);
}

void gtkObservePick_marks(const VisuPick *info, gpointer data)
{
  gchar *infos, *errors;
  GtkWidget *wd;
  gchar numero[256];

  if (currentAction == action_pick)
    {
      marksAndMesures(info, data);
      if (pickMesureGet_newsAvailable(pickMesure))
	{
	  infos = getPickMesureInfos(pickMesure);
	  errors = getPickMesureErrors(pickMesure);
	  if (infos)
	    gtk_label_set_text(GTK_LABEL(labelPickOut), infos);
	  if (errors)
	    gtk_label_set_text(GTK_LABEL(labelPickError), errors);
	}
    }
  else if (currentAction == action_move)
    {
      /* No current selected node or new selected node. */
      if (!movedNode || movedNode != info->node)
	{
	  movedNode = info->node;
	  wd = lookup_widget(observeWindow, "labelMoveId");
	  if (movedNode)
	    {
	      sprintf(numero, _("%d (node id)"), movedNode->number);
	      gtk_label_set_markup(GTK_LABEL(wd), numero);
	      /* Set the origin position values. */
	      moveNodeOrigin[0] = movedNode->x;
	      moveNodeOrigin[1] = movedNode->y;
	      moveNodeOrigin[2] = movedNode->z;
	      sprintf(numero, "%5.2f", movedNode->x);
	      gtk_label_set_text(GTK_LABEL(labelOriginX), numero);
	      sprintf(numero, "%5.2f", movedNode->y);
	      gtk_label_set_text(GTK_LABEL(labelOriginY), numero);
	      sprintf(numero, "%5.2f", movedNode->z);
	      gtk_label_set_text(GTK_LABEL(labelOriginZ), numero);
	    }
	  else
	    {
	      gtk_label_set_markup(GTK_LABEL(wd), GTK_PICKOBSERVE_NO_NODE);
	      numero[0] = '\0';
	      gtk_label_set_text(GTK_LABEL(labelOriginX), numero);
	      gtk_label_set_text(GTK_LABEL(labelOriginY), numero);
	      gtk_label_set_text(GTK_LABEL(labelOriginZ), numero);
	    }
	}
      /* Drawing changing values (when drag for example). */
      if (movedNode)
	{
	  disableCallbacks = 1;
	  numericalEntrySet_value(NUMERICAL_ENTRY(entryMoveX), movedNode->x);
	  numericalEntrySet_value(NUMERICAL_ENTRY(entryMoveY), movedNode->y);
	  numericalEntrySet_value(NUMERICAL_ENTRY(entryMoveZ), movedNode->z);
	  disableCallbacks = 0;
	}
      else
	{
	  disableCallbacks = 1;
	  numericalEntrySet_value(NUMERICAL_ENTRY(entryMoveX), 0.);
	  numericalEntrySet_value(NUMERICAL_ENTRY(entryMoveY), 0.);
	  numericalEntrySet_value(NUMERICAL_ENTRY(entryMoveZ), 0.);
	  disableCallbacks = 0;
	}
    }
}

void gtkObservePickInit_session()
{
  gint posx, posy;
  GtkWidget *wd;
  VisuData *data;

  renderingWindowBlock_defaultIneractiveMode(RENDERING_WINDOW(currentRenderingWindow));
  renderingWindowPush_message(RENDERING_WINDOW(currentRenderingWindow), "");

  data = renderingWindowGet_visuData(RENDERING_WINDOW(currentRenderingWindow));
  g_return_if_fail(data);
  pickMesure = initPickMesure(data, TRUE, TRUE);
  openGLInteractiveInit_session((GenericRenderingWindow)currentRenderingWindow,
				gtkObservePick_marks, (gpointer)pickMesure, stopPickObserveGtk);

  movedNode = (VisuNode*)0;

  gtk_window_get_position(GTK_WINDOW(mainWindow), &posx, &posy);
  DBG_fprintf(stderr, "Gtk observePick : get command panel position (%d,%d).\n", posx, posy);
  visuHideWindow(GTK_WINDOW(mainWindow));
  /* At the first call, if the window does not exist, we create it. */
  if (!observeWindow)
    gtkObservePickBuild_window();
  DBG_fprintf(stderr, "Gtk observePick : set observe position (%d,%d).\n", posx, posy);
  gtk_window_move(GTK_WINDOW(observeWindow), posx, posy);
  visuShowWindow(GTK_WINDOW(observeWindow));

  setSensitiveActionSensitive(currentAction);
  switch (currentAction)
    {
    case action_observe:
      openGLInteractiveBegin_observe();
      break;
    case action_pick:
      openGLInteractiveBegin_pick();
      break;
    case action_move:
      openGLInteractiveBegin_move();
      break;
    case action_mark:
      openGLInteractiveBegin_mark(data);
      break;
    }
  flagDisableChangePickObserve = FALSE;
}

void onCloseButtonClicked(GtkButton *button, gpointer user_data)
{
/*   GtkWidget *radio; */

  gtk_label_set_text(GTK_LABEL(labelPickOut), "");
  gtk_label_set_text(GTK_LABEL(labelPickError), "");

/*   radio = lookup_widget(observeWindow, "radioObserve"); */
/*   if (!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radio))) */
  endPickMesure(pickMesure);

  flagDisableChangePickObserve = TRUE;
  openGLInteractiveEnd_session();

  renderingWindowPop_message(RENDERING_WINDOW(currentRenderingWindow));
  renderingWindowUnblock_defaultIneractiveMode(RENDERING_WINDOW(currentRenderingWindow));

  visuHideWindow(GTK_WINDOW(observeWindow));
  visuShowWindow(GTK_WINDOW(mainWindow));
}

static void setSensitiveObserve(gboolean value)
{
  GtkWidget *wd;

  wd = lookup_widget(observeWindow, "hboxObserve");
  gtk_widget_set_sensitive(wd, value);
  wd = lookup_widget(observeWindow, "tableObserve");
  gtk_widget_set_sensitive(wd, value);
  if (openGLInteractiveGet_preferedObserveMethod() == OPENGL_OBSERVE_CONSTRAINED)
    gtk_widget_set_sensitive(spinOmega, FALSE);
  else
    gtk_widget_set_sensitive(spinOmega, value);
}
static void setSensitiveMove(gboolean value)
{
  GtkWidget *wd;

  wd = lookup_widget(observeWindow, "tableMoveNodes");
  gtk_widget_set_sensitive(wd, value);
}
static void setSensitiveMark(gboolean value)
{
  GtkWidget *wd;

/*   wd = lookup_widget(observeWindow, "tableMoveNodes"); */
/*   gtk_widget_set_sensitive(wd, value); */
}

static void setSensitiveActionSensitive(GtkPickObserveActionId id)
{
  currentAction = id;
  setSensitiveObserve((id == action_observe));
  setSensitiveMove((id == action_move));
  setSensitiveMark((id == action_mark));
}


/****************/
/* Private part */
/****************/

/* Connect the listeners on the signal emitted by the OpenGL server. */
void connectSignalsObservePick()
{
  GtkWidget *wd;

  g_signal_connect(G_OBJECT(visu), "dataReadyForRendering",
		   G_CALLBACK(visuDataChanged), (gpointer)0);

  wd = lookup_widget(observeWindow, "buttonBackToCommandPanel");
  g_signal_connect(G_OBJECT(wd), "clicked",
		   G_CALLBACK(onCloseButtonClicked), (gpointer)0);
  wd = lookup_widget(observeWindow, "radioObserve");
  g_signal_connect(G_OBJECT(wd), "toggled",
		   G_CALLBACK(radioObserveToggled), (gpointer)0);
  wd = lookup_widget(observeWindow, "radioPick");
  g_signal_connect(G_OBJECT(wd), "toggled",
		   G_CALLBACK(radioPickToggled), (gpointer)0);
  wd = lookup_widget(observeWindow, "radioMove");
  g_signal_connect(G_OBJECT(wd), "toggled",
		   G_CALLBACK(radioMoveToggled), (gpointer)0);
  wd = lookup_widget(observeWindow, "radioSelect");
  g_signal_connect(G_OBJECT(wd), "toggled",
		   G_CALLBACK(radioMarkToggled), (gpointer)0);



  wd = lookup_widget(observeWindow, "checkAllowTranslations");
  g_signal_connect(G_OBJECT(wd), "toggled",
		   G_CALLBACK(translationChecked), (gpointer)0);
  wd = lookup_widget(observeWindow, "spinTransX");
  g_signal_connect(G_OBJECT(wd), "value-changed",
		   G_CALLBACK(translationChanged), GINT_TO_POINTER(0));
  currentUserTranslation[0] = gtk_spin_button_get_value(GTK_SPIN_BUTTON(wd));
  wd = lookup_widget(observeWindow, "spinTransY");
  g_signal_connect(G_OBJECT(wd), "value-changed",
		   G_CALLBACK(translationChanged), GINT_TO_POINTER(1));
  currentUserTranslation[1] = gtk_spin_button_get_value(GTK_SPIN_BUTTON(wd));
  wd = lookup_widget(observeWindow, "spinTransZ");
  g_signal_connect(G_OBJECT(wd), "value-changed",
		   G_CALLBACK(translationChanged), GINT_TO_POINTER(2));
  currentUserTranslation[2] = gtk_spin_button_get_value(GTK_SPIN_BUTTON(wd));
  g_signal_connect(G_OBJECT(visu), "dataLoaded",
		   G_CALLBACK(applyTranslationsOnVisuDataChanged), (gpointer)0);

  wd = lookup_widget(observeWindow, "radioObserveConstrained");
  g_signal_connect(G_OBJECT(wd), "toggled",
		   G_CALLBACK(observeMethodChanged), GINT_TO_POINTER(OPENGL_OBSERVE_CONSTRAINED));
  wd = lookup_widget(observeWindow, "radioObserveWalker");
  g_signal_connect(G_OBJECT(wd), "toggled",
		   G_CALLBACK(observeMethodChanged), GINT_TO_POINTER(OPENGL_OBSERVE_WALKER));

  wd = lookup_widget(observeWindow, "notebookAction");
  g_signal_connect(G_OBJECT(wd), "switch-page",
		   G_CALLBACK(onTabActionChanged), (gpointer)0);

  wd = lookup_widget(observeWindow, "checkDrawDistance");
  g_signal_connect(G_OBJECT(wd), "toggled",
		   G_CALLBACK(onDrawDistanceChecked), (gpointer)0);
  wd = lookup_widget(observeWindow, "buttonEraseDistances");
  g_signal_connect(G_OBJECT(wd), "clicked",
		   G_CALLBACK(onEraseDistanceClicked), (gpointer)0);

  g_signal_connect(G_OBJECT(entryMoveX), "value-changed",
		   G_CALLBACK(onMovePositionChanged), GINT_TO_POINTER(0));
  g_signal_connect(G_OBJECT(entryMoveY), "value-changed",
		   G_CALLBACK(onMovePositionChanged), GINT_TO_POINTER(1));
  g_signal_connect(G_OBJECT(entryMoveZ), "value-changed",
		   G_CALLBACK(onMovePositionChanged), GINT_TO_POINTER(2));
  wd = lookup_widget(observeWindow, "buttonMoveOriginal");
  g_signal_connect(G_OBJECT(wd), "clicked",
		   G_CALLBACK(onMoveToOriginalClicked), (gpointer)0);

  wd = lookup_widget(observeWindow, "buttonEraseMarks");
  g_signal_connect(G_OBJECT(wd), "clicked",
		   G_CALLBACK(onEraseMarksClicked), (gpointer)0);

  g_signal_connect(G_OBJECT(observeWindow), "delete-event",
		   G_CALLBACK(onKillObserveEvent), (gpointer)0);
  g_signal_connect(G_OBJECT(observeWindow), "destroy-event",
		   G_CALLBACK(onKillObserveEvent), (gpointer)0);
}

void visuDataChanged(GObject *obj, VisuData *dataObj, gpointer bool)
{
  gboolean periodic;

  if (dataObj)
    {
      DBG_fprintf(stderr, "Gtk Observe/Pick : caught 'dataReadyForRendering' signal,"
		  " setting sensitivity.\n");

      g_signal_connect(G_OBJECT(dataObj), "ElementRenderedChanged",
		       G_CALLBACK(visuElementRenderChanged), (gpointer)0);

/*       signalCameraChangedId = */
	g_signal_connect(G_OBJECT(dataObj), "OpenGLThetaPhiOmega",
			 G_CALLBACK(refreshCameraSpinValues), (gpointer)0);
	g_signal_connect(G_OBJECT(dataObj), "OpenGLThetaPhiOmega",
			 G_CALLBACK(refreshMoveAxesValues), (gpointer)0);
/*       signalCameraChangedId = */
	g_signal_connect(G_OBJECT(dataObj), "OpenGLXsYs",
			 G_CALLBACK(refreshCameraSpinValues), (gpointer)0);
/*       signalCameraChangedId = */
	g_signal_connect(G_OBJECT(dataObj), "OpenGLGross",
			 G_CALLBACK(refreshCameraSpinValues), (gpointer)0);
/*       signalCameraChangedId = */
	g_signal_connect(G_OBJECT(dataObj), "OpenGLPersp",
			 G_CALLBACK(refreshCameraSpinValues), (gpointer)0);

      periodic = visuDataGet_periodic(dataObj);
      gtk_widget_set_sensitive(lookup_widget(observeWindow, "hboxTranslations"),
			       periodic);
      gtk_widget_set_sensitive(lookup_widget(observeWindow, "checkAllowTranslations"),
			       periodic);
    }
}

void applyTranslation()
{
  float cartCoord[3];
  VisuData *data;

  data = renderingWindowGet_visuData(RENDERING_WINDOW(currentRenderingWindow));
  visuDataConvert_boxCoordinatestoXYZ(data, cartCoord, currentUserTranslation);
/*   fprintf(stderr, "%f %f %f\n", cartCoord[0], cartCoord[1], cartCoord[2]); */
  visuDataSet_XYZtranslation(data, cartCoord);
  visuData_constrainedInTheBox(data);
  visuDataEmit_nodePositionChanged(data);
  visuData_createAllNodes(data);
  g_signal_emit (visu, VISU_GET_CLASS (visu)->OpenGLAskForReDraw_signal_id,
		 0 , NULL);
}
void translationChecked(GtkToggleButton* button, gpointer data)
{
  float cartCoord[3];
  VisuData *dataObj;

  if (gtk_toggle_button_get_active(button))
    {
      applyTranslation();
    }
  else
    {
      cartCoord[0] = 0.;
      cartCoord[1] = 0.;
      cartCoord[2] = 0.;
      dataObj = renderingWindowGet_visuData(RENDERING_WINDOW(currentRenderingWindow));
      visuDataSet_XYZtranslation(dataObj, cartCoord);
      visuData_constrainedFree(dataObj);
      visuDataEmit_nodePositionChanged(dataObj);
      visuData_createAllNodes(dataObj);
      g_signal_emit (visu, VISU_GET_CLASS (visu)->OpenGLAskForReDraw_signal_id,
		     0 , NULL);
    }
}

void translationChanged(GtkSpinButton* button, gpointer data)
{
  float trans;
  GtkWidget *wd;
  int i;
  int spin;

  spin = GPOINTER_TO_INT(data);
  if (spin < 0 || spin > 2)
    {
      fprintf(stderr, "WARNING! 'translationChanged' has been called with a"
	      " wrong 'data' argument.\n");
      return;
    }

  trans = gtk_spin_button_get_value(button);
  if (trans == currentUserTranslation[spin])
    return;

  currentUserTranslation[spin] = trans;

  wd = lookup_widget(observeWindow, "checkAllowTranslations");
  if (!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(wd)))
    return;

  applyTranslation();
}

void applyTranslationsOnVisuDataChanged(GObject *obj, VisuData* visuData, gpointer data)
{
  float cartCoord[3];
  GtkWidget *wd;
  gboolean periodic;
  
  if (!visuData)
    return;

  wd = lookup_widget(observeWindow, "checkAllowTranslations");
  if (!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(wd)))
    return;

  periodic = visuDataGet_periodic(visuData);
  if (!periodic)
    return;

  DBG_fprintf(stderr, "Gtk Pick/Observe : Catch 'dataLoaded' signal,"
	      " applying current translations.\n");

  visuDataConvert_boxCoordinatestoXYZ(visuData, cartCoord, currentUserTranslation);
  visuDataSet_XYZtranslation(visuData, cartCoord);
  visuData_constrainedInTheBox(visuData);
}


void observeMethodChanged(GtkToggleButton* button, gpointer data)
{
  int method;
  RenderingWindow *window;

  if (!gtk_toggle_button_get_active(button))
    return;

  method = GPOINTER_TO_INT(data);
  openGLInteractiveSet_preferedObserveMethod(method);
  if (method == OPENGL_OBSERVE_CONSTRAINED)
    {
      window = RENDERING_WINDOW(visuRenderingWindowGet_current());
      g_return_if_fail(window);

      gtk_widget_set_sensitive(spinOmega, FALSE);
      if (visuDataSet_angleOfView(renderingWindowGet_visuData(window),
				  0., 0., 0., MASK_OMEGA))
	g_signal_emit (visu, VISU_GET_CLASS (visu)->OpenGLAskForReDraw_signal_id,
		       0 , NULL);
    }
  else
    gtk_widget_set_sensitive(spinOmega, TRUE);
}


/* Ask the OpenGL server to refresh the values of the spins
   controlling the position of the camera. */
static void refreshCameraSpinValues(VisuData *obj, OpenGLView *view, gpointer data)
{
  g_return_if_fail(view && view->camera);

  disableCallbacks = 1;
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinTheta), (gdouble)view->camera->theta);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinPhi),   (gdouble)view->camera->phi);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinOmega), (gdouble)view->camera->omega);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinXs),    (gdouble)view->camera->xs);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinYs),    (gdouble)view->camera->ys);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinGross), (gdouble)view->camera->gross);
  gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinPersp), (gdouble)view->camera->d_red);
  disableCallbacks = 0;
}

static void refreshMoveAxesValues(VisuData *obj, OpenGLView *view, gpointer data)
{
  gint id;
  int i;
  float x[3], y[3];
  GtkWidget *wd;
  char tmpChr[12];

  wd = lookup_widget(observeWindow, "notebookAction");
  id = gtk_notebook_get_current_page(GTK_NOTEBOOK(wd));
  if (id + 1 == action_move)
    {
      OpenGLViewGet_screenAxes(view, x, y);
      for (i = 0; i < 3; i++)
	{
	  sprintf(tmpChr, "%5.3f", x[i]);
	  gtk_label_set_text(GTK_LABEL(labelScreenX[i]), tmpChr);
	  sprintf(tmpChr, "%5.3f", y[i]);
	  gtk_label_set_text(GTK_LABEL(labelScreenY[i]), tmpChr);
	}
    }
}
static void onMovePositionChanged(NumericalEntry *entry, double value, gpointer data)
{
  double *valOfNode;
  RenderingWindow *window;
  VisuData *dataObj;

  g_return_if_fail(movedNode);

  if (disableCallbacks)
    return;

  if (GPOINTER_TO_INT(data) == 0)
    valOfNode = &movedNode->x;
  else if (GPOINTER_TO_INT(data) == 1)
    valOfNode = &movedNode->y;
  else if (GPOINTER_TO_INT(data) == 2)
    valOfNode = &movedNode->z;
  else
    {
      g_warning("Bad 'data' argument for callback 'onMovePositionChanged'.");
      return;
    }
  
  if (*valOfNode == value)
    return;

  window = RENDERING_WINDOW(visuRenderingWindowGet_current());
  g_return_if_fail(window);

  *valOfNode = value;
  dataObj = renderingWindowGet_visuData(window);
  visuData_createNodes(dataObj, dataObj->fromIntToVisuElement[movedNode->posElement]);
  visuDataEmit_nodePositionChanged(renderingWindowGet_visuData(window));

  g_signal_emit (visu, VISU_GET_CLASS (visu)->OpenGLAskForReDraw_signal_id,
		 0 , NULL);
}
static void onMoveToOriginalClicked(GtkButton *button, gpointer data)
{
  RenderingWindow *window;
  VisuData *dataObj;

  g_return_if_fail(movedNode);

  window = RENDERING_WINDOW(visuRenderingWindowGet_current());
  g_return_if_fail(window);

  movedNode->x = moveNodeOrigin[0];
  movedNode->y = moveNodeOrigin[1];
  movedNode->z = moveNodeOrigin[2];
  dataObj = renderingWindowGet_visuData(window);
  visuData_createNodes(dataObj, dataObj->fromIntToVisuElement[movedNode->posElement]);
  visuDataEmit_nodePositionChanged(renderingWindowGet_visuData(window));

  disableCallbacks = 1;
  numericalEntrySet_value(NUMERICAL_ENTRY(entryMoveX), moveNodeOrigin[0]);
  numericalEntrySet_value(NUMERICAL_ENTRY(entryMoveY), moveNodeOrigin[1]);
  numericalEntrySet_value(NUMERICAL_ENTRY(entryMoveZ), moveNodeOrigin[2]);
  disableCallbacks = 0;

  g_signal_emit (visu, VISU_GET_CLASS (visu)->OpenGLAskForReDraw_signal_id,
		 0 , NULL);
}

/* Give a name to the widgets present in this window
   to be able to affect them with a theme. */
void setNamesGtkWidgetObservePick()
{
  GtkWidget *wd;
  int method;
  float *translation, boxTrans[3];
  VisuData *data;

  gtk_widget_set_name(observeWindow, "message");
/*   wd = lookup_widget(observeWindow, "titreObserve"); */
/*   gtk_widget_set_name(wd, "message_title"); */
  wd = lookup_widget(observeWindow, "labelInfoObservePick");
  gtk_widget_set_name(wd, "label_info");

/*   wd = lookup_widget(observeWindow, "labelObserve"); */
/*   gtk_widget_set_name(wd, "label_head"); */
/*   wd = lookup_widget(observeWindow, "labelPick"); */
/*   gtk_widget_set_name(wd, "label_head"); */

  wd = lookup_widget(observeWindow, "labelTranslation");
  gtk_widget_set_name(wd, "label_head_2");
/*   wd = lookup_widget(observeWindow, "labelRotation"); */
/*   gtk_widget_set_name(wd, "label_head_2"); */
  wd = lookup_widget(observeWindow, "labelZoom");
  gtk_widget_set_name(wd, "label_head_2");

  wd = lookup_widget(observeWindow, "radioObserve");
  gtk_widget_set_name(wd, "message_radio");
  wd = lookup_widget(observeWindow, "radioPick");
  gtk_widget_set_name(wd, "message_radio");
  wd = lookup_widget(observeWindow, "radioMove");
  gtk_widget_set_name(wd, "message_radio");
  wd = lookup_widget(observeWindow, "radioSelect");
  gtk_widget_set_name(wd, "message_radio");

  spinTheta = lookup_widget(observeWindow, "spinTheta");
  spinPhi = lookup_widget(observeWindow, "spinPhi");
  spinOmega = lookup_widget(observeWindow, "spinOmega");
  spinXs = lookup_widget(observeWindow, "spinDx");
  spinYs = lookup_widget(observeWindow, "spinDy");
  spinGross = lookup_widget(observeWindow, "spinGross");
  spinPersp = lookup_widget(observeWindow, "spinPersp");

  if (openGLInteractiveGet_preferedObserveMethod() == OPENGL_OBSERVE_CONSTRAINED)
    gtk_widget_set_sensitive(spinOmega, FALSE);

  labelPickOut = lookup_widget(observeWindow, "pickInfo");
  labelPickError = lookup_widget(observeWindow, "pickComment");
  gtk_widget_set_name(labelPickError, "label_error");

  wd = lookup_widget(observeWindow, "checkDrawDistance");
  gtk_widget_set_name(wd, "message_radio");

  wd = lookup_widget(observeWindow, "notebookAction");
  gtk_widget_set_name(wd, "message_notebook");

  wd = lookup_widget(observeWindow, "labelMoveId");
  gtk_label_set_markup(GTK_LABEL(wd), GTK_PICKOBSERVE_NO_NODE);

  labelOriginX = lookup_widget(observeWindow, "labelOriginalX");
  labelOriginY = lookup_widget(observeWindow, "labelOriginalY");
  labelOriginZ = lookup_widget(observeWindow, "labelOriginalZ");

  labelScreenX[0] = lookup_widget(observeWindow, "labelScreenX_X");
  labelScreenX[1] = lookup_widget(observeWindow, "labelScreenX_Y");
  labelScreenX[2] = lookup_widget(observeWindow, "labelScreenX_Z");
  labelScreenY[0] = lookup_widget(observeWindow, "labelScreenY_X");
  labelScreenY[1] = lookup_widget(observeWindow, "labelScreenY_Y");
  labelScreenY[2] = lookup_widget(observeWindow, "labelScreenY_Z");

  wd = lookup_widget(observeWindow, "tableMoveNodes");
  entryMoveX = numericalEntry_new(0.);
  gtk_entry_set_width_chars(GTK_ENTRY(entryMoveX), 5);
  gtk_table_attach(GTK_TABLE(wd), entryMoveX, 1, 2, 2, 3,
		   GTK_SHRINK, GTK_SHRINK, 0, 0);
  gtk_widget_show(entryMoveX);
  entryMoveY = numericalEntry_new(0.);
  gtk_entry_set_width_chars(GTK_ENTRY(entryMoveY), 5);
  gtk_table_attach(GTK_TABLE(wd), entryMoveY, 2, 3, 2, 3,
		   GTK_SHRINK, GTK_SHRINK, 0, 0);
  gtk_widget_show(entryMoveY);
  entryMoveZ = numericalEntry_new(0.);
  gtk_entry_set_width_chars(GTK_ENTRY(entryMoveZ), 5);
  gtk_table_attach(GTK_TABLE(wd), entryMoveZ, 3, 4, 2, 3,
		   GTK_SHRINK, GTK_SHRINK, 0, 0);
  gtk_widget_show(entryMoveZ);

  wd = lookup_widget(observeWindow, "checkAllowTranslations");
  gtk_widget_set_name(wd, "message_radio");

  method = openGLInteractiveGet_preferedObserveMethod();
  wd = lookup_widget(observeWindow, "radioObserveConstrained");
  gtk_widget_set_name(wd, "message_radio");
  if (method == OPENGL_OBSERVE_CONSTRAINED)
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(wd), TRUE);
  wd = lookup_widget(observeWindow, "radioObserveWalker");
  gtk_widget_set_name(wd, "message_radio");
  if (method == OPENGL_OBSERVE_WALKER)
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(wd), TRUE);

  data = renderingWindowGet_visuData(RENDERING_WINDOW(currentRenderingWindow));
  /* Set the translation values if available. */
  if (data)
    {
      translation = visuDataGet_XYZtranslation(data);
      if (translation && translation[0] != 0. &&
	  translation[1] != 0. && translation[2] != 0.)
	{
	  visuDataConvert_XYZtoBoxCoordinates(data, boxTrans, translation);
	  g_free(translation);
	  wd = lookup_widget(observeWindow, "spinTransX");
	  gtk_spin_button_set_value(GTK_SPIN_BUTTON(wd), (gdouble)boxTrans[0]);
	  wd = lookup_widget(observeWindow, "spinTransY");
	  gtk_spin_button_set_value(GTK_SPIN_BUTTON(wd), (gdouble)boxTrans[1]);
	  wd = lookup_widget(observeWindow, "spinTransZ");
	  gtk_spin_button_set_value(GTK_SPIN_BUTTON(wd), (gdouble)boxTrans[2]);
	  wd = lookup_widget(observeWindow, "checkAllowTranslations");
	  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(wd), TRUE);  
	}
    }
}

gboolean onKillObserveEvent(GtkWidget *widget, GdkEvent *event, gpointer user_data)
{
  DBG_fprintf(stderr, "Gtk Pick/Observe : delete or destroy event cancelled.\n");
  onCloseButtonClicked((GtkButton*)0, (gpointer)0);

  return TRUE;
}

void visuElementRenderChanged(VisuData *dataObj, VisuElement *element, gpointer data)
{
  if (element->rendered)
    {
      DBG_fprintf(stderr, "Gtk Observe/Pick : caught 'ElementRenderedChanged' applying"
		  " translation for element '%s'.\n", element->name);
      if (visuData_constrainedElementInTheBox(dataObj, element))
	visuDataEmit_nodePositionChanged(dataObj);
    }
  else
    DBG_fprintf(stderr, "Gtk Observe/Pick : caught 'ElementRenderedChanged' but"
		" do not apply translation since element '%s' is masked.\n",
		element->name);
}

static void radioObserveToggled(GtkToggleButton *togglebutton, gpointer user_data)
{
  GtkWidget *labelHelp;

  if (!gtk_toggle_button_get_active(togglebutton))
    return;

  DBG_fprintf(stderr, "Gtk observePick : Toggle of the radio button in observe window.\n");

  labelHelp = lookup_widget(observeWindow, "labelInfoObservePick");
  gtk_label_set_markup(GTK_LABEL(labelHelp), markupObserveHelp);

  flagDisableChangePickObserve = TRUE;
/*   unSetReferencePickMesure(pickMesure); */
/*   gtk_label_set_text(GTK_LABEL(labelPickOut), ""); */
/*   gtk_label_set_text(GTK_LABEL(labelPickError), ""); */
  setSensitiveActionSensitive(action_observe);
  openGLInteractiveBegin_observe();

  flagDisableChangePickObserve = FALSE;
}
static void radioPickToggled(GtkToggleButton *togglebutton, gpointer user_data)
{
  GtkWidget *labelHelp;

  if (!gtk_toggle_button_get_active(togglebutton))
    return;

  DBG_fprintf(stderr, "Gtk observePick : Toggle of the radio button in observe window.\n");

  labelHelp = lookup_widget(observeWindow, "labelInfoObservePick");
  gtk_label_set_markup(GTK_LABEL(labelHelp), markupPickHelp);

  setSensitiveActionSensitive(action_pick);
  openGLInteractiveBegin_pick();

  flagDisableChangePickObserve = FALSE;
}
static void radioMoveToggled(GtkToggleButton *togglebutton, gpointer user_data)
{
  GtkWidget *labelHelp;
  RenderingWindow *window;
  VisuData *data;
  OpenGLView *view;

  if (!gtk_toggle_button_get_active(togglebutton))
    return;

  labelHelp = lookup_widget(observeWindow, "labelInfoObservePick");
  gtk_label_set_markup(GTK_LABEL(labelHelp), markupMoveHelp);

  setSensitiveActionSensitive(action_move);

  window = RENDERING_WINDOW(visuRenderingWindowGet_current());
  g_return_if_fail(window);
  data = renderingWindowGet_visuData(window);
  view = visuDataGet_openGLView(data);
  refreshMoveAxesValues(data, view, (gpointer)0);
  openGLInteractiveBegin_move();

  flagDisableChangePickObserve = FALSE;
}
static void radioMarkToggled(GtkToggleButton *togglebutton, gpointer user_data)
{
  GtkWidget *labelHelp;
  RenderingWindow *window;

  if (!gtk_toggle_button_get_active(togglebutton))
    return;

  labelHelp = lookup_widget(observeWindow, "labelInfoObservePick");
  gtk_label_set_markup(GTK_LABEL(labelHelp), markupMarkHelp);

  setSensitiveActionSensitive(action_mark);

  window = RENDERING_WINDOW(visuRenderingWindowGet_current());
  g_return_if_fail(window);
  openGLInteractiveBegin_mark(renderingWindowGet_visuData(window));

  flagDisableChangePickObserve = FALSE;
}

void onDrawDistanceChecked(GtkToggleButton* button, gpointer data)
{
  pickMesureSet_storeDistance(pickMesure, gtk_toggle_button_get_active(button));
}
void onEraseDistanceClicked(GtkButton *button, gpointer user_data)
{
  if (pickMesureRemove_allDistanceMarks(pickMesure))
    g_signal_emit (visu, VISU_GET_CLASS (visu)->OpenGLAskForReDraw_signal_id,
		   0 /* details */,
		   NULL);
}
static void onTabActionChanged(GtkNotebook *book, GtkNotebookPage *page,
			       guint num, gpointer data)
{
  GtkWidget *wd;

  DBG_fprintf(stderr, "Gtk Observe/Pick : change the action tab to %d.\n", num);
  switch (num + 1)
    {
    case action_pick:
      wd = lookup_widget(observeWindow, "radioPick");
      break;
    case action_move:
      wd = lookup_widget(observeWindow, "radioMove");
      break;
    case action_mark:
      wd = lookup_widget(observeWindow, "radioSelect");
      break;
    default:
      wd = (GtkWidget*)0;
    };

  if (wd)
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(wd), TRUE);
}
static void onEraseMarksClicked(GtkButton *button, gpointer user_data)
{
  RenderingWindow *window;

  window = RENDERING_WINDOW(visuRenderingWindowGet_current());
  g_return_if_fail(window);

  if (openGLInteractiveRemove_allMarks(renderingWindowGet_visuData(window)))
    g_signal_emit(visu, VISU_GET_CLASS (visu)->OpenGLAskForReDraw_signal_id,
		  0 , NULL);
}
