/* cereimg.c
 * Copyright (C) 2002-2004 Pascal Eberhard <pascal.ebo@netcourrier.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/* cereimg.c
 * Copyright (C) 2000  Red Hat, Inc.,  Jonathan Blandford <jrb@redhat.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include <stdlib.h>

#include <gtk/gtk.h>
#include "cereimg.h"
//#include "gtkintl.h"
//#include "log.h"

static void cereimg_get_property  (GObject                    *object,
						    guint                       param_id,
						    GValue                     *value,
						    GParamSpec                 *pspec);
static void cereimg_set_property  (GObject                    *object,
						    guint                       param_id,
						    const GValue               *value,
						    GParamSpec                 *pspec);
static void cereimg_init       (Cereimg      *celltext);
static void cereimg_class_init (CereimgClass *class);
static void cereimg_finalize   (GObject                    *object);
static void cereimg_create_stock_pixbuf (Cereimg *cellimg,
							  GtkWidget             *widget);
static void cereimg_get_size   (GtkCellRenderer            *cell,
						 GtkWidget                  *widget,
						 GdkRectangle               *rectangle,
						 gint                       *x_offset,
						 gint                       *y_offset,
						 gint                       *width,
						 gint                       *height);
static void cereimg_render     (GtkCellRenderer            *cell,
						 GdkWindow                  *window,
						 GtkWidget                  *widget,
						 GdkRectangle               *background_area,
						 GdkRectangle               *cell_area,
						 GdkRectangle               *expose_area,
						 GtkCellRendererState        flags);

static gint
cereimg_activate (GtkCellRenderer      *cell, GdkEvent             *event,
                  GtkWidget            *widget, const gchar          *path,
                  GdkRectangle         *background_area,
                  GdkRectangle         *cell_area,
                  GtkCellRendererState  flags);

enum {
	PROP_ZERO,
	PROP_PIXBUF,
	PROP_PIXBUF_EXPANDER_OPEN,
	PROP_PIXBUF_EXPANDER_CLOSED,
	PROP_STOCK_ID,
	PROP_STOCK_SIZE,
	PROP_STOCK_DETAIL,
        PROP_ACTIVATABLE,
        PROP_BACKGROUND
};

enum {
  CLICKED,
  LAST_SIGNAL
};

static guint cereimg_cell_signals[LAST_SIGNAL] = { 0 };


static gpointer parent_class;

#define CELLTRACE_KEY "gtk-cell-renderer-pixbuf-info"

typedef struct _CereimgInfo CereimgInfo;
struct _CereimgInfo
{
  gchar *stock_id;
  GtkIconSize stock_size;
  gchar *stock_detail;
};

GType
cereimg_get_type (void)
{
  static GType cell_pixbuf_type = 0;

  if (!cell_pixbuf_type)
    {
      static const GTypeInfo cell_pixbuf_info =
      {
	sizeof (CereimgClass),
	NULL,		/* base_init */
	NULL,		/* base_finalize */
	(GClassInitFunc) cereimg_class_init,
	NULL,		/* class_finalize */
	NULL,		/* class_data */
	sizeof (Cereimg),
	0,              /* n_preallocs */
	(GInstanceInitFunc) cereimg_init,
      };

      cell_pixbuf_type =
	g_type_register_static (GTK_TYPE_CELL_RENDERER, "Cereimg",
			        &cell_pixbuf_info, 0);
    }

  return cell_pixbuf_type;
}

static void
cereimg_init (Cereimg *cellimg)
{
  CereimgInfo *cellinfo;

  cellinfo = g_new0 (CereimgInfo, 1);
  cellinfo->stock_size = GTK_ICON_SIZE_MENU;
  g_object_set_data (G_OBJECT (cellimg), CELLTRACE_KEY, cellinfo);
  cellimg->activatable = TRUE;
  GTK_CELL_RENDERER (cellimg)->mode = GTK_CELL_RENDERER_MODE_ACTIVATABLE;

}

static void
cereimg_class_init (CereimgClass *class)
{
  GObjectClass *object_class = G_OBJECT_CLASS (class);
  GtkCellRendererClass *cell_class = GTK_CELL_RENDERER_CLASS (class);

  parent_class = g_type_class_peek_parent (class);

  object_class->finalize = cereimg_finalize;

  object_class->get_property = cereimg_get_property;
  object_class->set_property = cereimg_set_property;

  cell_class->get_size = cereimg_get_size;
  cell_class->render = cereimg_render;

  cell_class->activate = cereimg_activate;

  g_object_class_install_property (object_class,
				   PROP_PIXBUF,
				   g_param_spec_object ("pixbuf",
							"Pixbuf Object",
							"The pixbuf to render",
							GDK_TYPE_PIXBUF,
							G_PARAM_READABLE |
							G_PARAM_WRITABLE));

  g_object_class_install_property (object_class,
				   PROP_PIXBUF_EXPANDER_OPEN,
				   g_param_spec_object ("pixbuf_expander_open",
							"Pixbuf Expander Open",
							"Pixbuf for open expander",
							GDK_TYPE_PIXBUF,
							G_PARAM_READABLE |
							G_PARAM_WRITABLE));

  g_object_class_install_property (object_class,
				   PROP_PIXBUF_EXPANDER_CLOSED,
				   g_param_spec_object ("pixbuf_expander_closed",
							"Pixbuf Expander Closed",
							"Pixbuf for closed expander",
							GDK_TYPE_PIXBUF,
							G_PARAM_READABLE |
							G_PARAM_WRITABLE));

  g_object_class_install_property (object_class,
				   PROP_STOCK_ID,
				   g_param_spec_string ("stock_id",
							"Stock ID",
							"The stock ID of the stock icon to render",
							NULL,
							G_PARAM_READWRITE));

  g_object_class_install_property (object_class,
				   PROP_STOCK_SIZE,
				   g_param_spec_enum ("stock_size",
						      "Size",
						      "The size of the rendered icon",
						      GTK_TYPE_ICON_SIZE,
						      GTK_ICON_SIZE_MENU,
						      G_PARAM_READWRITE));

  g_object_class_install_property (object_class,
				   PROP_STOCK_DETAIL,
				   g_param_spec_string ("stock_detail",
							"Detail",
							"Render detail to pass to the theme engine",
							NULL,
							G_PARAM_READWRITE));

  g_object_class_install_property (object_class,
      PROP_ACTIVATABLE,
      g_param_spec_boolean ("activatable",
        "Activatable", "The image can be clicked",
        TRUE,
        G_PARAM_READABLE | G_PARAM_WRITABLE));

  g_object_class_install_property (object_class,
      PROP_BACKGROUND,
      g_param_spec_string ("background",
      "Background color name",
      "Background color as a string",
      NULL,
      G_PARAM_WRITABLE));

  cereimg_cell_signals[CLICKED] = 
    g_signal_new("clicked",
                 G_OBJECT_CLASS_TYPE (object_class),
                 G_SIGNAL_RUN_LAST,
                 G_STRUCT_OFFSET (CereimgClass, clicked),
                 NULL, NULL,
                 g_cclosure_marshal_VOID__STRING,
                 G_TYPE_NONE, 1,
                 G_TYPE_STRING);
  
}

static void
cereimg_finalize (GObject *object)
{
  Cereimg *cellimg = GTK_CEREIMG (object);
  CereimgInfo *cellinfo = g_object_get_data (object, CELLTRACE_KEY);

  if (cellimg->pixbuf && cellinfo->stock_id)
    g_object_unref (cellimg->pixbuf);

  if (cellinfo->stock_id)
    g_free (cellinfo->stock_id);

  if (cellinfo->stock_detail)
    g_free (cellinfo->stock_detail);

  g_free (cellinfo);
  g_object_set_data (object, CELLTRACE_KEY, NULL);

  (* G_OBJECT_CLASS (parent_class)->finalize) (object);
}

static void
cereimg_get_property (GObject        *object,
				       guint           param_id,
				       GValue         *value,
				       GParamSpec     *pspec)
{
  Cereimg *cellimg = GTK_CEREIMG (object);
  CereimgInfo *cellinfo = g_object_get_data (object, CELLTRACE_KEY);
  
  switch (param_id)
    {
    case PROP_PIXBUF:
      g_value_set_object (value,
                          cellimg->pixbuf ? G_OBJECT (cellimg->pixbuf) : NULL);
      break;
    case PROP_PIXBUF_EXPANDER_OPEN:
      g_value_set_object (value,
                          cellimg->pixbuf_expander_open ? G_OBJECT (cellimg->pixbuf_expander_open) : NULL);
      break;
    case PROP_PIXBUF_EXPANDER_CLOSED:
      g_value_set_object (value,
                          cellimg->pixbuf_expander_closed ? G_OBJECT (cellimg->pixbuf_expander_closed) : NULL);
      break;
    case PROP_STOCK_ID:
      g_value_set_string (value, cellinfo->stock_id);
      break;
    case PROP_STOCK_SIZE:
      g_value_set_enum (value, cellinfo->stock_size);
      break;
    case PROP_STOCK_DETAIL:
      g_value_set_string (value, cellinfo->stock_detail);
      break;
    case PROP_ACTIVATABLE:
      g_value_set_boolean (value, cellimg->activatable);
      break;
    case PROP_BACKGROUND:
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
      break;
    }
}


static void
cereimg_set_property (GObject      *object,
				       guint         param_id,
				       const GValue *value,
				       GParamSpec   *pspec)
{
  GdkPixbuf *pixbuf;
  Cereimg *cellimg = GTK_CEREIMG (object);
  CereimgInfo *cellinfo = g_object_get_data (object, CELLTRACE_KEY);
  
  switch (param_id)
    {
    case PROP_PIXBUF:
      pixbuf = (GdkPixbuf*) g_value_get_object (value);
      if (pixbuf)
        g_object_ref (pixbuf);
      if (cellimg->pixbuf)
	g_object_unref (cellimg->pixbuf);
      cellimg->pixbuf = pixbuf;
      break;
    case PROP_PIXBUF_EXPANDER_OPEN:
      pixbuf = (GdkPixbuf*) g_value_get_object (value);
      if (pixbuf)
        g_object_ref (pixbuf);
      if (cellimg->pixbuf_expander_open)
	g_object_unref (cellimg->pixbuf_expander_open);
      cellimg->pixbuf_expander_open = pixbuf;
      break;
    case PROP_PIXBUF_EXPANDER_CLOSED:
      pixbuf = (GdkPixbuf*) g_value_get_object (value);
      if (pixbuf)
        g_object_ref (pixbuf);
      if (cellimg->pixbuf_expander_closed)
	g_object_unref (cellimg->pixbuf_expander_closed);
      cellimg->pixbuf_expander_closed = pixbuf;
      break;
    case PROP_STOCK_ID:
      if (cellinfo->stock_id)
        g_free (cellinfo->stock_id);
      cellinfo->stock_id = g_strdup (g_value_get_string (value));
      g_object_notify (G_OBJECT (object), "stock_id");
      break;
    case PROP_STOCK_SIZE:
      cellinfo->stock_size = g_value_get_enum (value);
      g_object_notify (G_OBJECT (object), "stock_size");
      break;
    case PROP_STOCK_DETAIL:
      if (cellinfo->stock_detail)
        g_free (cellinfo->stock_detail);
      cellinfo->stock_detail = g_strdup (g_value_get_string (value));
      g_object_notify (G_OBJECT (object), "stock_detail");
      break;
    case PROP_ACTIVATABLE:
      cellimg->activatable = g_value_get_boolean (value);
      g_object_notify (G_OBJECT (object), "activatable");
      break;
    case PROP_BACKGROUND:
      {
        cellimg->background_set = FALSE;
        if (!g_value_get_string (value))
          g_warning("Don't know color, value is NULL");
        else if (gdk_color_parse (g_value_get_string (value),
                                  &cellimg->background_color))
          cellimg->background_set = TRUE;
        else
          g_warning("Don't know color `%s'", g_value_get_string (value));
      }
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
      break;
    }

  if (cellimg->pixbuf && cellinfo->stock_id)
    {
      g_object_unref (cellimg->pixbuf);
      cellimg->pixbuf = NULL;
    }
}

/**
 * cereimg_new:
 * 
 * Creates a new #Cereimg. Adjust rendering
 * parameters using object properties. Object properties can be set
 * globally (with g_object_set()). Also, with #GtkTreeViewColumn, you
 * can bind a property to a value in a #GtkTreeModel. For example, you
 * can bind the "pixbuf" property on the cell renderer to a pixbuf value
 * in the model, thus rendering a different image in each row of the
 * #GtkTreeView.
 * 
 * Return value: the new cell renderer
 **/
GtkCellRenderer *
cereimg_new (void)
{
  return g_object_new (GTK_TYPE_CEREIMG, NULL);
}

static void
cereimg_create_stock_pixbuf (Cereimg *cellimg,
					      GtkWidget             *widget)
{
  CereimgInfo *cellinfo = g_object_get_data (G_OBJECT (cellimg), CELLTRACE_KEY);

  if (cellimg->pixbuf)
    g_object_unref (cellimg->pixbuf);

  cellimg->pixbuf = gtk_widget_render_icon (widget,
					       cellinfo->stock_id,
					       cellinfo->stock_size,
					       cellinfo->stock_detail);
}

static void
cereimg_get_size (GtkCellRenderer *cell,
				   GtkWidget       *widget,
				   GdkRectangle    *cell_area,
				   gint            *x_offset,
				   gint            *y_offset,
				   gint            *width,
				   gint            *height)
{
  Cereimg *cellimg = (Cereimg *) cell;
  CereimgInfo *cellinfo = g_object_get_data (G_OBJECT (cell), CELLTRACE_KEY);
  gint pixbuf_width = 0;
  gint pixbuf_height = 0;
  gint calc_width;
  gint calc_height;

  if (!cellimg->pixbuf && cellinfo->stock_id)
    cereimg_create_stock_pixbuf (cellimg, widget);

  if (cellimg->pixbuf)
    {
      pixbuf_width = gdk_pixbuf_get_width (cellimg->pixbuf);
      pixbuf_height = gdk_pixbuf_get_height (cellimg->pixbuf);
    }
  if (cellimg->pixbuf_expander_open)
    {
      pixbuf_width = MAX (pixbuf_width, gdk_pixbuf_get_width (cellimg->pixbuf_expander_open));
      pixbuf_height = MAX (pixbuf_height, gdk_pixbuf_get_height (cellimg->pixbuf_expander_open));
    }
  if (cellimg->pixbuf_expander_closed)
    {
      pixbuf_width = MAX (pixbuf_width, gdk_pixbuf_get_width (cellimg->pixbuf_expander_closed));
      pixbuf_height = MAX (pixbuf_height, gdk_pixbuf_get_height (cellimg->pixbuf_expander_closed));
    }
  
  calc_width = (gint) GTK_CELL_RENDERER (cellimg)->xpad * 2 + pixbuf_width;
  calc_height = (gint) GTK_CELL_RENDERER (cellimg)->ypad * 2 + pixbuf_height;
  
  if (x_offset) *x_offset = 0;
  if (y_offset) *y_offset = 0;

  if (cell_area && pixbuf_width > 0 && pixbuf_height > 0)
    {
      if (x_offset)
	{
	  *x_offset = GTK_CELL_RENDERER (cellimg)->xalign * (cell_area->width - calc_width - (2 * GTK_CELL_RENDERER (cellimg)->xpad));
	  *x_offset = MAX (*x_offset, 0) + GTK_CELL_RENDERER (cellimg)->xpad;
	}
      if (y_offset)
	{
	  *y_offset = GTK_CELL_RENDERER (cellimg)->yalign * (cell_area->height - calc_height - (2 * GTK_CELL_RENDERER (cellimg)->ypad));
	  *y_offset = MAX (*y_offset, 0) + GTK_CELL_RENDERER (cellimg)->ypad;
	}
    }

  if (width)
    *width = calc_width;
  
  if (height)
    *height = calc_height;
}

static void
cereimg_render (GtkCellRenderer  *cell,
				 GdkWindow            *window,
				 GtkWidget            *widget,
				 GdkRectangle         *background_area,
				 GdkRectangle         *cell_area,
				 GdkRectangle         *expose_area,
				 GtkCellRendererState  flags)

{
  Cereimg *cellimg = (Cereimg *) cell;
  CereimgInfo *cellinfo = g_object_get_data (G_OBJECT (cell), CELLTRACE_KEY);
  GdkPixbuf *pixbuf;
  GdkRectangle pix_rect;
  GdkRectangle draw_rect;
  gboolean stock_pixbuf = FALSE;

  GdkGC *gc;
  gboolean use_background;

  use_background = (cellimg->background_set == TRUE) && 
                   ((flags & GTK_CELL_RENDERER_SELECTED) != 
                                                   GTK_CELL_RENDERER_SELECTED);

  if (use_background)
  {
    //gdk_color_parse("#ccccff",&cellimg->background_color);
    gc = gdk_gc_new (window);
    gdk_gc_set_rgb_fg_color (gc, &cellimg->background_color);
    gdk_draw_rectangle (window, gc, TRUE,
                        background_area->x, background_area->y,
                        background_area->width, background_area->height);
    //background_area->width+2 not needed anymore.
  }
  else
  {
    gc = widget->style->black_gc;
  }

  pixbuf = cellimg->pixbuf;
  if (cell->is_expander)
    {
      if (cell->is_expanded &&
	  cellimg->pixbuf_expander_open != NULL)
	pixbuf = cellimg->pixbuf_expander_open;
      else if (! cell->is_expanded &&
	       cellimg->pixbuf_expander_closed != NULL)
	pixbuf = cellimg->pixbuf_expander_closed;
    }

  if (!pixbuf && !cellinfo->stock_id)
  {
    if (use_background)
      g_object_unref(gc);
    return;
  }
  else if (!pixbuf && cellinfo->stock_id)
    stock_pixbuf = TRUE;

  cereimg_get_size (cell, widget, cell_area,
                    &pix_rect.x, &pix_rect.y,
                    &pix_rect.width, &pix_rect.height);

  if (stock_pixbuf)
    pixbuf = cellimg->pixbuf;
  
  pix_rect.x += cell_area->x;
  pix_rect.y += cell_area->y;
  pix_rect.width -= cell->xpad * 2;
  pix_rect.height -= cell->ypad * 2;

  
  if (gdk_rectangle_intersect (cell_area, &pix_rect, &draw_rect))
  {
    gdk_pixbuf_render_to_drawable (
		     pixbuf,
		     window/*drawable*/,
                     gc/*widget->style->black_gc*/,
		     /* pixbuf 0, 0 is at pix_rect.x, pix_rect.y */
		     draw_rect.x - pix_rect.x/* src_x */,
		     draw_rect.y - pix_rect.y/* src_y */,
		     draw_rect.x/* dst_x  */,
		     draw_rect.y/* dst_y */,
		     draw_rect.width/* width */,
		     draw_rect.height/* height */,
		     GDK_RGB_DITHER_NORMAL,
		     0, 0);
#if 0
    gdk_draw_pixbuf (window,
                     gc/*widget->style->black_gc*/,
		     pixbuf,
		     /* pixbuf 0, 0 is at pix_rect.x, pix_rect.y */
		     draw_rect.x - pix_rect.x,
		     draw_rect.y - pix_rect.y,
		     draw_rect.x,
		     draw_rect.y,
		     draw_rect.width,
		     draw_rect.height,
		     GDK_RGB_DITHER_NORMAL,
		     0, 0);
#endif
  }

  if (use_background)
    g_object_unref(gc);
}

static gint
cereimg_activate (GtkCellRenderer      *cell,
                  GdkEvent             *event,
                  GtkWidget            *widget,
                  const gchar          *path,
                  GdkRectangle         *background_area,
                  GdkRectangle         *cell_area,
                  GtkCellRendererState  flags)
{
 g_signal_emit (cell, cereimg_cell_signals[CLICKED], 0, path);
 return TRUE;
}


#if 0
GtkWidget *create_tree(void)
{
  GtkTreeStore *store;
  GtkWidget *treeview;
  GtkTreeSelection *select;
  GtkCellRenderer *renderer;
  GtkTreeViewColumn *column;
  GtkTreeIter iter1;
  GdkPixbuf         *pixbuf_tmp;
  
  pixbuf_tmp = gdk_pixbuf_new_from_file("../src/unknown.png", NULL);
  store = gtk_tree_store_new(2, G_TYPE_STRING, G_TYPE_POINTER);
  gtk_tree_store_append(store, &iter1, NULL);
  gtk_tree_store_set(store, &iter1, 0, "le premier", 1, 0, -1);
  gtk_tree_store_append(store, &iter1, NULL);
  gtk_tree_store_set(store, &iter1, 0, "/usr/share/icons", 1, 0, -1);
  treeview = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store));
  g_object_unref(G_OBJECT(store));
  select = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview));
  gtk_tree_selection_set_mode(select, GTK_SELECTION_SINGLE);

  renderer = gtk_cell_renderer_text_new();
  column = gtk_tree_view_column_new_with_attributes("Name", renderer, "text", 0, NULL);
  gtk_tree_view_append_column(GTK_TREE_VIEW(treeview), column);
  
  renderer = gtk_cell_renderer_pixbuf_new();
  g_object_set(renderer, "pixbuf", pixbuf_tmp, NULL);
  column = gtk_tree_view_column_new_with_attributes("Pix", renderer, NULL);

  return treeview;
}

int main(int argc, char**argv)
{
  GtkWidget *w;
  GtkWidget *tree;

  gtk_init(&argc, &argv);
  w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(w), "Treeview cell renderer: cereimg");
  tree = create_tree();
  gtk_container_add(GTK_CONTAINER(w), tree);
  gtk_widget_show_all(w);

  gtk_main();
  return 0;
}

#endif
