/*   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 "panelFogBgColor.h"

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

#include <support.h>
#include <gtk_main.h>
#include <visu_tools.h>
#include <visu_gtk.h>
#include <visu_extset.h>
#include <extensions/fogAndBGColor.h>
#include <coreTools/toolColor.h>

/**
 * SECTION:panelFogBgColor
 * @short_description: The widget to tune the background and the fog.
 *
 * <para>This is the user interface for fog and the background. The
 * background can be either uniform or use a bitmap picture. The fog
 * can be of different colours, custom or background.</para>
 */

/* Sensitive widget in this subpanel. */
static GtkWidget *checkFogIsOn;
static GtkWidget *rangeFogStart, *rangeFogEnd;
static GtkWidget *radioBgFog, *radioOtherFog;
static GtkWidget *rgbBgColor[4];
static GtkWidget *rgbFogColor[3];
static GtkWidget *bgImageWd, *checkFollowZoom, *checkImageTitle;

/* Private functions. */
static GtkWidget *createInteriorFogBgColor(VisuUiMain *ui);
static gboolean loadBgFile(gpointer data);

/* Local callbacks. */
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 11
static void onBgImageSet(GtkFileChooserButton *filechooserbutton, gpointer data);
static void onFileNotified(VisuGlExtBg *bg, GParamSpec *pspec,
                           GtkFileChooserButton *button);
#else
static void onBgImageSet(GtkDialog *dialog, gint response, gpointer data);
#endif
#if GTK_MAJOR_VERSION == 2 && GTK_MINOR_VERSION < 6
static void onBgImageChoose(GtkButton *bt, gpointer data);
#endif
static void onBgImageUnset(GtkButton *bt, gpointer data);
static void onBgImageFollow(GtkToggleButton *bt, gpointer data);

static GtkWidget *panelFogBgColor;
static int disableCallbacksFogBgColor;

VisuUiPanel* visu_ui_panel_bg_init(VisuUiMain *ui)
{
  char *cl = _("Fog and background color");
  char *tl = _("Fog & bg");

  panelFogBgColor = visu_ui_panel_newWithIconFromPath("Panel_fog_and_bg_color", cl, tl,
                                                      "stock-fog_20.png");
  if (!panelFogBgColor)
    return (VisuUiPanel*)0;
  gtk_container_add(GTK_CONTAINER(panelFogBgColor), createInteriorFogBgColor(ui));
  visu_ui_panel_setDockable(VISU_UI_PANEL(panelFogBgColor), TRUE);

  /* Private parameters. */
  disableCallbacksFogBgColor = 0;

  return VISU_UI_PANEL(panelFogBgColor);
}

static void update_preview_cb(GtkFileChooser *file_chooser, gpointer data)
{
  GtkWidget *preview;
  char *filename;
  GdkPixbuf *pixbuf;
  gboolean have_preview;

  preview = GTK_WIDGET (data);
  filename = gtk_file_chooser_get_preview_filename (file_chooser);

  if (filename)
    pixbuf = gdk_pixbuf_new_from_file_at_size (filename, 128, 128, NULL);
  else
    pixbuf = (GdkPixbuf*)0;
  have_preview = (pixbuf != NULL);
  g_free (filename);

  gtk_image_set_from_pixbuf (GTK_IMAGE (preview), pixbuf);
  if (pixbuf)
    g_object_unref (pixbuf);

  gtk_file_chooser_set_preview_widget_active(file_chooser, have_preview);
}

static GtkWidget *createInteriorFogBgColor(VisuUiMain *ui)
{
  GtkWidget *vbox, *hbox;
  GtkWidget *label;
  GtkWidget *table;
#define RED_LABEL   _("R:")
#define GREEN_LABEL _("G:")
#define BLUE_LABEL  _("B:")
#define ALPHA_LABEL  _("A:")
  char *rgb[4];
  const char *rgbName[4] = {"scroll_r", "scroll_g", "scroll_b", "scroll_a"};
  const char *rgbProp[4] = {"bg-red", "bg-green", "bg-blue", "bg-alpha"};
  const char *fogProp[4] = {"fog-red", "fog-green", "fog-blue", "fog-alpha"};
  int i;
  GtkWidget *dialog, *bt, *preview;
  GtkFileFilter *filters;
  VisuGlNodeScene *scene;
#if GTK_MAJOR_VERSION == 2 && GTK_MINOR_VERSION < 12
  GtkTooltips *tooltips;

  tooltips = gtk_tooltips_new ();
#endif

  rgb[0] = RED_LABEL;
  rgb[1] = GREEN_LABEL;
  rgb[2] = BLUE_LABEL;
  rgb[3] = ALPHA_LABEL;

  scene = visu_ui_rendering_window_getGlScene(visu_ui_main_getRendering(ui));
    
  vbox = gtk_vbox_new(FALSE, 0);
  gtk_widget_set_margin_start(vbox, 5);
  gtk_widget_set_margin_end(vbox, 5);

  table = gtk_grid_new();
  tool_grid_resize(table, 5, 2);
  gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 5);
  hbox = gtk_hbox_new(FALSE, 0);
  gtk_grid_attach(GTK_GRID(table), hbox, 0, 0, 2, 1);
  label = gtk_label_new(_("Background:"));
  gtk_widget_set_name(label, "label_head");
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 2);
  for (i = 0; i < 4; i++)
    {
      label = gtk_label_new(rgb[i]);
      gtk_grid_attach(GTK_GRID(table), label, 0, i + 1, 1, 1);
      rgbBgColor[i] = gtk_hscale_new_with_range(0., 1., 0.001);
      g_object_bind_property(scene, rgbProp[i],
                             gtk_range_get_adjustment(GTK_RANGE(rgbBgColor[i])), "value",
                             G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
      gtk_scale_set_value_pos(GTK_SCALE(rgbBgColor[i]),
			      GTK_POS_RIGHT);
      gtk_widget_set_name(rgbBgColor[i], rgbName[i]);
      gtk_widget_set_hexpand(rgbBgColor[i], TRUE);
      gtk_grid_attach(GTK_GRID(table), rgbBgColor[i], 1, i + 1, 1, 1);
    }
  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
  label = gtk_label_new(_("Insert an image:"));
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 5);
  dialog = gtk_file_chooser_dialog_new(_("Choose a background image"),
				       (GtkWindow*)0,
				       GTK_FILE_CHOOSER_ACTION_OPEN,
				       TOOL_ICON_CANCEL, GTK_RESPONSE_CANCEL,
				       TOOL_ICON_OPEN, GTK_RESPONSE_ACCEPT,
				       NULL);
  filters = gtk_file_filter_new();
  gtk_file_filter_add_pixbuf_formats(filters);
  gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(dialog), filters);
  preview = gtk_image_new();
  gtk_file_chooser_set_preview_widget(GTK_FILE_CHOOSER(dialog), preview);
  gtk_file_chooser_set_preview_widget_active(GTK_FILE_CHOOSER(dialog), FALSE);
  g_signal_connect(GTK_FILE_CHOOSER(dialog), "update-preview",
		   G_CALLBACK(update_preview_cb), preview);
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 5
  bgImageWd = gtk_file_chooser_button_new_with_dialog(dialog);
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 11
  g_signal_connect(G_OBJECT(bgImageWd), "file-set",
		   G_CALLBACK(onBgImageSet), (gpointer)0);
  g_signal_connect(visu_gl_node_scene_getBgImage(scene), "notify::background-file",
                   G_CALLBACK(onFileNotified), bgImageWd);
  onFileNotified(visu_gl_node_scene_getBgImage(scene),
                 (GParamSpec*)0, GTK_FILE_CHOOSER_BUTTON(bgImageWd));
#else
  g_signal_connect(G_OBJECT(dialog), "response",
		   G_CALLBACK(onBgImageSet), (gpointer)bgImageWd);
#endif
#else
  bgImageWd = gtk_button_new_from_stock(GTK_STOCK_OPEN);
  g_signal_connect(G_OBJECT(dialog), "clicked",
		   G_CALLBACK(onBgImageChoose), (gpointer)dialog);
#endif
  gtk_box_pack_start(GTK_BOX(hbox), bgImageWd, TRUE, TRUE, 0);
  bt = gtk_button_new();
  gtk_widget_set_tooltip_text(bt, _("Remove the background image."));
  gtk_container_add(GTK_CONTAINER(bt),
		    gtk_image_new_from_icon_name("edit-clear", GTK_ICON_SIZE_MENU));
  gtk_box_pack_start(GTK_BOX(hbox), bt, FALSE, FALSE, 5);
  g_signal_connect(G_OBJECT(bt), "clicked",
		   G_CALLBACK(onBgImageUnset), (gpointer)bgImageWd);
  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 5);
  checkFollowZoom = gtk_check_button_new_with_mnemonic(_("_follow camera"));
  g_signal_connect(G_OBJECT(checkFollowZoom), "toggled",
		   G_CALLBACK(onBgImageFollow), (gpointer)0);
  gtk_box_pack_end(GTK_BOX(hbox), checkFollowZoom, FALSE, FALSE, 0);
  checkImageTitle = gtk_check_button_new_with_mnemonic(_("_display filename"));
  g_object_bind_property(visu_gl_node_scene_getBgImage(scene),
                         "display-background-filename",
                         checkImageTitle, "active",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_box_pack_end(GTK_BOX(hbox), checkImageTitle, FALSE, FALSE, 0);

  hbox = gtk_hbox_new(FALSE, 0);
  label = gtk_label_new(_("Use fog:"));
  gtk_widget_set_name(label, "label_head");
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 2);
  checkFogIsOn = gtk_check_button_new();
  g_object_bind_property(scene, "fog-active", checkFogIsOn, "active",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_box_pack_start(GTK_BOX(hbox), checkFogIsOn, FALSE, FALSE, 2);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 5);
  
  table = gtk_grid_new();
  tool_grid_resize(table, 2, 2);
  gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 5);
  label = gtk_label_new(_("Start:"));
  gtk_label_set_xalign(GTK_LABEL(label), 1.);
  gtk_grid_attach(GTK_GRID(table), label, 0, 0, 1, 1);
  rangeFogStart = gtk_hscale_new_with_range(0., 1., 0.001);
  g_object_bind_property(scene, "fog-start", 
                         gtk_range_get_adjustment(GTK_RANGE(rangeFogStart)), "value",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 11
  gtk_range_set_restrict_to_fill_level(GTK_RANGE(rangeFogStart), TRUE);
  gtk_range_set_show_fill_level(GTK_RANGE(rangeFogStart), TRUE);
#endif
  gtk_scale_set_value_pos(GTK_SCALE(rangeFogStart),
			  GTK_POS_RIGHT);
  gtk_widget_set_hexpand(rangeFogStart, TRUE);
  gtk_grid_attach(GTK_GRID(table), rangeFogStart, 1, 0, 1, 1);
  label = gtk_label_new(_("End:"));
  gtk_label_set_xalign(GTK_LABEL(label), 1.);
  gtk_grid_attach(GTK_GRID(table), label, 0, 1, 1, 1);
  rangeFogEnd = gtk_hscale_new_with_range(0., 1., 0.001);
  g_object_bind_property(scene, "fog-full", 
                         gtk_range_get_adjustment(GTK_RANGE(rangeFogEnd)), "value",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 11
  g_object_bind_property(gtk_range_get_adjustment(GTK_RANGE(rangeFogEnd)), "value",
                         rangeFogStart, "fill-level", G_BINDING_SYNC_CREATE);
#endif
  gtk_scale_set_value_pos(GTK_SCALE(rangeFogEnd),
			  GTK_POS_RIGHT);
  gtk_widget_set_hexpand(rangeFogEnd, TRUE);
  gtk_grid_attach(GTK_GRID(table), rangeFogEnd, 1, 1, 1, 1);

  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 5);
  label = gtk_label_new(_("Color:"));
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 2);
  radioBgFog = gtk_radio_button_new_with_label(NULL, _("background color"));
  g_object_bind_property(scene, "fog-follows-bg", radioBgFog, "active",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_box_pack_start(GTK_BOX(hbox), radioBgFog, FALSE, FALSE, 2);
  radioOtherFog =
    gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(radioBgFog),
						_("specific color"));
  g_object_bind_property(scene, "fog-follows-bg", radioOtherFog, "active",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL | G_BINDING_INVERT_BOOLEAN);
  gtk_box_pack_start(GTK_BOX(hbox), radioOtherFog, FALSE, FALSE, 2);

  table = gtk_grid_new();
  tool_grid_resize(table, 5, 2);
  gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 5);
  for (i = 0; i < 3; i++)
    {
      label = gtk_label_new(rgb[i]);
      gtk_grid_attach(GTK_GRID(table), label, 0, i + 1, 1, 1);
      rgbFogColor[i] = gtk_hscale_new_with_range(0., 1., 0.001);
      g_object_bind_property(scene, fogProp[i],
                             gtk_range_get_adjustment(GTK_RANGE(rgbFogColor[i])), "value",
                             G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
      g_object_bind_property(radioOtherFog, "active", rgbFogColor[i], "sensitive",
                             G_BINDING_SYNC_CREATE);
      gtk_scale_set_value_pos(GTK_SCALE(rgbFogColor[i]),
			      GTK_POS_RIGHT);
      gtk_widget_set_sensitive(rgbFogColor[i], FALSE);
      gtk_widget_set_name(rgbFogColor[i], rgbName[i]);
      gtk_widget_set_hexpand(rgbFogColor[i], TRUE);
      gtk_grid_attach(GTK_GRID(table), rgbFogColor[i], 1, i + 1, 1, 1);
    }

  gtk_widget_show_all(vbox);

  return vbox;
}

/*************/
/* Callbacks */
/*************/
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 11
static void onBgImageSet(GtkFileChooserButton *filechooserbutton, gpointer data _U_)
{
  gchar *filename;

  DBG_fprintf(stderr, "Panel Fog & Bg: bg image changed.\n");
  filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filechooserbutton));
  if (!filename)
    return;
  g_idle_add(loadBgFile, (gpointer)filename);
}
#else
static void onBgImageSet(GtkDialog *dialog, gint response, gpointer data _U_)
{
  gchar *filename;

  if (response != GTK_RESPONSE_ACCEPT)
    return;

  filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
  g_idle_add(loadBgFile, (gpointer)filename);
}
#endif
#if GTK_MAJOR_VERSION == 2 && GTK_MINOR_VERSION < 6
static void onBgImageChoose(GtkButton *bt, gpointer data)
{
  gchar *filename;

  if (gtk_dialog_run(GTK_DIALOG(data)) != GTK_RESPONSE_ACCEPT)
    return;

  filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(data));
  g_idle_add(loadBgFile, (gpointer)filename);
}
#endif
static gboolean loadBgFile(gpointer data)
{
  GError *error;
  VisuGlNodeScene *scene;

  scene = visu_ui_rendering_window_getGlScene(visu_ui_main_class_getDefaultRendering());
  error = (GError*)0;
  visu_gl_ext_bg_setFile(visu_gl_node_scene_getBgImage(scene),
                         (const gchar*)data, &error);

  if (error)
    {
      visu_ui_raiseWarning(_("Load image file"), error->message, (GtkWindow*)0);
      g_error_free(error);
    }
  g_free(data);
  return G_SOURCE_REMOVE;
}
static void onBgImageUnset(GtkButton *bt _U_, gpointer data)
{
  VisuGlNodeScene *scene;
  scene = visu_ui_rendering_window_getGlScene(visu_ui_main_class_getDefaultRendering());
  visu_gl_ext_bg_setFile(visu_gl_node_scene_getBgImage(scene), (const gchar*)0, NULL);
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 5
  gtk_file_chooser_unselect_all(GTK_FILE_CHOOSER(data));
#endif
}
static void onBgImageFollow(GtkToggleButton *bt, gpointer data _U_)
{
  VisuGlView *view;
  VisuGlNodeScene *scene;

  view = visu_ui_panel_getView(VISU_UI_PANEL(panelFogBgColor));
  g_return_if_fail(view);

  scene = visu_ui_rendering_window_getGlScene(visu_ui_main_class_getDefaultRendering());
  visu_gl_ext_bg_setFollowCamera(visu_gl_node_scene_getBgImage(scene),
                                 gtk_toggle_button_get_active(bt),
                                 view->camera.gross, view->camera.xs, view->camera.ys);
}
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 5
static void onFileNotified(VisuGlExtBg *bg, GParamSpec *pspec _U_,
                           GtkFileChooserButton *button)
{
  gchar *path;

  g_object_get(bg, "background-file", &path, NULL);
  if (path)
    gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(button), path);
  else
    gtk_file_chooser_unselect_all(GTK_FILE_CHOOSER(button));
  g_free(path);
}
#endif
