/*   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.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <unistd.h> /* For the access markers R_OK, W_OK ... */
#include <string.h>

#include "gtk_save.h"

#include "visu_gtk.h"
#include "gtk_main.h"
#include "visu_configFile.h"
#include "visu_tools.h"
#include "visu_basic.h"
#include "gtk_renderingWindowWidget.h"
#include "visu_commandLine.h"
#include "extensions/planes.h"
#include "panelModules/panelPlanes.h"
#include "panelModules/panelSurfaces.h"
#include "panelModules/panelGeometry.h"

/**
 * SECTION: gtk_save
 * @short_description: The load/save dialog for resources and
 * parameters.
 *
 * <para>The save dialog proposes to load or save resources, both
 * parameters or resources.</para>
 */

static guint saveResourcesContextId, saveParametersContextId;
static gchar *lastParsedDir;
static GtkWidget *checkXMLResources, *checkXMLParameters, *checkXMLCommandLine;
static GtkWidget *checkExportXML;

/* Local Callbacks. */
static void onLoadResButtonClicked(GtkButton *button, gpointer data);
static void onSaveResButtonClicked(GtkButton *button, gpointer data);
static void onSelectionResourcesChange(GtkFileChooser *fileChooser, gpointer *data);
static void onLoadResourcesSelected(GtkFileChooser *fileChooser, gpointer *data);
static void onTextEntryChange(GtkEditable *entry, gpointer data);

static void onSaveParButtonClicked(GtkButton *button, gpointer data);

/* Local methods. */
static void showAlertMessage(GtkWidget *saveDialog, gchar* message, gboolean warning, VisuConfigFileKind type);
static void saveAction(VisuConfigFileKind kind, GtkWidget *saveDialog, GtkEntry *entry);

/* The completion tree model. */
enum
  {
    GTK_SAVE_FILE_NAME,
    GTK_SAVE_NB_COLUMNS
  };

/**
 * visu_ui_save_initBuild: (skip)
 *
 * Create the save window, conect the signals and run it as a modal dialog.
 */
void visu_ui_save_initBuild()
{
  GtkWidget *saveDialog;
  GtkWidget *wd, *label;
  GtkEntryCompletion *completion;
  const gchar *directory;
  gchar *file, *dir;
  GList *resList;
  GtkListStore *listOfFiles;
  const gchar *currentResPath;
  int i, j;
  GDir *gdir;
  const gchar *fileFromDir;

  saveDialog = create_saveDialog();
  gtk_widget_set_name(saveDialog, "message");

  /* Set style. */
  wd = lookup_widget(saveDialog, "labelSaveDialog");
  gtk_widget_set_name(wd, "message_title");

  wd = lookup_widget(saveDialog, "notebookSave");
  gtk_widget_set_name(wd, "message_notebook");

  wd = lookup_widget(saveDialog, "labelResources");
  gtk_widget_set_name(wd, "label_head");
  wd = lookup_widget(saveDialog, "labelParameters");
  gtk_widget_set_name(wd, "label_head");

  wd = lookup_widget(saveDialog, "imageWarningResources");
  gtk_widget_hide(wd);
  wd = lookup_widget(saveDialog, "imageWarningParameters");
  gtk_widget_hide(wd);

  wd = lookup_widget(saveDialog, "statusbarResources");
  gtk_widget_set_name(wd, "message_statusbar");
  wd = lookup_widget(saveDialog, "statusbarParameters");
  gtk_widget_set_name(wd, "message_statusbar");

  wd = lookup_widget(saveDialog, "labelHelp");
  gtk_widget_set_name(wd, "label_info");
  wd = lookup_widget(saveDialog, "labelHelpTips");
  gtk_widget_set_name(wd, "label_info");

  /* Set default values. */
  wd = lookup_widget(saveDialog, "checkLimitOnVisuData");
  g_object_bind_property(visu_ui_main_class_getDefaultRendering(), "data",
                         wd, "sensitive", G_BINDING_SYNC_CREATE);
  gtk_widget_set_name(wd, "message_radio");
  wd = lookup_widget(saveDialog, "notebookResources");
  gtk_notebook_set_current_page(GTK_NOTEBOOK(wd), 1);
  gtk_widget_set_name(wd, "message_notebook");


  /* Local variables. */
  listOfFiles = gtk_list_store_new(GTK_SAVE_NB_COLUMNS,
				   G_TYPE_STRING);
  gtk_tree_sortable_set_sort_column_id(GTK_TREE_SORTABLE(listOfFiles),
				       GTK_SAVE_FILE_NAME, GTK_SORT_ASCENDING);
  lastParsedDir = (gchar*)0;

  /* Set initial values. */
  wd = lookup_widget(saveDialog, "filechooserwidgetResources");
  directory = visu_ui_main_getLastOpenDirectory(visu_ui_main_class_getCurrentPanel());
  if (directory)
    gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(wd), directory);
  g_signal_connect(G_OBJECT(wd), "selection-changed",
		   G_CALLBACK(onSelectionResourcesChange),
		   (gpointer)lookup_widget(saveDialog, "buttonLoadResources"));
  g_signal_connect(G_OBJECT(wd), "file-activated",
		   G_CALLBACK(onLoadResourcesSelected), (gpointer)saveDialog);

  wd = lookup_widget(saveDialog, "statusbarResources");
  saveResourcesContextId = gtk_statusbar_get_context_id(GTK_STATUSBAR(wd), "Resources");

  wd = lookup_widget(saveDialog, "comboboxentryParameters");
  gtk_widget_set_name(wd, "message_entry");
  resList = visu_config_file_getPathList(VISU_CONFIG_FILE_PARAMETER);
  for (file = visu_config_file_getNextValidPath(VISU_CONFIG_FILE_PARAMETER,
					      W_OK, &resList, 1);
       file;
       file = visu_config_file_getNextValidPath(VISU_CONFIG_FILE_PARAMETER,
					      W_OK, &resList, 1))
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(wd), (const gchar*)0, file);
  completion = gtk_entry_completion_new();
  gtk_entry_completion_set_model(completion, GTK_TREE_MODEL(listOfFiles));
  gtk_entry_completion_set_text_column(completion, GTK_SAVE_FILE_NAME);
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 5
  gtk_entry_completion_set_inline_completion(completion, TRUE);
#endif
  gtk_entry_set_completion(GTK_ENTRY(gtk_bin_get_child(GTK_BIN(wd))), completion);
  g_signal_connect(G_OBJECT(gtk_bin_get_child(GTK_BIN(wd))), "changed",
		   G_CALLBACK(onTextEntryChange), (gpointer)0);
  gtk_combo_box_set_active(GTK_COMBO_BOX(wd), 0);


  wd = lookup_widget(saveDialog, "comboboxentryResources");
  gtk_widget_set_name(wd, "message_entry");
  currentResPath = visu_config_file_getPath(VISU_CONFIG_FILE_RESOURCE);
  DBG_fprintf(stderr, " | current resource path '%s'.\n", currentResPath);
  j = i = 0;
  resList = visu_config_file_getPathList(VISU_CONFIG_FILE_RESOURCE);
  for (file = visu_config_file_getNextValidPath(VISU_CONFIG_FILE_RESOURCE,
                                                W_OK, &resList, 1);
       file;
       file = visu_config_file_getNextValidPath(VISU_CONFIG_FILE_RESOURCE,
                                                W_OK, &resList, 1))
    {
      if (!strcmp(file, currentResPath))
	j = i;
      DBG_fprintf(stderr, " | '%s' (%s).\n", file, currentResPath);
      gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(wd), (const gchar*)0, file);
      i += 1;
    }
  /* Add all res file of the cwd. */
  DBG_fprintf(stderr, "Gtk Save: looking for res files in '%s'.\n", currentResPath);
  dir = g_get_current_dir();
  gdir = g_dir_open(dir, 0, NULL);
  if (gdir)
    {
      fileFromDir = g_dir_read_name(gdir);
      while(fileFromDir)
        {
          if (g_strrstr(fileFromDir, ".res") &&
              strcmp(fileFromDir, "v_sim.res") &&
              !access(fileFromDir, W_OK))
            {
              file = g_build_filename(directory, fileFromDir, NULL);
              DBG_fprintf(stderr, " | '%s'.\n", file);
              gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(wd), (const gchar*)0, file);
              g_free(file);
            }
          fileFromDir = g_dir_read_name(gdir);
        }
      g_dir_close(gdir);
    }
  g_free(dir);

  completion = gtk_entry_completion_new();
  gtk_entry_completion_set_model(completion, GTK_TREE_MODEL(listOfFiles));
  gtk_entry_completion_set_text_column(completion, GTK_SAVE_FILE_NAME);
#if GTK_MAJOR_VERSION > 2 || GTK_MINOR_VERSION > 5
  gtk_entry_completion_set_inline_completion(completion, TRUE);
#endif
  gtk_entry_set_completion(GTK_ENTRY(gtk_bin_get_child(GTK_BIN(wd))), completion);
  g_signal_connect(G_OBJECT(gtk_bin_get_child(GTK_BIN(wd))), "changed",
		   G_CALLBACK(onTextEntryChange), (gpointer)0);
  gtk_combo_box_set_active(GTK_COMBO_BOX(wd), j);

  wd = lookup_widget(saveDialog, "labelTipsResources");
  gtk_label_set_line_wrap(GTK_LABEL(wd), FALSE);
  gtk_label_set_markup(GTK_LABEL(wd), _("A description of all resource markups is"
					" available on:"
					"\n   <span font_desc=\"monospace\"><u>"
					VISU_WEB_SITE"/sample.html#resources"
					"</u></span>."));

  /* Set callbacks. */
  wd = lookup_widget(saveDialog, "buttonLoadResources");
  g_signal_connect(G_OBJECT(wd), "clicked",
		   G_CALLBACK(onLoadResButtonClicked), (gpointer)saveDialog);
  wd = lookup_widget(saveDialog, "buttonSaveResources");
  g_signal_connect(G_OBJECT(wd), "clicked",
		   G_CALLBACK(onSaveResButtonClicked), (gpointer)saveDialog);
  wd = lookup_widget(saveDialog, "buttonSaveParameters");
  g_signal_connect(G_OBJECT(wd), "clicked",
		   G_CALLBACK(onSaveParButtonClicked), (gpointer)saveDialog);

#if DEBUG == 1
  wd = lookup_widget(saveDialog, "vbox16");
  checkXMLResources =
    gtk_check_button_new_with_mnemonic(_("Export all resource descriptions"
					 " to an _XML file"));
  gtk_box_pack_start(GTK_BOX(wd), checkXMLResources, FALSE, FALSE, 0);
  gtk_container_set_border_width(GTK_CONTAINER(checkXMLResources), 5);
  gtk_widget_set_name(checkXMLResources, "message_radio");
  gtk_widget_show(checkXMLResources);

  wd = lookup_widget(saveDialog, "vbox18");
  checkXMLParameters =
    gtk_check_button_new_with_mnemonic(_("Export all parameter descriptions"
					 " to an _XML file"));
  gtk_box_pack_start(GTK_BOX(wd), checkXMLParameters, FALSE, FALSE, 0);
  gtk_container_set_border_width(GTK_CONTAINER(checkXMLParameters), 5);
  gtk_widget_set_name(checkXMLParameters, "message_radio");
  gtk_widget_show(checkXMLParameters);

  checkXMLCommandLine =
    gtk_check_button_new_with_mnemonic(_("Export all command line _options"
					 " to an XML file"));
  gtk_box_pack_start(GTK_BOX(wd), checkXMLCommandLine, FALSE, FALSE, 0);
  gtk_container_set_border_width(GTK_CONTAINER(checkXMLCommandLine), 5);
  gtk_widget_set_name(checkXMLCommandLine, "message_radio");
  gtk_widget_show(checkXMLCommandLine);
#else
  checkXMLResources = (GtkWidget*)0;
  checkXMLParameters = (GtkWidget*)0;
  checkXMLCommandLine = (GtkWidget*)0;
#endif

  wd = lookup_widget(saveDialog, "vbox16");
  checkExportXML =
    gtk_check_button_new_with_mnemonic(_("Append all settings in a single XML file (including planes, surfaces…)"));
  gtk_box_pack_start(GTK_BOX(wd), checkExportXML, FALSE, FALSE, 0);
  gtk_container_set_border_width(GTK_CONTAINER(checkExportXML), 5);
  gtk_widget_set_name(checkExportXML, "message_radio");
  gtk_widget_show(checkExportXML);

  wd = lookup_widget(saveDialog, "vbox18");
  label = gtk_label_new("");
  gtk_label_set_line_wrap(GTK_LABEL(label), FALSE);
  gtk_label_set_markup(GTK_LABEL(label), _("A description of all parameter markups is"
					   " available on:\n"
					   "   <span font_desc=\"monospace\"><u>"
					   VISU_WEB_SITE"/sample.html#parameters"
					   "</u></span>."));
  gtk_label_set_xalign(GTK_LABEL(label), 0.);
  gtk_box_pack_end(GTK_BOX(wd), label, FALSE, FALSE, 10);
  gtk_widget_show(label);

  /* Run the dialog. */
  gtk_dialog_run(GTK_DIALOG(saveDialog));
  g_object_unref(listOfFiles);
  if (lastParsedDir)
    g_free(lastParsedDir);
  gtk_widget_destroy(saveDialog);
}

static void onLoadResourcesSelected(GtkFileChooser *fileChooser _U_, gpointer *data)
{
  onLoadResButtonClicked((GtkButton*)0, data);
}

static void onSelectionResourcesChange(GtkFileChooser *fileChooser, gpointer *data)
{
  gchar *filename;

  g_return_if_fail(GTK_BUTTON(data));
  
  filename = gtk_file_chooser_get_filename(fileChooser);
  if (!filename)
    {
      gtk_widget_set_sensitive(GTK_WIDGET(data), FALSE);
      return;
    }

  DBG_fprintf(stderr, "Gtk Save : selected a new potential"
	      " resources file : '%s'.\n", filename);
  gtk_widget_set_sensitive(GTK_WIDGET(data),
			   !g_file_test(filename, G_FILE_TEST_IS_DIR));
  g_free(filename);
}

static void onLoadResButtonClicked(GtkButton *button _U_, gpointer data)
{
  GtkWidget *file_selector;
  gchar *filename, *basename;
  gchar *directory;
  int res;
  GString *message;
  GError *error;

  g_return_if_fail(GTK_DIALOG(data));

  file_selector = lookup_widget(GTK_WIDGET(data), "filechooserwidgetResources");
  g_return_if_fail(file_selector);

  filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(file_selector));
  directory = gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(file_selector));
  visu_ui_main_setLastOpenDirectory(visu_ui_main_class_getCurrentPanel(),
                                    directory, VISU_UI_DIR_CONF);
  g_free(directory);

  error = (GError*)0;
  res = visu_config_file_load(VISU_CONFIG_FILE_RESOURCE, filename, &error);
  if (error)
    {
      visu_ui_raiseWarningLong(_("Loading a file"), error->message,
			       GTK_WINDOW(data));
      g_error_free(error);
    }

  basename = g_path_get_basename(filename);
  g_free (filename);
  message = g_string_new("");
  if (res)
    g_string_append_printf(message, _("File '%s' succesfully loaded."), basename);
  else
    g_string_append_printf(message, _("File '%s' not or partially loaded."),
			   basename);
  showAlertMessage(GTK_WIDGET(data), message->str, !res, VISU_CONFIG_FILE_KIND_RESOURCE);
  g_string_free(message, TRUE);
  g_free(basename);
}

static void onSaveResButtonClicked(GtkButton *button _U_, gpointer data)
{
  GtkWidget *entry;

  g_return_if_fail(GTK_IS_DIALOG(data));

  entry = gtk_bin_get_child
    (GTK_BIN(lookup_widget(GTK_WIDGET(data), "comboboxentryResources")));

  if (!strstr(gtk_entry_get_text(GTK_ENTRY(entry)), ".xml") &&
      gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkExportXML)))
    {
      showAlertMessage(GTK_WIDGET(data), _("Choose a filename with '.xml' to append other settings."), TRUE, VISU_CONFIG_FILE_KIND_RESOURCE);
    }
  else
    {
      saveAction(VISU_CONFIG_FILE_KIND_RESOURCE, GTK_WIDGET(data), GTK_ENTRY(entry));
      gtk_widget_grab_default(lookup_widget(GTK_WIDGET(data), "closeButtonSave"));
    }
}

static void onSaveParButtonClicked(GtkButton *button _U_, gpointer data)
{
  GtkWidget *entry;

  g_return_if_fail(GTK_IS_DIALOG(data));

  entry = gtk_bin_get_child
    (GTK_BIN(lookup_widget(GTK_WIDGET(data), "comboboxentryParameters")));
  saveAction(VISU_CONFIG_FILE_KIND_PARAMETER, GTK_WIDGET(data), GTK_ENTRY(entry));
  gtk_widget_grab_default(lookup_widget(GTK_WIDGET(data), "closeButtonSave"));
}

static gboolean _appendAllSettings(const gchar *filename, GError **error)
{
  VisuGlNodeScene *scene;
  VisuGlExtPlanes *planes;

  scene = visu_ui_rendering_window_getGlScene(visu_ui_main_class_getDefaultRendering());
  planes = visu_gl_node_scene_addPlanes(scene);
  if (!visu_plane_set_exportXMLFile(planes->planes, filename, error))
    return FALSE;

  if (!visu_gl_node_scene_marksToFile(scene, filename, error))
    return FALSE;

  if (!visu_ui_panel_surfaces_exportXMLFile(filename, error))
    return FALSE;

  if (!visu_gl_node_scene_exportPathsToXML(scene, filename, error))
    return FALSE;

  return TRUE;
}

static void saveAction(VisuConfigFileKind kind, GtkWidget *saveDialog, GtkEntry *entry)
{
  GtkWidget *wd;
  gchar *file, *tmpFile, *basename, *fileUTF8;
  GString *message;
  gboolean resOk;
  gsize ecrit, lu;
  int lines;
  VisuUiRenderingWindow *window;
  VisuData *dataObj;
  GError *error;
  GtkTreeIter iter;
  GtkListStore *listOfFiles;
  GtkEntryCompletion *completion;

  g_return_if_fail(saveDialog && entry);

  file = g_filename_from_utf8(gtk_entry_get_text(entry), -1, &lu, &ecrit, NULL);
  
  if (g_file_test(file, G_FILE_TEST_IS_DIR))
    {
      tmpFile=
	g_build_filename(file, visu_config_file_getDefaultFilename(kind), NULL);
      g_free(file);
      file = tmpFile;
    }
  
  wd = lookup_widget(saveDialog, "checkLimitOnVisuData");
  dataObj = (VisuData*)0;
  if (kind == VISU_CONFIG_FILE_KIND_RESOURCE)
    {
      window = visu_ui_main_class_getDefaultRendering();
      if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(wd)))
        dataObj = visu_gl_node_scene_getData(visu_ui_rendering_window_getGlScene(window));
    }

  error = (GError*)0;
  lines = 0;
  if (kind == VISU_CONFIG_FILE_KIND_RESOURCE && checkXMLResources &&
      gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkXMLResources)))
    resOk = visu_config_file_exportToXML(VISU_CONFIG_FILE_RESOURCE, file, &error);
  else if (kind == VISU_CONFIG_FILE_KIND_RESOURCE && strstr(file, ".xml"))
    {
      resOk = visu_config_file_saveResourcesToXML(file, &lines, dataObj, &error);
      resOk = resOk && _appendAllSettings(file, &error);
    }
  else if (kind == VISU_CONFIG_FILE_KIND_PARAMETER && checkXMLParameters &&
	   gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkXMLParameters)))
    resOk = visu_config_file_exportToXML(VISU_CONFIG_FILE_PARAMETER, file, &error);
  else if (kind == VISU_CONFIG_FILE_KIND_PARAMETER && checkXMLCommandLine &&
	   gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkXMLCommandLine)))
    resOk = commandLineExport(file, &error);
  else if (kind == VISU_CONFIG_FILE_KIND_PARAMETER)
    resOk = visu_config_file_save(VISU_CONFIG_FILE_PARAMETER, file, &lines, dataObj, &error);
  else
    resOk = visu_config_file_save(VISU_CONFIG_FILE_RESOURCE, file, &lines, dataObj, &error);
  if (!resOk && error)
    {
      visu_ui_raiseWarningLong(_("Saving a file"), error->message,
			       GTK_WINDOW(saveDialog));
      g_error_free(error);
    }
  
  basename = g_path_get_basename(file);
  message = g_string_new("");
  if (resOk)
    g_string_append_printf(message, _("File '%s' succesfully written (%d lines)."),
			   basename, lines);
  else
    g_string_append_printf(message, _("File '%s' not written."), basename);
  showAlertMessage(saveDialog, message->str, !resOk, kind);
  g_string_free(message, TRUE);
  g_free(basename);

  /* If file is written, we add it to the completion list. */
  if (resOk)
    {
      completion = gtk_entry_get_completion(GTK_ENTRY(entry));
      g_return_if_fail(completion);

      listOfFiles = GTK_LIST_STORE(gtk_entry_completion_get_model(completion));
      g_return_if_fail(listOfFiles);

      fileUTF8 = g_filename_from_utf8(file, -1, NULL, NULL, NULL);
      if(fileUTF8)
	{
	  gtk_list_store_append(listOfFiles, &iter);
	  gtk_list_store_set(listOfFiles, &iter,
			     GTK_SAVE_FILE_NAME, fileUTF8,
			     -1);
	  g_free(fileUTF8);
	}
    }

  g_free(file);
}

static void showAlertMessage(GtkWidget *saveDialog, gchar* message, gboolean warning, VisuConfigFileKind type)
{
  GtkWidget *wd;

  g_return_if_fail(saveDialog);

  if (type == VISU_CONFIG_FILE_KIND_RESOURCE)
    wd = lookup_widget(saveDialog, "imageWarningResources");
  else
    wd = lookup_widget(saveDialog, "imageWarningParameters");
  if (warning)
    gtk_widget_show(wd);
  else
    gtk_widget_hide(wd);

  if (type == VISU_CONFIG_FILE_KIND_RESOURCE)
    {
      wd = lookup_widget(saveDialog, "statusbarResources");
      gtk_statusbar_pop(GTK_STATUSBAR(wd), saveResourcesContextId);
      gtk_statusbar_push(GTK_STATUSBAR(wd), saveResourcesContextId, message);
    }
  else
    {
      wd = lookup_widget(saveDialog, "statusbarParameters");
      gtk_statusbar_pop(GTK_STATUSBAR(wd), saveParametersContextId);
      gtk_statusbar_push(GTK_STATUSBAR(wd), saveParametersContextId, message);
    }
}

static void onTextEntryChange(GtkEditable *entry, gpointer data _U_)
{
  gboolean reParse;
  GtkTreeIter iter;
  GtkListStore *listOfFiles;
  GtkEntryCompletion *completion;
  gchar *dirEntry, *dirBrowsed;
  GDir *gdir;
  const gchar *fileFromDir, *fileEntry;
  gsize ecrit, lu;
  gchar *fileUTF8, *saveFile, *saveFileUTF8;

  fileEntry = gtk_entry_get_text(GTK_ENTRY(entry));
  if (!fileEntry || !fileEntry[0])
    return;

  DBG_fprintf(stderr, "Gtk Save : browse directory to populate the completion.\n");
  completion = gtk_entry_get_completion(GTK_ENTRY(entry));
  g_return_if_fail(completion);

  listOfFiles = GTK_LIST_STORE(gtk_entry_completion_get_model(completion));
  g_return_if_fail(listOfFiles);

  reParse = FALSE;
  if (!lastParsedDir)
    reParse = TRUE;
  else
    {
      dirEntry = g_path_get_dirname(fileEntry);
      DBG_fprintf(stderr, "Gtk Save : current and last directories...\n %s\n %s\n",
		  dirEntry, lastParsedDir);
      if (strcmp(dirEntry, lastParsedDir))
	reParse = TRUE;
      g_free(dirEntry);
    }

  DBG_fprintf(stderr, "Gtk Save : reparse is needed : %d.\n", reParse);

  if (!reParse)
    {
      gtk_entry_completion_complete(completion);
      return;
    }

  gtk_list_store_clear(listOfFiles);
  dirEntry = g_path_get_dirname(fileEntry);
  g_free(lastParsedDir);
  lastParsedDir = dirEntry;
  dirBrowsed = g_filename_from_utf8(dirEntry, -1, &lu, &ecrit, NULL);
  gdir = g_dir_open(dirBrowsed, 0, NULL);
  if (!gdir)
    {
      g_free(dirBrowsed);
      return;
    }
  fileFromDir = g_dir_read_name(gdir);
  while (fileFromDir)
    {
/*       DBG_fprintf(stderr, "Gtk Save : adding '%s' to completion list.\n", fileFromDir); */
      fileUTF8 = g_filename_from_utf8(fileFromDir, -1, NULL, NULL, NULL);
      if(fileUTF8)
	{
	  saveFile = g_build_filename(dirBrowsed, fileFromDir, NULL);
	  if (g_file_test(saveFile, G_FILE_TEST_IS_DIR))
	    saveFileUTF8 = g_build_filename(dirEntry, fileUTF8, "/", NULL);
	  else
	    saveFileUTF8 = g_build_filename(dirEntry, fileUTF8, NULL);
	  gtk_list_store_append(listOfFiles, &iter);
	  gtk_list_store_set(listOfFiles, &iter,
			     GTK_SAVE_FILE_NAME, saveFileUTF8,
			     -1);
	  g_free(fileUTF8);
	  g_free(saveFile);
	}
      fileFromDir = g_dir_read_name(gdir);
    }
  g_free(dirBrowsed);
  DBG_fprintf(stderr, "Gtk Save : summiting new list of completion.\n");
  gtk_entry_completion_complete(completion);
  DBG_fprintf(stderr, "Gtk Save : summition OK.\n");
}
