/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2005)
  
	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-2005)

	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 "panelOpenGL.h"

#include <gtk/gtk.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <visu_gtk.h>
#include <visu_tools.h>
#include <support.h>
#include <gtk_main.h>
#include <opengl.h>
#include <visu_extension.h>
#include <openGLFunctions/light.h>
#include <openGLFunctions/renderingMode.h>
#include <openGLFunctions/view.h>

/**
 * SECTION: panelOpenGL
 * @short_description: The tab where OpenGL options like lights or
 * quality are setup.
 *
 * <para>Nothing tunable here.</para>
 */

static int disableCallbacksOpenGL;
static GtkListStore *light_list_store;
static GtkWidget *panelOpenGL;

#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 5
static GtkListStore *renderingListStore;
#endif

#define OPENGL_FOLLOW_GLOBAL_RENDERING_MODE _("Follow global setting")
#define DEFAULT_GL VISU_GL(visu_ui_rendering_window_getGlScene(visu_ui_main_class_getDefaultRendering()))

/* Private functions. */
static GtkWidget *createInteriorOpenGL();

/* Local callbacks. */
void addPresetOneLightClicked(GtkButton *button, gpointer data);
void addPresetFourLightsClicked(GtkButton *button, gpointer data);
static void selectionChanged(GtkTreeSelection *tree, gpointer data);
static void addNewLightClicked(GtkButton *button, gpointer data);
static void removeSelectedLightsClicked(GtkButton *button, gpointer data);
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 5
static void renderingModeEdited(GtkCellRendererText *cellrenderertext,
				gchar *path, gchar *text, gpointer user_data);
#endif
static void onOpenGLEnter(VisuUiPanel *visu_ui_panel, gpointer data);

VisuUiPanel* visu_ui_panel_gl_init(VisuUiMain *ui _U_)
{
  char *cl = _("Set OpenGL parameters");
  char *tl = _("OpenGL");

  panelOpenGL = visu_ui_panel_newWithIconFromPath("Panel_opengl", cl, tl,
					      "stock-opengl_20.png");
  if (!panelOpenGL)
    return (VisuUiPanel*)0;

  gtk_container_add(GTK_CONTAINER(panelOpenGL), createInteriorOpenGL());
  visu_ui_panel_setDockable(VISU_UI_PANEL(panelOpenGL), TRUE);

  /* Create the callbacks of all the sensitive widgets. */
  g_signal_connect(G_OBJECT(panelOpenGL), "page-entered",
		   G_CALLBACK(onOpenGLEnter), (gpointer)0);

  /* Private parameters. */
  disableCallbacksOpenGL = 0;

  return VISU_UI_PANEL(panelOpenGL);
}

enum {
  LIGHT_POINTER_TO,
  LIGHT_ENABLED,
  LIGHT_POSITION0,
  LIGHT_POSITION1,
  LIGHT_POSITION2,
  LIGHT_MULTIPLIER,
  LIGHT_N_PARAMETERS
};

enum {
  RENDERING_POINTER_TO,
  RENDERING_NAME,
  RENDERING_MODE,
  RENDERING_N_PARAMETERS
};

void light_store_in_list_store(gpointer data, gpointer user_data)
{
  VisuGlLight *light0 = data;
  GtkTreeIter iter;
  GtkListStore *list;

  g_return_if_fail(user_data);
  list = GTK_LIST_STORE(user_data);

  gtk_list_store_append(list, &iter);
  gtk_list_store_set(list, &iter,
		     LIGHT_POINTER_TO, (gpointer)light0,
		     LIGHT_ENABLED, light0->enabled,
		     LIGHT_POSITION0, light0->position[0],
		     LIGHT_POSITION1, light0->position[1],
		     LIGHT_POSITION2, light0->position[2], 
		     LIGHT_MULTIPLIER, light0->multiplier, -1);
}

void light_tree_show_hide(GtkCellRendererToggle *cell_renderer, 
			  gchar *string_path, gpointer user_data)
{
  GtkTreePath* path = gtk_tree_path_new_from_string(string_path);
  GtkTreeIter iter;
  gboolean status;
  VisuGlLight *light0;
  GtkListStore *list;

  g_return_if_fail(user_data);
  list = GTK_LIST_STORE(user_data);

  if(gtk_tree_model_get_iter(GTK_TREE_MODEL(light_list_store), &iter, path) == FALSE)
    return;

  status = gtk_cell_renderer_toggle_get_active(cell_renderer) ? FALSE : TRUE;
  gtk_list_store_set(list, &iter,
		     LIGHT_ENABLED, status, -1);
  gtk_tree_model_get(GTK_TREE_MODEL(list), &iter,
		     LIGHT_POINTER_TO, &light0, -1);

  light0->enabled = status;

  visu_gl_applyLights(DEFAULT_GL);
}

void light_update(GtkCellRendererText *cellrenderertext _U_,
		  gchar *path, gchar *text, gpointer user_data)
{
  GtkTreeIter iter;
  float new_value = atof(text);
  VisuGlLight *light0;

  if(gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(light_list_store),
					 &iter, path))
    {      
      gtk_list_store_set(light_list_store, &iter,
			 GPOINTER_TO_INT(user_data), new_value, -1);
      gtk_tree_model_get(GTK_TREE_MODEL(light_list_store), &iter, 
			 LIGHT_POINTER_TO, &light0, -1);
    }

  if (GPOINTER_TO_INT(user_data) == LIGHT_MULTIPLIER)
    light0->multiplier = new_value;
  else
    light0->position[GPOINTER_TO_INT(user_data)-LIGHT_POSITION0] = new_value;
			 
  visu_gl_applyLights(DEFAULT_GL);
}

static void light_sync_lists(GtkListStore *list)
{
  g_return_if_fail(list);

  gtk_list_store_clear(list);
  g_list_foreach(visu_gl_lights_getList(visu_gl_getLights(DEFAULT_GL)),
		 light_store_in_list_store, (gpointer)list);  
}

GtkWidget* lights_make_tree_view()
{
  GtkTreeViewColumn* column; 
  GtkCellRenderer *cell_show = gtk_cell_renderer_toggle_new();
  GtkCellRenderer *cell_float;
  GtkWidget *light_tree_view;

  light_list_store =
    gtk_list_store_new(LIGHT_N_PARAMETERS, G_TYPE_POINTER,
		       G_TYPE_BOOLEAN, G_TYPE_FLOAT, G_TYPE_FLOAT,
		       G_TYPE_FLOAT, G_TYPE_FLOAT);
  light_tree_view =
    gtk_tree_view_new_with_model(GTK_TREE_MODEL(light_list_store));

  light_sync_lists(light_list_store);

  g_signal_connect(cell_show, "toggled", G_CALLBACK(light_tree_show_hide),
		   (gpointer)light_list_store);

  column = gtk_tree_view_column_new_with_attributes(_("Use"), cell_show,
						    "active", LIGHT_ENABLED, NULL);
  gtk_tree_view_column_set_expand(column, FALSE);
  gtk_tree_view_column_set_alignment(column, 0.5);
  gtk_tree_view_append_column (GTK_TREE_VIEW (light_tree_view), column);

  cell_float = gtk_cell_renderer_text_new();
  g_object_set(G_OBJECT(cell_float), "editable", TRUE, NULL);
  g_signal_connect(G_OBJECT(cell_float), "edited",
		   G_CALLBACK(light_update), GINT_TO_POINTER(LIGHT_POSITION0));
  column = gtk_tree_view_column_new_with_attributes(_("x"), cell_float,
						    "text", LIGHT_POSITION0, NULL);
  gtk_tree_view_append_column (GTK_TREE_VIEW (light_tree_view), column);
  
  cell_float = gtk_cell_renderer_text_new();
  g_object_set(G_OBJECT(cell_float), "editable", TRUE, NULL);
  g_signal_connect(G_OBJECT(cell_float), "edited",
		   G_CALLBACK(light_update), GINT_TO_POINTER(LIGHT_POSITION1));
  column = gtk_tree_view_column_new_with_attributes(_("y"), cell_float,
						    "text", LIGHT_POSITION1, NULL);
  gtk_tree_view_append_column (GTK_TREE_VIEW (light_tree_view), column);

  cell_float = gtk_cell_renderer_text_new();
  g_object_set(G_OBJECT(cell_float), "editable", TRUE, NULL);
  g_signal_connect(G_OBJECT(cell_float), "edited",
		   G_CALLBACK(light_update), GINT_TO_POINTER(LIGHT_POSITION2));
  column = gtk_tree_view_column_new_with_attributes(_("z"), cell_float,
						    "text", LIGHT_POSITION2, NULL);
  gtk_tree_view_append_column (GTK_TREE_VIEW (light_tree_view), column);

  cell_float = gtk_cell_renderer_text_new();
  g_object_set(G_OBJECT(cell_float), "editable", TRUE, NULL);
  g_signal_connect(G_OBJECT(cell_float), "edited",
		   G_CALLBACK(light_update), GINT_TO_POINTER(LIGHT_MULTIPLIER));
  column = gtk_tree_view_column_new_with_attributes(_("power"), cell_float,
						    "text", LIGHT_MULTIPLIER, NULL);
  gtk_tree_view_append_column (GTK_TREE_VIEW (light_tree_view), column);
  gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (light_tree_view), TRUE);

  gtk_tree_selection_set_mode(gtk_tree_view_get_selection(GTK_TREE_VIEW(light_tree_view)),
			      GTK_SELECTION_MULTIPLE);

  return light_tree_view;
}

GtkWidget* make_renderingTreeView()
{
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 5
  GtkTreeViewColumn* column; 
  GtkCellRenderer *renderer;
  GtkWidget *renderingTreeView;
  GtkListStore *namesListStore;
  GtkTreeIter iter;
  const char** names;
  int i;
  GList *list, *all;
  VisuGlRenderingMode mode;
  gchar *label;
  const char *modeName;

  /* Initialize the model that store the possibilities
     for the cellRendererComboBox. */
  namesListStore = gtk_list_store_new(1, G_TYPE_STRING);
  gtk_list_store_append(namesListStore, &iter);
  gtk_list_store_set(namesListStore, &iter,
		     0, OPENGL_FOLLOW_GLOBAL_RENDERING_MODE, -1);
  names = visu_gl_rendering_getAllModeLabels();
  for (i = 0; names[i]; i++)
    {
      gtk_list_store_append(namesListStore, &iter);
      gtk_list_store_set(namesListStore, &iter,
			 0, names[i], -1);
    }

  /* Initialize the model that stores the extensions. */
  renderingListStore =
    gtk_list_store_new(RENDERING_N_PARAMETERS, G_TYPE_POINTER,
		       G_TYPE_STRING, G_TYPE_STRING);
  all = visu_gl_ext_set_getAll
    (VISU_GL_EXT_SET(visu_ui_rendering_window_getGlScene(visu_ui_main_class_getDefaultRendering())));
  for (list = all; list; list = g_list_next(list))
    {
      mode = visu_gl_ext_getPreferedRenderingMode(VISU_GL_EXT(list->data));
      if (mode == VISU_GL_RENDERING_FOLLOW)
        modeName = OPENGL_FOLLOW_GLOBAL_RENDERING_MODE;
      else
        modeName = names[mode];
      g_object_get(G_OBJECT(list->data), "label", &label, NULL);
      gtk_list_store_append(renderingListStore, &iter);
      gtk_list_store_set(renderingListStore, &iter,
                         RENDERING_POINTER_TO, list->data,
                         RENDERING_NAME, label,
                         RENDERING_MODE, modeName, -1);
      g_free(label);
    }
  g_list_free(all);

  renderingTreeView =
    gtk_tree_view_new_with_model(GTK_TREE_MODEL(renderingListStore));

  renderer = gtk_cell_renderer_text_new();
  column = gtk_tree_view_column_new_with_attributes(_("name of extension"), renderer,
						    "text", RENDERING_NAME, NULL);
  gtk_tree_view_column_set_alignment(column, 0.);
  gtk_tree_view_append_column(GTK_TREE_VIEW(renderingTreeView), column);

  renderer = gtk_cell_renderer_combo_new();
  g_object_set(G_OBJECT(renderer), "has-entry", FALSE,
	       "model", namesListStore, "text-column", 0,
	       "editable", TRUE, NULL);
  g_signal_connect(G_OBJECT(renderer), "edited",
		   G_CALLBACK(renderingModeEdited), (gpointer)renderingListStore);
  column = gtk_tree_view_column_new_with_attributes(_("mode"), renderer,
						    "text", RENDERING_MODE, NULL);
  gtk_tree_view_column_set_expand(column, TRUE);
  gtk_tree_view_column_set_alignment(column, 0.5);
  gtk_tree_view_append_column(GTK_TREE_VIEW(renderingTreeView), column);

  g_object_unref(namesListStore);
  
  return renderingTreeView;
#else
  return (GtkWidget*)0;
#endif
}
  
void addNewLightClicked(GtkButton *button _U_, gpointer data)
{
  VisuGlLight *light0;
  GtkTreeIter iter;
  gboolean status;

  g_return_if_fail(data);

  if (!visu_gl_lights_available(visu_gl_getLights(DEFAULT_GL)))
    {
      visu_ui_raiseWarning(_("OpenGL"),
			   _("The maximm number of lights allowed by OpenGL"
			     " has been reached, can't add more."), (GtkWindow*)0);
      return;
    }

  light0 = visu_gl_light_newDefault();
  status = visu_gl_lights_add(visu_gl_getLights(DEFAULT_GL), light0);

  if (!status)
    return;

  gtk_list_store_append(GTK_LIST_STORE(data), &iter);
  gtk_list_store_set(GTK_LIST_STORE(data), &iter,
		     LIGHT_POINTER_TO, (gpointer)light0,
		     LIGHT_ENABLED, light0->enabled,
		     LIGHT_POSITION0, light0->position[0],
		     LIGHT_POSITION1, light0->position[1],
		     LIGHT_POSITION2, light0->position[2], 
		     LIGHT_MULTIPLIER, light0->multiplier, -1);

  visu_gl_applyLights(DEFAULT_GL);
}
void removeSelectedLightsClicked(GtkButton *button _U_, gpointer data)
{
  GList *tmpLst, *selectedRows;
  GtkTreeIter iter;
  gboolean validIter;
  VisuGlLight *light0;
  GtkTreeIter *removableIter;

  g_return_if_fail(GTK_TREE_SELECTION(data));

  selectedRows =
    gtk_tree_selection_get_selected_rows(GTK_TREE_SELECTION(data), NULL);
  tmpLst = selectedRows;
  while (tmpLst)
    {
      validIter = gtk_tree_model_get_iter(GTK_TREE_MODEL(light_list_store),
					  &iter, (GtkTreePath*)tmpLst->data);
      gtk_tree_path_free((GtkTreePath*)tmpLst->data);
      tmpLst->data = (gpointer)0;
      if (!validIter)
	g_warning("Wrong 'path' variable in 'removeSelectedLightsClicked' method.\n");
      else
	{
	  gtk_tree_model_get(GTK_TREE_MODEL(light_list_store), &iter,
			     LIGHT_POINTER_TO, &light0,
			     -1);
	  visu_gl_lights_remove(visu_gl_getLights(DEFAULT_GL), light0);
	  removableIter = g_malloc(sizeof(GtkTreeIter));
	  *removableIter = iter;
	  tmpLst->data = (gpointer)removableIter;
	}
      tmpLst = g_list_next(tmpLst);
    }
  tmpLst = selectedRows;
  while (tmpLst)
    {
      if (tmpLst->data)
	{
	  gtk_list_store_remove(light_list_store, (GtkTreeIter*)tmpLst->data);
	  g_free(tmpLst->data);
	}
      tmpLst = g_list_next(tmpLst);
    }  
  g_list_free(selectedRows);

  visu_gl_applyLights(DEFAULT_GL);
}
void selectionChanged(GtkTreeSelection *tree, gpointer data)
{
  gint nb;

  g_return_if_fail(GTK_WIDGET(data));

  nb = gtk_tree_selection_count_selected_rows(tree);
  if (nb == 0)
    gtk_widget_set_sensitive(GTK_WIDGET(data), FALSE);
  else
    gtk_widget_set_sensitive(GTK_WIDGET(data), TRUE);
}

static gboolean precToSpin(GBinding *binding _U_,
                           const GValue *source_value,
                           GValue *target_value,
                           gpointer user_data _U_)
{
  g_value_set_double(target_value, 100. * g_value_get_float(source_value));
  return TRUE;
}
static gboolean precFromSpin(GBinding *binding _U_,
                             const GValue *source_value,
                             GValue *target_value,
                             gpointer user_data _U_)
{
  g_value_set_float(target_value, g_value_get_double(source_value) / 100.);
  return TRUE;
}
static GtkWidget *createInteriorOpenGL()
{
  GtkWidget *vbox, *hbox;
  GtkWidget *label;
  GtkWidget *scrollLight;
  GtkWidget *button;
  GtkWidget *image;
  GtkWidget *scroll, *viewport;
  GtkWidget *expanderLight, *vbox2, *expand;
  GtkWidget *light_tree_view;
  GtkWidget *checkAntialiasing, *checkImmediateDrawing, *checkTransparency;
  GtkWidget *checkStereo, *spinStereoAngle, *comboOpenGLRendering, *spinPrecision;
  const char** names, **ids;
  int i;
  VisuGl *gl = DEFAULT_GL;
  VisuGlView *view;
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 5
  GtkWidget *scrollRendering, *expanderRendering, *renderingTreeView;
#endif

  scroll = gtk_scrolled_window_new(NULL, NULL);
  gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
				 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);

  viewport = gtk_viewport_new(NULL, NULL);
  gtk_container_add(GTK_CONTAINER(scroll), viewport);

  vbox = gtk_vbox_new(FALSE, 0);
  gtk_container_add(GTK_CONTAINER(viewport), vbox);

  /*************************/
  /* Rendering parameters. */
  /*************************/
  view = visu_gl_node_scene_getGlView(visu_ui_rendering_window_getGlScene(visu_ui_main_class_getDefaultRendering()));
  expand = gtk_expander_new(_("<b>Rendering options:</b>"));
  gtk_expander_set_expanded(GTK_EXPANDER(expand), TRUE);
  label = gtk_expander_get_label_widget(GTK_EXPANDER(expand));
  gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
  gtk_widget_set_name(label, "label_head");
  gtk_box_pack_start(GTK_BOX(vbox), expand, FALSE, FALSE, 5);

  vbox2 = gtk_vbox_new(FALSE, 0);
  gtk_widget_set_margin_start(vbox2, 5);
  gtk_container_add(GTK_CONTAINER(expand), vbox2);
  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox2), hbox, FALSE, FALSE, 2);
  label = gtk_label_new(_("Precision:"));
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 2);
  spinPrecision = gtk_spin_button_new_with_range(10, 500, 5);
  g_object_bind_property_full(view, "precision", spinPrecision, "value",
                              G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
                              precToSpin, precFromSpin, (gpointer)0, (GDestroyNotify)0);
  gtk_box_pack_start(GTK_BOX(hbox), spinPrecision, FALSE, FALSE, 2);
  label = gtk_label_new("%");
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 2);
  comboOpenGLRendering = gtk_combo_box_text_new();
  names = visu_gl_rendering_getAllModeLabels();
  ids = visu_gl_rendering_getAllModes();
  if (names && ids)
    for (i = 0; names[i] && ids[i]; i++)
      gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(comboOpenGLRendering), ids[i], names[i]);
  else
    g_warning("No OpenGL rendering mode available.");
  g_object_bind_property(gl, "mode", comboOpenGLRendering, "active",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_box_pack_end(GTK_BOX(hbox), comboOpenGLRendering, FALSE, FALSE, 2);
  label = gtk_label_new(_("Mode:"));
  gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 2);
  
  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox2), hbox, FALSE, FALSE, 2);
  label = gtk_label_new(_("Antialiase lines:"));
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 2);
  checkAntialiasing = gtk_check_button_new();
  g_object_bind_property(gl, "antialias", checkAntialiasing, "active",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_box_pack_start(GTK_BOX(hbox), checkAntialiasing, FALSE, FALSE, 2);

  checkTransparency = gtk_check_button_new();
  g_object_bind_property(gl, "true-transparency", checkTransparency, "active",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_box_pack_end(GTK_BOX(hbox), checkTransparency, FALSE, FALSE, 2);
  label = gtk_label_new(_("Enhanced transparency:"));
  gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 2);

  hbox = gtk_hbox_new(FALSE, 0);
  gtk_widget_set_sensitive(hbox, visu_gl_getStereoCapability(DEFAULT_GL));
  gtk_box_pack_start(GTK_BOX(vbox2), hbox, FALSE, FALSE, 5);
  label = gtk_label_new(_("Use stereo rendering:"));
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 2);
  checkStereo = gtk_check_button_new();
  g_object_bind_property(gl, "stereo", checkStereo, "active",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_box_pack_start(GTK_BOX(hbox), checkStereo, FALSE, FALSE, 2);
  /* Degrees. */
  label = gtk_label_new(_("deg."));
  gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 2);
  spinStereoAngle = gtk_spin_button_new_with_range(0.5,25.,0.1);
  g_object_bind_property(gl, "stereo-angle", spinStereoAngle, "value",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_box_pack_end(GTK_BOX(hbox), spinStereoAngle, FALSE, FALSE, 2);
  label = gtk_label_new(_("angle:"));
  gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 1);

  /******************************/
  /* Rendering mode parameters. */
  /******************************/
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 5
  expanderRendering = gtk_expander_new(_("Per extension rendering mode:"));
  label = gtk_expander_get_label_widget(GTK_EXPANDER(expanderRendering));
  gtk_box_pack_start(GTK_BOX(vbox2), expanderRendering, TRUE, TRUE, 5);
  scrollRendering = gtk_scrolled_window_new(NULL, NULL);
  gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrollRendering),
				 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
  gtk_widget_set_size_request(scrollRendering, -1, 125);
  gtk_container_add(GTK_CONTAINER(expanderRendering), scrollRendering);
  renderingTreeView = make_renderingTreeView();
  gtk_container_add(GTK_CONTAINER(scrollRendering), renderingTreeView);
#endif
  
  /******************/
  /* Other options. */
  /******************/
  hbox = gtk_hbox_new(FALSE, 0);
  label = gtk_label_new(_("<b>Redraw immediately after changes:</b>"));
  gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
  gtk_widget_set_name(label, "label_head");
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 2);
  checkImmediateDrawing = gtk_check_button_new();
  g_object_bind_property(gl, "immediate", checkImmediateDrawing, "active",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_box_pack_start(GTK_BOX(hbox), checkImmediateDrawing, FALSE, FALSE, 2);
  gtk_widget_show(checkImmediateDrawing);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 5);

  /*********************/
  /* VisuGlLight parameters. */
  /*********************/
  expanderLight = gtk_expander_new(_("<b>Light sources:</b>"));
  label = gtk_expander_get_label_widget(GTK_EXPANDER(expanderLight));
  gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
  gtk_widget_set_name(label, "label_head");
  gtk_box_pack_start(GTK_BOX(vbox), expanderLight, FALSE, FALSE, 5);
  hbox = gtk_hbox_new(FALSE, 0);
  gtk_container_add(GTK_CONTAINER(expanderLight), hbox);
  scrollLight = gtk_scrolled_window_new (NULL, NULL);
  gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrollLight),
				 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
  gtk_box_pack_start(GTK_BOX(hbox), scrollLight, TRUE, TRUE, 0);
  light_tree_view = lights_make_tree_view();
  gtk_container_add(GTK_CONTAINER(scrollLight), light_tree_view);
  vbox2 = gtk_vbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(hbox), vbox2, FALSE, FALSE, 0);
  button = gtk_button_new();
  image = gtk_image_new_from_icon_name("list-add",
                                       GTK_ICON_SIZE_BUTTON);
  gtk_container_add(GTK_CONTAINER(button), image);
  g_signal_connect(G_OBJECT(button), "clicked",
		   G_CALLBACK(addNewLightClicked),
		   (gpointer)gtk_tree_view_get_model(GTK_TREE_VIEW(light_tree_view)));
  gtk_box_pack_start(GTK_BOX(vbox2), button, FALSE, FALSE, 1);
  button = gtk_button_new();
  gtk_widget_set_sensitive(button, FALSE);
  image = gtk_image_new_from_icon_name("list-remove",
                                       GTK_ICON_SIZE_BUTTON);
  gtk_container_add(GTK_CONTAINER(button), image);
  g_signal_connect(G_OBJECT(button), "clicked",
		   G_CALLBACK(removeSelectedLightsClicked),
		   (gpointer)gtk_tree_view_get_selection(GTK_TREE_VIEW(light_tree_view)));
  gtk_box_pack_start(GTK_BOX(vbox2), button, FALSE, FALSE, 1);
  g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(light_tree_view))),
		   "changed", G_CALLBACK(selectionChanged), (gpointer)button);

  button = gtk_button_new();
  image = create_pixmap((GtkWidget*)0, "stock-one-light_20.png");
  gtk_container_add(GTK_CONTAINER(button), image);
  g_signal_connect(G_OBJECT(button), "clicked",
		   G_CALLBACK(addPresetOneLightClicked),
		   (gpointer)gtk_tree_view_get_model(GTK_TREE_VIEW(light_tree_view)));
  gtk_box_pack_end(GTK_BOX(vbox2), button, FALSE, FALSE, 1);
  button = gtk_button_new();
  image = create_pixmap((GtkWidget*)0, "stock-four-lights_20.png");
  gtk_container_add(GTK_CONTAINER(button), image);
  g_signal_connect(G_OBJECT(button), "clicked",
		   G_CALLBACK(addPresetFourLightsClicked),
		   (gpointer)gtk_tree_view_get_model(GTK_TREE_VIEW(light_tree_view)));
  gtk_box_pack_end(GTK_BOX(vbox2), button, FALSE, FALSE, 1);

  gtk_widget_show_all(scroll);
  return scroll;
}

/*************/
/* Callbacks */
/*************/
static void onOpenGLEnter(VisuUiPanel *visu_ui_panel _U_, gpointer data _U_)
{
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 5
  const gchar **names;
  gchar *name;
  GtkTreeIter iter;
  gboolean valid;
  VisuGlExt *ext;
  VisuGlRenderingMode mode;
#endif

  disableCallbacksOpenGL = 1;
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 5
  names = visu_gl_rendering_getAllModeLabels();
  valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(renderingListStore), &iter);
  while(valid)
    {
      gtk_tree_model_get(GTK_TREE_MODEL(renderingListStore), &iter,
			 RENDERING_POINTER_TO, &ext,
			 RENDERING_MODE, &name, -1);
      mode = visu_gl_ext_getPreferedRenderingMode(ext);
      if (mode < VISU_GL_RENDERING_N_MODES && strcmp(names[mode], name))
        gtk_list_store_set(renderingListStore, &iter,
                           RENDERING_MODE, names[mode], -1);
      else if (mode == VISU_GL_RENDERING_FOLLOW &&
               strcmp(OPENGL_FOLLOW_GLOBAL_RENDERING_MODE, name))
        gtk_list_store_set(renderingListStore, &iter, RENDERING_MODE,
                           OPENGL_FOLLOW_GLOBAL_RENDERING_MODE, -1);
      g_free(name);
      valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(renderingListStore), &iter);
    }
#endif
  disableCallbacksOpenGL = 0;
}
void addPresetOneLightClicked(GtkButton *button _U_, gpointer data)
{
  VisuGlLight *light;
  gboolean status;

  g_return_if_fail(data);

  status = visu_gl_lights_removeAll(visu_gl_getLights(DEFAULT_GL));

  light = visu_gl_light_newDefault();
  status = visu_gl_lights_add(visu_gl_getLights(DEFAULT_GL), light) || status;

  light_sync_lists(GTK_LIST_STORE(data)); 

  visu_gl_applyLights(DEFAULT_GL);
}
void addPresetFourLightsClicked(GtkButton *button _U_, gpointer data)
{
  VisuGlLight *light;
  gboolean status;

  g_return_if_fail(data);

  status = visu_gl_lights_removeAll(visu_gl_getLights(DEFAULT_GL));

  light = visu_gl_light_newDefault();
  light->multiplier = 0.25;
  status = visu_gl_lights_add(visu_gl_getLights(DEFAULT_GL), light) || status;

  light = visu_gl_light_newDefault();
  light->position[0] *= -1.;
  light->multiplier = 0.25;
  status = visu_gl_lights_add(visu_gl_getLights(DEFAULT_GL), light) || status;

  light = visu_gl_light_newDefault();
  light->position[1] *= -1.;
  light->multiplier = 0.25;
  status = visu_gl_lights_add(visu_gl_getLights(DEFAULT_GL), light) || status;

  light = visu_gl_light_newDefault();
  light->position[0] *= -1.;
  light->position[1] *= -1.;
  light->multiplier = 0.25;
  status = visu_gl_lights_add(visu_gl_getLights(DEFAULT_GL), light) || status;

  light_sync_lists(GTK_LIST_STORE(data)); 

  visu_gl_applyLights(DEFAULT_GL);
}
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 5
static void renderingModeEdited(GtkCellRendererText *cellrenderertext _U_,
				gchar *path, gchar *text, gpointer user_data)
{
  GtkListStore *list;
  gboolean valid;
  GtkTreeIter iter;
  const char** names;
  int mode;
  VisuGlExt *ext;

  if (disableCallbacksOpenGL)
    return;

  list = GTK_LIST_STORE(user_data);
  g_return_if_fail(list);

  valid = gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(list),
					      &iter, path);
  g_return_if_fail(valid);

  if (!strcmp(text, OPENGL_FOLLOW_GLOBAL_RENDERING_MODE))
    {
      valid = TRUE;
      mode = VISU_GL_RENDERING_FOLLOW;
    }
  else
    {
      valid = FALSE;
      names = visu_gl_rendering_getAllModeLabels();
      for (mode = 0; names[mode] && !valid; mode++)
	valid = !strcmp(text, names[mode]);
      mode -= 1;
    }
  g_return_if_fail(valid);

  gtk_tree_model_get(GTK_TREE_MODEL(list), &iter, 
		     RENDERING_POINTER_TO, &ext, -1);
  valid = visu_gl_ext_setPreferedRenderingMode(ext, mode);

  if (mode == VISU_GL_RENDERING_FOLLOW)
    gtk_list_store_set(list, &iter,
		       RENDERING_MODE, OPENGL_FOLLOW_GLOBAL_RENDERING_MODE, -1);
  else
    {
      names = visu_gl_rendering_getAllModeLabels();
      gtk_list_store_set(list, &iter,
			 RENDERING_MODE, names[mode], -1);
    }
}
#endif
