/* PIKA - Photo and Image Kooker Application
 * a rebranding of The GNU Image Manipulation Program (created with heckimp)
 * A derived work which may be trivial. However, any changes may be (C)2023 by Aldercone Studio
 *
 * Original copyright, applying to most contents (license remains unchanged): 
 * Copyright (C) 1995 Spencer Kimball and Peter Mattis
 *
 * pikadock.c
 * Copyright (C) 2001-2018 Michael Natterer <mitch@gimp.org>
 *
 * 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 3 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, see <https://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <gegl.h>
#include <gtk/gtk.h>

#include "libpikawidgets/pikawidgets.h"

#include "widgets-types.h"

#include "core/pika.h"
#include "core/pikacontext.h"

#include "menus/menus.h"

#include "pikadialogfactory.h"
#include "pikadock.h"
#include "pikadockable.h"
#include "pikadockbook.h"
#include "pikadockcolumns.h"
#include "pikadockcontainer.h"
#include "pikadockwindow.h"
#include "pikapanedbox.h"
#include "pikauimanager.h"
#include "pikawidgets-utils.h"

#include "pika-intl.h"


enum
{
  BOOK_ADDED,
  BOOK_REMOVED,
  DESCRIPTION_INVALIDATED,
  GEOMETRY_INVALIDATED,
  LAST_SIGNAL
};


struct _PikaDockPrivate
{
  GtkWidget *main_vbox;
  GtkWidget *paned_vbox;

  GList     *dockbooks;

  gint       ID;
};


static void       pika_dock_dispose                (GObject      *object);

static gchar    * pika_dock_real_get_description   (PikaDock     *dock,
                                                    gboolean      complete);
static void       pika_dock_real_book_added        (PikaDock     *dock,
                                                    PikaDockbook *dockbook);
static void       pika_dock_real_book_removed      (PikaDock     *dock,
                                                    PikaDockbook *dockbook);
static void       pika_dock_invalidate_description (PikaDock     *dock);
static gboolean   pika_dock_dropped_cb             (GtkWidget    *notebook,
                                                    GtkWidget    *child,
                                                    gint          insert_index,
                                                    gpointer      data);


G_DEFINE_TYPE_WITH_PRIVATE (PikaDock, pika_dock, GTK_TYPE_BOX)

#define parent_class pika_dock_parent_class

static guint dock_signals[LAST_SIGNAL] = { 0 };


static void
pika_dock_class_init (PikaDockClass *klass)
{
  GObjectClass   *object_class = G_OBJECT_CLASS (klass);
  GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);

  dock_signals[BOOK_ADDED] =
    g_signal_new ("book-added",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaDockClass, book_added),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 1,
                  PIKA_TYPE_DOCKBOOK);

  dock_signals[BOOK_REMOVED] =
    g_signal_new ("book-removed",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaDockClass, book_removed),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 1,
                  PIKA_TYPE_DOCKBOOK);

  dock_signals[DESCRIPTION_INVALIDATED] =
    g_signal_new ("description-invalidated",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaDockClass, description_invalidated),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 0);

  dock_signals[GEOMETRY_INVALIDATED] =
    g_signal_new ("geometry-invalidated",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (PikaDockClass, geometry_invalidated),
                  NULL, NULL, NULL,
                  G_TYPE_NONE, 0);

  object_class->dispose          = pika_dock_dispose;

  klass->get_description         = pika_dock_real_get_description;
  klass->set_host_geometry_hints = NULL;
  klass->book_added              = pika_dock_real_book_added;
  klass->book_removed            = pika_dock_real_book_removed;
  klass->description_invalidated = NULL;
  klass->geometry_invalidated    = NULL;

  gtk_widget_class_set_css_name (widget_class, "PikaDock");
}

static void
pika_dock_init (PikaDock *dock)
{
  static gint  dock_ID = 1;
  gchar       *name    = NULL;

  gtk_orientable_set_orientation (GTK_ORIENTABLE (dock),
                                  GTK_ORIENTATION_VERTICAL);

  dock->p = pika_dock_get_instance_private (dock);
  dock->p->ID = dock_ID++;

  name = g_strdup_printf ("pika-internal-dock-%d", dock->p->ID);
  gtk_widget_set_name (GTK_WIDGET (dock), name);
  g_free (name);

  dock->p->main_vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0);
  gtk_box_pack_start (GTK_BOX (dock), dock->p->main_vbox, TRUE, TRUE, 0);
  gtk_widget_show (dock->p->main_vbox);

  dock->p->paned_vbox = pika_paned_box_new (FALSE, 0, GTK_ORIENTATION_VERTICAL);
  pika_paned_box_set_dropped_cb (PIKA_PANED_BOX (dock->p->paned_vbox),
                                 pika_dock_dropped_cb,
                                 dock);
  gtk_box_pack_start (GTK_BOX (dock->p->main_vbox), dock->p->paned_vbox,
                      TRUE, TRUE, 0);
  gtk_widget_show (dock->p->paned_vbox);
}

static void
pika_dock_dispose (GObject *object)
{
  PikaDock *dock = PIKA_DOCK (object);

  while (dock->p->dockbooks)
    {
      PikaDockbook *dockbook = dock->p->dockbooks->data;

      g_object_ref (dockbook);
      pika_dock_remove_book (dock, dockbook);
      gtk_widget_destroy (GTK_WIDGET (dockbook));
      g_object_unref (dockbook);
    }

  G_OBJECT_CLASS (parent_class)->dispose (object);
}

static gchar *
pika_dock_real_get_description (PikaDock *dock,
                                gboolean  complete)
{
  GString *desc;
  GList   *list;

  desc = g_string_new (NULL);

  for (list = pika_dock_get_dockbooks (dock);
       list;
       list = g_list_next (list))
    {
      PikaDockbook *dockbook = list->data;
      GList        *children;
      GList        *child;

      if (complete)
        {
          /* Include all dockables */
          children = gtk_container_get_children (GTK_CONTAINER (dockbook));
        }
      else
        {
          GtkWidget *dockable = NULL;
          gint       page_num = 0;

          page_num = gtk_notebook_get_current_page (GTK_NOTEBOOK (dockbook));
          dockable = gtk_notebook_get_nth_page (GTK_NOTEBOOK (dockbook), page_num);

          /* Only include active dockables */
          children = g_list_append (NULL, dockable);
        }

      for (child = children; child; child = g_list_next (child))
        {
          PikaDockable *dockable = child->data;

          g_string_append (desc, pika_dockable_get_name (dockable));

          if (g_list_next (child))
            g_string_append (desc, PIKA_DOCK_DOCKABLE_SEPARATOR);
        }

      g_list_free (children);

      if (g_list_next (list))
        g_string_append (desc, PIKA_DOCK_BOOK_SEPARATOR);
    }

  return g_string_free (desc, FALSE);
}

static void
pika_dock_real_book_added (PikaDock     *dock,
                           PikaDockbook *dockbook)
{
  g_signal_connect_object (dockbook, "switch-page",
                           G_CALLBACK (pika_dock_invalidate_description),
                           dock, G_CONNECT_SWAPPED);
}

static void
pika_dock_real_book_removed (PikaDock     *dock,
                             PikaDockbook *dockbook)
{
  g_signal_handlers_disconnect_by_func (dockbook,
                                        pika_dock_invalidate_description,
                                        dock);
}

static void
pika_dock_invalidate_description (PikaDock *dock)
{
  g_return_if_fail (PIKA_IS_DOCK (dock));

  g_signal_emit (dock, dock_signals[DESCRIPTION_INVALIDATED], 0);
}

static gboolean
pika_dock_dropped_cb (GtkWidget *notebook,
                      GtkWidget *child,
                      gint       insert_index,
                      gpointer   data)
{
  PikaDock          *dock     = PIKA_DOCK (data);
  PikaDockbook      *dockbook = PIKA_DOCKBOOK (notebook);
  PikaDockable      *dockable = PIKA_DOCKABLE (child);
  PikaDialogFactory *factory;
  GtkWidget         *new_dockbook;

  /*  if dropping to the same dock, take care that we don't try
   *  to reorder the *only* dockable in the dock
   */
  if (pika_dockbook_get_dock (dockbook) == dock)
    {
      GList *children    = gtk_container_get_children (GTK_CONTAINER (dockable));
      gint   n_dockables = g_list_length (children);
      gint   n_books     = g_list_length (pika_dock_get_dockbooks (dock));

      g_list_free (children);

      if (n_books == 1 && n_dockables == 1)
        return TRUE; /* successfully do nothing */
    }

  /* Detach the dockable from the old dockbook */
  g_object_ref (dockable);
  gtk_notebook_detach_tab (GTK_NOTEBOOK (notebook), child);

  /* Create a new dockbook */
  factory = pika_dock_get_dialog_factory (dock);
  new_dockbook = pika_dockbook_new (menus_get_global_menu_factory (pika_dialog_factory_get_context (factory)->pika));
  pika_dock_add_book (dock, PIKA_DOCKBOOK (new_dockbook), insert_index);

  /* Add the dockable to new new dockbook */
  gtk_notebook_append_page (GTK_NOTEBOOK (new_dockbook), child, NULL);
  g_object_unref (dockable);

  return TRUE;
}


/*  public functions  */

/**
 * pika_dock_get_description:
 * @dock:
 * @complete: If %TRUE, only includes the active dockables, i.e. not the
 *            dockables in a non-active GtkNotebook tab
 *
 * Returns: A string describing the contents of the dock.
 **/
gchar *
pika_dock_get_description (PikaDock *dock,
                           gboolean  complete)
{
  g_return_val_if_fail (PIKA_IS_DOCK (dock), NULL);

  if (PIKA_DOCK_GET_CLASS (dock)->get_description)
    return PIKA_DOCK_GET_CLASS (dock)->get_description (dock, complete);

  return NULL;
}

/**
 * pika_dock_set_host_geometry_hints:
 * @dock:   The dock
 * @window: The #GtkWindow to adapt to hosting the dock
 *
 * Some docks have some specific needs on the #GtkWindow they are
 * in. This function allows such docks to perform any such setup on
 * the #GtkWindow they are in/will be put in.
 **/
void
pika_dock_set_host_geometry_hints (PikaDock  *dock,
                                   GtkWindow *window)
{
  g_return_if_fail (PIKA_IS_DOCK (dock));
  g_return_if_fail (GTK_IS_WINDOW (window));

  if (PIKA_DOCK_GET_CLASS (dock)->set_host_geometry_hints)
    PIKA_DOCK_GET_CLASS (dock)->set_host_geometry_hints (dock, window);
}

/**
 * pika_dock_invalidate_geometry:
 * @dock:
 *
 * Call when the dock needs to setup its host #GtkWindow with
 * GtkDock::set_host_geometry_hints().
 **/
void
pika_dock_invalidate_geometry (PikaDock *dock)
{
  g_return_if_fail (PIKA_IS_DOCK (dock));

  g_signal_emit (dock, dock_signals[GEOMETRY_INVALIDATED], 0);
}

/**
 * pika_dock_update_with_context:
 * @dock:
 * @context:
 *
 * Set the @context on all dockables in the @dock.
 **/
void
pika_dock_update_with_context (PikaDock    *dock,
                               PikaContext *context)
{
  GList *iter = NULL;

  for (iter = pika_dock_get_dockbooks (dock);
       iter;
       iter = g_list_next (iter))
    {
      PikaDockbook *dockbook = PIKA_DOCKBOOK (iter->data);

      pika_dockbook_update_with_context (dockbook, context);
    }
}

/**
 * pika_dock_get_context:
 * @dock:
 *
 * Returns: The #PikaContext for the #PikaDockWindow the @dock is in.
 **/
PikaContext *
pika_dock_get_context (PikaDock *dock)
{
  PikaContext *context = NULL;

  g_return_val_if_fail (PIKA_IS_DOCK (dock), NULL);

  /* First try PikaDockColumns */
  if (! context)
    {
      PikaDockColumns *dock_columns;

      dock_columns =
        PIKA_DOCK_COLUMNS (gtk_widget_get_ancestor (GTK_WIDGET (dock),
                                                    PIKA_TYPE_DOCK_COLUMNS));

      if (dock_columns)
        context = pika_dock_columns_get_context (dock_columns);
    }

  /* Then PikaDockWindow */
  if (! context)
    {
      PikaDockWindow *dock_window = pika_dock_window_from_dock (dock);

      if (dock_window)
        context = pika_dock_window_get_context (dock_window);
    }

  return context;
}

/**
 * pika_dock_get_dialog_factory:
 * @dock:
 *
 * Returns: The #PikaDialogFactory for the #PikaDockWindow the @dock
 *          is in.
 **/
PikaDialogFactory *
pika_dock_get_dialog_factory (PikaDock *dock)
{
  PikaDialogFactory *dialog_factory = NULL;

  g_return_val_if_fail (PIKA_IS_DOCK (dock), NULL);

  /* First try PikaDockColumns */
  if (! dialog_factory)
    {
      PikaDockColumns *dock_columns;

      dock_columns =
        PIKA_DOCK_COLUMNS (gtk_widget_get_ancestor (GTK_WIDGET (dock),
                                                    PIKA_TYPE_DOCK_COLUMNS));

      if (dock_columns)
        dialog_factory = pika_dock_columns_get_dialog_factory (dock_columns);
    }

  /* Then PikaDockWindow */
  if (! dialog_factory)
    {
      PikaDockWindow *dock_window = pika_dock_window_from_dock (dock);

      if (dock_window)
        dialog_factory = pika_dock_container_get_dialog_factory (PIKA_DOCK_CONTAINER (dock_window));
    }

  return dialog_factory;
}

/**
 * pika_dock_get_ui_manager:
 * @dock:
 *
 * Returns: The #PikaUIManager for the #PikaDockWindow the @dock is
 *          in.
 **/
PikaUIManager *
pika_dock_get_ui_manager (PikaDock *dock)
{
  PikaUIManager *ui_manager = NULL;

  g_return_val_if_fail (PIKA_IS_DOCK (dock), NULL);

  /* First try PikaDockColumns */
  if (! ui_manager)
    {
      PikaDockColumns *dock_columns;

      dock_columns =
        PIKA_DOCK_COLUMNS (gtk_widget_get_ancestor (GTK_WIDGET (dock),
                                                    PIKA_TYPE_DOCK_COLUMNS));

      if (dock_columns)
        ui_manager = pika_dock_columns_get_ui_manager (dock_columns);
    }

  /* Then PikaDockContainer */
  if (! ui_manager)
    {
      PikaDockWindow *dock_window = pika_dock_window_from_dock (dock);

      if (dock_window)
        {
          PikaDockContainer *dock_container = PIKA_DOCK_CONTAINER (dock_window);

          ui_manager = pika_dock_container_get_ui_manager (dock_container);
        }
    }

  return ui_manager;
}

GList *
pika_dock_get_dockbooks (PikaDock *dock)
{
  g_return_val_if_fail (PIKA_IS_DOCK (dock), NULL);

  return dock->p->dockbooks;
}

gint
pika_dock_get_n_dockables (PikaDock *dock)
{
  GList *list = NULL;
  gint   n    = 0;

  g_return_val_if_fail (PIKA_IS_DOCK (dock), 0);

  for (list = dock->p->dockbooks; list; list = list->next)
    n += gtk_notebook_get_n_pages (GTK_NOTEBOOK (list->data));

  return n;
}

GtkWidget *
pika_dock_get_main_vbox (PikaDock *dock)
{
  g_return_val_if_fail (PIKA_IS_DOCK (dock), NULL);

  return dock->p->main_vbox;
}

GtkWidget *
pika_dock_get_vbox (PikaDock *dock)
{
  g_return_val_if_fail (PIKA_IS_DOCK (dock), NULL);

  return dock->p->paned_vbox;
}

void
pika_dock_set_id (PikaDock *dock,
                  gint      ID)
{
  g_return_if_fail (PIKA_IS_DOCK (dock));

  dock->p->ID = ID;
}

gint
pika_dock_get_id (PikaDock *dock)
{
  g_return_val_if_fail (PIKA_IS_DOCK (dock), 0);

  return dock->p->ID;
}

void
pika_dock_add_book (PikaDock     *dock,
                    PikaDockbook *dockbook,
                    gint          index)
{
  g_return_if_fail (PIKA_IS_DOCK (dock));
  g_return_if_fail (PIKA_IS_DOCKBOOK (dockbook));
  g_return_if_fail (pika_dockbook_get_dock (dockbook) == NULL);

  pika_dockbook_set_dock (dockbook, dock);

  g_signal_connect_object (dockbook, "dockable-added",
                           G_CALLBACK (pika_dock_invalidate_description),
                           dock, G_CONNECT_SWAPPED);
  g_signal_connect_object (dockbook, "dockable-removed",
                           G_CALLBACK (pika_dock_invalidate_description),
                           dock, G_CONNECT_SWAPPED);
  g_signal_connect_object (dockbook, "dockable-reordered",
                           G_CALLBACK (pika_dock_invalidate_description),
                           dock, G_CONNECT_SWAPPED);

  dock->p->dockbooks = g_list_insert (dock->p->dockbooks, dockbook, index);
  pika_paned_box_add_widget (PIKA_PANED_BOX (dock->p->paned_vbox),
                             GTK_WIDGET (dockbook),
                             index);
  gtk_widget_show (GTK_WIDGET (dockbook));

  pika_dock_invalidate_description (dock);

  g_signal_emit (dock, dock_signals[BOOK_ADDED], 0, dockbook);
}

void
pika_dock_remove_book (PikaDock     *dock,
                       PikaDockbook *dockbook)
{
  g_return_if_fail (PIKA_IS_DOCK (dock));
  g_return_if_fail (PIKA_IS_DOCKBOOK (dockbook));
  g_return_if_fail (pika_dockbook_get_dock (dockbook) == dock);

  pika_dockbook_set_dock (dockbook, NULL);

  g_signal_handlers_disconnect_by_func (dockbook,
                                        pika_dock_invalidate_description,
                                        dock);

  /* Ref the dockbook so we can emit the "book-removed" signal and
   * pass it as a parameter before it's destroyed
   */
  g_object_ref (dockbook);

  dock->p->dockbooks = g_list_remove (dock->p->dockbooks, dockbook);
  pika_paned_box_remove_widget (PIKA_PANED_BOX (dock->p->paned_vbox),
                                GTK_WIDGET (dockbook));

  pika_dock_invalidate_description (dock);

  g_signal_emit (dock, dock_signals[BOOK_REMOVED], 0, dockbook);

  g_object_unref (dockbook);
}
