/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Damien
	CALISTE, laboratoire L_Sim, (2016)
  
	Adresse 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 : Damien
	CALISTE, laboratoire L_Sim, (2016)

	E-mail address:
	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 "ui_link.h"

#include <support.h>
#include <interface.h>

#include <extraGtkFunctions/gtk_colorComboBoxWidget.h>
#include <extraGtkFunctions/gtk_stippleComboBoxWidget.h>
#include <extraGtkFunctions/gtk_shadeComboBoxWidget.h>

#include <pairsModeling/wire_renderer.h>
#include <pairsModeling/cylinder_renderer.h>
#include <pairsModeling/iface_cylinder.h>

/**
 * SECTION:ui_link
 * @short_description: Defines a widget to setup a link.
 *
 * <para>A set of widgets to setup the rendring of a link.</para>
 */

/**
 * VisuUiLinkClass:
 * @parent: the parent class;
 *
 * A short way to identify #_VisuUiLinkClass structure.
 *
 * Since: 3.8
 */
/**
 * VisuUiLink:
 *
 * An opaque structure.
 *
 * Since: 3.8
 */
/**
 * VisuUiLinkPrivate:
 *
 * Private fields for #VisuUiLink objects.
 *
 * Since: 3.8
 */
struct _VisuUiLinkPrivate
{
  gboolean dispose_has_run;

  VisuGlExtPairs *ext;
  VisuData *dataObj;

  VisuPairLink *model;
  GList *addLinks;

  GtkWidget *spinMin, *spinMax, *comboColor;
  GBinding *bind_min, *bind_max, *bind_color;

  GList *renderers;
  GtkWidget *comboExt;
  gulong renderer_sig;

  GtkWidget *vboxWire;
  GtkWidget *spinThickness, *comboStipple, *comboToolShade, *checkNonLinear;
  GBinding *bind_width, *bind_stipple, *bind_shade, *bind_useShade;

  GtkWidget *vboxCylinder;
  GtkWidget *spinCylinderRadius, *radioCylinderUser, *radioCylinderElement, *radioCylinderNode;
  GBinding *bind_radius, *bind_user, *bind_element, *bind_node;
};

static void visu_ui_link_finalize(GObject* obj);
static void visu_ui_link_dispose(GObject* obj);
static void visu_ui_link_get_property(GObject* obj, guint property_id,
                                      GValue *value, GParamSpec *pspec);
static void visu_ui_link_set_property(GObject* obj, guint property_id,
                                      const GValue *value, GParamSpec *pspec);

enum
  {
    PROP_0,
    MODEL_PROP,
    EXT_PROP,
    DATA_PROP,
    N_PROP
  };
static GParamSpec *_properties[N_PROP];

static void _setRenderer(VisuUiLink *link, VisuGlExtPairs *ext);
static void _bind(VisuUiLink *link, GObject *obj, const gchar *source, const gchar *target);
static void _bindFull(VisuUiLink *link, GObject *obj, const gchar *source,
                      const gchar *target, GBindingTransformFunc func, gpointer data);

/* Local callbacks. */
static void onDistanceAutoSet(GtkButton *button, VisuUiLink *link);
static void onRendererChanged(VisuUiLink *ui, VisuPairLink *link, VisuGlExtPairs *ext);
static void onComboChanged(VisuUiLink *ui, GtkComboBox *combo);
static gboolean _toCheck(GBinding *binding, const GValue *source_value,
                         GValue *target_value, gpointer data);
static gboolean _toEqual(GBinding *binding, const GValue *source_value,
                         GValue *target_value, gpointer data);

G_DEFINE_TYPE_WITH_CODE(VisuUiLink, visu_ui_link, GTK_TYPE_BOX,
                        G_ADD_PRIVATE(VisuUiLink))

static void visu_ui_link_class_init(VisuUiLinkClass *klass)
{
  DBG_fprintf(stderr, "Ui Link: creating the class of the widget.\n");
  DBG_fprintf(stderr, "                     - adding new signals ;\n");

  /* Connect freeing methods. */
  G_OBJECT_CLASS(klass)->dispose = visu_ui_link_dispose;
  G_OBJECT_CLASS(klass)->finalize = visu_ui_link_finalize;
  G_OBJECT_CLASS(klass)->set_property = visu_ui_link_set_property;
  G_OBJECT_CLASS(klass)->get_property = visu_ui_link_get_property;

  /**
   * VisuUiLink::model:
   *
   * Store the link to display properties of.
   *
   * Since: 3.8
   */
  _properties[MODEL_PROP] = g_param_spec_object("model", "Model",
                                                "link to display properties of",
                                                VISU_TYPE_PAIR_LINK, G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), MODEL_PROP,
				  _properties[MODEL_PROP]);
  /**
   * VisuUiLink::renderer:
   *
   * Store the renderer used to draw links.
   *
   * Since: 3.8
   */
  _properties[EXT_PROP] = g_param_spec_object("renderer", "Renderer",
                                              "renderer object to draw links",
                                              VISU_TYPE_GL_EXT_PAIRS, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY);
  g_object_class_install_property(G_OBJECT_CLASS(klass), EXT_PROP,
				  _properties[EXT_PROP]);
  /**
   * VisuUiLink::data:
   *
   * The full set of nodes, used to calculate the auto-distance.
   *
   * Since: 3.8
   */
  _properties[DATA_PROP] = g_param_spec_object("data", "Data",
                                               "full set of nodes",
                                               VISU_TYPE_DATA, G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), DATA_PROP,
				  _properties[DATA_PROP]);
}
static void visu_ui_link_get_property(GObject* obj, guint property_id,
                                        GValue *value, GParamSpec *pspec)
{
  VisuUiLink *self = VISU_UI_LINK(obj);

  DBG_fprintf(stderr, "Ui Link: get property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case MODEL_PROP:
      g_value_set_object(value, self->priv->model);
      DBG_fprintf(stderr, "%p.\n", (gpointer)self->priv->model);
      break;
    case EXT_PROP:
      g_value_set_object(value, self->priv->ext);
      DBG_fprintf(stderr, "%p.\n", (gpointer)self->priv->ext);
      break;
    case DATA_PROP:
      g_value_set_object(value, self->priv->dataObj);
      DBG_fprintf(stderr, "%p.\n", g_value_get_object(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_link_set_property(GObject* obj, guint property_id,
                                      const GValue *value, GParamSpec *pspec)
{
  VisuUiLink *self = VISU_UI_LINK(obj);

  DBG_fprintf(stderr, "Ui Link: set property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case MODEL_PROP:
      DBG_fprintf(stderr, "%p.\n", g_value_get_object(value));
      visu_ui_link_bind(self, VISU_PAIR_LINK(g_value_get_object(value)));
      break;
    case EXT_PROP:
      DBG_fprintf(stderr, "%p.\n", g_value_get_object(value));
      _setRenderer(self, VISU_GL_EXT_PAIRS(g_value_get_object(value)));
      break;
    case DATA_PROP:
      DBG_fprintf(stderr, "%p.\n", g_value_get_object(value));
      g_set_object(&self->priv->dataObj, g_value_get_object(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_link_dispose(GObject *obj)
{
  VisuUiLink *self = VISU_UI_LINK(obj);
  DBG_fprintf(stderr, "Ui Link: dispose object %p.\n", (gpointer)obj);

  if (self->priv->dispose_has_run)
    return;
  self->priv->dispose_has_run = TRUE;

  visu_ui_link_bind(self, (VisuPairLink*)0);
  _setRenderer(self, (VisuGlExtPairs*)0);
  visu_ui_link_setAddLinks(self, (GList*)0);

  /* Chain up to the parent class */
  G_OBJECT_CLASS(visu_ui_link_parent_class)->dispose(obj);
}
static void visu_ui_link_finalize(GObject *obj)
{
  g_return_if_fail(obj);

  DBG_fprintf(stderr, "Ui Link: finalize object %p.\n", (gpointer)obj);
  g_list_free_full(VISU_UI_LINK(obj)->priv->renderers, g_object_unref);

  /* Chain up to the parent class */
  G_OBJECT_CLASS(visu_ui_link_parent_class)->finalize(obj);
  DBG_fprintf(stderr, " | freeing ... OK.\n");
}

static void visu_ui_link_init(VisuUiLink *obj)
{
  GtkWidget *label, *vbox, *hbox, *wd;
#if GTK_MAJOR_VERSION == 2 && GTK_MINOR_VERSION < 12
  GtkTooltips *tooltips;
  tooltips = gtk_tooltips_new ();
#endif

  DBG_fprintf(stderr, "Extension Link: initializing a new object (%p).\n",
	      (gpointer)obj);
  
  gtk_orientable_set_orientation(GTK_ORIENTABLE(obj), GTK_ORIENTATION_VERTICAL);

  obj->priv = visu_ui_link_get_instance_private(obj);
  obj->priv->dispose_has_run = FALSE;

  obj->priv->model = (VisuPairLink*)0;
  obj->priv->ext   = (VisuGlExtPairs*)0;
  obj->priv->dataObj = (VisuData*)0;
  obj->priv->renderers = (GList*)0;
  obj->priv->addLinks = (GList*)0;

  /* Create the part for the link parameters. */
  label = gtk_label_new(_("<b>Link parameters:</b>\t <span size=\"small\">"
			  "(apply to one or more selected rows)</span>"));
  gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
  gtk_label_set_xalign(GTK_LABEL(label), 0.);
  gtk_box_pack_start(GTK_BOX(obj), label, FALSE, FALSE, 5);

  /* Create widgets that apply to all checked pairs. */
  vbox = gtk_vbox_new(FALSE, 0);
  g_object_bind_property(obj, "model", vbox, "sensitive", G_BINDING_SYNC_CREATE);
  gtk_widget_set_margin_start(vbox, 10);
  gtk_box_pack_start(GTK_BOX(obj), vbox, FALSE, FALSE, 0);

  hbox = gtk_hbox_new(FALSE, 3);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);

  label = gtk_label_new(_("From: "));
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);
  gtk_label_set_xalign(GTK_LABEL(label), 1.0);
  obj->priv->spinMin = gtk_spin_button_new_with_range(0, 100, 0.05);
  _bind(obj, G_OBJECT(obj->priv->spinMin), "value", "min");
  gtk_spin_button_set_numeric(GTK_SPIN_BUTTON(obj->priv->spinMin), TRUE);
  gtk_entry_set_width_chars(GTK_ENTRY(obj->priv->spinMin), 4);
  gtk_box_pack_start(GTK_BOX(hbox), obj->priv->spinMin, FALSE, FALSE, 0);

  label = gtk_label_new(_(" to: "));
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);
  gtk_label_set_xalign(GTK_LABEL(label), 1.0);
  obj->priv->spinMax = gtk_spin_button_new_with_range(0, 100, 0.05);
  _bind(obj, G_OBJECT(obj->priv->spinMax), "value", "max");
  gtk_spin_button_set_numeric(GTK_SPIN_BUTTON(obj->priv->spinMax), TRUE);
  gtk_entry_set_width_chars(GTK_ENTRY(obj->priv->spinMax), 4);
  gtk_box_pack_start(GTK_BOX(hbox), obj->priv->spinMax, FALSE, FALSE, 0);

  wd = gtk_button_new_with_mnemonic(_("_Auto set"));
  gtk_box_pack_start(GTK_BOX(hbox), wd, FALSE, FALSE, 0);
  g_signal_connect(G_OBJECT(wd), "clicked",
		   G_CALLBACK(onDistanceAutoSet), obj);
  gtk_tooltips_set_tip(tooltips, wd,
		       _("Set the distance criterion to select the first"
			 " pick in the distance distribution between all"
			 " nodes of the selected types."), NULL);

  obj->priv->comboColor = visu_ui_color_combobox_new(TRUE);
  _bind(obj, G_OBJECT(obj->priv->comboColor), "color", "color");
  gtk_box_pack_end(GTK_BOX(hbox), obj->priv->comboColor, FALSE, FALSE, 0);

  /* The pair method line. */
  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);

  obj->priv->comboExt = gtk_combo_box_text_new();
  gtk_box_pack_start(GTK_BOX(hbox), obj->priv->comboExt, FALSE, FALSE, 0);
  gtk_widget_set_valign(obj->priv->comboExt, GTK_ALIGN_START);

  obj->priv->vboxWire = gtk_vbox_new(FALSE, 0);
  gtk_box_pack_end(GTK_BOX(hbox), obj->priv->vboxWire, TRUE, TRUE, 0);

  obj->priv->vboxCylinder = gtk_vbox_new(FALSE, 0);
  gtk_box_pack_end(GTK_BOX(hbox), obj->priv->vboxCylinder, TRUE, TRUE, 0);

  /* The wire interface. */
  hbox = gtk_hbox_new(FALSE, 10);
  gtk_box_pack_start(GTK_BOX(obj->priv->vboxWire), hbox, FALSE, FALSE, 0);

  label = gtk_label_new(_("Thickness:"));
  gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
  gtk_label_set_xalign(GTK_LABEL(label), 1.);
  obj->priv->spinThickness = gtk_spin_button_new_with_range(1, 10, 1);
  _bind(obj, G_OBJECT(obj->priv->spinThickness), "value", "width");
  gtk_box_pack_start(GTK_BOX(hbox), obj->priv->spinThickness, FALSE, FALSE, 0);
  gtk_spin_button_set_numeric(GTK_SPIN_BUTTON(obj->priv->spinThickness), TRUE);
  gtk_entry_set_width_chars(GTK_ENTRY(obj->priv->spinThickness), 3);
  label = gtk_label_new(_("Pattern:"));
  gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
  gtk_label_set_xalign(GTK_LABEL(label), 1.);
  obj->priv->comboStipple = visu_ui_stipple_combobox_new();
  _bind(obj, G_OBJECT(obj->priv->comboStipple), "value", "stipple");
  gtk_box_pack_start(GTK_BOX(hbox), obj->priv->comboStipple, FALSE, FALSE, 0);

  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(obj->priv->vboxWire), hbox, FALSE, FALSE, 0);

  obj->priv->comboToolShade = visu_ui_shade_combobox_new(TRUE, FALSE);
  _bind(obj, G_OBJECT(obj->priv->comboToolShade), "shade", "shade");
  gtk_box_pack_end(GTK_BOX(hbox), obj->priv->comboToolShade, FALSE, FALSE, 0);
  obj->priv->checkNonLinear = gtk_check_button_new_with_mnemonic
    (_("Color _varies with length:"));
  _bindFull(obj, G_OBJECT(obj->priv->comboToolShade), "active", "shade", _toCheck, obj);
  gtk_box_pack_end(GTK_BOX(hbox), obj->priv->checkNonLinear, FALSE, FALSE, 0);
  g_object_bind_property(obj->priv->checkNonLinear, "active",
                         obj->priv->comboToolShade, "sensitive",
                         G_BINDING_SYNC_CREATE);

  /* The cylinder interface. */
  hbox = gtk_hbox_new(FALSE, 10);
  gtk_box_pack_start(GTK_BOX(obj->priv->vboxCylinder), hbox, FALSE, FALSE, 0);

  label = gtk_label_new(_("Radius:"));
  gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
  gtk_label_set_xalign(GTK_LABEL(label), 1.);
  obj->priv->spinCylinderRadius = gtk_spin_button_new_with_range(VISU_PAIR_CYLINDER_RADIUS_MIN,
                                                                 VISU_PAIR_CYLINDER_RADIUS_MAX,
                                                                 0.02);
  _bind(obj, G_OBJECT(obj->priv->spinCylinderRadius), "value", "radius");
  gtk_box_pack_start(GTK_BOX(hbox), obj->priv->spinCylinderRadius, FALSE, FALSE, 0);

  hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(obj->priv->vboxCylinder), hbox, FALSE, FALSE, 0);

  label = gtk_label_new(_("Color:"));
  gtk_label_set_xalign(GTK_LABEL(label), 1.);
  gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);

  obj->priv->radioCylinderUser = gtk_radio_button_new_with_mnemonic(NULL, _("_user defined"));
  _bindFull(obj, G_OBJECT(obj->priv->radioCylinderUser), "active", "color-type",
            _toEqual, GINT_TO_POINTER(VISU_CYLINDER_COLOR_USER));
  gtk_widget_set_name(obj->priv->radioCylinderUser, "message_radio");
  gtk_box_pack_start(GTK_BOX(hbox), obj->priv->radioCylinderUser, FALSE, FALSE, 0);

  obj->priv->radioCylinderElement = gtk_radio_button_new_with_mnemonic(NULL, _("_elements"));
  _bindFull(obj, G_OBJECT(obj->priv->radioCylinderElement), "active", "color-type",
            _toEqual, GINT_TO_POINTER(VISU_CYLINDER_COLOR_ELEMENT));
  gtk_widget_set_name(obj->priv->radioCylinderElement, "message_radio");
  gtk_box_pack_start(GTK_BOX(hbox), obj->priv->radioCylinderElement, FALSE, FALSE, 0);
#if GTK_MAJOR_VERSION >= 3
  gtk_radio_button_join_group(GTK_RADIO_BUTTON(obj->priv->radioCylinderElement),
                              GTK_RADIO_BUTTON(obj->priv->radioCylinderUser));
#else
  gtk_radio_button_set_group(GTK_RADIO_BUTTON(obj->priv->radioCylinderElement),
                             gtk_radio_button_get_group(GTK_RADIO_BUTTON(obj->priv->radioCylinderUser)));
#endif

  obj->priv->radioCylinderNode = gtk_radio_button_new_with_mnemonic(NULL, _("_nodes"));
  _bindFull(obj, G_OBJECT(obj->priv->radioCylinderNode), "active", "color-type",
            _toEqual, GINT_TO_POINTER(VISU_CYLINDER_COLOR_NODE));
  gtk_widget_set_name(obj->priv->radioCylinderNode, "message_radio");
  gtk_box_pack_start(GTK_BOX(hbox), obj->priv->radioCylinderNode, FALSE, FALSE, 0);
#if GTK_MAJOR_VERSION >= 3
  gtk_radio_button_join_group(GTK_RADIO_BUTTON(obj->priv->radioCylinderNode),
                              GTK_RADIO_BUTTON(obj->priv->radioCylinderUser));
#else
  gtk_radio_button_set_group(GTK_RADIO_BUTTON(obj->priv->radioCylinderNode),
                             gtk_radio_button_get_group(GTK_RADIO_BUTTON(obj->priv->radioCylinderUser)));
#endif

  gtk_widget_show_all(GTK_WIDGET(obj));

  gtk_widget_set_no_show_all(obj->priv->vboxWire, TRUE);
  gtk_widget_set_no_show_all(obj->priv->vboxCylinder, TRUE);
  gtk_widget_hide(obj->priv->vboxCylinder);
}


/**
 * visu_ui_link_new:
 * @pairs: a #VisuGlExtPairs object.
 *
 * Creates a new #VisuUiLink to allow to setup link rendering characteristics.
 *
 * Since: 3.8
 *
 * Returns: a pointer to the newly created widget.
 */
GtkWidget* visu_ui_link_new(VisuGlExtPairs *pairs)
{
  DBG_fprintf(stderr,"Ui Link: new object.\n");
  
  return GTK_WIDGET(g_object_new(VISU_TYPE_UI_LINK, "renderer", pairs, NULL));
}

static GObject* _objectCopy(GObject *data, gpointer add _U_)
{
  return g_object_ref(data);
}
static void _setRenderer(VisuUiLink *link, VisuGlExtPairs *ext)
{
  GList *lst;
  gchar *id;

  if (ext)
    {
      g_object_ref(ext);
      link->priv->renderer_sig = g_signal_connect_swapped(G_OBJECT(ext), "renderer-changed",
                                                          G_CALLBACK(onRendererChanged), link);
    }
  if (link->priv->ext)
    {
      g_signal_handler_disconnect(G_OBJECT(link->priv->ext), link->priv->renderer_sig);
      g_object_unref(link->priv->ext);
    }
  link->priv->ext = ext;
  
  if (!ext)
    return;

  if (link->priv->renderers)
    g_list_free_full(link->priv->renderers, g_object_unref);
  link->priv->renderers = g_list_copy_deep(visu_gl_ext_pairs_getAllLinkRenderer(ext),
                                           (GCopyFunc)_objectCopy, (gpointer)0);
  for (lst = link->priv->renderers; lst; lst = g_list_next(lst))
    {
      g_object_get(G_OBJECT(lst->data), "label", &id, NULL);
      gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(link->priv->comboExt), NULL, id);
      g_free(id);
    }
  g_signal_connect_swapped(G_OBJECT(link->priv->comboExt), "changed",
                           G_CALLBACK(onComboChanged), link);
}
static void onRendererChanged(VisuUiLink *ui, VisuPairLink *link, VisuGlExtPairs *ext)
{
  VisuPairLinkRenderer *renderer;

  if (link != ui->priv->model)
    return;

  renderer = visu_gl_ext_pairs_getLinkRenderer(ext, link);
  gtk_combo_box_set_active(GTK_COMBO_BOX(ui->priv->comboExt),
                           g_list_index(ui->priv->renderers, renderer));
  g_object_set(G_OBJECT(ui->priv->vboxWire),
               "visible", VISU_IS_PAIR_WIRE_RENDERER(renderer) || !ui->priv->model, NULL);
  g_object_set(G_OBJECT(ui->priv->vboxCylinder),
               "visible", VISU_IS_PAIR_CYLINDER_RENDERER(renderer), NULL);
}
static void onComboChanged(VisuUiLink *ui, GtkComboBox *combo)
{
  VisuPairLinkRenderer *renderer;
  GList *it;

  renderer = g_list_nth_data(ui->priv->renderers, gtk_combo_box_get_active(combo));
  visu_gl_ext_pairs_setLinkRenderer(ui->priv->ext, ui->priv->model, renderer);
  for (it = ui->priv->addLinks; it; it = g_list_next(it))
    visu_gl_ext_pairs_setLinkRenderer(ui->priv->ext, VISU_PAIR_LINK(it->data), renderer);
}
static gboolean _fromShade(GBinding *binding _U_, const GValue *source_value,
                           GValue *target_value, gpointer data)
{
  VisuUiLink *self = VISU_UI_LINK(data);
  ToolShade *shade;

  shade = (ToolShade*)g_value_get_boxed(source_value);

  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(self->priv->checkNonLinear),
                               (shade != (ToolShade*)0));
  if (!shade)
    return FALSE;
  g_value_set_boxed(target_value, shade);
  return TRUE;
}
static gboolean _notNull(GBinding *binding _U_, const GValue *source_value,
                         GValue *target_value, gpointer data _U_)
{
  g_value_set_boolean(target_value, g_value_get_boxed(source_value) != (gpointer)0);
  return TRUE;
}
static gboolean _toCheck(GBinding *binding _U_, const GValue *source_value,
                         GValue *target_value, gpointer data)
{
  VisuUiLink *self = VISU_UI_LINK(data);
  ToolShade *shade;

  if (g_value_get_boolean(source_value))
    shade = visu_ui_shade_combobox_getSelection(VISU_UI_SHADE_COMBOBOX(self->priv->comboToolShade));
  else
    shade = (ToolShade*)0;
  g_value_set_boxed(target_value, shade);
  return TRUE;
}
static gboolean _fromEqual(GBinding *binding _U_, const GValue *source_value,
                           GValue *target_value, gpointer data)
{
  if (g_value_get_uint(source_value) != (guint)GPOINTER_TO_INT(data))
    return FALSE;
  g_value_set_boolean(target_value, TRUE);
  return TRUE;
}
static gboolean _toEqual(GBinding *binding _U_, const GValue *source_value,
                         GValue *target_value, gpointer data)
{
  if (!g_value_get_boolean(source_value))
    return FALSE;
  g_value_set_uint(target_value, (guint)GPOINTER_TO_INT(data));
  return TRUE;
}
/**
 * visu_ui_link_bind:
 * @link: a #VisuUiLink object.
 * @model: (transfer full): a #VisuPairLink object.
 *
 * Bind the properties of @model to be displayed by @link.
 *
 * Since: 3.8
 **/
void visu_ui_link_bind(VisuUiLink *link, VisuPairLink *model)
{
  g_return_if_fail(VISU_IS_UI_LINK(link));

  if (link->priv->model == model)
    return;

  if (link->priv->model)
    {
      g_object_unref(G_OBJECT(link->priv->bind_min));
      g_object_unref(G_OBJECT(link->priv->bind_max));
      g_object_unref(G_OBJECT(link->priv->bind_color));

      g_object_unref(G_OBJECT(link->priv->bind_width));
      g_object_unref(G_OBJECT(link->priv->bind_stipple));
      g_object_unref(G_OBJECT(link->priv->bind_shade));
      g_object_unref(G_OBJECT(link->priv->bind_useShade));

      g_object_unref(G_OBJECT(link->priv->bind_radius));
      g_object_unref(G_OBJECT(link->priv->bind_user));
      g_object_unref(G_OBJECT(link->priv->bind_element));
      g_object_unref(G_OBJECT(link->priv->bind_node));

      g_object_unref(G_OBJECT(link->priv->model));
    }
  link->priv->model = model;
  if (model)
    {
      g_object_ref(G_OBJECT(model));
      link->priv->bind_min =
        g_object_bind_property(model, "min", link->priv->spinMin, "value",
                               G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
      link->priv->bind_max =
        g_object_bind_property(model, "max", link->priv->spinMax, "value",
                               G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
      link->priv->bind_color =
        g_object_bind_property(model, "color", link->priv->comboColor, "color",
                               G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);

      link->priv->bind_width =
        g_object_bind_property(model, "width", link->priv->spinThickness, "value",
                               G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
      link->priv->bind_stipple =
        g_object_bind_property(model, "stipple", link->priv->comboStipple, "value",
                               G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
      link->priv->bind_shade =
        g_object_bind_property_full(model, "shade", link->priv->comboToolShade, "shade",
                                    G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
                                    _fromShade, NULL, link, (GDestroyNotify)0);
      link->priv->bind_useShade =
        g_object_bind_property_full(model, "shade", link->priv->checkNonLinear, "active",
                                    G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
                                    _notNull, _toCheck, link, (GDestroyNotify)0);

      link->priv->bind_radius =
        g_object_bind_property(model, "radius", link->priv->spinCylinderRadius, "value",
                               G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
      link->priv->bind_user =
        g_object_bind_property_full
        (model, "color-type", link->priv->radioCylinderUser, "active",
         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
         _fromEqual, _toEqual, GINT_TO_POINTER(VISU_CYLINDER_COLOR_USER), (GDestroyNotify)0);
      link->priv->bind_element =
        g_object_bind_property_full
        (model, "color-type", link->priv->radioCylinderElement, "active",
         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
         _fromEqual, _toEqual, GINT_TO_POINTER(VISU_CYLINDER_COLOR_ELEMENT), (GDestroyNotify)0);
      link->priv->bind_node =
        g_object_bind_property_full
        (model, "color-type", link->priv->radioCylinderNode, "active",
         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL,
         _fromEqual, _toEqual, GINT_TO_POINTER(VISU_CYLINDER_COLOR_NODE), (GDestroyNotify)0);

      onRendererChanged(link, model, link->priv->ext);
    }
  g_object_notify_by_pspec(G_OBJECT(link), _properties[MODEL_PROP]);
}

struct _BindData
{
  VisuUiLink *link;
  const gchar *target;
  GBindingTransformFunc func;
  gpointer data;
};
static void _freeBind(gpointer data, GClosure *closure _U_)
{
  g_free(data);
}
static void onNotify(struct _BindData *str, GParamSpec *pspec, GObject *obj)
{
  GValue value = G_VALUE_INIT;
  GValue target = G_VALUE_INIT;
  GList *it;

  if (!str->link->priv->addLinks)
    return;

  g_value_init(&value, G_PARAM_SPEC_VALUE_TYPE(pspec));
  g_object_get_property(obj, g_param_spec_get_name(pspec), &value);

  if (!str->func)
    for (it = str->link->priv->addLinks; it; it = g_list_next(it))
      g_object_set_property(G_OBJECT(it->data), str->target, &value);
  else
    {
      pspec = g_object_class_find_property(G_OBJECT_GET_CLASS(str->link->priv->model),
                                           str->target);
      g_value_init(&target, G_PARAM_SPEC_VALUE_TYPE(pspec));
      if (str->func((GBinding*)0, &value, &target, str->data))
        for (it = str->link->priv->addLinks; it; it = g_list_next(it))
          g_object_set_property(G_OBJECT(it->data), str->target, &target);
      g_value_unset(&target);
    }

  g_value_unset(&value);
}
static void _bind(VisuUiLink *link, GObject *obj, const gchar *source, const gchar *target)
{
  _bindFull(link, obj, source, target, NULL, NULL);
}
static void _bindFull(VisuUiLink *link, GObject *obj, const gchar *source,
                      const gchar *target, GBindingTransformFunc func, gpointer data)
{
  gchar *id;
  struct _BindData *str;

  str = g_malloc(sizeof(struct _BindData));
  str->link = link;
  str->target = target;
  str->func = func;
  str->data = data;

  id = g_strdup_printf("notify::%s", source);
  g_signal_connect_data(obj, id, G_CALLBACK(onNotify), str, _freeBind, G_CONNECT_SWAPPED);
  g_free(id);
}
/**
 * visu_ui_link_setAddLinks:
 * @link: a #VisuUiLink object.
 * @lst: (element-type VisuPairLink): a list of #VisuPairLink objects.
 *
 * Set the list of additional #VisuPairLink to be updated when the
 * model of @link is updated, see visu_ui_link_bind().
 *
 * Since: 3.8
 **/
void visu_ui_link_setAddLinks(VisuUiLink *link, GList *lst)
{
  GList *it;

  g_return_if_fail(VISU_IS_UI_LINK(link));

  g_list_free_full(link->priv->addLinks, g_object_unref);
  link->priv->addLinks = (GList*)0;

  for (it = lst; it; it = g_list_next(it))
    if (it->data != (gpointer)link->priv->model)
      {
        g_object_ref(G_OBJECT(it->data));
        link->priv->addLinks = g_list_prepend(link->priv->addLinks, it->data);
      }
}

static void onDistanceAutoSet(GtkButton *button _U_, VisuUiLink *link)
{
  gfloat from, to;

  visu_pair_getBondDistance(visu_pair_set_getFromLink(visu_gl_ext_pairs_getSet(link->priv->ext), link->priv->model), link->priv->dataObj, &from, &to);
  
  visu_pair_link_setDistance(link->priv->model, from, VISU_DISTANCE_MIN);
  visu_pair_link_setDistance(link->priv->model, to, VISU_DISTANCE_MAX);
}
