gsd-keyboard-manager.c 52.3 KB
Newer Older
William Jon McCann's avatar
William Jon McCann committed
1
2
3
4
/* -*- 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>
5
 * Written by Sergey V. Oudaltsov <svu@users.sourceforge.net>
William Jon McCann's avatar
William Jon McCann committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 *
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 */

#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 <X11/XKBlib.h>
#include <X11/keysym.h>
43
#include <X11/extensions/XKBrules.h>
William Jon McCann's avatar
William Jon McCann committed
44

45
46
#define GNOME_DESKTOP_USE_UNSTABLE_API
#include <libgnome-desktop/gnome-xkb-info.h>
47

48
49
50
51
#ifdef HAVE_IBUS
#include <ibus.h>
#endif

52
#include "gnome-settings-session.h"
53
#include "gnome-settings-profile.h"
William Jon McCann's avatar
William Jon McCann committed
54
#include "gsd-keyboard-manager.h"
55
#include "gsd-input-helper.h"
56
#include "gsd-enums.h"
William Jon McCann's avatar
William Jon McCann committed
57
58
59

#define GSD_KEYBOARD_MANAGER_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GSD_TYPE_KEYBOARD_MANAGER, GsdKeyboardManagerPrivate))

60
#define GSD_KEYBOARD_DIR "org.gnome.settings-daemon.peripherals.keyboard"
William Jon McCann's avatar
William Jon McCann committed
61

62
63
#define KEY_REPEAT         "repeat"
#define KEY_CLICK          "click"
64
#define KEY_INTERVAL       "repeat-interval"
65
66
#define KEY_DELAY          "delay"
#define KEY_CLICK_VOLUME   "click-volume"
67
#define KEY_REMEMBER_NUMLOCK_STATE "remember-numlock-state"
68
#define KEY_NUMLOCK_STATE  "numlock-state"
William Jon McCann's avatar
William Jon McCann committed
69

70
71
72
73
#define KEY_BELL_VOLUME    "bell-volume"
#define KEY_BELL_PITCH     "bell-pitch"
#define KEY_BELL_DURATION  "bell-duration"
#define KEY_BELL_MODE      "bell-mode"
William Jon McCann's avatar
William Jon McCann committed
74

75
76
#define KEY_SWITCHER "input-sources-switcher"

77
78
79
80
81
82
#define GNOME_DESKTOP_INTERFACE_DIR "org.gnome.desktop.interface"

#define KEY_GTK_IM_MODULE    "gtk-im-module"
#define GTK_IM_MODULE_SIMPLE "gtk-im-context-simple"
#define GTK_IM_MODULE_IBUS   "ibus"

83
84
85
86
#define GNOME_DESKTOP_INPUT_SOURCES_DIR "org.gnome.desktop.input-sources"

#define KEY_CURRENT_INPUT_SOURCE "current"
#define KEY_INPUT_SOURCES        "sources"
Rui Matos's avatar
Rui Matos committed
87
#define KEY_KEYBOARD_OPTIONS     "xkb-options"
88

89
90
#define INPUT_SOURCE_TYPE_XKB  "xkb"
#define INPUT_SOURCE_TYPE_IBUS "ibus"
91

92
93
#define DEFAULT_LANGUAGE "en_US"

William Jon McCann's avatar
William Jon McCann committed
94
95
struct GsdKeyboardManagerPrivate
{
96
	guint      start_idle_id;
97
        GSettings *settings;
98
        GSettings *input_sources_settings;
99
        GSettings *interface_settings;
100
        GnomeXkbInfo *xkb_info;
101
102
103
#ifdef HAVE_IBUS
        IBusBus   *ibus;
        GHashTable *ibus_engines;
104
        GHashTable *ibus_xkb_engines;
105
        GCancellable *ibus_cancellable;
106
        gboolean session_is_fallback;
107
#endif
108
        gint       xkb_event_base;
109
        GsdNumLockState old_state;
110
111
112
        GdkDeviceManager *device_manager;
        guint device_added_id;
        guint device_removed_id;
113
114
115

        gboolean input_sources_switcher_spawned;
        GPid input_sources_switcher_pid;
William Jon McCann's avatar
William Jon McCann committed
116
117
118
119
120
};

static void     gsd_keyboard_manager_class_init  (GsdKeyboardManagerClass *klass);
static void     gsd_keyboard_manager_init        (GsdKeyboardManager      *keyboard_manager);
static void     gsd_keyboard_manager_finalize    (GObject                 *object);
121
122
123
static gboolean apply_input_sources_settings     (GSettings               *settings,
                                                  gpointer                 keys,
                                                  gint                     n_keys,
124
                                                  GsdKeyboardManager      *manager);
125
126
static void     set_gtk_im_module                (GsdKeyboardManager      *manager,
                                                  const gchar             *new_module);
William Jon McCann's avatar
William Jon McCann committed
127
128
129
130
131

G_DEFINE_TYPE (GsdKeyboardManager, gsd_keyboard_manager, G_TYPE_OBJECT)

static gpointer manager_object = NULL;

132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
static void
init_builder_with_sources (GVariantBuilder *builder,
                           GSettings       *settings)
{
        const gchar *type;
        const gchar *id;
        GVariantIter iter;
        GVariant *sources;

        sources = g_settings_get_value (settings, KEY_INPUT_SOURCES);

        g_variant_builder_init (builder, G_VARIANT_TYPE ("a(ss)"));

        g_variant_iter_init (&iter, sources);
        while (g_variant_iter_next (&iter, "(&s&s)", &type, &id))
                g_variant_builder_add (builder, "(ss)", type, id);

        g_variant_unref (sources);
}

static gboolean
schema_is_installed (const gchar *name)
{
        const gchar * const *schemas;
        const gchar * const *s;

        schemas = g_settings_list_schemas ();
        for (s = schemas; *s; ++s)
                if (g_str_equal (*s, name))
                        return TRUE;

        return FALSE;
}

166
167
168
169
170
171
172
173
174
#ifdef HAVE_IBUS
static void
clear_ibus (GsdKeyboardManager *manager)
{
        GsdKeyboardManagerPrivate *priv = manager->priv;

        g_cancellable_cancel (priv->ibus_cancellable);
        g_clear_object (&priv->ibus_cancellable);
        g_clear_pointer (&priv->ibus_engines, g_hash_table_destroy);
175
        g_clear_pointer (&priv->ibus_xkb_engines, g_hash_table_destroy);
176
        g_clear_object (&priv->ibus);
177
178
}

179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
static gchar *
make_xkb_source_id (const gchar *engine_id)
{
        gchar *id;
        gchar *p;
        gint n_colons = 0;

        /* engine_id is like "xkb:layout:variant:lang" where
         * 'variant' and 'lang' might be empty */

        engine_id += 4;

        for (p = (gchar *)engine_id; *p; ++p)
                if (*p == ':')
                        if (++n_colons == 2)
                                break;
        if (!*p)
                return NULL;

        id = g_strndup (engine_id, p - engine_id + 1);

        id[p - engine_id] = '\0';

        /* id is "layout:variant" where 'variant' might be empty */

        for (p = id; *p; ++p)
                if (*p == ':') {
                        if (*(p + 1) == '\0')
                                *p = '\0';
                        else
                                *p = '+';
                        break;
                }

        /* id is "layout+variant" or "layout" */

        return id;
}

218
219
220
221
222
223
224
static void
fetch_ibus_engines_result (GObject            *object,
                           GAsyncResult       *result,
                           GsdKeyboardManager *manager)
{
        GsdKeyboardManagerPrivate *priv = manager->priv;
        GList *list, *l;
225
226
227
228
229
230
        GError *error = NULL;

        /* engines shouldn't be there yet */
        g_return_if_fail (priv->ibus_engines == NULL);

        g_clear_object (&priv->ibus_cancellable);
231
232
233
234
235
236
237
238
239
240
241
242

        list = ibus_bus_list_engines_async_finish (priv->ibus,
                                                   result,
                                                   &error);
        if (!list && error) {
                g_warning ("Couldn't finish IBus request: %s", error->message);
                g_error_free (error);

                clear_ibus (manager);
                return;
        }

243
        /* Maps IBus engine ids to engine description objects */
244
        priv->ibus_engines = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_object_unref);
245
246
        /* Maps XKB source id strings to engine description objects */
        priv->ibus_xkb_engines = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
247
248
249

        for (l = list; l; l = l->next) {
                IBusEngineDesc *engine = l->data;
250
251
252
253
254
255
256
257
258
259
260
                const gchar *engine_id = ibus_engine_desc_get_name (engine);

                g_hash_table_replace (priv->ibus_engines, (gpointer)engine_id, engine);

                if (strncmp ("xkb:", engine_id, 4) == 0) {
                        gchar *xkb_source_id = make_xkb_source_id (engine_id);
                        if (xkb_source_id)
                                g_hash_table_replace (priv->ibus_xkb_engines,
                                                      xkb_source_id,
                                                      engine);
                }
261
262
263
        }
        g_list_free (list);

264
        apply_input_sources_settings (priv->input_sources_settings, NULL, 0, manager);
265
266
267
268
269
270
271
}

static void
fetch_ibus_engines (GsdKeyboardManager *manager)
{
        GsdKeyboardManagerPrivate *priv = manager->priv;

272
273
274
275
        /* engines shouldn't be there yet */
        g_return_if_fail (priv->ibus_engines == NULL);
        g_return_if_fail (priv->ibus_cancellable == NULL);

276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
        priv->ibus_cancellable = g_cancellable_new ();

        ibus_bus_list_engines_async (priv->ibus,
                                     -1,
                                     priv->ibus_cancellable,
                                     (GAsyncReadyCallback)fetch_ibus_engines_result,
                                     manager);
}

static void
maybe_start_ibus (GsdKeyboardManager *manager,
                  GVariant           *sources)
{
        gboolean need_ibus = FALSE;
        GVariantIter iter;
        const gchar *type;

293
294
295
        if (manager->priv->session_is_fallback)
                return;

296
297
298
299
300
301
302
303
304
305
        g_variant_iter_init (&iter, sources);
        while (g_variant_iter_next (&iter, "(&s&s)", &type, NULL))
                if (g_str_equal (type, INPUT_SOURCE_TYPE_IBUS)) {
                        need_ibus = TRUE;
                        break;
                }

        if (!need_ibus)
                return;

306
307
308
309
310
311
312
313
        if (!manager->priv->ibus) {
                ibus_init ();
                manager->priv->ibus = ibus_bus_new_async ();
                g_signal_connect_swapped (manager->priv->ibus, "connected",
                                          G_CALLBACK (fetch_ibus_engines), manager);
                g_signal_connect_swapped (manager->priv->ibus, "disconnected",
                                          G_CALLBACK (clear_ibus), manager);
        }
314
315
316
317
318
319
320
321
322
323
324
        /* IBus doesn't export API in the session bus. The only thing
         * we have there is a well known name which we can use as a
         * sure-fire way to activate it. */
        g_bus_unwatch_name (g_bus_watch_name (G_BUS_TYPE_SESSION,
                                              IBUS_SERVICE_IBUS,
                                              G_BUS_NAME_WATCHER_FLAGS_AUTO_START,
                                              NULL,
                                              NULL,
                                              NULL,
                                              NULL));
}
325

326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
static void
set_ibus_engine_finish (GObject            *object,
                        GAsyncResult       *res,
                        GsdKeyboardManager *manager)
{
        gboolean result;
        IBusBus *ibus = IBUS_BUS (object);
        GsdKeyboardManagerPrivate *priv = manager->priv;
        GError *error = NULL;

        g_clear_object (&priv->ibus_cancellable);

        result = ibus_bus_set_global_engine_async_finish (ibus, res, &error);
        if (!result) {
                g_warning ("Couldn't set IBus engine: %s", error->message);
                g_error_free (error);
        }
}

static void
set_ibus_engine (GsdKeyboardManager *manager,
                 const gchar        *engine_id)
{
        GsdKeyboardManagerPrivate *priv = manager->priv;

351
352
353
        g_return_if_fail (priv->ibus != NULL);
        g_return_if_fail (priv->ibus_engines != NULL);

354
355
356
357
358
359
360
361
362
363
364
365
        g_cancellable_cancel (priv->ibus_cancellable);
        g_clear_object (&priv->ibus_cancellable);
        priv->ibus_cancellable = g_cancellable_new ();

        ibus_bus_set_global_engine_async (priv->ibus,
                                          engine_id,
                                          -1,
                                          priv->ibus_cancellable,
                                          (GAsyncReadyCallback)set_ibus_engine_finish,
                                          manager);
}

366
367
368
369
370
371
372
373
374
375
376
377
378
379
static void
set_ibus_xkb_engine (GsdKeyboardManager *manager,
                     const gchar        *xkb_id)
{
        IBusEngineDesc *engine;
        GsdKeyboardManagerPrivate *priv = manager->priv;

        if (!priv->ibus_xkb_engines)
                return;

        engine = g_hash_table_lookup (priv->ibus_xkb_engines, xkb_id);
        if (!engine)
                return;

380
        set_ibus_engine (manager, ibus_engine_desc_get_name (engine));
381
}
382

383
384
/* XXX: See upstream bug:
 * https://codereview.appspot.com/6586075/ */
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
static gchar *
layout_from_ibus_layout (const gchar *ibus_layout)
{
        const gchar *p;

        /* we get something like "layout(variant)[option1,option2]" */

        p = ibus_layout;
        while (*p) {
                if (*p == '(' || *p == '[')
                        break;
                p += 1;
        }

        return g_strndup (ibus_layout, p - ibus_layout);
}

static gchar *
variant_from_ibus_layout (const gchar *ibus_layout)
{
        const gchar *a, *b;

        /* we get something like "layout(variant)[option1,option2]" */

        a = ibus_layout;
        while (*a) {
                if (*a == '(')
                        break;
                a += 1;
        }
        if (!*a)
                return NULL;

        a += 1;
        b = a;
        while (*b) {
                if (*b == ')')
                        break;
                b += 1;
        }
        if (!*b)
                return NULL;

        return g_strndup (a, b - a);
}

static gchar **
options_from_ibus_layout (const gchar *ibus_layout)
{
        const gchar *a, *b;
        GPtrArray *opt_array;

        /* we get something like "layout(variant)[option1,option2]" */

        a = ibus_layout;
        while (*a) {
                if (*a == '[')
                        break;
                a += 1;
        }
        if (!*a)
                return NULL;

        opt_array = g_ptr_array_new ();

        do {
                a += 1;
                b = a;
                while (*b) {
                        if (*b == ',' || *b == ']')
                                break;
                        b += 1;
                }
                if (!*b)
                        goto out;

                g_ptr_array_add (opt_array, g_strndup (a, b - a));

                a = b;
        } while (*a && *a == ',');

out:
        g_ptr_array_add (opt_array, NULL);
        return (gchar **) g_ptr_array_free (opt_array, FALSE);
}
470
471
472
473
474
475

static const gchar *
engine_from_locale (void)
{
        const gchar *locale;
        const gchar *locale_engine[][2] = {
476
477
478
479
                { "as_IN", "m17n:as:phonetic" },
                { "bn_IN", "m17n:bn:inscript" },
                { "gu_IN", "m17n:gu:inscript" },
                { "hi_IN", "m17n:hi:inscript" },
480
                { "ja_JP", "anthy" },
481
                { "kn_IN", "m17n:kn:kgp" },
482
                { "ko_KR", "hangul" },
483
484
485
486
487
488
489
490
                { "mai_IN", "m17n:mai:inscript" },
                { "ml_IN", "m17n:ml:inscript" },
                { "mr_IN", "m17n:mr:inscript" },
                { "or_IN", "m17n:or:inscript" },
                { "pa_IN", "m17n:pa:inscript" },
                { "sd_IN", "m17n:sd:inscript" },
                { "ta_IN", "m17n:ta:tamil99" },
                { "te_IN", "m17n:te:inscript" },
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
                { "zh_CN", "pinyin" },
                { "zh_HK", "cangjie3" },
                { "zh_TW", "chewing" },
        };
        gint i;

        locale = setlocale (LC_CTYPE, NULL);
        if (!locale)
                return NULL;

        for (i = 0; i < G_N_ELEMENTS (locale_engine); ++i)
                if (g_str_has_prefix (locale, locale_engine[i][0]))
                        return locale_engine[i][1];

        return NULL;
}

static void
509
add_ibus_sources_from_locale (GSettings *settings)
510
{
511
512
        const gchar *locale_engine;
        GVariantBuilder builder;
513

514
515
516
        locale_engine = engine_from_locale ();
        if (!locale_engine)
                return;
517

518
519
520
        init_builder_with_sources (&builder, settings);
        g_variant_builder_add (&builder, "(ss)", INPUT_SOURCE_TYPE_IBUS, locale_engine);
        g_settings_set_value (settings, KEY_INPUT_SOURCES, g_variant_builder_end (&builder));
521
522
523
}

static void
524
convert_ibus (GSettings *settings)
525
526
{
        GVariantBuilder builder;
527
528
        GSettings *ibus_settings;
        gchar **engines, **e;
529

530
        if (!schema_is_installed ("org.freedesktop.ibus.general"))
531
532
533
                return;

        init_builder_with_sources (&builder, settings);
534
535
536
537
538
539

        ibus_settings = g_settings_new ("org.freedesktop.ibus.general");
        engines = g_settings_get_strv (ibus_settings, "preload-engines");
        for (e = engines; *e; ++e)
                g_variant_builder_add (&builder, "(ss)", INPUT_SOURCE_TYPE_IBUS, *e);

540
        g_settings_set_value (settings, KEY_INPUT_SOURCES, g_variant_builder_end (&builder));
541
542
543

        g_strfreev (engines);
        g_object_unref (ibus_settings);
544
}
545
546
#endif  /* HAVE_IBUS */

William Jon McCann's avatar
William Jon McCann committed
547
static gboolean
548
xkb_set_keyboard_autorepeat_rate (guint delay, guint interval)
William Jon McCann's avatar
William Jon McCann committed
549
{
550
        return XkbSetAutoRepeatRate (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
William Jon McCann's avatar
William Jon McCann committed
551
552
553
554
555
                                     XkbUseCoreKbd,
                                     delay,
                                     interval);
}

556
557
static gboolean
check_xkb_extension (GsdKeyboardManager *manager)
558
559
560
{
        Display *dpy = GDK_DISPLAY_XDISPLAY (gdk_display_get_default ());
        int opcode, error_base, major, minor;
561
        gboolean have_xkb;
William Jon McCann's avatar
William Jon McCann committed
562

563
        have_xkb = XkbQueryExtension (dpy,
564
565
566
567
                                      &opcode,
                                      &manager->priv->xkb_event_base,
                                      &error_base,
                                      &major,
568
                                      &minor);
569
        return have_xkb;
570
571
572
}

static void
573
xkb_init (GsdKeyboardManager *manager)
574
575
576
577
578
579
{
        Display *dpy;

        dpy = GDK_DISPLAY_XDISPLAY (gdk_display_get_default ());
        XkbSelectEventDetails (dpy,
                               XkbUseCoreKbd,
580
                               XkbStateNotify,
581
582
                               XkbModifierLockMask,
                               XkbModifierLockMask);
583
}
William Jon McCann's avatar
William Jon McCann committed
584
585
586
587
588
589
590
591
592

static unsigned
numlock_NumLock_modifier_mask (void)
{
        Display *dpy = GDK_DISPLAY_XDISPLAY (gdk_display_get_default ());
        return XkbKeysymToModifiers (dpy, XK_Num_Lock);
}

static void
593
numlock_set_xkb_state (GsdNumLockState new_state)
William Jon McCann's avatar
William Jon McCann committed
594
595
596
{
        unsigned int num_mask;
        Display *dpy = GDK_DISPLAY_XDISPLAY (gdk_display_get_default ());
597
        if (new_state != GSD_NUM_LOCK_STATE_ON && new_state != GSD_NUM_LOCK_STATE_OFF)
William Jon McCann's avatar
William Jon McCann committed
598
599
                return;
        num_mask = numlock_NumLock_modifier_mask ();
600
        XkbLockModifiers (dpy, XkbUseCoreKbd, num_mask, new_state == GSD_NUM_LOCK_STATE_ON ? num_mask : 0);
William Jon McCann's avatar
William Jon McCann committed
601
602
}

603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
static const char *
num_lock_state_to_string (GsdNumLockState numlock_state)
{
	switch (numlock_state) {
	case GSD_NUM_LOCK_STATE_UNKNOWN:
		return "GSD_NUM_LOCK_STATE_UNKNOWN";
	case GSD_NUM_LOCK_STATE_ON:
		return "GSD_NUM_LOCK_STATE_ON";
	case GSD_NUM_LOCK_STATE_OFF:
		return "GSD_NUM_LOCK_STATE_OFF";
	default:
		return "UNKNOWN";
	}
}

William Jon McCann's avatar
William Jon McCann committed
618
static GdkFilterReturn
619
620
621
xkb_events_filter (GdkXEvent *xev_,
		   GdkEvent  *gdkev_,
		   gpointer   user_data)
William Jon McCann's avatar
William Jon McCann committed
622
{
623
        XEvent *xev = (XEvent *) xev_;
624
	XkbEvent *xkbev = (XkbEvent *) xev;
625
        GsdKeyboardManager *manager = (GsdKeyboardManager *) user_data;
William Jon McCann's avatar
William Jon McCann committed
626

627
628
        if (xev->type != manager->priv->xkb_event_base ||
            xkbev->any.xkb_type != XkbStateNotify)
629
630
631
632
633
634
635
636
637
638
		return GDK_FILTER_CONTINUE;

	if (xkbev->state.changed & XkbModifierLockMask) {
		unsigned num_mask = numlock_NumLock_modifier_mask ();
		unsigned locked_mods = xkbev->state.locked_mods;
		GsdNumLockState numlock_state;

		numlock_state = (num_mask & locked_mods) ? GSD_NUM_LOCK_STATE_ON : GSD_NUM_LOCK_STATE_OFF;

		if (numlock_state != manager->priv->old_state) {
639
640
641
			g_debug ("New num-lock state '%s' != Old num-lock state '%s'",
				 num_lock_state_to_string (numlock_state),
				 num_lock_state_to_string (manager->priv->old_state));
642
643
644
645
646
647
648
			g_settings_set_enum (manager->priv->settings,
					     KEY_NUMLOCK_STATE,
					     numlock_state);
			manager->priv->old_state = numlock_state;
		}
	}

William Jon McCann's avatar
William Jon McCann committed
649
650
651
        return GDK_FILTER_CONTINUE;
}

652
static void
653
install_xkb_filter (GsdKeyboardManager *manager)
William Jon McCann's avatar
William Jon McCann committed
654
655
{
        gdk_window_add_filter (NULL,
656
                               xkb_events_filter,
657
                               manager);
William Jon McCann's avatar
William Jon McCann committed
658
659
}

660
static void
661
remove_xkb_filter (GsdKeyboardManager *manager)
662
663
{
        gdk_window_remove_filter (NULL,
664
                                  xkb_events_filter,
665
666
667
                                  manager);
}

668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
static void
free_xkb_component_names (XkbComponentNamesRec *p)
{
        g_return_if_fail (p != NULL);

        free (p->keymap);
        free (p->keycodes);
        free (p->types);
        free (p->compat);
        free (p->symbols);
        free (p->geometry);

        g_free (p);
}

static void
upload_xkb_description (const gchar          *rules_file_path,
                        XkbRF_VarDefsRec     *var_defs,
                        XkbComponentNamesRec *comp_names)
{
        Display *display = GDK_DISPLAY_XDISPLAY (gdk_display_get_default ());
        XkbDescRec *xkb_desc;
        gchar *rules_file;

        /* Upload it to the X server using the same method as setxkbmap */
        xkb_desc = XkbGetKeyboardByName (display,
                                         XkbUseCoreKbd,
                                         comp_names,
                                         XkbGBN_AllComponentsMask,
                                         XkbGBN_AllComponentsMask &
                                         (~XkbGBN_GeometryMask), True);
        if (!xkb_desc) {
                g_warning ("Couldn't upload new XKB keyboard description");
                return;
        }

        XkbFreeKeyboard (xkb_desc, 0, True);

        rules_file = g_path_get_basename (rules_file_path);

        if (!XkbRF_SetNamesProp (display, rules_file, var_defs))
                g_warning ("Couldn't update the XKB root window property");

        g_free (rules_file);
}

static gchar *
language_code_from_locale (const gchar *locale)
{
        if (!locale || !locale[0] || !locale[1])
                return NULL;

        if (!locale[2] || locale[2] == '_' || locale[2] == '.')
                return g_strndup (locale, 2);

        if (!locale[3] || locale[3] == '_' || locale[3] == '.')
                return g_strndup (locale, 3);

        return NULL;
}

static gchar *
build_xkb_group_string (const gchar *user,
                        const gchar *locale,
                        const gchar *latin)
{
        gchar *string;
        gsize length = 0;
        guint commas = 2;

        if (latin)
                length += strlen (latin);
        else
                commas -= 1;

        if (locale)
                length += strlen (locale);
        else
                commas -= 1;

        length += strlen (user) + commas + 1;

        string = malloc (length);

        if (locale && latin)
                sprintf (string, "%s,%s,%s", user, locale, latin);
        else if (locale)
                sprintf (string, "%s,%s", user, locale);
        else if (latin)
                sprintf (string, "%s,%s", user, latin);
        else
                sprintf (string, "%s", user);

        return string;
}

static gboolean
layout_equal (const gchar *layout_a,
              const gchar *variant_a,
              const gchar *layout_b,
              const gchar *variant_b)
{
        return !g_strcmp0 (layout_a, layout_b) && !g_strcmp0 (variant_a, variant_b);
}

static void
replace_layout_and_variant (GsdKeyboardManager *manager,
                            XkbRF_VarDefsRec   *xkb_var_defs,
                            const gchar        *layout,
                            const gchar        *variant)
{
        /* Toolkits need to know about both a latin layout to handle
         * accelerators which are usually defined like Ctrl+C and a
         * layout with the symbols for the language used in UI strings
         * to handle mnemonics like Alt+Ф, so we try to find and add
         * them in XKB group slots after the layout which the user
         * actually intends to type with. */
        const gchar *latin_layout = "us";
        const gchar *latin_variant = "";
        const gchar *locale_layout = NULL;
        const gchar *locale_variant = NULL;
789
790
791
        const gchar *locale;
        gchar *language;

792
793
794
        if (!layout)
                return;

795
796
797
        if (!variant)
                variant = "";

798
799
800
        locale = setlocale (LC_MESSAGES, NULL);
        /* If LANG is empty, default to en_US */
        if (!locale)
801
                language = g_strdup (DEFAULT_LANGUAGE);
802
803
        else
                language = language_code_from_locale (locale);
804

805
806
807
        if (!language)
                language = language_code_from_locale (DEFAULT_LANGUAGE);

808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
        gnome_xkb_info_get_layout_info_for_language (manager->priv->xkb_info,
                                                     language,
                                                     NULL,
                                                     NULL,
                                                     NULL,
                                                     &locale_layout,
                                                     &locale_variant);
        g_free (language);

        /* We want to minimize the number of XKB groups if we have
         * duplicated layout+variant pairs.
         *
         * Also, if a layout doesn't have a variant we still have to
         * include it in the variants string because the number of
         * variants must agree with the number of layouts. For
         * instance:
         *
         * layouts:  "us,ru,us"
         * variants: "dvorak,,"
         */
        if (layout_equal (latin_layout, latin_variant, locale_layout, locale_variant) ||
            layout_equal (latin_layout, latin_variant, layout, variant)) {
                latin_layout = NULL;
                latin_variant = NULL;
        }

        if (layout_equal (locale_layout, locale_variant, layout, variant)) {
                locale_layout = NULL;
                locale_variant = NULL;
        }

        free (xkb_var_defs->layout);
        xkb_var_defs->layout = build_xkb_group_string (layout, locale_layout, latin_layout);

        free (xkb_var_defs->variant);
        xkb_var_defs->variant = build_xkb_group_string (variant, locale_variant, latin_variant);
}

Rui Matos's avatar
Rui Matos committed
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
static gchar *
build_xkb_options_string (gchar **options)
{
        gchar *string;

        if (*options) {
                gint i;
                gsize len;
                gchar *ptr;

                /* First part, getting length */
                len = 1 + strlen (options[0]);
                for (i = 1; options[i] != NULL; i++)
                        len += strlen (options[i]);
                len += (i - 1); /* commas */

                /* Second part, building string */
                string = malloc (len);
                ptr = g_stpcpy (string, *options);
                for (i = 1; options[i] != NULL; i++) {
                        ptr = g_stpcpy (ptr, ",");
                        ptr = g_stpcpy (ptr, options[i]);
                }
        } else {
                string = malloc (1);
                *string = '\0';
        }

        return string;
}

877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
static gchar **
append_options (gchar **a,
                gchar **b)
{
        gchar **c, **p;

        if (!a && !b)
                return NULL;
        else if (!a)
                return g_strdupv (b);
        else if (!b)
                return g_strdupv (a);

        c = g_new0 (gchar *, g_strv_length (a) + g_strv_length (b) + 1);
        p = c;

        while (*a) {
                *p = g_strdup (*a);
                p += 1;
                a += 1;
        }
        while (*b) {
                *p = g_strdup (*b);
                p += 1;
                b += 1;
        }

        return c;
}

Rui Matos's avatar
Rui Matos committed
907
908
static void
add_xkb_options (GsdKeyboardManager *manager,
909
910
                 XkbRF_VarDefsRec   *xkb_var_defs,
                 gchar             **extra_options)
Rui Matos's avatar
Rui Matos committed
911
912
{
        gchar **options;
913
        gchar **settings_options;
Rui Matos's avatar
Rui Matos committed
914

915
916
917
918
        settings_options = g_settings_get_strv (manager->priv->input_sources_settings,
                                                KEY_KEYBOARD_OPTIONS);
        options = append_options (settings_options, extra_options);
        g_strfreev (settings_options);
Rui Matos's avatar
Rui Matos committed
919
920
921
922
923
924
925

        free (xkb_var_defs->options);
        xkb_var_defs->options = build_xkb_options_string (options);

        g_strfreev (options);
}

926
static void
927
928
apply_xkb_settings (GsdKeyboardManager *manager,
                    const gchar        *layout,
929
930
                    const gchar        *variant,
                    gchar             **options)
931
932
933
934
935
936
937
{
        XkbRF_RulesRec *xkb_rules;
        XkbRF_VarDefsRec *xkb_var_defs;
        gchar *rules_file_path;

        gnome_xkb_info_get_var_defs (&rules_file_path, &xkb_var_defs);

938
        add_xkb_options (manager, xkb_var_defs, options);
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
        replace_layout_and_variant (manager, xkb_var_defs, layout, variant);

        gdk_error_trap_push ();

        xkb_rules = XkbRF_Load (rules_file_path, NULL, True, True);
        if (xkb_rules) {
                XkbComponentNamesRec *xkb_comp_names;
                xkb_comp_names = g_new0 (XkbComponentNamesRec, 1);

                XkbRF_GetComponents (xkb_rules, xkb_var_defs, xkb_comp_names);
                upload_xkb_description (rules_file_path, xkb_var_defs, xkb_comp_names);

                free_xkb_component_names (xkb_comp_names);
                XkbRF_Free (xkb_rules, True);
        } else {
                g_warning ("Couldn't load XKB rules");
        }

        if (gdk_error_trap_pop ())
                g_warning ("Error loading XKB rules");

        gnome_xkb_info_free_var_defs (xkb_var_defs);
        g_free (rules_file_path);
}

964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
static void
set_gtk_im_module (GsdKeyboardManager *manager,
                   const gchar        *new_module)
{
        GsdKeyboardManagerPrivate *priv = manager->priv;
        gchar *current_module;

        current_module = g_settings_get_string (priv->interface_settings,
                                                KEY_GTK_IM_MODULE);
        if (!g_str_equal (current_module, new_module))
                g_settings_set_string (priv->interface_settings,
                                       KEY_GTK_IM_MODULE,
                                       new_module);
        g_free (current_module);
}

980
static gboolean
981
apply_input_sources_settings (GSettings          *settings,
982
983
                              gpointer            keys,
                              gint                n_keys,
984
985
986
987
988
                              GsdKeyboardManager *manager)
{
        GsdKeyboardManagerPrivate *priv = manager->priv;
        GVariant *sources;
        guint current;
989
        guint n_sources;
990
991
        const gchar *type = NULL;
        const gchar *id = NULL;
992
993
994
        gchar *layout = NULL;
        gchar *variant = NULL;
        gchar **options = NULL;
995
996
997

        sources = g_settings_get_value (priv->input_sources_settings, KEY_INPUT_SOURCES);
        current = g_settings_get_uint (priv->input_sources_settings, KEY_CURRENT_INPUT_SOURCE);
998
        n_sources = g_variant_n_children (sources);
999

1000
        if (n_sources < 1)
1001
                goto exit;
1002
1003

        if (current >= n_sources) {
1004
1005
                g_settings_set_uint (priv->input_sources_settings,
                                     KEY_CURRENT_INPUT_SOURCE,
1006
                                     n_sources - 1);
1007
1008
1009
                goto exit;
        }

1010
1011
1012
1013
#ifdef HAVE_IBUS
        maybe_start_ibus (manager, sources);
#endif

1014
1015
        g_variant_get_child (sources, current, "(&s&s)", &type, &id);

1016
        if (g_str_equal (type, INPUT_SOURCE_TYPE_XKB)) {
1017
1018
1019
1020
1021
                const gchar *l, *v;
                gnome_xkb_info_get_layout_info (priv->xkb_info, id, NULL, NULL, &l, &v);

                layout = g_strdup (l);
                variant = g_strdup (v);
1022
1023
1024
1025
1026
1027

                if (!layout || !layout[0]) {
                        g_warning ("Couldn't find XKB input source '%s'", id);
                        goto exit;
                }
                set_gtk_im_module (manager, GTK_IM_MODULE_SIMPLE);
1028
1029
1030
#ifdef HAVE_IBUS
                set_ibus_xkb_engine (manager, id);
#endif
1031
1032
1033
1034
        } else if (g_str_equal (type, INPUT_SOURCE_TYPE_IBUS)) {
#ifdef HAVE_IBUS
                IBusEngineDesc *engine_desc = NULL;

1035
1036
1037
                if (priv->session_is_fallback)
                        goto exit;

1038
1039
1040
1041
1042
1043
                if (priv->ibus_engines)
                        engine_desc = g_hash_table_lookup (priv->ibus_engines, id);
                else
                        goto exit; /* we'll be called again when ibus is up and running */

                if (engine_desc) {
1044
1045
1046
1047
1048
1049
1050
1051
                        const gchar *ibus_layout;
                        ibus_layout = ibus_engine_desc_get_layout (engine_desc);

                        if (ibus_layout) {
                                layout = layout_from_ibus_layout (ibus_layout);
                                variant = variant_from_ibus_layout (ibus_layout);
                                options = options_from_ibus_layout (ibus_layout);
                        }
1052
1053
1054
1055
1056
                } else {
                        g_warning ("Couldn't find IBus input source '%s'", id);
                        goto exit;
                }

1057
                set_gtk_im_module (manager, GTK_IM_MODULE_IBUS);
1058
                set_ibus_engine (manager, id);
1059
1060
1061
1062
1063
#else
                g_warning ("IBus input source type specified but IBus support was not compiled");
#endif
        } else {
                g_warning ("Unknown input source type '%s'", type);
1064
1065
1066
        }

 exit:
1067
        apply_xkb_settings (manager, layout, variant, options);
1068
        g_variant_unref (sources);
1069
1070
1071
        g_free (layout);
        g_free (variant);
        g_strfreev (options);
1072
1073
1074
        /* Prevent individual "changed" signal invocations since we
           don't need them. */
        return TRUE;
1075
1076
}

William Jon McCann's avatar
William Jon McCann committed
1077
static void
1078
apply_bell (GsdKeyboardManager *manager)
William Jon McCann's avatar
William Jon McCann committed
1079
{
1080
	GSettings       *settings;
William Jon McCann's avatar
William Jon McCann committed
1081
1082
1083
1084
1085
        XKeyboardControl kbdcontrol;
        gboolean         click;
        int              bell_volume;
        int              bell_pitch;
        int              bell_duration;
1086
        GsdBellMode      bell_mode;
1087
        int              click_volume;
William Jon McCann's avatar
William Jon McCann committed
1088

Bastien Nocera's avatar
Bastien Nocera committed
1089
1090
        g_debug ("Applying the bell settings");
        settings      = manager->priv->settings;
1091
1092
        click         = g_settings_get_boolean  (settings, KEY_CLICK);
        click_volume  = g_settings_get_int   (settings, KEY_CLICK_VOLUME);
1093

1094
1095
        bell_pitch    = g_settings_get_int   (settings, KEY_BELL_PITCH);
        bell_duration = g_settings_get_int   (settings, KEY_BELL_DURATION);
William Jon McCann's avatar
William Jon McCann committed
1096

1097
1098
        bell_mode = g_settings_get_enum (settings, KEY_BELL_MODE);
        bell_volume   = (bell_mode == GSD_BELL_MODE_ON) ? 50 : 0;
William Jon McCann's avatar
William Jon McCann committed
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109

        /* 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;
1110
1111

        gdk_error_trap_push ();
1112
        XChangeKeyboardControl (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()),
William Jon McCann's avatar
William Jon McCann committed
1113
1114
1115
                                KBKeyClickPercent | KBBellPercent | KBBellPitch | KBBellDuration,
                                &kbdcontrol);

1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
        XSync (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), FALSE);
        gdk_error_trap_pop_ignored ();
}

static void
apply_numlock (GsdKeyboardManager *manager)
{
	GSettings *settings;
        gboolean rnumlock;

Bastien Nocera's avatar
Bastien Nocera committed
1126
        g_debug ("Applying the num-lock settings");
1127
        settings = manager->priv->settings;
1128
        rnumlock = g_settings_get_boolean  (settings, KEY_REMEMBER_NUMLOCK_STATE);
1129
1130
        manager->priv->old_state = g_settings_get_enum (manager->priv->settings, KEY_NUMLOCK_STATE);

1131
        gdk_error_trap_push ();
1132
1133
1134
        if (rnumlock) {
                g_debug ("Remember num-lock is set, so applying setting '%s'",
                         num_lock_state_to_string (manager->priv->old_state));
1135
                numlock_set_xkb_state (manager->priv->old_state);
1136
        }
William Jon McCann's avatar
William Jon McCann committed
1137

1138
        XSync (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()), FALSE);
1139
        gdk_error_trap_pop_ignored ();
William Jon McCann's avatar
William Jon McCann committed
1140
1141
}

1142
1143
1144
1145
1146
1147
1148
1149
static void
apply_repeat (GsdKeyboardManager *manager)
{
	GSettings       *settings;
        gboolean         repeat;
        guint            interval;
        guint            delay;

Bastien Nocera's avatar
Bastien Nocera committed
1150
1151
        g_debug ("Applying the repeat settings");
        settings      = manager->priv->settings;
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
        repeat        = g_settings_get_boolean  (settings, KEY_REPEAT);
        interval      = g_settings_get_uint  (settings, KEY_INTERVAL);
        delay         = g_settings_get_uint  (settings, KEY_DELAY);

        gdk_error_trap_push ();
        if (repeat) {
                gboolean rate_set = FALSE;

                XAutoRepeatOn (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()));
                /* Use XKB in preference */
                rate_set = xkb_set_keyboard_autorepeat_rate (delay, interval);

                if (!rate_set)
                        g_warning ("Neither XKeyboard not Xfree86's keyboard extensions are available,\n"
                                   "no way to support keyboard autorepeat rate settings");
        } else {
                XAutoRepeatOff (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ()));
        }

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

static void
apply_all_settings (GsdKeyboardManager *manager)
{
	apply_repeat (manager);
	apply_bell (manager);
	apply_numlock (manager);
}

1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
static void
set_input_sources_switcher (GsdKeyboardManager *manager,
                            gboolean            state)
{
        if (state) {
                GError *error = NULL;
                char *args[2];

                if (manager->priv->input_sources_switcher_spawned)
                        set_input_sources_switcher (manager, FALSE);

                args[0] = LIBEXECDIR "/gsd-input-sources-switcher";
                args[1] = NULL;

                g_spawn_async (NULL, args, NULL,
                               0, NULL, NULL,
                               &manager->priv->input_sources_switcher_pid, &error);

                manager->priv->input_sources_switcher_spawned = (error == NULL);

                if (error) {
                        g_warning ("Couldn't spawn %s: %s", args[0], error->message);
                        g_error_free (error);
                }
        } else if (manager->priv->input_sources_switcher_spawned) {
                kill (manager->priv->input_sources_switcher_pid, SIGHUP);
                g_spawn_close_pid (manager->priv->input_sources_switcher_pid);
                manager->priv->input_sources_switcher_spawned = FALSE;
        }
}

static gboolean
enable_switcher (GsdKeyboardManager *manager)
{
        GsdInputSourcesSwitcher switcher;

        switcher = g_settings_get_enum (manager->priv->settings, KEY_SWITCHER);

        return switcher != GSD_INPUT_SOURCES_SWITCHER_OFF;
}

1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
static void
settings_changed (GSettings          *settings,
                  const char         *key,
                  GsdKeyboardManager *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);
1236
1237
	} else if (g_strcmp0 (key, KEY_REMEMBER_NUMLOCK_STATE) == 0) {
		g_debug ("Remember Num-Lock state '%s' changed, applying num-lock settings", key);
1238
		apply_numlock (manager);
1239
1240
	} else if (g_strcmp0 (key, KEY_NUMLOCK_STATE) == 0) {
		g_debug ("Num-Lock state '%s' changed, will apply at next startup", key);
1241
1242
1243
1244
1245
	} else if (g_strcmp0 (key, KEY_REPEAT) == 0 ||
		 g_strcmp0 (key, KEY_INTERVAL) == 0 ||
		 g_strcmp0 (key, KEY_DELAY) == 0) {
		g_debug ("Key repeat setting '%s' changed, applying key repeat settings", key);
		apply_repeat (manager);
1246
1247
        } else if (g_strcmp0 (key, KEY_SWITCHER) == 0) {
                set_input_sources_switcher (manager, enable_switcher (manager));
1248
1249
1250
1251
1252
1253
	} else {
		g_warning ("Unhandled settings change, key '%s'", key);
	}

}

1254
1255
1256
1257
1258
1259
1260
1261
1262
static void
device_added_cb (GdkDeviceManager   *device_manager,
                 GdkDevice          *device,
                 GsdKeyboardManager *manager)
{
        GdkInputSource source;

        source = gdk_device_get_source (device);
        if (source == GDK_SOURCE_KEYBOARD) {
Bastien Nocera's avatar
Bastien Nocera committed
1263
                g_debug ("New keyboard plugged in, applying all settings");
1264
                apply_input_sources_settings (manager->priv->input_sources_settings, NULL, 0, manager);
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
                run_custom_command (device, COMMAND_DEVICE_ADDED);
        }
}

static void
device_removed_cb (GdkDeviceManager   *device_manager,
                   GdkDevice          *device,
                   GsdKeyboardManager *manager)
{
        GdkInputSource source;

        source = gdk_device_get_source (device);
        if (source == GDK_SOURCE_KEYBOARD) {
                run_custom_command (device, COMMAND_DEVICE_REMOVED);
        }
}

static void
set_devicepresence_handler (GsdKeyboardManager *manager)
{
        GdkDeviceManager *device_manager;

        device_manager = gdk_display_get_device_manager (gdk_display_get_default ());

        manager->priv->device_added_id = g_signal_connect (G_OBJECT (device_manager), "device-added",
                                                           G_CALLBACK (device_added_cb), manager);
        manager->priv->device_removed_id = g_signal_connect (G_OBJECT (device_manager), "device-removed",
                                                             G_CALLBACK (device_removed_cb), manager);
        manager->priv->device_manager = device_manager;
}

1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
static void
create_sources_from_current_xkb_config (GSettings *settings)
{
        GVariantBuilder builder;
        XkbRF_VarDefsRec *xkb_var_defs;
        gchar *tmp;
        gchar **layouts = NULL;
        gchar **variants = NULL;
        guint i, n;

        gnome_xkb_info_get_var_defs (&tmp, &xkb_var_defs);
        g_free (tmp);

        if (xkb_var_defs->layout)
                layouts = g_strsplit (xkb_var_defs->layout, ",", 0);
        if (xkb_var_defs->variant)
                variants = g_strsplit (xkb_var_defs->variant, ",", 0);

        gnome_xkb_info_free_var_defs (xkb_var_defs);

        if (!layouts)
                goto out;

        if (variants && variants[0])
                n = MIN (g_strv_length (layouts), g_strv_length (variants));
        else
                n = g_strv_length (layouts);

        g_variant_builder_init (&builder, G_VARIANT_TYPE ("a(ss)"));
        for (i = 0; i < n && layouts[i][0]; ++i) {
                if (variants && variants[i] && variants[i][0])
                        tmp = g_strdup_printf ("%s+%s", layouts[i], variants[i]);
                else
                        tmp = g_strdup (layouts[i]);

                g_variant_builder_add (&builder, "(ss)", INPUT_SOURCE_TYPE_XKB, tmp);
                g_free (tmp);
        }
        g_settings_set_value (settings, KEY_INPUT_SOURCES, g_variant_builder_end (&builder));
out:
        g_strfreev (layouts);
        g_strfreev (variants);
}

1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
static void
convert_libgnomekbd_options (GSettings *settings)
{
        GPtrArray *opt_array;
        GSettings *libgnomekbd_settings;
        gchar **options, **o;

        if (!schema_is_installed ("org.gnome.libgnomekbd.keyboard"))
                return;

        opt_array = g_ptr_array_new_with_free_func (g_free);

        libgnomekbd_settings = g_settings_new ("org.gnome.libgnomekbd.keyboard");
        options = g_settings_get_strv (libgnomekbd_settings, "options");

        for (o = options; *o; ++o) {
                gchar **strv;

                strv = g_strsplit (*o, "\t", 2);
                if (strv[0] && strv[1]) {
                        /* We don't want the group switcher because
                         * it's incompatible with the way we use XKB
                         * groups. */
                        if (!g_str_has_prefix (strv[1], "grp:"))
                                g_ptr_array_add (opt_array, g_strdup (strv[1]));
                }
                g_strfreev (strv);
        }
        g_ptr_array_add (opt_array, NULL);

        g_settings_set_strv (settings, KEY_KEYBOARD_OPTIONS, (const gchar * const*) opt_array->pdata);

        g_strfreev (options);
        g_object_unref (libgnomekbd_settings);
        g_ptr_array_free (opt_array, TRUE);
}

static void
convert_libgnomekbd_layouts (GSettings *settings)
{
        GVariantBuilder builder;
        GSettings *libgnomekbd_settings;
        gchar **layouts, **l;

        if (!schema_is_installed ("org.gnome.libgnomekbd.keyboard"))
                return;

        init_builder_with_sources (&builder, settings);

        libgnomekbd_settings = g_settings_new ("org.gnome.libgnomekbd.keyboard");
        layouts = g_settings_get_strv (libgnomekbd_settings, "layouts");

        for (l = layouts; *l; ++l) {
                gchar *id;
                gchar **strv;

                strv = g_strsplit (*l, "\t", 2);
                if (strv[0] && !strv[1])
                        id = g_strdup (strv[0]);
                else if (strv[0] && strv[1])
                        id = g_strdup_printf ("%s+%s", strv[0], strv[1]);
                else
                        id = NULL;

                if (id)
                        g_variant_builder_add (&builder, "(ss)", INPUT_SOURCE_TYPE_XKB, id);

                g_free (id);
                g_strfreev (strv);
        }

        g_settings_set_value (settings, KEY_INPUT_SOURCES, g_variant_builder_end (&builder));

        g_strfreev (layouts);
        g_object_unref (libgnomekbd_settings);
}

static void
maybe_convert_old_settings (GSettings *settings)
{
        GVariant *sources;
        gchar **options;
        gchar *stamp_dir_path = NULL;
        gchar *stamp_file_path = NULL;
        GError *error = NULL;

        stamp_dir_path = g_build_filename (g_get_user_data_dir (), PACKAGE_NAME, NULL);
        if (g_mkdir_with_parents (stamp_dir_path, 0755)) {
                g_warning ("Failed to create directory %s: %s", stamp_dir_path, g_strerror (errno));
                goto out;
        }

        stamp_file_path = g_build_filename (stamp_dir_path, "input-sources-converted", NULL);
        if (g_file_test (stamp_file_path, G_FILE_TEST_EXISTS))
                goto out;

        sources = g_settings_get_value (settings, KEY_INPUT_SOURCES);
        if (g_variant_n_children (sources) < 1) {
                convert_libgnomekbd_layouts (settings);
#ifdef HAVE_IBUS
                convert_ibus (settings);
#endif
        }
        g_variant_unref (sources);

        options = g_settings_get_strv (settings, KEY_KEYBOARD_OPTIONS);
        if (g_strv_length (options) < 1)
                convert_libgnomekbd_options (settings);
        g_strfreev (options);

        if (!g_file_set_contents (stamp_file_path, "", 0, &error)) {
                g_warning ("%s", error->message);
                g_error_free (error);
        }
out:
        g_free (stamp_file_path);
        g_free (stamp_dir_path);
}

1459
1460
1461
static void
maybe_create_input_sources (GsdKeyboardManager *manager)
{
1462
        GSettings *settings;
1463
1464
        GVariant *sources;

1465
        settings = manager->priv->input_sources_settings;
1466

1467
1468
1469
1470
        if (g_getenv ("RUNNING_UNDER_GDM")) {
                create_sources_from_current_xkb_config (settings);
                return;
        }
1471

1472
1473
1474
        maybe_convert_old_settings (settings);

        /* if we still don't have anything do some educated guesses */
1475
        sources = g_settings_get_value (settings, KEY_INPUT_SOURCES);
1476
        if (g_variant_n_children (sources) < 1) {
1477
                create_sources_from_current_xkb_config (settings);
1478
1479
1480
1481
#ifdef HAVE_IBUS
                add_ibus_sources_from_locale (settings);
#endif
        }
1482
        g_variant_unref (sources);
1483
1484
}

1485
1486
static gboolean
start_keyboard_idle_cb (GsdKeyboardManager *manager)
William Jon McCann's avatar
William Jon McCann committed
1487
{
1488
#ifdef HAVE_IBUS
1489
        GDBusProxy *proxy;
1490
#endif
1491
1492
1493
        GVariant *prop;
        const gchar *name;

1494
1495
        gnome_settings_profile_start (NULL);

William Jon McCann's avatar
William Jon McCann committed
1496
        g_debug ("Starting keyboard manager");
1497

1498
        manager->priv->settings = g_settings_new (GSD_KEYBOARD_DIR);
1499

1500
	xkb_init (manager);
1501

1502
1503
	set_devicepresence_handler (manager);

1504
        manager->priv->input_sources_settings = g_settings_new (GNOME_DESKTOP_INPUT_SOURCES_DIR);
1505
        manager->priv->interface_settings = g_settings_new (GNOME_DESKTOP_INTERFACE_DIR);
1506
1507
        manager->priv->xkb_info = gnome_xkb_info_new ();

1508
1509
        maybe_create_input_sources (manager);

1510
#ifdef HAVE_IBUS
1511
1512
1513
1514
        proxy = gnome_settings_session_get_session_proxy ();
        prop = g_dbus_proxy_get_cached_property (proxy, "session-name");
        if (prop) {
                g_variant_get (prop, "&s", &name);
Rui Matos's avatar
Rui Matos committed
1515
                manager->priv->session_is_fallback = g_strcmp0 (name, "gnome") != 0;
1516
1517
1518
1519
1520
1521
                g_variant_unref (prop);
        } else {
                manager->priv->session_is_fallback = FALSE;
                g_warning ("failed to get SessionName, assuming gnome\n");
        }
        g_object_unref (proxy);
1522
#endif /* HAVE_IBUS */
1523

1524
        apply_input_sources_settings (manager->priv->input_sources_settings, NULL, 0, manager);
1525
        /* apply current settings before we install the callback */
Bastien Nocera's avatar
Bastien Nocera committed
1526
        g_debug ("Started the keyboard plugin, applying all settings");
1527
        apply_all_settings (manager);
1528

1529
        g_signal_connect (G_OBJECT (manager->priv->settings), "changed",
1530
                          G_CALLBACK (settings_changed), manager);
1531
        g_signal_connect (G_OBJECT (manager->priv->input_sources_settings), "change-event",