/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
 *
 * Copyright © 2001 Ximian, Inc.
 * Copyright (C) 2007 William Jon McCann <mccann@jhu.edu>
 * Written by Sergey V. Oudaltsov <svu@users.sourceforge.net>
 *
 * 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, see <http://www.gnu.org/licenses/>.
 *
 */

#include "config.h"

#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#include <locale.h>

#include <glib.h>
#include <glib/gi18n.h>
#include <gdk/gdk.h>
#include <gdk/gdkx.h>
#include <gtk/gtk.h>

#include "cinnamon-settings-profile.h"
#include "cinnamon-settings-session.h"
#include "csd-keyboard-manager.h"
#include "csd-enums.h"
#include "migrate-settings.h"

#define CSD_KEYBOARD_DIR "org.cinnamon.settings-daemon.peripherals.keyboard"

#define KEY_CLICK          "click"
#define KEY_CLICK_VOLUME   "click-volume"

#define KEY_BELL_VOLUME    "bell-volume"
#define KEY_BELL_PITCH     "bell-pitch"
#define KEY_BELL_DURATION  "bell-duration"
#define KEY_BELL_MODE      "bell-mode"
#define KEY_BELL_CUSTOM_FILE "bell-custom-file"

struct _CsdKeyboardManager
{
        GObject    parent;

        guint      start_idle_id;
        GSettings *settings;
};

static void     csd_keyboard_manager_class_init  (CsdKeyboardManagerClass *klass);
static void     csd_keyboard_manager_init        (CsdKeyboardManager      *keyboard_manager);
static void     csd_keyboard_manager_finalize    (GObject                 *object);

G_DEFINE_TYPE (CsdKeyboardManager, csd_keyboard_manager, G_TYPE_OBJECT)

static gpointer manager_object = NULL;

static void
apply_bell (CsdKeyboardManager *manager)
{
    GSettings       *settings;
        XKeyboardControl kbdcontrol;
        gboolean         click;
        int              bell_volume;
        int              bell_pitch;
        int              bell_duration;
        CsdBellMode      bell_mode;
        int              click_volume;

        if (cinnamon_settings_session_is_wayland ())
                return;

        g_debug ("Applying the bell settings");
        settings      = manager->settings;
        click         = g_settings_get_boolean  (settings, KEY_CLICK);
        click_volume  = g_settings_get_int   (settings, KEY_CLICK_VOLUME);

        bell_pitch    = g_settings_get_int   (settings, KEY_BELL_PITCH);
        bell_duration = g_settings_get_int   (settings, KEY_BELL_DURATION);

        bell_mode = g_settings_get_enum (settings, KEY_BELL_MODE);
        bell_volume   = (bell_mode == CSD_BELL_MODE_ON) ? 50 : 0;

        /* as percentage from 0..100 inclusive */
        if (click_volume < 0) {
                click_volume = 0;
        } else if (click_volume > 100) {
                click_volume = 100;
        }
        kbdcontrol.key_click_percent = click ? click_volume : 0;
        kbdcontrol.bell_percent = bell_volume;
        kbdcontrol.bell_pitch = bell_pitch;
        kbdcontrol.bell_duration = bell_duration;

        gdk_error_trap_push ();
        XChangeKeyboardControl (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
                                KBKeyClickPercent | KBBellPercent | KBBellPitch | KBBellDuration,
                                &kbdcontrol);

        XSync (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), FALSE);
        gdk_error_trap_pop_ignored ();
}

static void
apply_all_settings (CsdKeyboardManager *manager)
{
    apply_bell (manager);
}

static void
settings_changed (GSettings          *settings,
                  const char         *key,
                  CsdKeyboardManager *manager)
{
    if (g_strcmp0 (key, KEY_CLICK) == 0||
        g_strcmp0 (key, KEY_CLICK_VOLUME) == 0 ||
        g_strcmp0 (key, KEY_BELL_PITCH) == 0 ||
        g_strcmp0 (key, KEY_BELL_DURATION) == 0 ||
        g_strcmp0 (key, KEY_BELL_MODE) == 0) {
        g_debug ("Bell setting '%s' changed, applying bell settings", key);
        apply_bell (manager);
    } else if (g_strcmp0 (key, KEY_BELL_CUSTOM_FILE) == 0){
        g_debug ("Ignoring '%s' setting change", KEY_BELL_CUSTOM_FILE);
    } else {
        g_warning ("Unhandled settings change, key '%s'", key);
    }

}

static gboolean
start_keyboard_idle_cb (CsdKeyboardManager *manager)
{
        cinnamon_settings_profile_start (NULL);

        g_debug ("Starting keyboard manager");

        manager->settings = g_settings_new (CSD_KEYBOARD_DIR);

        if (!cinnamon_settings_session_is_wayland ()) {
                /* apply current settings before we install the callback */
                g_debug ("Started the keyboard plugin, applying all settings");
                apply_all_settings (manager);

                g_signal_connect (G_OBJECT (manager->settings), "changed",
                                  G_CALLBACK (settings_changed), manager);
        }

        cinnamon_settings_profile_end (NULL);

        manager->start_idle_id = 0;

        return FALSE;
}

gboolean
csd_keyboard_manager_start (CsdKeyboardManager *manager,
                            GError            **error)
{
        cinnamon_settings_profile_start (NULL);

        manager->start_idle_id = g_idle_add ((GSourceFunc) start_keyboard_idle_cb, manager);
        g_source_set_name_by_id (manager->start_idle_id, "[gnome-settings-daemon] start_keyboard_idle_cb");

        cinnamon_settings_profile_end (NULL);

        return TRUE;
}

void
csd_keyboard_manager_stop (CsdKeyboardManager *manager)
{
        g_debug ("Stopping keyboard manager");

        g_clear_object (&manager->settings);
}

static void
csd_keyboard_manager_class_init (CsdKeyboardManagerClass *klass)
{
        GObjectClass   *object_class = G_OBJECT_CLASS (klass);

        object_class->finalize = csd_keyboard_manager_finalize;
}

static void
csd_keyboard_manager_init (CsdKeyboardManager *manager)
{
}

static void
csd_keyboard_manager_finalize (GObject *object)
{
        CsdKeyboardManager *keyboard_manager;

        g_return_if_fail (object != NULL);
        g_return_if_fail (CSD_IS_KEYBOARD_MANAGER (object));

        keyboard_manager = CSD_KEYBOARD_MANAGER (object);

        g_return_if_fail (keyboard_manager != NULL);

        csd_keyboard_manager_stop (keyboard_manager);

        if (keyboard_manager->start_idle_id != 0)
                g_source_remove (keyboard_manager->start_idle_id);

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

static void
migrate_keyboard_settings (void)
{
        CsdSettingsMigrateEntry entries[] = {
                { "repeat",          "repeat",          NULL },
                { "repeat-interval", "repeat-interval", NULL },
                { "delay",           "delay",           NULL }
        };

        csd_settings_migrate_check ("org.cinnamon.settings-daemon.peripherals.keyboard.deprecated",
                                    "/org/cinnamon/settings-daemon/peripherals/keyboard/",
                                    "org.cinnamon.desktop.peripherals.keyboard",
                                    "/org/cinnamon/desktop/peripherals/keyboard/",
                                    entries, G_N_ELEMENTS (entries));
}

CsdKeyboardManager *
csd_keyboard_manager_new (void)
{
        if (manager_object != NULL) {
                g_object_ref (manager_object);
        } else {
                migrate_keyboard_settings ();
                manager_object = g_object_new (CSD_TYPE_KEYBOARD_MANAGER, NULL);
                g_object_add_weak_pointer (manager_object,
                                           (gpointer *) &manager_object);
        }

        return CSD_KEYBOARD_MANAGER (manager_object);
}
