/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* GTK - The GIMP Toolkit
 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser 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 "gtkundo.h"
#include "gtkmarshalers.h"
#include <string.h>


typedef struct {
  GQueue *actions;
} ActionGroup;

typedef struct {
  guint type;
  GtkUndoAction *action;
} Wrapper;


static GtkUndoActionClass *types;
static guint last_type;

#define WRAPPER_VTABLE(wrapper__)   (&types[(wrapper__)->type])
#define TYPE_VTABLE(type__)         (&types[type__])
#define TYPE_IS_REGISTERED(type__)  ((type__) && (type__) <= last_type)


static void     gtk_undo_stack_finalize     (GObject        *object);
static void     gtk_undo_stack_set_property (GObject        *object,
                                             guint           prop_id,
                                             const GValue   *value,
                                             GParamSpec     *pspec);
static void     gtk_undo_stack_get_property (GObject        *object,
                                             guint           prop_id,
                                             GValue         *value,
                                             GParamSpec     *pspec);

static void     gtk_undo_stack_undo_real    (GtkUndoStack   *stack);
static void     gtk_undo_stack_redo_real    (GtkUndoStack   *stack);

static void     action_stack_free           (GSList        **stack,
                                             gpointer        doc);


G_DEFINE_TYPE(GtkUndoStack, gtk_undo_stack, G_TYPE_OBJECT)

enum {
  PROP_0,
  PROP_DOCUMENT,
  PROP_CAN_UNDO,
  PROP_CAN_REDO
};

enum {
  UNDO,
  REDO,
  LAST_SIGNAL
};

static guint signals[LAST_SIGNAL];

static void
gtk_undo_stack_class_init (GtkUndoStackClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);

  gobject_class->set_property = gtk_undo_stack_set_property;
  gobject_class->get_property = gtk_undo_stack_get_property;
  gobject_class->finalize = gtk_undo_stack_finalize;

  klass->undo = gtk_undo_stack_undo_real;
  klass->redo = gtk_undo_stack_redo_real;

  g_object_class_install_property (gobject_class,
                                   PROP_DOCUMENT,
                                   g_param_spec_pointer ("document",
                                                         "document",
                                                         "document",
                                                         G_PARAM_CONSTRUCT | G_PARAM_READWRITE));

  g_object_class_install_property (gobject_class,
                                   PROP_CAN_UNDO,
                                   g_param_spec_boolean ("can-undo",
                                                         "can-undo",
                                                         "can-undo",
                                                         FALSE,
                                                         G_PARAM_READABLE));

  g_object_class_install_property (gobject_class,
                                   PROP_CAN_REDO,
                                   g_param_spec_boolean ("can-redo",
                                                         "can-redo",
                                                         "can-redo",
                                                         FALSE,
                                                         G_PARAM_READABLE));

  signals[UNDO] =
          g_signal_new ("undo",
                        G_OBJECT_CLASS_TYPE (klass),
                        G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
                        G_STRUCT_OFFSET (GtkUndoStackClass, undo),
                        NULL, NULL,
                        _gtk_marshal_VOID__VOID,
                        G_TYPE_NONE, 0);

  signals[REDO] =
          g_signal_new ("redo",
                        G_OBJECT_CLASS_TYPE (klass),
                        G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
                        G_STRUCT_OFFSET (GtkUndoStackClass, redo),
                        NULL, NULL,
                        _gtk_marshal_VOID__VOID,
                        G_TYPE_NONE, 0);
}


static void
gtk_undo_stack_init (G_GNUC_UNUSED GtkUndoStack *stack)
{
}


GtkUndoStack*
gtk_undo_stack_new (gpointer document)
{
  return g_object_new (GTK_TYPE_UNDO_STACK,
                       "document", document,
                       NULL);
}


static void
gtk_undo_stack_finalize (GObject *object)
{
  GtkUndoStack *stack = GTK_UNDO_STACK (object);

  action_stack_free (&stack->undo_stack, stack->document);
  action_stack_free (&stack->redo_stack, stack->document);

  G_OBJECT_CLASS(gtk_undo_stack_parent_class)->finalize (object);
}


static void
gtk_undo_stack_set_property (GObject        *object,
                           guint           prop_id,
                           const GValue   *value,
                           GParamSpec     *pspec)
{
  GtkUndoStack *stack = GTK_UNDO_STACK (object);

  switch (prop_id)
    {
      case PROP_DOCUMENT:
        stack->document = g_value_get_pointer (value);
        break;

      default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
        break;
    }
}


static void
gtk_undo_stack_get_property (GObject        *object,
                           guint           prop_id,
                           GValue         *value,
                           GParamSpec     *pspec)
{
  GtkUndoStack *stack = GTK_UNDO_STACK (object);

  switch (prop_id)
    {
      case PROP_DOCUMENT:
        g_value_set_pointer (value, stack->document);
        break;

      case PROP_CAN_UNDO:
        g_value_set_boolean (value, gtk_undo_stack_can_undo (stack));
        break;

      case PROP_CAN_REDO:
        g_value_set_boolean (value, gtk_undo_stack_can_redo (stack));
        break;

      default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
        break;
    }
}


guint
gtk_undo_action_register (GtkUndoActionClass *klass)
{
  GtkUndoActionClass *tmp;

  g_return_val_if_fail (klass != NULL, 0);
  g_return_val_if_fail (klass->undo != NULL && klass->redo != NULL, 0);
  g_return_val_if_fail (klass->merge != NULL && klass->destroy != NULL, 0);

  tmp = g_new (GtkUndoActionClass, last_type + 2);
  if (last_type)
    memcpy (tmp, types, sizeof(GtkUndoActionClass) * (last_type + 1));
  g_free (types);
  types = tmp;

  memcpy (&types[last_type+1], klass, sizeof(GtkUndoActionClass));

  return ++last_type;
}


void
gtk_undo_stack_undo (GtkUndoStack *stack)
{
  g_return_if_fail (GTK_IS_UNDO_STACK (stack));
  g_signal_emit (stack, signals[UNDO], 0);
}


void
gtk_undo_stack_redo (GtkUndoStack *stack)
{
  g_return_if_fail (GTK_IS_UNDO_STACK (stack));
  g_signal_emit (stack, signals[REDO], 0);
}


gboolean
gtk_undo_stack_can_undo (GtkUndoStack *stack)
{
  g_return_val_if_fail (GTK_IS_UNDO_STACK (stack), FALSE);
  return stack->undo_stack != NULL;
}


gboolean
gtk_undo_stack_can_redo (GtkUndoStack *stack)
{
  g_return_val_if_fail (GTK_IS_UNDO_STACK (stack), FALSE);
  return stack->redo_stack != NULL;
}


static void
action_group_undo (ActionGroup    *group,
                   GtkUndoStack     *stack)
{
  GList *l;

  for (l = group->actions->head; l != NULL; l = l->next)
  {
    Wrapper *wrapper = l->data;
    WRAPPER_VTABLE(wrapper)->undo (wrapper->action, stack->document);
  }
}


static void
action_group_redo (ActionGroup    *group,
                   GtkUndoStack     *stack)
{
  GList *l;

  for (l = group->actions->tail; l != NULL; l = l->prev)
  {
    Wrapper *wrapper = l->data;
    WRAPPER_VTABLE(wrapper)->redo (wrapper->action, stack->document);
  }
}


static void
gtk_undo_stack_undo_real (GtkUndoStack *stack)
{
  ActionGroup *group;
  GSList *link;
  gboolean notify_redo;

  g_return_if_fail (stack->undo_stack != NULL);

  stack->frozen++;

  link = stack->undo_stack;
  group = link->data;
  stack->undo_stack = g_slist_delete_link (stack->undo_stack, link);
  notify_redo = stack->redo_stack == NULL;
  stack->redo_stack = g_slist_prepend (stack->redo_stack, group);
  stack->new_group = TRUE;

  action_group_undo (group, stack);

  stack->frozen--;

  g_object_freeze_notify (G_OBJECT (stack));

  if (!stack->undo_stack)
    g_object_notify (G_OBJECT (stack), "can-undo");
  if (notify_redo)
    g_object_notify (G_OBJECT (stack), "can-redo");

  g_object_thaw_notify (G_OBJECT (stack));
}


static void
gtk_undo_stack_redo_real (GtkUndoStack *stack)
{
  ActionGroup *group;
  GSList *link;
  gboolean notify_undo;

  g_return_if_fail (stack->redo_stack != NULL);

  stack->frozen++;

  link = stack->redo_stack;
  group = link->data;
  stack->redo_stack = g_slist_delete_link (stack->redo_stack, link);
  notify_undo = stack->undo_stack == NULL;
  stack->undo_stack = g_slist_prepend (stack->undo_stack, group);
  stack->new_group = TRUE;

  action_group_redo (group, stack);

  stack->frozen--;

  g_object_freeze_notify (G_OBJECT (stack));

  if (!stack->redo_stack)
    g_object_notify (G_OBJECT (stack), "can-redo");
  if (notify_undo)
    g_object_notify (G_OBJECT (stack), "can-undo");

  g_object_thaw_notify (G_OBJECT (stack));
}


static Wrapper *
wrapper_new (guint          type,
             GtkUndoAction *action)
{
  Wrapper *w = g_new0 (Wrapper, 1);
  w->type = type;
  w->action = action;
  return w;
}


static void
wrapper_free (Wrapper  *wrapper,
              gpointer  doc)
{
  if (wrapper)
  {
    WRAPPER_VTABLE(wrapper)->destroy (wrapper->action, doc);
    g_free (wrapper);
  }
}


static void
action_group_free (ActionGroup *group,
                   gpointer     doc)
{
  if (group)
  {
    g_queue_foreach (group->actions, (GFunc) wrapper_free, doc);
    g_queue_free (group->actions);
    g_free (group);
  }
}


static ActionGroup*
action_group_new (void)
{
  ActionGroup *group = g_new0 (ActionGroup, 1);
  group->actions = g_queue_new ();
  return group;
}


static void
action_stack_free (GSList **stack,
                   gpointer doc)
{
  g_slist_foreach (*stack, (GFunc) action_group_free, doc);
  g_slist_free (*stack);
  *stack = NULL;
}


void
gtk_undo_stack_clear (GtkUndoStack *stack)
{
  gboolean notify_redo, notify_undo;

  g_return_if_fail (GTK_IS_UNDO_STACK (stack));

  notify_undo = stack->undo_stack != NULL;
  notify_redo = stack->redo_stack != NULL;

  action_stack_free (&stack->undo_stack, stack->document);
  action_stack_free (&stack->redo_stack, stack->document);
  stack->new_group = FALSE;

  g_object_freeze_notify (G_OBJECT (stack));

  if (notify_undo)
    g_object_notify (G_OBJECT (stack), "can-undo");
  if (notify_redo)
    g_object_notify (G_OBJECT (stack), "can-redo");

  g_object_thaw_notify (G_OBJECT (stack));
}


static gboolean
action_group_merge (ActionGroup    *group,
                    guint           type,
                    GtkUndoAction  *action,
                    gpointer        doc)
{
  Wrapper *old;

  old = group->actions->head ? group->actions->head->data : NULL;

  if (!old || old->type != type)
    return FALSE;

  if (WRAPPER_VTABLE(old)->merge (old->action, action, doc))
  {
    TYPE_VTABLE(type)->destroy (action, doc);
    return TRUE;
  }
  else
  {
    return FALSE;
  }
}

static void
action_group_add (ActionGroup    *group,
                  guint           type,
                  GtkUndoAction  *action,
                  gboolean        try_merge,
                  gpointer        doc)
{
  if (!try_merge || !action_group_merge (group, type, action, doc))
  {
    Wrapper *wrapper = wrapper_new (type, action);
    g_queue_push_head (group->actions, wrapper);
  }
}


void
gtk_undo_stack_add_action (GtkUndoStack     *stack,
                         guint           type,
                         GtkUndoAction  *action)
{
  gboolean notify_redo, notify_undo;
  ActionGroup *group;

  g_return_if_fail (GTK_IS_UNDO_STACK (stack));
  g_return_if_fail (action != NULL);
  g_return_if_fail (TYPE_IS_REGISTERED (type));

  if (stack->frozen)
  {
    TYPE_VTABLE(type)->destroy (action, stack->document);
    return;
  }

  notify_undo = stack->undo_stack == NULL;
  notify_redo = stack->redo_stack != NULL;

  if (!stack->undo_stack || stack->new_group)
  {
    group = action_group_new ();
    stack->undo_stack = g_slist_prepend (stack->undo_stack, group);
    action_group_add (group, type, action, FALSE, stack->document);
  }
  else if (stack->do_continue)
  {
    group = stack->undo_stack->data;
    action_group_add (group, type, action, TRUE, stack->document);
  }
  else
  {
    group = stack->undo_stack->data;

    if (!action_group_merge (group, type, action, stack->document))
    {
      group = action_group_new ();
      stack->undo_stack = g_slist_prepend (stack->undo_stack, group);
      action_group_add (group, type, action, TRUE, stack->document);
    }
  }

  stack->new_group = FALSE;
  if (stack->continue_group)
      stack->do_continue = TRUE;

  action_stack_free (&stack->redo_stack, stack->document);

  g_object_freeze_notify (G_OBJECT (stack));

  if (notify_undo)
    g_object_notify (G_OBJECT (stack), "can-undo");
  if (notify_redo)
    g_object_notify (G_OBJECT (stack), "can-redo");

  g_object_thaw_notify (G_OBJECT (stack));
}


void
gtk_undo_stack_start_group (GtkUndoStack *stack)
{
  g_return_if_fail (GTK_IS_UNDO_STACK (stack));
  stack->continue_group++;
}


void
gtk_undo_stack_end_group (GtkUndoStack *stack)
{
  g_return_if_fail (GTK_IS_UNDO_STACK (stack));
  g_return_if_fail (stack->continue_group > 0);
  if (!--stack->continue_group)
      stack->do_continue = FALSE;
}


void
gtk_undo_stack_new_group (GtkUndoStack *stack)
{
  g_return_if_fail (GTK_IS_UNDO_STACK (stack));
  stack->new_group = TRUE;
}


void
gtk_undo_stack_freeze (GtkUndoStack *stack)
{
  g_return_if_fail (GTK_IS_UNDO_STACK (stack));

  if (!stack->frozen++)
    gtk_undo_stack_clear (stack);
}


void
gtk_undo_stack_thaw (GtkUndoStack *stack)
{
  g_return_if_fail (GTK_IS_UNDO_STACK (stack));
  g_return_if_fail (stack->frozen > 0);
  stack->frozen--;
}


gboolean
gtk_undo_stack_frozen (GtkUndoStack *stack)
{
  return stack->frozen > 0;
}
