/* egglinkbutton.c
 * 
 * Copyright (C) 2005 Emmanuele Bassi <ebassi@gmail.com>
 * All rights reserved.
 *
 * Based on gnome-href code by:
 * 	James Henstridge <james@daa.com.au>
 * 
 * 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, Cambridge, MA 02139, USA.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string.h>

#include <gtk/gtklabel.h>
#include <gtk/gtkdnd.h>
#include <gdk/gdkcolor.h>
#include <gdk/gdkcursor.h>

#ifndef EGG_COMPILATION
#include <glib/gi18n.h>
#else
#define _(x) (x)
#define N_(x) (x)
#endif

#include "egglinkbutton.h"

struct _EggLinkButtonPrivate
{
  gchar *uri;
  gchar *text;

  GtkWidget *label;
  
  GdkCursor *hand_cursor;
  
  guint active : 1;
};

enum
{
  PROP_0,
  
  PROP_URI,
  PROP_ACTIVE
};

#define EGG_LINK_BUTTON_GET_PRIVATE(obj)	(G_TYPE_INSTANCE_GET_PRIVATE ((obj), EGG_TYPE_LINK_BUTTON, EggLinkButtonPrivate))

static void egg_link_button_class_init   (EggLinkButtonClass *klass);
static void egg_link_button_init         (EggLinkButton      *link_button);
static void egg_link_button_finalize     (GObject            *object);
static void egg_link_button_get_property (GObject            *object,
					  guint               prop_id,
					  GValue             *value,
					  GParamSpec         *pspec);
static void egg_link_button_set_property (GObject            *object,
					  guint               prop_id,
					  const GValue       *value,
					  GParamSpec         *pspec);

static void egg_link_button_style_set    (GtkWidget          *widget,
					  GtkStyle           *old_style);

static void egg_link_button_clicked      (GtkButton          *button);

static gboolean egg_link_button_enter_cb (GtkWidget          *widget,
					  GdkEventCrossing   *event,
					  gpointer            user_data);
static gboolean egg_link_button_leave_cb (GtkWidget          *widget,
					  GdkEventCrossing   *event,
					  gpointer            user_data);

static void egg_link_button_drag_data_get_cb (GtkWidget        *widget,
					      GdkDragContext   *context,
					      GtkSelectionData *selection,
					      guint             _info,
					      guint             _time,
					      gpointer          user_data);


static const GtkTargetEntry link_drop_types[] = {
	{ "text/uri-list", 0, 0 },
	{ "_NETSCAPE_URL", 0, 0 }
};

static const gint n_link_drop_types = sizeof(link_drop_types) /
				      sizeof(link_drop_types[0]);


static GObjectClass *parent_class = NULL;

static EggLinkButtonActivateFunc activate_uri_hook = NULL;
static gpointer activate_uri_hook_data = NULL;
static GDestroyNotify activate_uri_hook_destroy = NULL;

GType
egg_link_button_get_type (void)
{
  static GType link_button_type = 0;
  
  if (!link_button_type)
    {
      static const GTypeInfo link_button_info =
      {
        sizeof (EggLinkButtonClass),
        NULL, /* base_init */
        NULL, /* base_finalize */
        (GClassInitFunc) egg_link_button_class_init,
        NULL, /* class_finalize */
        NULL, /* class_data */
        sizeof (EggLinkButton),
        0,    /* n_preallocs */
        (GInstanceInitFunc) egg_link_button_init,
      };
      
      link_button_type =
        g_type_register_static (GTK_TYPE_BUTTON, "EggLinkButton",
        			&link_button_info, 0);
    }
  
  return link_button_type;
}

static void
egg_link_button_class_init (EggLinkButtonClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
  GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
  GtkButtonClass *button_class = GTK_BUTTON_CLASS (klass);
  
  parent_class = g_type_class_peek_parent (klass);
  
  gobject_class->set_property = egg_link_button_set_property;
  gobject_class->get_property = egg_link_button_get_property;
  gobject_class->finalize = egg_link_button_finalize;
  
  widget_class->style_set = egg_link_button_style_set;
  
  button_class->clicked = egg_link_button_clicked;
  
  /**
   * EggLinkButton:uri
   * 
   * The URI bound to this button.
   *
   * Since: 2.x
   */
  g_object_class_install_property (gobject_class,
  				   PROP_URI,
  				   g_param_spec_string ("uri",
  				   			_("URI"),
  				   			_("The URI bound to this button"),
  				   			"http://www.gtk.org",
  				   			G_PARAM_READWRITE));
  /**
   * EggLinkButton:active
   *
   * Whether the button is active or not.
   *
   * Since: 2.x
   */
  g_object_class_install_property (gobject_class,
  				   PROP_ACTIVE,
  				   g_param_spec_boolean ("active",
  				   			 _("Active"),
  				   			 _("Whether the link button is active or not"),
  				   			 TRUE,
  				   			 G_PARAM_READWRITE));
  
  /**
   * EggLinkButton:link_color
   *
   * The color used when drawing the link.
   *
   * Since: 2.x
   */
  gtk_widget_class_install_style_property (widget_class,
  					   g_param_spec_boxed ("link-color",
  					   		       _("Link Color"),
  					   		       _("Color used for the hyperlink"),
  					   		       GDK_TYPE_COLOR,
  					   		       G_PARAM_READABLE));
#if 0
  /**
   * EggLinkButton:link_color_hover
   *
   * The color used when hovering with the mouse over the link.
   *
   * Since: 2.x
   */
  gtk_widget_class_install_style_property (widget_class,
   					   g_param_spec_boxed ("link-hover-color",
  							       _("Hover Link Color"),
   					    		       _("Color used when hovering over the link"),
   					    		       GDK_TYPE_COLOR,
   					    		       G_PARAM_READABLE));
  /**
   * EggLinkButton:link_color_active
   *
   * The color used when the link has been activated.
   *
   * Since: 2.x
   */
  gtk_widget_class_install_style_property (widget_class,
   					   g_param_spec_boxed ("link-active-color",
   					    		       _("Active Link Color"),
   					    		       _("Color used when the link has been activated"),
   					    		       GDK_TYPE_COLOR,
   					    		       G_PARAM_READABLE));
#endif
  
  g_type_class_add_private (gobject_class, sizeof (EggLinkButtonPrivate));
}

static void
egg_link_button_init (EggLinkButton *link_button)
{
  EggLinkButtonPrivate *priv;
  
  priv = EGG_LINK_BUTTON_GET_PRIVATE (link_button),
  link_button->priv = priv;
  
  priv->text = NULL;
  priv->uri = NULL;
  
  priv->active = TRUE;
  
  priv->hand_cursor = gdk_cursor_new (GDK_HAND2);
  
  gtk_button_set_relief (GTK_BUTTON (link_button), GTK_RELIEF_NONE);
  
  g_signal_connect (link_button, "enter-notify-event",
  		    G_CALLBACK (egg_link_button_enter_cb), NULL);
  g_signal_connect (link_button, "leave-notify-event",
  		    G_CALLBACK (egg_link_button_leave_cb), NULL);
  g_signal_connect (link_button, "drag-data-get",
  		    G_CALLBACK (egg_link_button_drag_data_get_cb), NULL);
  
  /* enable drag source */
  gtk_drag_source_set (GTK_WIDGET (link_button),
  		       GDK_BUTTON1_MASK,
  		       link_drop_types, n_link_drop_types,
  		       GDK_ACTION_COPY);  		       
}

static void
egg_link_button_finalize (GObject *object)
{
  EggLinkButton *link_button = EGG_LINK_BUTTON (object);
  EggLinkButtonPrivate *priv = link_button->priv;
  
  g_free (priv->uri);
  g_free (priv->text);
  
  priv->label = NULL;
  
  gdk_cursor_unref (priv->hand_cursor);
  
  G_OBJECT_CLASS (parent_class)->finalize (object);
}

static void
egg_link_button_get_property (GObject    *object,
			      guint       prop_id,
			      GValue     *value,
			      GParamSpec *pspec)
{
  EggLinkButton *link_button = EGG_LINK_BUTTON (object);
  EggLinkButtonPrivate *priv = EGG_LINK_BUTTON_GET_PRIVATE (link_button);
  
  switch (prop_id)
    {
    case PROP_URI:
      g_value_set_string (value, priv->uri);
      break;
    case PROP_ACTIVE:
      g_value_set_boolean (value, priv->active);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static void
egg_link_button_set_property (GObject      *object,
			      guint         prop_id,
			      const GValue *value,
			      GParamSpec   *pspec)
{
  EggLinkButton *link_button = EGG_LINK_BUTTON (object);
  
  switch (prop_id)
    {
    case PROP_URI:
      egg_link_button_set_uri (link_button, g_value_get_string (value));
      break;
    case PROP_ACTIVE:
      egg_link_button_set_active (link_button, g_value_get_boolean (value));
      break;
    default:
/*      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); */
      break;
    }
}

static void
egg_link_button_style_set (GtkWidget *widget,
			   GtkStyle  *old_style)
{
  EggLinkButtonPrivate *priv = EGG_LINK_BUTTON_GET_PRIVATE (widget);
  GdkColor default_color = { 0, 0x0000, 0x0000, 0xffff };
  GdkColor *link_color = NULL;
  
  gtk_widget_style_get (widget, "link_color", &link_color, NULL);
  if (!link_color)
    {
      link_color = &default_color;
    }
  
  if (!priv->label)
    priv->label = gtk_bin_get_child (GTK_BIN (widget));
  
  gtk_widget_modify_fg (priv->label, GTK_STATE_NORMAL, link_color);
  gtk_widget_modify_fg (priv->label, GTK_STATE_ACTIVE, link_color);
  gtk_widget_modify_fg (priv->label, GTK_STATE_PRELIGHT, link_color);
  gtk_widget_modify_fg (priv->label, GTK_STATE_SELECTED, link_color);
 
  if (link_color != &default_color)
    gdk_color_free (link_color);
}

static gboolean
egg_link_button_enter_cb (GtkWidget        *widget,
			  GdkEventCrossing *crossing,
			  gpointer          user_data)
{
  EggLinkButtonPrivate *priv = EGG_LINK_BUTTON_GET_PRIVATE (widget);
  gchar *markup;
  
  g_free (priv->text);
  priv->text = g_strdup (gtk_label_get_label (GTK_LABEL (priv->label)));
  
  markup = g_strdup_printf ("<u>%s</u>", priv->text);
  gtk_label_set_use_markup (GTK_LABEL (priv->label), TRUE);
  gtk_label_set_label (GTK_LABEL (priv->label), markup);
  
  gdk_window_set_cursor (widget->window, priv->hand_cursor);
  
  /* XXX - add "hover" style here */
  
  g_free (markup);

  return FALSE;
}

static gboolean
egg_link_button_leave_cb (GtkWidget        *widget,
			  GdkEventCrossing *crossing,
			  gpointer          user_data)
{
  EggLinkButtonPrivate *priv = EGG_LINK_BUTTON_GET_PRIVATE (widget);
  gdk_window_set_cursor (widget->window, NULL);

  gtk_label_set_use_markup (GTK_LABEL (priv->label), FALSE);  
  gtk_label_set_label (GTK_LABEL (priv->label), priv->text);
  
  /* XXX - add "hover" style here */
  
  return FALSE;
}

static void
egg_link_button_drag_data_get_cb (GtkWidget        *widget,
				  GdkDragContext   *context,
				  GtkSelectionData *selection,
				  guint             _info,
				  guint             _time,
				  gpointer          user_data)
{
  EggLinkButtonPrivate *priv = EGG_LINK_BUTTON_GET_PRIVATE (widget);
  gchar *uri;
  
  uri = g_strdup_printf ("%s\r\n", priv->uri);
  gtk_selection_data_set (selection,
  			  selection->target,
  			  8,
  			  uri, strlen (uri));
  
  g_free (uri);
}

/* we want our hook function to be called when the user clicks on the
 * button, regardless of any callbacks that might be attached to its
 * "clicked" signal.
 */
static void
egg_link_button_clicked (GtkButton *button)
{
  EggLinkButton *link_button = EGG_LINK_BUTTON (button);
  EggLinkButtonPrivate *priv = link_button->priv;
  
  if (activate_uri_hook && priv->active)
    (* activate_uri_hook) (link_button,
                           priv->uri,
                           activate_uri_hook_data);

  /* XXX - add "active" style here */
}

/**
 * egg_link_button_new:
 * @uri: a valid URI
 *
 * Creates a new #EggLinkButton with the URI as its text.
 *
 * Return value: a new link button widget.
 */
GtkWidget *
egg_link_button_new (const gchar *uri)
{
  gchar *utf8_uri = NULL;
  GtkWidget *retval;
  
  g_return_val_if_fail (uri != NULL, NULL);
  
  if (g_utf8_validate (uri, -1, NULL))
    {
      utf8_uri = g_strdup (uri);
    }
  else
    {
      GError *conv_err = NULL;
    
      utf8_uri = g_locale_to_utf8 (uri, -1, NULL, NULL, &conv_err);
      if (conv_err)
        {
          g_warning ("Attempting to convert URI `%s' to UTF-8, but failed "
                     "with error: %s\n",
                     uri,
                     conv_err->message);
          g_error_free (conv_err);
        
          utf8_uri = g_strdup (_("Invalid URI"));
        }
    }
  
  retval = g_object_new (EGG_TYPE_LINK_BUTTON,
  			 "uri", uri,
  			 "label", utf8_uri,
  			 NULL);
  
  g_free (utf8_uri);
  
  return retval;
}

/**
 * egg_link_button_new_with_label:
 * @uri: a valid URI
 * @label: the text of the button
 *
 * Creates a new #EggLinkButton containing a label.
 *
 * Return value: a new link button widget.
 */
GtkWidget *
egg_link_button_new_with_label (const gchar *uri,
				const gchar *label)
{
  GtkWidget *retval;
  
  g_return_val_if_fail (uri != NULL, FALSE);
  
  if (!label)
    return egg_link_button_new (uri);

  retval = g_object_new (EGG_TYPE_LINK_BUTTON,
		         "label", label,
			 "uri", uri,
			 NULL);

  return retval;
}

/**
 * egg_link_button_new_with_mnemonic:
 * @uri: a valid URI
 * @label: the text of the button, with an underscore in front of the mnemonic
 *    character
 *
 * Creates a new #EggLinkButton containing a label.  The label will be created
 * using gtk_label_new_with_mnemonic(), so underscores in @label indicate the
 * mnemonic for the button.
 *
 * Return value: a new link button widget.
 */
GtkWidget *
egg_link_button_new_with_mnemonic (const gchar *uri,
				   const gchar *label)
{
  GtkWidget *retval;
  
  g_return_val_if_fail (uri != NULL, NULL);
  
  if (!label)
    return egg_link_button_new (uri);
  
  retval = g_object_new (EGG_TYPE_LINK_BUTTON,
  		         "label", label,
  		         "uri", uri,
  		         "use-underline", TRUE,
  		         NULL);
  
  return retval;
}

/**
 * egg_link_button_set_uri:
 * @link_button: a #EggLinkButton
 * @uri: a valid URI
 *
 * Sets @uri as the URI where the #EggLinkButton points.
 */
void
egg_link_button_set_uri (EggLinkButton *link_button,
			 const gchar   *uri)
{
  EggLinkButtonPrivate *priv;
  
  g_return_if_fail (EGG_IS_LINK_BUTTON (link_button));
  g_return_if_fail (uri != NULL);
  
  priv = EGG_LINK_BUTTON_GET_PRIVATE (link_button);
  
  if (priv->uri)
    g_free (priv->uri);
  
  priv->uri = g_strdup (uri);
}

/**
 * egg_link_button_get_uri:
 * @link_button: a #EggLinkButton
 *
 * Retrieves the URI set using egg_link_button_set_uri().
 *
 * Return value: a valid URI.  The returned string is owned by the link button
 *   and should not be modified or freed.
 */
G_CONST_RETURN gchar *
egg_link_button_get_uri (EggLinkButton *link_button)
{
  g_return_val_if_fail (EGG_IS_LINK_BUTTON (link_button), NULL);
  
  return link_button->priv->uri;
}

/**
 * egg_link_button_set_active:
 * @link_button: a #EggLinkButton
 * @is_active: whether this link button is active or not
 *
 * Sets whether @link_button should be active or not.
 */
void
egg_link_button_set_active (EggLinkButton *link_button,
			    gboolean       is_active)
{
  g_return_if_fail (EGG_IS_LINK_BUTTON (link_button));
  
  if (link_button->priv->active == is_active)
    return;
  
  link_button->priv->active = is_active;
  
  g_object_notify (G_OBJECT (link_button), "active");
}

/**
 * egg_link_button_get_active:
 * @link_button: a #EggLinkButton
 *
 * Gets whether @link_button is active or not.
 *
 * Return value: %TRUE if the link button is active, %FALSE otherwise.
 */
gboolean
egg_link_button_get_active (EggLinkButton *link_button)
{
  g_return_val_if_fail (EGG_IS_LINK_BUTTON (link_button), FALSE);
  
  return link_button->priv->active;
}

/**
 * egg_link_button_uri_hook:
 * @link_button: a #EggLinkButton
 * @func: a function to call when a URL link is activated.
 * @data: data to pass to @func
 * @data_destroy: #GDestroyNotify for @data
 *
 * Installs a global function to be called whenever the user activates a
 * link button.
 *
 * Return value: the previous URI hook.
 */
EggLinkButtonActivateFunc
egg_link_button_set_uri_hook (EggLinkButtonActivateFunc func,
			      gpointer                  data,
			      GDestroyNotify            data_destroy)
{
  EggLinkButtonActivateFunc old;
  
  if (activate_uri_hook_destroy)
    (* activate_uri_hook_destroy) (activate_uri_hook_data);
  
  old = activate_uri_hook;
  
  activate_uri_hook = func;
  activate_uri_hook_data = data;
  activate_uri_hook_destroy = data_destroy;
  
  return old;
}
