/* 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
 *
 * 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 "libpikacolor/pikacolor.h"
#include "libpikaconfig/pikaconfig.h"
#include "libpikabase/pikabase.h"

#include "widgets-types.h"

#include "config/pikaguiconfig.h"

#include "core/pika.h"
#include "core/pikacontext.h"
#include "core/pikadatafactory.h"
#include "core/pikaerror.h"
#include "core/pikagradient.h"
#include "core/pikalist.h"
#include "core/pikapattern.h"
#include "core/pikatoolinfo.h"

#include "pikadeviceinfo.h"
#include "pikadevicemanager.h"
#include "pikadevices.h"

#include "pika-intl.h"


#define PIKA_DEVICE_MANAGER_DATA_KEY "pika-device-manager"


static gboolean devicerc_deleted = FALSE;


/*  public functions  */

void
pika_devices_init (Pika *pika)
{
  PikaDeviceManager *manager;

  g_return_if_fail (PIKA_IS_PIKA (pika));

  manager = g_object_get_data (G_OBJECT (pika), PIKA_DEVICE_MANAGER_DATA_KEY);

  g_return_if_fail (manager == NULL);

  manager = pika_device_manager_new (pika);

  g_object_set_data_full (G_OBJECT (pika),
                          PIKA_DEVICE_MANAGER_DATA_KEY, manager,
                          (GDestroyNotify) g_object_unref);
}

void
pika_devices_exit (Pika *pika)
{
  PikaDeviceManager *manager;

  g_return_if_fail (PIKA_IS_PIKA (pika));

  manager = pika_devices_get_manager (pika);

  g_return_if_fail (PIKA_IS_DEVICE_MANAGER (manager));

  g_object_set_data (G_OBJECT (pika), PIKA_DEVICE_MANAGER_DATA_KEY, NULL);
}

void
pika_devices_restore (Pika *pika)
{
  PikaDeviceManager *manager;
  GList             *list;
  GFile             *file;
  GError            *error = NULL;

  g_return_if_fail (PIKA_IS_PIKA (pika));

  manager = pika_devices_get_manager (pika);

  g_return_if_fail (PIKA_IS_DEVICE_MANAGER (manager));

  for (list = PIKA_LIST (manager)->queue->head;
       list;
       list = g_list_next (list))
    {
      PikaDeviceInfo *device_info = list->data;

      pika_device_info_save_tool (device_info);
      pika_device_info_set_default_tool (device_info);
    }

  file = pika_directory_file ("devicerc", NULL);

  if (pika->be_verbose)
    g_print ("Parsing '%s'\n", pika_file_get_utf8_name (file));

  if (! pika_config_deserialize_file (PIKA_CONFIG (manager),
                                      file,
                                      pika,
                                      &error))
    {
      if (error->code != PIKA_CONFIG_ERROR_OPEN_ENOENT)
        pika_message_literal (pika, NULL, PIKA_MESSAGE_ERROR, error->message);

      g_error_free (error);
      /* don't bail out here */
    }

  g_object_unref (file);

  for (list = PIKA_LIST (manager)->queue->head;
       list;
       list = g_list_next (list))
    {
      PikaDeviceInfo *device_info = list->data;

      if (! PIKA_TOOL_PRESET (device_info)->tool_options)
        {
          pika_device_info_save_tool (device_info);

          g_printerr ("%s: set default tool on loaded PikaDeviceInfo without tool options: %s\n",
                      G_STRFUNC, pika_object_get_name (device_info));
        }
    }

  if (! PIKA_GUI_CONFIG (pika->config)->devices_share_tool)
    {
      PikaDeviceInfo *current_device;

      current_device = pika_device_manager_get_current_device (manager);

      pika_device_info_restore_tool (current_device);
    }
}

void
pika_devices_save (Pika     *pika,
                   gboolean  always_save)
{
  PikaDeviceManager *manager;
  GFile             *file;
  GError            *error = NULL;

  g_return_if_fail (PIKA_IS_PIKA (pika));

  manager = pika_devices_get_manager (pika);

  g_return_if_fail (PIKA_IS_DEVICE_MANAGER (manager));

  if (devicerc_deleted && ! always_save)
    return;

  file = pika_directory_file ("devicerc", NULL);

  if (pika->be_verbose)
    g_print ("Writing '%s'\n", pika_file_get_utf8_name (file));

  if (! PIKA_GUI_CONFIG (pika->config)->devices_share_tool)
    {
      PikaDeviceInfo *current_device;

      current_device = pika_device_manager_get_current_device (manager);

      pika_device_info_save_tool (current_device);
    }

  if (! pika_config_serialize_to_file (PIKA_CONFIG (manager),
                                       file,
                                       "PIKA devicerc",
                                       "end of devicerc",
                                       NULL,
                                       &error))
    {
      pika_message_literal (pika, NULL, PIKA_MESSAGE_ERROR, error->message);
      g_error_free (error);
    }

  g_object_unref (file);

  devicerc_deleted = FALSE;
}

gboolean
pika_devices_clear (Pika    *pika,
                    GError **error)
{
  PikaDeviceManager *manager;
  GFile             *file;
  GError            *my_error = NULL;
  gboolean           success  = TRUE;

  g_return_val_if_fail (PIKA_IS_PIKA (pika), FALSE);

  manager = pika_devices_get_manager (pika);

  g_return_val_if_fail (PIKA_IS_DEVICE_MANAGER (manager), FALSE);

  file = pika_directory_file ("devicerc", NULL);

  if (! g_file_delete (file, NULL, &my_error) &&
      my_error->code != G_IO_ERROR_NOT_FOUND)
    {
      success = FALSE;

      g_set_error (error, PIKA_ERROR, PIKA_FAILED,
                   _("Deleting \"%s\" failed: %s"),
                   pika_file_get_utf8_name (file), my_error->message);
    }
  else
    {
      devicerc_deleted = TRUE;
    }

  g_clear_error (&my_error);
  g_object_unref (file);

  return success;
}

PikaDeviceManager *
pika_devices_get_manager (Pika *pika)
{
  PikaDeviceManager *manager;

  g_return_val_if_fail (PIKA_IS_PIKA (pika), NULL);

  manager = g_object_get_data (G_OBJECT (pika), PIKA_DEVICE_MANAGER_DATA_KEY);

  g_return_val_if_fail (PIKA_IS_DEVICE_MANAGER (manager), NULL);

  return manager;
}

GdkDevice *
pika_devices_get_from_event (Pika            *pika,
                             const GdkEvent  *event,
                             GdkDevice      **grab_device)
{
  GdkDevice *device;

  g_return_val_if_fail (PIKA_IS_PIKA (pika), NULL);
  g_return_val_if_fail (event != NULL, NULL);

  device = gdk_event_get_source_device (event);

  /*  initialize the default grab device to the event's device,
   *  because that is always either a master or a floating device,
   *  which is the types of devices we can make grabs on without
   *  disturbing side effects.
   */
  if (grab_device)
    *grab_device = gdk_event_get_device (event);

  if (gdk_device_get_source (device) == GDK_SOURCE_KEYBOARD)
    {
      switch (gdk_device_get_device_type (device))
        {
        case GDK_DEVICE_TYPE_MASTER:
          /*  this happens on focus synthesized focus changed events,
           *  and we can't do anything with the returned device, so
           *  return NULL
           */
          return NULL;

        case GDK_DEVICE_TYPE_SLAVE:
          /*  it makes no sense for us to distinguigh between
           *  different slave keyboards, so just always return
           *  their respective master
           */
          return gdk_device_get_associated_device (device);

        case GDK_DEVICE_TYPE_FLOATING:
          /*  we have no way of explicitly enabling floating
           *  keyboards, so we cannot get their events
           */
          g_return_val_if_reached (device);
       }
    }
  else
    {
      switch (gdk_device_get_device_type (device))
        {
        case GDK_DEVICE_TYPE_MASTER:
          /*  this can only happen for synthesized events which have
           *  no actual source, so return NULL to indicate that we
           *  cannot do anything with the event's device information
           */
          return NULL;

        case GDK_DEVICE_TYPE_SLAVE:
          /*  this is the tricky part: we do want to distingiugh slave
           *  devices, but only if we actually enabled them ourselves
           *  explicitly (like the pens of a tablet); however we
           *  usually don't enable the different incarnations of the
           *  mouse itself (like touchpad, trackpoint, usb mouse
           *  etc.), so for these return their respective master so
           *  its settings are used
           */
          if (gdk_device_get_mode (device) == GDK_MODE_DISABLED)
            {
              return gdk_device_get_associated_device (device);
            }

          return device;

        case GDK_DEVICE_TYPE_FLOATING:
          /*  we only get events for floating devices which have
           *  enabled ourselves, so return the floating device
           */
          return device;
        }
    }

  g_return_val_if_reached (device);
}

void
pika_devices_add_widget (Pika      *pika,
                         GtkWidget *widget)
{
  g_return_if_fail (PIKA_IS_PIKA (pika));
  g_return_if_fail (GTK_IS_WIDGET (widget));

  g_signal_connect (widget, "motion-notify-event",
                    G_CALLBACK (pika_devices_check_callback),
                    pika);
}

gboolean
pika_devices_check_callback (GtkWidget *widget,
                             GdkEvent  *event,
                             Pika      *pika)
{
  g_return_val_if_fail (event != NULL, FALSE);
  g_return_val_if_fail (PIKA_IS_PIKA (pika), FALSE);

  if (! pika->busy)
    {
      GdkDevice *device;

      device = pika_devices_get_from_event (pika, event, NULL);

      if (device)
        pika_devices_check_change (pika, device);
    }

  return FALSE;
}

gboolean
pika_devices_check_change (Pika      *pika,
                           GdkDevice *device)
{
  PikaDeviceManager *manager;
  PikaDeviceInfo    *device_info;

  g_return_val_if_fail (PIKA_IS_PIKA (pika), FALSE);
  g_return_val_if_fail (GDK_IS_DEVICE (device), FALSE);

  manager = pika_devices_get_manager (pika);

  g_return_val_if_fail (PIKA_IS_DEVICE_MANAGER (manager), FALSE);

  device_info = pika_device_info_get_by_device (device);

  if (! device_info)
    device_info = pika_device_manager_get_current_device (manager);

  if (device_info &&
      device_info != pika_device_manager_get_current_device (manager))
    {
      pika_device_manager_set_current_device (manager, device_info);
      return TRUE;
    }

  return FALSE;
}
