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

	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 <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <gdk-pixbuf/gdk-pixbuf.h>

#include "dumpThroughGdkPixbuf.h"
#include <visu_tools.h>

/**
 * SECTION:dumpThroughGdkPixbuf
 * @short_description: add an export capability into PNG and JPG files.
 *
 * This provides a write routine to export V_Sim views into PNG and JPG
 * files. It uses the GdkPixbuf to do it.
 */

static gpointer waitData;
static ToolVoidDataFunc waitFunc;

static gboolean writeViewInPngFormat(ToolFileFormat *format, const char* filename,
				      VisuGlNodeScene *scene, guint width, guint height,
				      GError **error, ToolVoidDataFunc functionWait,
                                      gpointer data);
static gboolean writeViewInJpegFormat(ToolFileFormat *format, const char* filename,
				      VisuGlNodeScene *scene, guint width, guint height,
				      GError **error, ToolVoidDataFunc functionWait,
                                      gpointer data);

static VisuDump *png = NULL;
static VisuDump *jpeg = NULL;

const VisuDump* visu_dump_png_getStatic()
{
  const gchar *typePng[] = {"*.png", (char*)0};

  if (png)
    return png;

  png = VISU_DUMP(visu_dump_scene_new(_("Png file"), typePng, writeViewInPngFormat, TRUE));
  
  waitFunc = (ToolVoidDataFunc)0;
  waitData = (gpointer)0;

  return png;
}

const VisuDump* visu_dump_jpeg_getStatic()
{
  const gchar *typeJpeg[] = {"*.jpg", "*.jpeg", (char*)0};

  if (jpeg)
    return jpeg;

  jpeg = VISU_DUMP(visu_dump_scene_new(_("Jpeg file"), typeJpeg, writeViewInJpegFormat, FALSE));

  tool_file_format_addPropertyInt(TOOL_FILE_FORMAT(jpeg), "quality",
                                  _("Compression ratio (given in percent)"), 85);
  
  waitFunc = (ToolVoidDataFunc)0;
  waitData = (gpointer)0;

  return jpeg;
}

static gboolean writeViewWithGdkPixbuf(ToolFileFormat *format, const char* filename,
                                       guint width, guint height, const gchar *type,
                                       VisuGlNodeScene *scene, GError **error)
{
  GdkPixbuf *pixbuf;
  gboolean success, hasAlpha;
  GArray *propName, *propValues;
  int length;
  gchar *str;
  ToolFileFormatIter iter;
  GArray *imageData;

  g_return_val_if_fail(error && !*error, FALSE);

  g_debug("Dump with GdkPixbuf: begin %s export in %dx%d : %s.",
	      type, width, height, filename);

  if (g_strcmp0(type, "png"))
    {
      length = 3;
      hasAlpha = FALSE;
    }
  else
    {
      length = 4;
      hasAlpha = TRUE;
    }
  imageData = visu_gl_ext_set_getPixmapData(VISU_GL_EXT_SET(scene),
                                            width, height, hasAlpha);
  if (!imageData)
    {
      *error = g_error_new(VISU_DUMP_ERROR, DUMP_ERROR_OPENGL,
                           _("Can't dump OpenGL area to data."));
      return FALSE;
    }
  pixbuf = gdk_pixbuf_new_from_data((guchar*)imageData->data,
				    GDK_COLORSPACE_RGB,
				    hasAlpha,
				    8,
				    width,
				    height,
				    length * width,
				    NULL,
				    (gpointer)0);

  if (!pixbuf)
    {
      *error = g_error_new(VISU_DUMP_ERROR, DUMP_ERROR_FILE,
			   _("Cannot convert pixmap to pixbuf."));
      return FALSE;
    }
  
  propName = g_array_new(TRUE, FALSE, sizeof(gchar*));
  propValues = g_array_new(TRUE, FALSE, sizeof(gchar*));
  iter.lst = (GList*)0;
  for (tool_file_format_iterNextProperty(format, &iter); iter.lst;
       tool_file_format_iterNextProperty(format, &iter))
    {
      str = g_strdup(iter.name);
      g_array_append_vals(propName, &str, 1);
      str = g_strdup_value_contents(iter.val);
      g_array_append_vals(propValues, &str, 1);
    }
  g_debug("Dump with GdkPixbuf: transfer properties.");
  success = gdk_pixbuf_savev(pixbuf, filename, type, (gchar**)propName->data,
                             (gchar**)propValues->data, error);
  g_strfreev((gchar**)g_array_free(propName, FALSE));
  g_strfreev((gchar**)g_array_free(propValues, FALSE));
  g_object_unref(pixbuf);
  g_array_free(imageData, TRUE);
  return success;
}

static gboolean writeViewInJpegFormat(ToolFileFormat *format, const char* filename,
				      VisuGlNodeScene *scene, guint width, guint height,
				      GError **error, ToolVoidDataFunc functionWait,
                                      gpointer data)
{
  int i, res;

  res = writeViewWithGdkPixbuf(format, filename, width, height, "jpeg",
			       scene, error);

  /* Must call 100 times functionWait if exists before leaving... */
  if (functionWait)
    for (i = 0; i < 100; i++)
      functionWait(data);

  return res;
}

static gboolean writeViewInPngFormat(ToolFileFormat *format, const char* filename,
                                     VisuGlNodeScene *scene, guint width, guint height,
                                     GError **error, ToolVoidDataFunc functionWait,
                                     gpointer data)
{
  int i, res;

  res = writeViewWithGdkPixbuf(format, filename, width, height, "png",
			       scene, error);

  /* Must call 100 times functionWait if exists before leaving... */
  if (functionWait)
    for (i = 0; i < 100; i++)
      functionWait(data);

  return res;
}
