/*   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 "visuElements.h"
#include "externalRenderingMethods_gtk.h"

#include <visu_object.h>
#include <visu_tools.h>
#include <visu_data.h>
#include <gtk_main.h>
#include <extraGtkFunctions/gtk_colorComboBoxWidget.h>
#include <renderingBackend/visu_windowInterface.h>
#include <gtk_renderingWindowWidget.h>

#define RED_ELE_LABEL   _("R:")
#define GREEN_ELE_LABEL _("G:")
#define BLUE_ELE_LABEL  _("B:")
#define ALPHA_ELE_LABEL _("Alph:")
#define AMB_ELE_LABEL _("amb:")
#define DIF_ELE_LABEL _("dif:")
#define SHI_ELE_LABEL _("shi:")
#define SPE_ELE_LABEL _("spe:")
#define EMI_ELE_LABEL _("emi:")

GtkListStore *listStoreVisuElements;
enum
  {
    COLUMN_NAME,  /* The label shown */
    COLUMN_POINTER_TO_DATA,  /* Pointer to the VisuElement. */
    COLUMN_POINTER_TO_COLOR, /* Pointer to the Color if available. */
    N_COLUMNS
  };
GtkWidget *elementsCombo;
GtkWidget *checkRendered;
GtkWidget *widgetVisuElementColor;
gint sortVisuElements(gpointer a, gpointer b);
char *getLabelOfElement(VisuElement *element);

/* Callbacks */
guint idRefreshComboElements;
void comboVisuElementsChanged(GtkComboBox *combobox, gpointer data);
static void resourcesChanged(GObject *object, gpointer data);
void colorVisuElementChanged(ColorComboBox *colorWd, Color *color, gpointer userData);
void checkRenderedChanged(GtkToggleButton *button, gpointer data);
void refreshComboElements(GObject *obj, VisuData *dataObj, gpointer userData);

subPanel* initPanelElements()
{
  char *cl = _("Set elements caracteristics");
  char *tl = _("Elements");
  char *ipn = "stock_palette_20.png";
  GtkWidget *child;
  int i;

  /* Initialise static values. */
  currentSelectedElement = (VisuElement*)0;

  child = createInteriorElements();
  visuSetElementsParameters = createSubPanelWithIconFromPath(cl, tl, ipn, child,
							     (onChangePanelFunc)0,
							     (onChangePanelFunc)0);
  if (!visuSetElementsParameters)
    return (subPanel*)0;

  /* Create the callbacks of all the sensitive widgets. */
  createCallBacksElements();

  /* call the visu add routine */
  addSubPanel(visuSetElementsParameters);

  /* Create the list of the available rendering method
     interfaces. */
  listOfRenderingInterfaces = g_hash_table_new_full(g_direct_hash,
						    g_direct_equal,
						    NULL, NULL);
  if (!listOfRenderingInterfaces)
    {
      allocationProblems();
      exit(1);
    }
  for (i = 0; listInitRendenringGtkPanelFunc[i]; i++)
    listInitRendenringGtkPanelFunc[i]();

  return visuSetElementsParameters;
}

GtkWidget *createInteriorElements()
{
  GtkWidget *label;
  GtkWidget *table, *hbox;
  GtkWidget *align;
  GtkWidget *scrollView;
  GtkCellRenderer *renderer;
  char *rgb[4];
  char *rgbName[4] = {"scroll_r", "scroll_g", "scroll_b", "scroll_a"};
  char *light[5];
  int i, j;
/*   GtkTreeModel *tree; */
/*   GtkTreeIter iter; */

  /* We create the structure that store the VisuElements */
  listStoreVisuElements = gtk_list_store_new (N_COLUMNS,
					      G_TYPE_STRING,
					      G_TYPE_POINTER,
					      G_TYPE_POINTER);
  
  rgb[0] = RED_ELE_LABEL;
  rgb[1] = GREEN_ELE_LABEL;
  rgb[2] = BLUE_ELE_LABEL;
  rgb[3] = ALPHA_ELE_LABEL;
  light[0] = AMB_ELE_LABEL;
  light[1] = DIF_ELE_LABEL;
  light[2] = SHI_ELE_LABEL;
  light[3] = SPE_ELE_LABEL;
  light[4] = EMI_ELE_LABEL;

  scrollView = gtk_scrolled_window_new((GtkAdjustment*)0,
				       (GtkAdjustment*)0);
  gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrollView),
				  GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
  gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrollView), GTK_SHADOW_NONE);
  vBoxElements = gtk_vbox_new(FALSE, 0);
  gtk_widget_set_sensitive(vBoxElements, FALSE);
  gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrollView), vBoxElements);


  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vBoxElements), hbox, FALSE, FALSE, 5);
  gtk_widget_show(hbox);
  label = gtk_label_new(_("Set caracteristics for :"));
  gtk_widget_set_name(label, "label_head");
  align = gtk_alignment_new(0., 0.5, 0., 0.);
  gtk_box_pack_start(GTK_BOX(hbox), align, TRUE, TRUE, 2);
  gtk_widget_show(align);
  gtk_container_add(GTK_CONTAINER(align), label);
  gtk_widget_show(label);
  /* We create the tree widget that show the methods. */
  elementsCombo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(listStoreVisuElements));
  renderer = gtk_cell_renderer_text_new();
  gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(elementsCombo), renderer, FALSE);
  gtk_cell_layout_add_attribute(GTK_CELL_LAYOUT(elementsCombo), renderer, "text", 0);
  gtk_box_pack_start(GTK_BOX(hbox), elementsCombo, TRUE, TRUE, 2);
  gtk_widget_show(elementsCombo);

  label = gtk_label_new(_("Standard resources"));
  gtk_widget_set_name(label, "label_head_2");
  gtk_box_pack_start(GTK_BOX(vBoxElements), label, FALSE, FALSE, 5);
  gtk_widget_show(label);

  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vBoxElements), hbox, FALSE, FALSE, 0);
  gtk_widget_show(hbox);
  label = gtk_label_new(_("Color: "));
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 2);
  gtk_widget_show(label);
  widgetVisuElementColor = colorComboBox_new(TRUE);
  gtk_box_pack_start(GTK_BOX(hbox), widgetVisuElementColor, FALSE, FALSE, 2);
  gtk_widget_show(widgetVisuElementColor);
  align = gtk_alignment_new(1., 0.5, 0., 0.);
  gtk_widget_show(align);
  gtk_box_pack_start(GTK_BOX(hbox), align, TRUE, TRUE, 2);
  checkRendered = gtk_check_button_new_with_label(_("rendered"));
  gtk_widget_show(checkRendered);
  gtk_container_add(GTK_CONTAINER(align), checkRendered);

  table = gtk_table_new(3, 2, FALSE);
  gtk_box_pack_start(GTK_BOX(vBoxElements), table, FALSE, FALSE, 5);
  gtk_widget_show(table);
  for (i = 0; i < 3; i++)
    {
      label = gtk_label_new(rgb[i]);
      gtk_table_attach(GTK_TABLE(table), label, 0, 1, i, i + 1,
		       GTK_SHRINK, GTK_SHRINK, 5, 0);
      gtk_widget_show(label);
      rgbElement[i] = gtk_hscale_new_with_range(0., 1., 0.001);
      gtk_scale_set_value_pos(GTK_SCALE(rgbElement[i]),
			      GTK_POS_RIGHT);
      gtk_widget_set_name(rgbElement[i], rgbName[i]);
      gtk_table_attach(GTK_TABLE(table), rgbElement[i],
		       1, 2, i, i + 1,
		       GTK_EXPAND | GTK_FILL, GTK_SHRINK, 5, 0);
      gtk_widget_show(rgbElement[i]);
    }
  table = gtk_table_new(3, 4, FALSE);
  gtk_box_pack_start(GTK_BOX(vBoxElements), table, FALSE, FALSE, 5);
  gtk_widget_show(table);
  for (i = 0; i < 2; i++)
    {
      for (j = 0; j < 2; j++)
	{
	  label = gtk_label_new(light[i * 2 + j]);
	  gtk_misc_set_alignment(GTK_MISC(label), 1., 0.5);
	  gtk_table_attach(GTK_TABLE(table), label, j * 2, j * 2 + 1, i, i + 1,
			   GTK_SHRINK, GTK_SHRINK, 1, 0);
	  gtk_widget_show(label);
	  lightingElement[i * 2 + j] =
	    gtk_hscale_new_with_range(0., 1., 0.01);
	  gtk_scale_set_value_pos(GTK_SCALE(lightingElement[i * 2 + j]),
				  GTK_POS_RIGHT);
	  gtk_widget_set_name(lightingElement[i * 2 +j], "scroll_mat");
	  gtk_table_attach(GTK_TABLE(table), lightingElement[i * 2 + j],
			   2 * j + 1, 2 * j + 2, i, i + 1,
			   GTK_EXPAND | GTK_FILL, GTK_SHRINK, 1, 0);
	  gtk_widget_show(lightingElement[i * 2 + j]);
	}
    }
  label = gtk_label_new(light[4]);
  gtk_misc_set_alignment(GTK_MISC(label), 1., 0.5);
  gtk_table_attach(GTK_TABLE(table), label, 0, 1, i, i + 1,
		   GTK_SHRINK, GTK_SHRINK, 1, 0);
  gtk_widget_show(label);
  lightingElement[4] =
    gtk_hscale_new_with_range(0., 1., 0.01);
  gtk_scale_set_value_pos(GTK_SCALE(lightingElement[4]),
			  GTK_POS_RIGHT);
  gtk_widget_set_name(lightingElement[4], "scroll_mat");
  gtk_table_attach(GTK_TABLE(table), lightingElement[4],
		   1, 2, i, i + 1,
		   GTK_EXPAND | GTK_FILL, GTK_SHRINK, 1, 0);
  gtk_widget_show(lightingElement[4]);
  label = gtk_label_new(rgb[3]);
  gtk_misc_set_alignment(GTK_MISC(label), 1., 0.5);
  gtk_table_attach(GTK_TABLE(table), label, 2, 3, i, i + 1,
		   GTK_SHRINK, GTK_SHRINK, 5, 0);
  gtk_widget_show(label);
  rgbElement[3] = gtk_hscale_new_with_range(0., 1., 0.01);
  gtk_scale_set_value_pos(GTK_SCALE(rgbElement[3]),
			  GTK_POS_RIGHT);
  gtk_widget_set_name(rgbElement[3], rgbName[3]);
  gtk_table_attach(GTK_TABLE(table), rgbElement[3],
		   3, 4, i, i + 1,
		   GTK_EXPAND | GTK_FILL, GTK_SHRINK, 1, 0);
  gtk_widget_show(rgbElement[3]);
  

  gtk_widget_show(vBoxElements);
  gtk_widget_show(scrollView);

  label = gtk_label_new(_("Rendering specific resources"));
  gtk_widget_set_name(label, "label_head_2");
  gtk_box_pack_start(GTK_BOX(vBoxElements), label, FALSE, FALSE, 5);
  gtk_widget_show(label);

  renderingMethodElements = (GtkWidget*)0;

  return scrollView;
}

void createCallBacksElements()
{
  int i;

  idRefreshComboElements = g_signal_connect(G_OBJECT(elementsCombo), "changed",
					    G_CALLBACK(comboVisuElementsChanged), (gpointer)0);
  g_signal_connect(G_OBJECT(widgetVisuElementColor), "color-selected",
		   G_CALLBACK(colorVisuElementChanged), (gpointer)0);
  g_signal_connect(G_OBJECT(checkRendered), "toggled",
		   G_CALLBACK(checkRenderedChanged), (gpointer)0);
  for (i = 0; i < 4; i++)
    g_signal_connect((gpointer)rgbElement[i], "value-changed",
		     G_CALLBACK(changedRGBElements), GINT_TO_POINTER(i));
  for (i = 0; i < 5; i++)
    g_signal_connect((gpointer)lightingElement[i], "value-changed",
		     G_CALLBACK(changedMaterialElements), GINT_TO_POINTER(i));
  /* Connect the signal emitted by visu when a new file is loaded. */
  g_signal_connect(G_OBJECT(visu), "dataReadyForRendering",
		   G_CALLBACK(refreshComboElements), (gpointer)0);
  /* Connect the signal emitted by visu when
     a new rendering method is selected. */
  g_signal_connect(G_OBJECT(visu), "renderingChanged",
		   G_CALLBACK(renderingMethodChanged), (gpointer)0);
  /* Connect the signal emitted by visu when
     a new rendering method is selected. */
  g_signal_connect(G_OBJECT(visu), "resourcesLoaded",
		   G_CALLBACK(resourcesChanged), (gpointer)0);
}

/*****************/
/* Miscellaneous */
/*****************/
gint sortVisuElements(gpointer a, gpointer b)
{
  return strcmp(((VisuElement*)a)->name, ((VisuElement*)b)->name);
}

/*************/
/* Callbacks */
/*************/
void refreshComboElements(GObject *obj, VisuData *dataObj, gpointer userData)
{
  int i;
  GList *listEle, *tmpLst;
  char *label;
  GtkTreeIter iter, selectedIter;
  Color *color;
  int posColor;
  float *rgba;
  VisuElement *prevSelectedElement;

  DBG_fprintf(stderr, "Panel Element : catch 'dataReadyForRendering' signal,"
	      " trying to rebuild element list.\n");
  if (dataObj)
    {
      if (visuDataGet_changeElementFlag(dataObj))
	{
	  DBG_fprintf(stderr,"Panel Element : not removing old elements"
		      " from the liststore of labels.\n");
	  return;
	}
    }

  DBG_fprintf(stderr,"Panel Element : removing old elements"
	      " from the liststore of labels.\n");

  /* Clear old list, and clean all pointers. */
  g_signal_handler_block(G_OBJECT(elementsCombo),
			 idRefreshComboElements);
  gtk_list_store_clear(listStoreVisuElements);
  prevSelectedElement = currentSelectedElement;
  currentSelectedElement = (VisuElement*)0;
  g_signal_handler_unblock(G_OBJECT(elementsCombo),
			   idRefreshComboElements);

  listEle = (GList*)0;
  if (dataObj)
    {
      DBG_fprintf(stderr,"Panel Element : creating %d labels for the"
		  " combobox of VisuElements.\n", dataObj->ntype);
      for(i = 0; i < dataObj->ntype; i++)
	listEle = g_list_append(listEle, (gpointer)dataObj->fromIntToVisuElement[i]);

      gtk_widget_set_sensitive(vBoxElements, TRUE);
    }
  else
    {
      DBG_fprintf(stderr, "Panel Element : there is no element available.\n");
      gtk_widget_set_sensitive(vBoxElements, FALSE);
    }
  listEle = g_list_sort(listEle, (GCompareFunc)sortVisuElements);
  
  tmpLst = listEle;
  while(tmpLst)
    {
      label = getLabelOfElement((VisuElement*)tmpLst->data);
      rgba = ((VisuElement*)tmpLst->data)->rgb;
      color = colorGet_byValues(&posColor, rgba[0], rgba[1], rgba[2], rgba[3]);
      gtk_list_store_append(listStoreVisuElements, &iter);
      gtk_list_store_set(listStoreVisuElements, &iter,
			 COLUMN_NAME, label,
			 COLUMN_POINTER_TO_DATA, tmpLst->data,
			 COLUMN_POINTER_TO_COLOR, color,
			 -1);
      free(label);
      if (tmpLst == listEle)
	selectedIter = iter;
      if (tmpLst->data == (gpointer)prevSelectedElement)
	selectedIter = iter;
      tmpLst = g_list_next(tmpLst);
    }
  if (listEle)
    gtk_combo_box_set_active_iter(GTK_COMBO_BOX(elementsCombo), &selectedIter);
  g_list_free(listEle);

  DBG_fprintf(stderr,"Panel Element : Refresh OK.\n");
}
void renderingMethodChanged(GObject *obj, gpointer userData)
{
  RenderingMethod *method;
/*   setSensitiveFunc sensitive; */
  elementChangedFunc change;
  createGtkWidgetFunc create;
  int sans;

  sans = 1;
  method = getRenderingMethodInUse();
  if (method)
    {
      getRenderingInterface(method, &change, &create);
      if (change && create)
	{
	  sans = 0;
	  DBG_fprintf(stderr,"Panel Element : set the gtk interface for"
		      " the method '%s'.\n", method->name);
	  setElementChangedFunc(change);
	  changeRenderingMethodInterface(create());
	}
    }
  if (sans)
    {
      DBG_fprintf(stderr,"Panel Element : set the gtk interface to null.\n");
      setElementChangedFunc((elementChangedFunc)0);
      changeRenderingMethodInterface((GtkWidget*)0);
    }
}
void comboVisuElementsChanged(GtkComboBox *combobox, gpointer data)
{
  GtkTreeModel *tree;
  gboolean selected;
  GtkTreeIter iter;
  VisuElement *ele;
  char *key;
  int i;
  Color *color;

  selected = gtk_combo_box_get_active_iter(combobox, &iter);
  if (selected)
    {
      tree = gtk_combo_box_get_model(combobox);
      ele = (VisuElement*)0;
      color = (Color*)0;
      gtk_tree_model_get(tree, &iter,
			 COLUMN_POINTER_TO_DATA, &ele,
			 COLUMN_POINTER_TO_COLOR, &color, -1);
      if (!ele)
	{
	  fprintf(stderr, "WARNING! Can't find the VisuElement from the"
		  " GtkComboBox of the Panel Element.\n");
	  return;
	}
    }
  else
    {
      fprintf(stderr, "WARNING! Can't find the selected VisuElement in the"
	      " GtkComboBox of the Panel Element.\n");
      return;
    }

  DBG_fprintf(stderr, "Panel Element : set the selected VisuElement to '%s'.\n", ele->name);
  currentSelectedElement = ele;
  for (i = 0; i < 4; i++)
    gtk_range_set_value(GTK_RANGE(rgbElement[i]), (gdouble)currentSelectedElement->rgb[i]);
  for (i = 0; i < 5; i++)
    gtk_range_set_value(GTK_RANGE(lightingElement[i]), (gdouble)currentSelectedElement->material[i]);
  if (color)
    colorComboBoxSet_selectionByColor(COLOR_COMBOX(widgetVisuElementColor), color);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkRendered), visuElementGet_rendered(ele));

  if (currentSelectedElement && updateRenderingMethodResources)
    updateRenderingMethodResources((gpointer)currentSelectedElement);
}
void changedRGBElements(GtkRange *rg, gpointer data)
{
  GtkAdjustment *adj;
  int numRGB, res;
  gboolean selected;
  GtkTreeIter iter;
  RenderingWindow *window;

  adj = gtk_range_get_adjustment(rg);
  g_return_if_fail(currentSelectedElement);

  numRGB = GPOINTER_TO_INT(data);
  g_return_if_fail(numRGB >= 0 && numRGB < 4);

  res = visuElementSet_RGBValue(currentSelectedElement, numRGB,
				(float)gtk_adjustment_get_value(adj));
  if (res)
    {
      /* Unset the store color in the GtkListStore */
      selected = gtk_combo_box_get_active_iter(GTK_COMBO_BOX(elementsCombo), &iter);
      if (selected)
	gtk_list_store_set(listStoreVisuElements, &iter,
			   COLUMN_POINTER_TO_COLOR, (gpointer)0, -1);
      if (res > 0)
	{
	  window = RENDERING_WINDOW(visuRenderingWindowGet_current());
	  g_return_if_fail(window);
	  visuData_createNodes(renderingWindowGet_visuData(window), currentSelectedElement);
	}

      g_signal_emit (visu, VISU_GET_CLASS (visu)->OpenGLAskForReDraw_signal_id,
		     0 , NULL);
    }
}
void colorVisuElementChanged(ColorComboBox *colorWd, Color *color, gpointer userData)
{
  int res, i;
  int selected;
  GtkTreeIter iter;
  GtkTreeModel *tree;
  float rgba[4];
  int position;
  VisuElement *ele;
  RenderingWindow *window;

  DBG_fprintf(stderr, "Panel Elements : Catch 'color-selected' signal (%p).\n", (gpointer) color);

  selected = gtk_combo_box_get_active_iter(GTK_COMBO_BOX(elementsCombo), &iter);
  if (selected)
    {
      /* Get the pointer of the current visuElement */
      gtk_tree_model_get(GTK_TREE_MODEL(listStoreVisuElements), &iter,
			 COLUMN_POINTER_TO_DATA, &ele, -1);
      /* Set the store color in the GtkListStore */
      gtk_list_store_set(listStoreVisuElements, &iter,
			 COLUMN_POINTER_TO_COLOR, (gpointer)color, -1);
    }
  else
    return;
  res = visuElementSet_allRGBValues(ele, color->rgba);
  if (res)
    {
      for (i = 0; i < 4; i++)
	gtk_range_set_value(GTK_RANGE(rgbElement[i]), ele->rgb[i]);
      if (res > 0)
	{
	  window = RENDERING_WINDOW(visuRenderingWindowGet_current());
	  g_return_if_fail(window);
	  visuData_createNodes(renderingWindowGet_visuData(window), ele);
	}
      g_signal_emit (visu, VISU_GET_CLASS (visu)->OpenGLAskForReDraw_signal_id,
		     0 , NULL);
    }
}
void changedMaterialElements(GtkRange *rg, gpointer data)
{
  GtkAdjustment *adj;
  int res;
  RenderingWindow *window;

  g_return_if_fail(currentSelectedElement);

  g_return_if_fail(GPOINTER_TO_INT(data) >= 0 && GPOINTER_TO_INT(data) < 5);

  adj = gtk_range_get_adjustment(rg);

  res = visuElementSet_materialValue(currentSelectedElement, GPOINTER_TO_INT(data),
				     (float)gtk_adjustment_get_value(adj));
  if (res)
    {
      if (res > 0)
	{
	  window = RENDERING_WINDOW(visuRenderingWindowGet_current());
	  g_return_if_fail(window);
	  visuData_createNodes(renderingWindowGet_visuData(window), currentSelectedElement);
	}
      g_signal_emit (visu, VISU_GET_CLASS (visu)->OpenGLAskForReDraw_signal_id,
		     0 , NULL);
    }
}
static void resourcesChanged(GObject *object, gpointer data)
{
  int i;
  gboolean validIter;
  GtkTreeIter iter;
  VisuElement *ele;
  Color *colorPrev, *color;
  int posColor;

  /* The resources loading could have changed Color of the element,
     so we check all the list. */
  DBG_fprintf(stderr, "Panel Elements : catch the 'resourcesChanged'"
	      " signal, checking color pointers.\n");
  validIter = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(listStoreVisuElements), &iter);
  while (validIter)
    {
      /* Get the pointer of the current visuElement */
      gtk_tree_model_get(GTK_TREE_MODEL(listStoreVisuElements), &iter,
			 COLUMN_POINTER_TO_COLOR, &colorPrev,
			 COLUMN_POINTER_TO_DATA, &ele, -1);
      color = colorGet_byValues(&posColor, ele->rgb[0], ele->rgb[1], ele->rgb[2], ele->rgb[3]);
      DBG_fprintf(stderr, " | element '%s' : previous color %p - new color %p.\n",
		  ele->name, (gpointer)colorPrev, (gpointer)color);
      if (colorPrev != color)
	gtk_list_store_set(listStoreVisuElements, &iter,
			   COLUMN_POINTER_TO_COLOR, (gpointer)color, -1);

      validIter = gtk_tree_model_iter_next(GTK_TREE_MODEL(listStoreVisuElements), &iter);
    }

  if (!currentSelectedElement)
    return;

  for (i = 0; i < 4; i++)
    gtk_range_set_value(GTK_RANGE(rgbElement[i]), currentSelectedElement->rgb[i]);
  for (i = 0; i < 5; i++)
    gtk_range_set_value(GTK_RANGE(lightingElement[i]), currentSelectedElement->material[i]);
  if (currentSelectedElement && updateRenderingMethodResources)
    updateRenderingMethodResources(currentSelectedElement);
}
void checkRenderedChanged(GtkToggleButton *button, gpointer data)
{
  int res;
  GenericRenderingWindow window;

  res = visuElementSet_rendered(currentSelectedElement,
				gtk_toggle_button_get_active(button));
  if (res)
    {
      window = visuRenderingWindowGet_current();
      g_return_if_fail(window);

      visuDataEmit_elementRenderedChange(visuRenderingWindowGet_visuData(window),
					 currentSelectedElement);
      visuData_createNodes(visuRenderingWindowGet_visuData(window),
			   currentSelectedElement);
      g_signal_emit (visu, VISU_GET_CLASS (visu)->OpenGLAskForReDraw_signal_id,
		     0 /* details */,
		     NULL);
    }
}


/********************/
/* Private methods. */
/********************/
char *getLabelOfElement(VisuElement *element)
{
  GString *str;
  char *res;

  str = g_string_new("");
  if (!str)
    {
      allocationProblems();
      exit(1);
    }
  g_string_append_printf(str, _("Element '%s'"), element->name);
  res = str->str;
  g_string_free(str, FALSE);
  return res;
}


/*******************/
/* Public Methods. */
/*******************/
/* It allows the client to set the method use to update
   user defined values. */
void setElementChangedFunc(elementChangedFunc func)
{
  updateRenderingMethodResources = func;
}
/* It adds the interface widget in the subPanel. The variable
   renderingMethodElements pints then to this widget. If
   renderingMethodElements has already a target, this target is
   freed via gtk_widget_destroy. If interface is a null pointer
   the previous renderingMethodElements is removed, but
   nothing replaces it. */
void changeRenderingMethodInterface(GtkWidget* interface)
{
  DBG_fprintf(stderr, "Panel Element : caught 'resourcesLoaded' signal.\n");
  if (renderingMethodElements)
    {
      /* note that gtk_destroy automatically remove
	 renderingMethodElements for its container, so
	 a call to gtk_container_remove is not necessary. */
      DBG_fprintf(stderr, "Panel Element : removing old rendering specific widget.\n");
      gtk_widget_destroy(renderingMethodElements);
    }

  renderingMethodElements = interface;

  if (interface)
    {
      gtk_box_pack_start(GTK_BOX(vBoxElements), interface,
			 FALSE, FALSE, 5);
      gtk_box_reorder_child(GTK_BOX(vBoxElements), interface, 6);
      gtk_widget_show(interface);
    }

  if (currentSelectedElement && updateRenderingMethodResources)
    updateRenderingMethodResources(currentSelectedElement);
}


/* RenderingMethod gtk interface. */

/* This method allows to initiate the method
   to deal with the interface. */
void setInterfaceMethods(RenderingMethod *method,
/* 			 setSensitiveFunc sensitive, */
			 elementChangedFunc change,
			 createGtkWidgetFunc create)
{
  GtkRenderingInterface *interface;

  if (!method)
    return;

  /* Search for an already existing GtkRenderingInterface
     for this name. */
  interface = g_hash_table_lookup(listOfRenderingInterfaces,
				  (gpointer)method);
  if (interface)
    {
      interface->newElementInterface = change;
      interface->createInterface = create;
    }
  else
    {
      interface = malloc(sizeof(GtkRenderingInterface));
      if (!interface)
	{
	  allocationProblems();
	  exit(1);
	}
      interface->newElementInterface = change;
      interface->createInterface = create;
      g_hash_table_insert(listOfRenderingInterfaces,
			  (gpointer)method,
			  (gpointer)interface);
    }
}
/* It reads the value of the interface methods. */
void getRenderingInterface(RenderingMethod *method,
			   elementChangedFunc *change,
			   createGtkWidgetFunc *create)
{
  GtkRenderingInterface *interface;

  *change = (elementChangedFunc)0;
  *create = (createGtkWidgetFunc)0;
  if (!method)
    return;

  interface = g_hash_table_lookup(listOfRenderingInterfaces,
				  (gpointer)method);
  if (interface)
    {
      *change = interface->newElementInterface;
      *create = interface->createInterface;
    }
}
