summaryrefslogtreecommitdiff
path: root/gtk/gtkimcontextsimple.c
blob: 627ed71c2367f73c17cdb1e618f991c72c6f2468 (plain)
1
2
3
4
5
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
166
167
168
169
170
171
172
173
174
175
176
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
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
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
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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
/* GTK - The GIMP Toolkit
 * Copyright (C) 2000 Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <gdk/gdk.h>

#include <stdlib.h>
#include <string.h>

#include "gtkprivate.h"
#include "gtkaccelgroup.h"
#include "gtkimcontextsimple.h"
#include "gtksettings.h"
#include "gtkwidget.h"
#include "gtkdebug.h"
#include "gtkintl.h"
#include "gtkcomposetable.h"
#include "gtkimmoduleprivate.h"

#include "gtkimcontextsimpleseqs.h"

/**
 * SECTION:gtkimcontextsimple
 * @Short_description: An input method context supporting table-based input methods
 * @Title: GtkIMContextSimple
 *
 * GtkIMContextSimple is a simple input method context supporting table-based
 * input methods. It has a built-in table of compose sequences that is derived
 * from the X11 Compose files.
 *
 * GtkIMContextSimple reads additional compose sequences from the first of the
 * following files that is found: ~/.config/gtk-3.0/Compose, ~/.XCompose,
 * /usr/share/X11/locale/$locale/Compose (for locales that have a nontrivial
 * Compose file). The syntax of these files is described in the Compose(5)
 * manual page.
 *
 * ## Unicode characters
 *
 * GtkIMContextSimple also supports numeric entry of Unicode characters
 * by typing Ctrl-Shift-u, followed by a hexadecimal Unicode codepoint.
 * For example, Ctrl-Shift-u 1 2 3 Enter yields U+0123 LATIN SMALL LETTER
 * G WITH CEDILLA, i.e. ģ.
 */

struct _GtkIMContextSimplePrivate
{
  guint16       *compose_buffer;
  int            compose_buffer_len;
  GString       *tentative_match;
  int            tentative_match_len;

  guint          in_hex_sequence : 1;
  guint          modifiers_dropped : 1;
};

/* From the values below, the value 30 means the number of different first keysyms
 * that exist in the Compose file (from Xorg). When running compose-parse.py without
 * parameters, you get the count that you can put here. Needed when updating the
 * gtkimcontextsimpleseqs.h header file (contains the compose sequences).
 */
const GtkComposeTableCompact gtk_compose_table_compact = {
  gtk_compose_seqs_compact,
  5,
  30,
  6
};

G_LOCK_DEFINE_STATIC (global_tables);
static GSList *global_tables;

static const guint16 gtk_compose_ignore[] = {
  GDK_KEY_Shift_L,
  GDK_KEY_Shift_R,
  GDK_KEY_Control_L,
  GDK_KEY_Control_R,
  GDK_KEY_Caps_Lock,
  GDK_KEY_Shift_Lock,
  GDK_KEY_Meta_L,
  GDK_KEY_Meta_R,
  GDK_KEY_Alt_L,
  GDK_KEY_Alt_R,
  GDK_KEY_Super_L,
  GDK_KEY_Super_R,
  GDK_KEY_Hyper_L,
  GDK_KEY_Hyper_R,
  GDK_KEY_Mode_switch,
  GDK_KEY_ISO_Level3_Shift
};

static void     gtk_im_context_simple_finalize           (GObject                  *obj);
static gboolean gtk_im_context_simple_filter_keypress    (GtkIMContext             *context,
							  GdkEventKey              *key);
static void     gtk_im_context_simple_reset              (GtkIMContext             *context);
static void     gtk_im_context_simple_get_preedit_string (GtkIMContext             *context,
							  char                    **str,
							  PangoAttrList           **attrs,
							  int                      *cursor_pos);
static void     gtk_im_context_simple_set_client_window  (GtkIMContext             *context,
                                                          GdkWindow                *window);


static void init_compose_table_async (GCancellable         *cancellable,
                                      GAsyncReadyCallback   callback,
                                      gpointer              user_data);

G_DEFINE_TYPE_WITH_PRIVATE (GtkIMContextSimple, gtk_im_context_simple, GTK_TYPE_IM_CONTEXT)

static void
gtk_im_context_simple_class_init (GtkIMContextSimpleClass *class)
{
  GtkIMContextClass *im_context_class = GTK_IM_CONTEXT_CLASS (class);
  GObjectClass *gobject_class = G_OBJECT_CLASS (class);

  im_context_class->filter_keypress = gtk_im_context_simple_filter_keypress;
  im_context_class->reset = gtk_im_context_simple_reset;
  im_context_class->get_preedit_string = gtk_im_context_simple_get_preedit_string;
  im_context_class->set_client_window = gtk_im_context_simple_set_client_window;
  gobject_class->finalize = gtk_im_context_simple_finalize;

  init_compose_table_async (NULL, NULL, NULL);
}

static char *
get_x11_compose_file_dir (void)
{
  char * compose_file_dir;

#if defined (X11_DATA_PREFIX)
  compose_file_dir = g_strdup (X11_DATA_PREFIX "/share/X11/locale");
#else
  compose_file_dir = g_build_filename (_gtk_get_datadir (), "X11", "locale", NULL);
#endif

  return compose_file_dir;
}

static void
gtk_im_context_simple_init_compose_table (void)
{
  char *path = NULL;
  const char *home;
  const char *locale;
  char **langs = NULL;
  char **lang = NULL;
  const char * const sys_langs[] = { "el_gr", "fi_fi", "pt_br", NULL };
  const char * const *sys_lang = NULL;
  char *x11_compose_file_dir = get_x11_compose_file_dir ();

  path = g_build_filename (g_get_user_config_dir (), "gtk-4.0", "Compose", NULL);
  if (g_file_test (path, G_FILE_TEST_EXISTS))
    {
      G_LOCK (global_tables);
      global_tables = gtk_compose_table_list_add_file (global_tables, path);
      G_UNLOCK (global_tables);

      g_free (path);
      return;
    }
  g_clear_pointer (&path, g_free);

  home = g_get_home_dir ();
  if (home == NULL)
    return;

  path = g_build_filename (home, ".XCompose", NULL);
  if (g_file_test (path, G_FILE_TEST_EXISTS))
    {
      G_LOCK (global_tables);
      global_tables = gtk_compose_table_list_add_file (global_tables, path);
      G_UNLOCK (global_tables);
      g_free (path);
      return;
    }
  g_clear_pointer (&path, g_free);

  locale = g_getenv ("LC_CTYPE");
  if (locale == NULL)
    locale = g_getenv ("LANG");
  if (locale == NULL)
    locale = "C";

  /* FIXME: https://bugzilla.gnome.org/show_bug.cgi?id=751826 */
  langs = g_get_locale_variants (locale);

  for (lang = langs; *lang; lang++)
    {
      if (g_str_has_prefix (*lang, "en_US"))
        break;
      if (**lang == 'C')
        break;

      /* Other languages just include en_us compose table. */
      for (sys_lang = sys_langs; *sys_lang; sys_lang++)
        {
          if (g_ascii_strncasecmp (*lang, *sys_lang, strlen (*sys_lang)) == 0)
            {
              path = g_build_filename (x11_compose_file_dir, *lang, "Compose", NULL);
              break;
            }
        }

      if (path == NULL)
        continue;

      if (g_file_test (path, G_FILE_TEST_EXISTS))
        break;
      g_clear_pointer (&path, g_free);
    }

  g_free (x11_compose_file_dir);
  g_strfreev (langs);

  if (path != NULL)
    {
      G_LOCK (global_tables);
      global_tables = gtk_compose_table_list_add_file (global_tables, path);
      G_UNLOCK (global_tables);
    }
  g_clear_pointer (&path, g_free);
}

static void
init_compose_table_thread_cb (GTask            *task,
                              gpointer          source_object,
                              gpointer          task_data,
                              GCancellable     *cancellable)
{
  gint64 before G_GNUC_UNUSED;

  if (g_task_return_error_if_cancelled (task))
    return;

  gtk_im_context_simple_init_compose_table ();
}

static void
init_compose_table_async (GCancellable         *cancellable,
                          GAsyncReadyCallback   callback,
                          gpointer              user_data)
{
  GTask *task = g_task_new (NULL, cancellable, callback, user_data);
  g_task_set_source_tag (task, init_compose_table_async);
  g_task_run_in_thread (task, init_compose_table_thread_cb);
  g_object_unref (task);
}

static void
gtk_im_context_simple_init (GtkIMContextSimple *context_simple)
{
  GtkIMContextSimplePrivate *priv;

  priv = context_simple->priv = gtk_im_context_simple_get_instance_private (context_simple);

  priv->compose_buffer_len = gtk_compose_table_compact.max_seq_len + 1;
  priv->compose_buffer = g_new0 (guint16, priv->compose_buffer_len);
  priv->tentative_match = g_string_new ("");
  priv->tentative_match_len = 0;
}

static void
gtk_im_context_simple_finalize (GObject *obj)
{
  GtkIMContextSimple *context_simple = GTK_IM_CONTEXT_SIMPLE (obj);
  GtkIMContextSimplePrivate *priv = context_simple->priv;;

  g_free (priv->compose_buffer);
  g_string_free (priv->tentative_match, TRUE);

  G_OBJECT_CLASS (gtk_im_context_simple_parent_class)->finalize (obj);
}

/**
 * gtk_im_context_simple_new:
 * 
 * Creates a new #GtkIMContextSimple.
 *
 * Returns: a new #GtkIMContextSimple.
 **/
GtkIMContext *
gtk_im_context_simple_new (void)
{
  return g_object_new (GTK_TYPE_IM_CONTEXT_SIMPLE, NULL);
}

static void
gtk_im_context_simple_commit_string (GtkIMContextSimple *context_simple,
                                     const char         *str)
{
  GtkIMContextSimplePrivate *priv = context_simple->priv;
  priv->in_hex_sequence = FALSE;
  g_string_set_size (priv->tentative_match, 0);
  priv->tentative_match_len = 0;
  priv->compose_buffer[0] = 0;

  g_signal_emit_by_name (context_simple, "preedit-changed");
  g_signal_emit_by_name (context_simple, "preedit-end");
  g_signal_emit_by_name (context_simple, "commit", str);
}

static void
gtk_im_context_simple_commit_char (GtkIMContextSimple *context_simple,
                                   gunichar            ch)
{
  char buf[8] = { 0, };

  g_unichar_to_utf8 (ch, buf);

  gtk_im_context_simple_commit_string (context_simple, buf);
}

/* In addition to the table-driven sequences, we allow Unicode hex
 * codes to be entered. The method chosen here is similar to the
 * one recommended in ISO 14755, but not exactly the same, since we
 * don’t want to steal 16 valuable key combinations.
 *
 * A hex Unicode sequence must be started with Ctrl-Shift-U, followed
 * by a sequence of hex digits entered with Ctrl-Shift still held.
 * Releasing one of the modifiers or pressing space while the modifiers
 * are still held commits the character. It is possible to erase
 * digits using backspace.
 *
 * As an extension to the above, we also allow to start the sequence
 * with Ctrl-Shift-U, then release the modifiers before typing any
 * digits, and enter the digits without modifiers.
 */

static gboolean
check_hex (GtkIMContextSimple *context_simple,
           int                 n_compose)
{
  GtkIMContextSimplePrivate *priv = context_simple->priv;
  /* See if this is a hex sequence, return TRUE if so */
  int i;
  GString *str;
  gulong n;
  char *nptr = NULL;
  char buf[7];

  g_string_set_size (priv->tentative_match, 0);
  priv->tentative_match_len = 0;

  str = g_string_new (NULL);
  
  i = 0;
  while (i < n_compose)
    {
      gunichar ch;
      
      ch = gdk_keyval_to_unicode (priv->compose_buffer[i]);
      
      if (ch == 0)
        return FALSE;

      if (!g_unichar_isxdigit (ch))
        return FALSE;

      buf[g_unichar_to_utf8 (ch, buf)] = '\0';

      g_string_append (str, buf);
      
      ++i;
    }

  n = strtoul (str->str, &nptr, 16);

  /* If strtoul fails it probably means non-latin digits were used;
   * we should in principle handle that, but we probably don't.
   */
  if (nptr - str->str < str->len)
    {
      g_string_free (str, TRUE);
      return FALSE;
    }
  else
    g_string_free (str, TRUE);

  if (g_unichar_validate (n))
    {
      g_string_set_size (priv->tentative_match, 0);
      g_string_append_unichar (priv->tentative_match, n);
      priv->tentative_match_len = n_compose;
    }
  
  return TRUE;
}

static void
beep_window (GdkWindow *window)
{
  GdkScreen *screen = gdk_window_get_screen (window);
  gboolean   beep;

  g_object_get (gtk_settings_get_for_screen (screen),
                "gtk-error-bell", &beep,
                NULL);

  if (beep)
    gdk_window_beep (window);
}

static gboolean
no_sequence_matches (GtkIMContextSimple *context_simple,
                     int                 n_compose,
                     GdkEventKey        *event)
{
  GtkIMContextSimplePrivate *priv = context_simple->priv;
  GtkIMContext *context;
  gunichar ch;

  context = GTK_IM_CONTEXT (context_simple);
  
  /* No compose sequences found, check first if we have a partial
   * match pending.
   */
  if (priv->tentative_match_len > 0)
    {
      int len = priv->tentative_match_len;
      int i;
      guint16 *compose_buffer;
      char *str;

      compose_buffer = alloca (sizeof (guint16) * priv->compose_buffer_len);

      memcpy (compose_buffer, priv->compose_buffer, sizeof (guint16) * priv->compose_buffer_len);

      str = g_strdup (priv->tentative_match->str);
      gtk_im_context_simple_commit_string (context_simple, str);
      g_free (str);

      for (i = 0; i < n_compose - len - 1; i++)
        {
          GdkEvent *tmp_event = gdk_event_copy ((GdkEvent *)event);
          tmp_event->key.keyval = compose_buffer[len + i];
	  
	  gtk_im_context_filter_keypress (context, (GdkEventKey *)tmp_event);
	  gdk_event_free (tmp_event);
	}

      return gtk_im_context_filter_keypress (context, event);
    }
  else
    {
      priv->compose_buffer[0] = 0;
      if (n_compose > 1)		/* Invalid sequence */
	{
	  beep_window (event->window);
          g_signal_emit_by_name (context, "preedit-changed");
          g_signal_emit_by_name (context, "preedit-end");
	  return TRUE;
	}
  
      ch = gdk_keyval_to_unicode (event->keyval);
      if (ch != 0 && !g_unichar_iscntrl (ch))
	{
	  gtk_im_context_simple_commit_char (context_simple, ch);
	  return TRUE;
	}
      else
	return FALSE;
    }
  return FALSE;
}

static gboolean
is_hex_keyval (guint keyval)
{
  gunichar ch = gdk_keyval_to_unicode (keyval);

  return g_unichar_isxdigit (ch);
}

static guint
canonical_hex_keyval (GdkEventKey *event)
{
  GdkKeymap *keymap = gdk_keymap_get_for_display (gdk_window_get_display (event->window));
  guint keyval;
  guint *keyvals = NULL;
  int n_vals = 0;
  int i;

  /* See if the keyval is already a hex digit */
  if (is_hex_keyval (event->keyval))
    return event->keyval;

  /* See if this key would have generated a hex keyval in
   * any other state, and return that hex keyval if so
   */
  gdk_keymap_get_entries_for_keycode (keymap,
                                      event->hardware_keycode,
                                      NULL,
                                      &keyvals, &n_vals);

  keyval = 0;
  i = 0;
  while (i < n_vals)
    {
      if (is_hex_keyval (keyvals[i]))
        {
          keyval = keyvals[i];
          break;
        }

      ++i;
    }

  g_free (keyvals);
  
  if (keyval)
    return keyval;
  else
    /* No way to make it a hex digit
     */
    return 0;
}

static gboolean
gtk_im_context_simple_filter_keypress (GtkIMContext *context,
				       GdkEventKey  *event)
{
  GtkIMContextSimple *context_simple = GTK_IM_CONTEXT_SIMPLE (context);
  GtkIMContextSimplePrivate *priv = context_simple->priv;
  GdkDisplay *display = gdk_window_get_display (event->window);
  GSList *tmp_list;
  int n_compose = 0;
  GdkModifierType hex_mod_mask;
  gboolean have_hex_mods;
  gboolean is_hex_start;
  gboolean is_hex_end;
  gboolean is_backspace;
  gboolean is_escape;
  guint hex_keyval;
  int i;
  gboolean compose_finish;
  gboolean compose_match;
  gunichar output_char;

  while (priv->compose_buffer[n_compose] != 0 && n_compose < priv->compose_buffer_len)
    n_compose++;

  if (event->type == GDK_KEY_RELEASE)
    {
      if (priv->in_hex_sequence &&
          (event->keyval == GDK_KEY_Control_L || event->keyval == GDK_KEY_Control_R ||
	   event->keyval == GDK_KEY_Shift_L || event->keyval == GDK_KEY_Shift_R))
	{
          if (priv->tentative_match->len > 0)
	    {
              char *str = g_strdup (priv->tentative_match->str);
	      gtk_im_context_simple_commit_string (context_simple, str);
              g_free (str);

	      return TRUE;
	    }
	  else if (n_compose == 0)
	    {
	      priv->modifiers_dropped = TRUE;

	      return TRUE;
	    }
	  else if (priv->in_hex_sequence)
	    {
	      /* invalid hex sequence */
	      beep_window (event->window);

              g_string_set_size (priv->tentative_match, 0);
	      priv->in_hex_sequence = FALSE;
	      priv->compose_buffer[0] = 0;

	      g_signal_emit_by_name (context_simple, "preedit-changed");
	      g_signal_emit_by_name (context_simple, "preedit-end");

	      return TRUE;
	    }
	}

      return FALSE;
    }

  /* Ignore modifier key presses */
  for (i = 0; i < G_N_ELEMENTS (gtk_compose_ignore); i++)
    if (event->keyval == gtk_compose_ignore[i])
      return FALSE;

  hex_mod_mask = gdk_keymap_get_modifier_mask (gdk_keymap_get_for_display (display),
                                               GDK_MODIFIER_INTENT_PRIMARY_ACCELERATOR);
  hex_mod_mask |= GDK_SHIFT_MASK;

  if (priv->in_hex_sequence && priv->modifiers_dropped)
    have_hex_mods = TRUE;
  else
    have_hex_mods = (event->state & (hex_mod_mask)) == hex_mod_mask;
  is_hex_start = event->keyval == GDK_KEY_U;
  is_hex_end = (event->keyval == GDK_KEY_space ||
                event->keyval == GDK_KEY_KP_Space ||
                event->keyval == GDK_KEY_Return ||
                event->keyval == GDK_KEY_ISO_Enter ||
                event->keyval == GDK_KEY_KP_Enter);
  is_backspace = event->keyval == GDK_KEY_BackSpace;
  is_escape = event->keyval == GDK_KEY_Escape;
  hex_keyval = canonical_hex_keyval (event);

  /* If we are already in a non-hex sequence, or
   * this keystroke is not hex modifiers + hex digit, don't filter
   * key events with accelerator modifiers held down. We only treat
   * Control and Alt as accel modifiers here, since Super, Hyper and
   * Meta are often co-located with Mode_Switch, Multi_Key or
   * ISO_Level3_Switch.
   */
  if (!have_hex_mods ||
      (n_compose > 0 && !priv->in_hex_sequence) ||
      (n_compose == 0 && !priv->in_hex_sequence && !is_hex_start) ||
      (priv->in_hex_sequence && !hex_keyval &&
       !is_hex_start && !is_hex_end && !is_escape && !is_backspace))
    {
      GdkModifierType no_text_input_mask;

      no_text_input_mask =
        gdk_keymap_get_modifier_mask (gdk_keymap_get_for_display (display),
                                      GDK_MODIFIER_INTENT_NO_TEXT_INPUT);

      if (event->state & no_text_input_mask ||
	  (priv->in_hex_sequence && priv->modifiers_dropped &&
	   (event->keyval == GDK_KEY_Return ||
	    event->keyval == GDK_KEY_ISO_Enter ||
	    event->keyval == GDK_KEY_KP_Enter)))
	{
	  return FALSE;
	}
    }
  
  /* Handle backspace */
  if (priv->in_hex_sequence && have_hex_mods && is_backspace)
    {
      if (n_compose > 0)
	{
	  n_compose--;
	  priv->compose_buffer[n_compose] = 0;
          check_hex (context_simple, n_compose);
	}
      else
	{
	  priv->in_hex_sequence = FALSE;
	}

      g_signal_emit_by_name (context_simple, "preedit-changed");

      if (!priv->in_hex_sequence)
        g_signal_emit_by_name (context_simple, "preedit-end");
      
      return TRUE;
    }

  if (!priv->in_hex_sequence && n_compose > 0 && is_backspace)
    {
      n_compose--;
      priv->compose_buffer[n_compose] = 0;

      g_signal_emit_by_name (context_simple, "preedit-changed");

      if (n_compose == 0)
        g_signal_emit_by_name (context_simple, "preedit-end");

      return TRUE;
    }

  /* Check for hex sequence restart */
  if (priv->in_hex_sequence && have_hex_mods && is_hex_start)
    {
      if (priv->tentative_match->len > 0)
	{
          char *str = g_strdup (priv->tentative_match->str);
	  gtk_im_context_simple_commit_string (context_simple, str);
          g_free (str);
	}
      else
	{
	  /* invalid hex sequence */
	  if (n_compose > 0)
	    beep_window (event->window);

          g_string_set_size (priv->tentative_match, 0);
	  priv->in_hex_sequence = FALSE;
	  priv->compose_buffer[0] = 0;
	}
    }
  
  /* Check for hex sequence start */
  if (!priv->in_hex_sequence && have_hex_mods && is_hex_start)
    {
      priv->compose_buffer[0] = 0;
      priv->in_hex_sequence = TRUE;
      priv->modifiers_dropped = FALSE;
      g_string_set_size (priv->tentative_match, 0);

      g_signal_emit_by_name (context_simple, "preedit-start");
      g_signal_emit_by_name (context_simple, "preedit-changed");
  
      return TRUE;
    }
  
  /* Then, check for compose sequences */
  if (priv->in_hex_sequence)
    {
      if (hex_keyval && n_compose < 6)
	priv->compose_buffer[n_compose++] = hex_keyval;
      else if (is_escape)
	{
	  gtk_im_context_simple_reset (context);
	  return TRUE;
	}
      else if (!is_hex_end)
	{
	  /* non-hex character in hex sequence, or sequence too long */
	  beep_window (event->window);
	  return TRUE;
	}
    }
  else
    {
      if (n_compose + 1 == priv->compose_buffer_len)
        {
          priv->compose_buffer_len += 1;
          priv->compose_buffer = g_renew (guint16, priv->compose_buffer, priv->compose_buffer_len);
        }

      priv->compose_buffer[n_compose++] = event->keyval;
    }

  priv->compose_buffer[n_compose] = 0;

  if (priv->in_hex_sequence)
    {
      /* If the modifiers are still held down, consider the sequence again */
      if (have_hex_mods)
        {
          /* space or return ends the sequence, and we eat the key */
          if (n_compose > 0 && is_hex_end)
            {
	      if (priv->tentative_match->len > 0)
		{
                  char *str = g_strdup (priv->tentative_match->str);
		  gtk_im_context_simple_commit_string (context_simple, str);
                  g_free (str);
		}
	      else
		{
		  /* invalid hex sequence */
		  beep_window (event->window);

                  g_string_set_size (priv->tentative_match, 0);
		  priv->in_hex_sequence = FALSE;
		  priv->compose_buffer[0] = 0;
		}
            }
          else if (!check_hex (context_simple, n_compose))
	    beep_window (event->window);

	  g_signal_emit_by_name (context_simple, "preedit-changed");

	  if (!priv->in_hex_sequence)
	    g_signal_emit_by_name (context_simple, "preedit-end");

	  return TRUE;
        }
    }
  else
    {
      gboolean success = FALSE;
      GString *output;

      output = g_string_new ("");

      G_LOCK (global_tables);

      tmp_list = global_tables;
      while (tmp_list)
        {
          if (gtk_compose_table_check ((GtkComposeTable *)tmp_list->data,
                                       priv->compose_buffer, n_compose,
                                       &compose_finish, &compose_match,
                                       output))
            {
              if (compose_finish)
                {
                  if (compose_match)
                    gtk_im_context_simple_commit_string (context_simple, output->str);
                }
              else
                {
                  if (compose_match)
                    {
                      g_string_assign (priv->tentative_match, output->str);
                      priv->tentative_match_len = n_compose;
                    }
                  g_signal_emit_by_name (context_simple, "preedit-changed");
                }

              success = TRUE;
              break;
            }

          tmp_list = tmp_list->next;
        }

      G_UNLOCK (global_tables);

      g_string_free (output, TRUE);

      if (success)
        return TRUE;

      if (gtk_compose_table_compact_check (&gtk_compose_table_compact,
                                           priv->compose_buffer, n_compose,
                                           &compose_finish, &compose_match,
                                           &output_char))
        {
          if (compose_finish)
            {
              if (compose_match)
                gtk_im_context_simple_commit_char (context_simple, output_char);
            }
          else
            {
              if (compose_match)
                {
                  g_string_set_size (priv->tentative_match, 0);
                  g_string_append_unichar (priv->tentative_match, output_char);
                  priv->tentative_match_len = n_compose;
                }
              g_signal_emit_by_name (context_simple, "preedit-changed");
            }

          return TRUE;
        }

      if (gtk_check_algorithmically (priv->compose_buffer, n_compose, &output_char))
        {
          if (output_char)
            gtk_im_context_simple_commit_char (context_simple, output_char);
          return TRUE;
        }
    }

  /* The current compose_buffer doesn't match anything */
  return no_sequence_matches (context_simple, n_compose, event);
}

static void
gtk_im_context_simple_reset (GtkIMContext *context)
{
  GtkIMContextSimple *context_simple = GTK_IM_CONTEXT_SIMPLE (context);
  GtkIMContextSimplePrivate *priv = context_simple->priv;

  priv->compose_buffer[0] = 0;

  if (priv->tentative_match->len > 0 || priv->in_hex_sequence)
    {
      priv->in_hex_sequence = FALSE;
      g_string_set_size (priv->tentative_match, 0);
      priv->tentative_match_len = 0;
      g_signal_emit_by_name (context_simple, "preedit-changed");
      g_signal_emit_by_name (context_simple, "preedit-end");
    }
}

static void
gtk_im_context_simple_get_preedit_string (GtkIMContext   *context,
                                          char          **str,
                                          PangoAttrList **attrs,
                                          int            *cursor_pos)
{
  GtkIMContextSimple *context_simple = GTK_IM_CONTEXT_SIMPLE (context);
  GtkIMContextSimplePrivate *priv = context_simple->priv;
  GString *s;
  int i;

  s = g_string_new ("");

  if (priv->in_hex_sequence)
    {
      g_string_append_c (s, 'u');

      for (i = 0; priv->compose_buffer[i]; i++)
        g_string_append_unichar (s, gdk_keyval_to_unicode (priv->compose_buffer[i]));
    }
  else if (priv->tentative_match->len > 0 && priv->compose_buffer[0] != 0)
    {
       g_string_append (s, priv->tentative_match->str);
    }
  else
    {
      for (i = 0; priv->compose_buffer[i]; i++)
        {
          if (priv->compose_buffer[i] == GDK_KEY_Multi_key)
            g_string_append_unichar (s, 0x2384); /* U+2384 COMPOSITION SYMBOL */
          else
            g_string_append_unichar (s, gdk_keyval_to_unicode (priv->compose_buffer[i]));
        }
    }

  if (cursor_pos)
    *cursor_pos = s->len;

  if (attrs)
    {
      *attrs = pango_attr_list_new ();

      if (s->len)
        {
          PangoAttribute *attr = pango_attr_underline_new (PANGO_UNDERLINE_SINGLE);
          attr->start_index = 0;
          attr->end_index = s->len;
          pango_attr_list_insert (*attrs, attr);
        }
    }

  if (str)
    *str = g_string_free (s, FALSE);
}

static void
gtk_im_context_simple_set_client_window  (GtkIMContext *context,
                                          GdkWindow    *window)
{
}

/**
 * gtk_im_context_simple_add_table: (skip)
 * @context_simple: A #GtkIMContextSimple
 * @data: (array): the table
 * @max_seq_len: Maximum length of a sequence in the table
 * @n_seqs: number of sequences in the table
 *
 * Adds an additional table to search to the input context.
 * Each row of the table consists of @max_seq_len key symbols
 * followed by two #guint16 interpreted as the high and low
 * words of a #gunicode value. Tables are searched starting
 * from the last added.
 *
 * The table must be sorted in dictionary order on the
 * numeric value of the key symbol fields. (Values beyond
 * the length of the sequence should be zero.)
 **/
void
gtk_im_context_simple_add_table (GtkIMContextSimple *context_simple,
				 guint16            *data,
				 int                 max_seq_len,
				 int                 n_seqs)
{
  g_return_if_fail (GTK_IS_IM_CONTEXT_SIMPLE (context_simple));

  G_LOCK (global_tables);

  global_tables = gtk_compose_table_list_add_array (global_tables,
                                                    data, max_seq_len, n_seqs);

  G_UNLOCK (global_tables);
}

/**
 * gtk_im_context_simple_add_compose_file:
 * @context_simple: A #GtkIMContextSimple
 * @compose_file: The path of compose file
 *
 * Adds an additional table from the X11 compose file.
 */
void
gtk_im_context_simple_add_compose_file (GtkIMContextSimple *context_simple,
                                        const char         *compose_file)
{
  g_return_if_fail (GTK_IS_IM_CONTEXT_SIMPLE (context_simple));

  G_LOCK (global_tables);

  global_tables = gtk_compose_table_list_add_file (global_tables, compose_file);

  G_UNLOCK (global_tables);
}