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

#include "gtk_numericalEntryWidget.h"

/**
 * SECTION:gtk_numericalEntryWidget
 * @short_description: Defines a widget to enter numerical values without
 * any boundary or precision constrains.
 * 
 * <para>This widget is based on the #GtkEntry widget but behaves more
 * like a #GtkSpinButton is fact. It is designed to enter numerical
 * values, but without any boundary or precision constrains. One can
 * use either plain or scientific notations.</para>
 */

enum {
  VALUE_CHANGED_SIGNAL,
  LAST_SIGNAL
};
static guint _signals[LAST_SIGNAL] = { 0 };
enum
  {
    PROP_0,
    VALUE_PROP,
    N_PROP
  };
static GParamSpec *properties[N_PROP];

#define VISU_UI_NUMERICAL_ENTRY_FORMAT_DEFAULT "%g"

struct _VisuUiNumericalEntry
{
  GtkEntry entry;

  double value;
  double printed_value;
  gchar *format;
/*   VisuUiNumericalEntryPrivate *private; */
};

struct _VisuUiNumericalEntryClass
{
  GtkEntryClass parent_class;

  void (*changed) (VisuUiNumericalEntry *numEntry, double oldValue);
};

static void visu_ui_numerical_entry_finalize(GObject *obj);
static void visu_ui_numerical_entry_get_property(GObject* obj, guint property_id,
                                                 GValue *value, GParamSpec *pspec);
static void visu_ui_numerical_entry_set_property(GObject* obj, guint property_id,
                                                 const GValue *value, GParamSpec *pspec);
static gboolean visu_ui_numerical_entry_focus_in(GtkWidget *wd, GdkEventFocus *event);
static gboolean visu_ui_numerical_entry_focus_out(GtkWidget *wd, GdkEventFocus *event);
static void visu_ui_numerical_entry_activate(GtkEntry *entry);

G_DEFINE_TYPE(VisuUiNumericalEntry, visu_ui_numerical_entry, GTK_TYPE_ENTRY)

/* Local methods. */
static void printStoredValue(VisuUiNumericalEntry* numericalEntry);
static gboolean parsePrintedValue(VisuUiNumericalEntry *numericalEntry, double *value);

static void visu_ui_numerical_entry_class_init(VisuUiNumericalEntryClass *klass)
{
  DBG_fprintf(stderr, "Gtk VisuUiNumericalEntry : creating the class of the widget.\n");

  DBG_fprintf(stderr, "                     - adding new signals ;\n");
  /**
   * VisuUiNumericalEntry::value-changed:
   * @entry: the #VisuUiNumericalEntry that emits the signal ;
   * @oldValue: the previous value.
   *
   * This signal is emitted when a new valid numerical value is entered.
   *
   * Since: 3.1
   */
  _signals[VALUE_CHANGED_SIGNAL] =
    g_signal_new ("value-changed",
		  G_TYPE_FROM_CLASS (klass),
		  G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION,
		  G_STRUCT_OFFSET (VisuUiNumericalEntryClass, changed),
		  NULL, 
		  NULL,                
		  g_cclosure_marshal_VOID__DOUBLE,
		  G_TYPE_NONE, 1, G_TYPE_DOUBLE);

  /* Connect freeing methods. */
  G_OBJECT_CLASS(klass)->finalize = visu_ui_numerical_entry_finalize;
  G_OBJECT_CLASS(klass)->set_property = visu_ui_numerical_entry_set_property;
  G_OBJECT_CLASS(klass)->get_property = visu_ui_numerical_entry_get_property;
  GTK_WIDGET_CLASS(klass)->focus_in_event  = visu_ui_numerical_entry_focus_in;
  GTK_WIDGET_CLASS(klass)->focus_out_event = visu_ui_numerical_entry_focus_out;
  GTK_ENTRY_CLASS(klass)->activate = visu_ui_numerical_entry_activate;

  /**
   * VisuUiNumericalEntry::value:
   *
   * Store the value in the entry.
   *
   * Since: 3.8
   */
  properties[VALUE_PROP] = g_param_spec_double("value", "Value", "numerical value",
                                               -G_MAXFLOAT, G_MAXFLOAT, 0.,
                                               G_PARAM_CONSTRUCT | G_PARAM_READWRITE);
  g_object_class_install_properties(G_OBJECT_CLASS(klass), N_PROP, properties);
}

static void visu_ui_numerical_entry_finalize(GObject *obj)
{
  VisuUiNumericalEntry *entry;

  g_return_if_fail(obj);

  DBG_fprintf(stderr, "Gtk VisuUiNumericalEntry: finalize object %p.\n", (gpointer)obj);

  entry = VISU_UI_NUMERICAL_ENTRY(obj);
  g_free(entry->format);

  /* Chain up to the parent class */
  G_OBJECT_CLASS(visu_ui_numerical_entry_parent_class)->finalize(obj);

  DBG_fprintf(stderr, "Gtk VisuUiNumericalEntry: freeing ... OK.\n");
}
static void visu_ui_numerical_entry_get_property(GObject* obj, guint property_id,
                                                 GValue *value, GParamSpec *pspec)
{
  VisuUiNumericalEntry *self = VISU_UI_NUMERICAL_ENTRY(obj);

  DBG_fprintf(stderr, "Gtk VisuUiNumericalEntry: get property '%s'.\n",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case VALUE_PROP:
      g_value_set_double(value, self->value);
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}
static void visu_ui_numerical_entry_set_property(GObject* obj, guint property_id,
                                                 const GValue *value, GParamSpec *pspec)
{
  VisuUiNumericalEntry *self = VISU_UI_NUMERICAL_ENTRY(obj);

  DBG_fprintf(stderr, "Gtk VisuUiNumericalEntry: set property '%s'.\n",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case VALUE_PROP:
      visu_ui_numerical_entry_setValue(self, g_value_get_double(value));
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}

static void visu_ui_numerical_entry_init(VisuUiNumericalEntry *numericalEntry)
{
  DBG_fprintf(stderr, "Gtk VisuUiNumericalEntry : initializing new object (%p).\n",
	      (gpointer)numericalEntry);

  numericalEntry->format = g_strdup(VISU_UI_NUMERICAL_ENTRY_FORMAT_DEFAULT);
}

/**
 * visu_ui_numerical_entry_new :
 * @value: the initial value.
 *
 * A #VisuUiNumericalEntry widget is like a #GtkEntry widget, but it only accepts
 * double precision values (written in plain format, e.g. 1.23456, or scientific
 * notation, e.g. 1.2345e6). The widget can't be blank and there is always
 * a value printed in it. If the user erase the current value or enter something
 * that is not a recognised double precision value, the widget returns to its previous
 * valid value.
 *
 * Returns: a newly created #VisuUiNumericalEntry widget.
 */
GtkWidget* visu_ui_numerical_entry_new(double value)
{
  return g_object_new(VISU_TYPE_UI_NUMERICAL_ENTRY, "value", value, NULL);
}

static void printStoredValue(VisuUiNumericalEntry* numericalEntry)
{
  gchar *str;

  g_return_if_fail(VISU_IS_UI_NUMERICAL_ENTRY(numericalEntry));

  str = g_strdup_printf(numericalEntry->format, numericalEntry->value);
  gtk_entry_set_text(GTK_ENTRY(numericalEntry), str);
  g_free(str);

  if (!parsePrintedValue(numericalEntry, &numericalEntry->printed_value))
    numericalEntry->printed_value = G_MAXFLOAT;
}
static gboolean parsePrintedValue(VisuUiNumericalEntry *numericalEntry, double *value)
{
  double valueDouble;
  gchar *last;

  g_return_val_if_fail(VISU_IS_UI_NUMERICAL_ENTRY(numericalEntry) && value, FALSE);
  
  valueDouble = g_ascii_strtod(gtk_entry_get_text(GTK_ENTRY(numericalEntry)),
			  &last);
  if (*last != '\0')
    {
      /* Wrong number. */
      visu_ui_numerical_entry_warnValue(numericalEntry, numericalEntry->value);
      return FALSE;
    }

  *value = valueDouble;
  return TRUE;
}

/**
 * visu_ui_numerical_entry_setValue:
 * @numericalEntry: a #VisuUiNumericalEntry widget ;
 * @value: a double precision value.
 *
 * Use this method to set the value for the given #numericalEntry widget.
 */
void visu_ui_numerical_entry_setValue(VisuUiNumericalEntry* numericalEntry, double value)
{
  double valueOld;

  g_return_if_fail(VISU_IS_UI_NUMERICAL_ENTRY(numericalEntry));

  if (value == numericalEntry->value)
    return;

  valueOld = numericalEntry->value;
  numericalEntry->value = value;

  printStoredValue(numericalEntry);

  DBG_fprintf(stderr, "Gtk VisuUiNumericalEntry : emitting 'value-changed' signal.\n");
  g_object_notify_by_pspec(G_OBJECT(numericalEntry), properties[VALUE_PROP]);
  g_signal_emit(G_OBJECT(numericalEntry),
		_signals[VALUE_CHANGED_SIGNAL], 0, valueOld, NULL);
}
/**
 * visu_ui_numerical_entry_getValue:
 * @numericalEntry: a #VisuUiNumericalEntry widget.
 *
 * You can get the value contained in the given @numericalEntry using this method.
 *
 * Returns: the double precision value printed in the #VisuUiNumericalEntry.
 */
double visu_ui_numerical_entry_getValue(VisuUiNumericalEntry *numericalEntry)
{
  g_return_val_if_fail(VISU_IS_UI_NUMERICAL_ENTRY(numericalEntry), 0.);

  return numericalEntry->value;
}

static void visu_ui_numerical_entry_activate(GtkEntry *entry)
{
  VisuUiNumericalEntry *numericalEntry = VISU_UI_NUMERICAL_ENTRY(entry);
  double valueDouble;

  if (parsePrintedValue(numericalEntry, &valueDouble) &&
      valueDouble != numericalEntry->printed_value)
    visu_ui_numerical_entry_setValue(numericalEntry, valueDouble);
}
static gboolean visu_ui_numerical_entry_focus_out(GtkWidget *wd, GdkEventFocus *event)
{
  visu_ui_numerical_entry_activate(GTK_ENTRY(wd));
  return GTK_WIDGET_CLASS(visu_ui_numerical_entry_parent_class)->focus_in_event(wd, event);
}
static gboolean visu_ui_numerical_entry_focus_in(GtkWidget *wd, GdkEventFocus *event)
{
  /* gtk_editable_select_region(GTK_EDITABLE(numericalEntry), 0, -1); */
  return GTK_WIDGET_CLASS(visu_ui_numerical_entry_parent_class)->focus_out_event(wd, event);
}
static gboolean _removeWarning(gpointer data)
{
  gtk_entry_set_icon_from_icon_name(GTK_ENTRY(data), GTK_ENTRY_ICON_SECONDARY, NULL);
  return FALSE;
}
/**
 * visu_ui_numerical_entry_warnValue:
 * @numericalEntry: a #VisuUiNumericalEntry object.
 * @fallback: a floating point value.
 *
 * Display a warning sign in the entry and fallback to the given value.
 *
 * Since: 3.8
 **/
void visu_ui_numerical_entry_warnValue(VisuUiNumericalEntry *numericalEntry, float fallback)
{
  g_return_if_fail(VISU_IS_UI_NUMERICAL_ENTRY(numericalEntry));

  gtk_entry_set_icon_from_icon_name(GTK_ENTRY(numericalEntry),
                                    GTK_ENTRY_ICON_SECONDARY, "dialog-warning");
  g_timeout_add_seconds(2, _removeWarning, (gpointer)numericalEntry);

  numericalEntry->value = G_MAXDOUBLE;
  visu_ui_numerical_entry_setValue(numericalEntry, fallback);
}
