/* -*- mode: C; c-basic-offset: 2 -*- */
/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Damien
	CALISTE, laboratoire L_Sim, (2020)
  
	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, (2020)

	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 "toolWriter.h"
#include <pango/pangocairo.h>
#include <cairo.h>

/**
 * SECTION: toolWriter
 * @short_description: a convenient tool to layout text on a surface.
 *
 * <para>This singleton can generate bit arrays representing a text.</para>
 */

/**
 * ToolWriter:
 *
 * Structure defining #ToolWriter objects.
 *
 * Since: 3.9
 */

struct _ToolWriterPrivate
{
  gboolean dispose_has_run;

  PangoLayout *layout;
  cairo_t *context;
  gboolean stroke;
};

static GObject* _constructor(GType type, guint n_construct_params,
                             GObjectConstructParam *construct_params);
static void _dispose(GObject *obj);

G_DEFINE_TYPE_WITH_CODE(ToolWriter, tool_writer, G_TYPE_OBJECT,
                        G_ADD_PRIVATE(ToolWriter))

static void tool_writer_class_init(ToolWriterClass *klass)
{
  G_OBJECT_CLASS(klass)->constructor = _constructor;
  G_OBJECT_CLASS(klass)->dispose = _dispose;
}
static void tool_writer_init(ToolWriter *obj)
{
  cairo_surface_t *surf;

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

  surf = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 0, 0);
  obj->priv->context = cairo_create(surf);
  cairo_surface_destroy(surf);

  obj->priv->layout = pango_cairo_create_layout(obj->priv->context);
  tool_writer_setSize(obj, TOOL_WRITER_FONT_NORMAL);

  obj->priv->stroke = FALSE;
}
static GObject* _constructor(GType type, guint n_construct_params,
                             GObjectConstructParam *construct_params)
{
  static GObject *self = NULL;

  if (self == NULL)
    {
      self = G_OBJECT_CLASS(tool_writer_parent_class)->constructor(
          type, n_construct_params, construct_params);
      g_object_add_weak_pointer(self, (gpointer) &self);
      return self;
    }

  return g_object_ref(self);
}
static void _dispose(GObject *obj)
{
  ToolWriter *writer = TOOL_WRITER(obj);

  if (writer->priv->dispose_has_run)
    return;

  writer->priv->dispose_has_run = TRUE;
  g_object_unref(writer->priv->layout);
  cairo_destroy(writer->priv->context);
}

/**
 * tool_writer_getStatic:
 *
 * Retrieve the #ToolWriter singleton.
 *
 * Since: 3.9
 *
 * Returns: (transfer full): the #ToolWriter singleton.
 **/
ToolWriter* tool_writer_getStatic(void)
{
  return g_object_new(TOOL_TYPE_WRITER, NULL);
}

/**
 * tool_writer_setSize:
 * @writer: a #ToolWriter object
 * @size: a font size
 *
 * Change the rendering font size for @writer.
 *
 * Since: 3.9
 */
void tool_writer_setSize(ToolWriter *writer, ToolWriterFontSize size)
{
  PangoFontDescription *desc;

  g_return_if_fail(TOOL_IS_WRITER(writer));

  switch (size)
    {
    case TOOL_WRITER_FONT_NORMAL:
      desc = pango_font_description_from_string("Mono Bold 11");
      break;
    case TOOL_WRITER_FONT_SMALL:
      desc = pango_font_description_from_string("Mono Bold 9");
      break;
    default:
      g_return_if_reached();
    }
  pango_layout_set_font_description(writer->priv->layout, desc);
  pango_font_description_free(desc);
}

/**
 * tool_writer_setStroke:
 * @writer: a #ToolWriter object
 * @stroke: a boolean
 *
 * Outline text with a black stroke or not.
 *
 * Since: 3.9
 **/
void tool_writer_setStroke(ToolWriter *writer, gboolean stroke)
{
  g_return_if_fail(TOOL_IS_WRITER(writer));

  writer->priv->stroke = stroke;
}

/**
 * tool_writer_layout:
 * @writer: the #ToolWriter singleton
 * @text: a text
 * @width: (out caller-allocates): a location to store the width
 * @height: (out caller-allocates): a location to store the height
 *
 * Compute the layout of @text and returns it in ARGB32 format.
 *
 * Since: 3.9
 *
 * Returns: (element-type gchar) (transfer full): a newly allocated buffer for the
 * rasterisation of @text.
 **/
GArray* tool_writer_layout(const ToolWriter *writer, const gchar *text,
                           guint *width, guint *height)
{
  cairo_t *ct;
  GArray *buf;
  gint w, h;
  cairo_surface_t *surf;

  g_return_val_if_fail(TOOL_IS_WRITER(writer), (GArray*)0);

  pango_layout_set_text(writer->priv->layout, text, -1);
  pango_layout_get_size(writer->priv->layout, &w, &h);
  w /= PANGO_SCALE;
  h /= PANGO_SCALE;

  buf = g_array_sized_new(FALSE, FALSE, sizeof(unsigned char), 4 * w * h);
  for (gint i = 0; i < w * h; i++)
    {
      char c[4] = {-1, -1, -1, 0};
      g_array_append_vals(buf, c, 4);
    }

  surf = cairo_image_surface_create_for_data((unsigned char*)buf->data,
                                             CAIRO_FORMAT_ARGB32, w, h, 4 * w);
  ct = cairo_create(surf);

  if (writer->priv->stroke)
    {
      double x, y;
      cairo_get_current_point(ct, &x, &y);
      pango_cairo_layout_path(ct, writer->priv->layout);
      cairo_set_source_rgba(ct, 0, 0, 0, 1);
      cairo_stroke(ct);
      cairo_move_to(ct, x, y);
    }
  cairo_set_source_rgba(ct, 1, 1, 1, 1);
  pango_cairo_show_layout(ct, writer->priv->layout);

  cairo_destroy(ct);
  cairo_surface_destroy(surf);
  if (width)
    *width = w;
  if (height)
    *height = h;
  return buf;
}
