gtkimmodule.c 22.4 KB
Newer Older
Cody Russell's avatar
Cody Russell committed
1
/* GTK - The GIMP Toolkit
Owen Taylor's avatar
Owen Taylor committed
2 3 4 5 6 7 8 9 10 11 12 13 14
 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * 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
Javier Jardón's avatar
Javier Jardón committed
15
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.Free
Owen Taylor's avatar
Owen Taylor committed
16 17 18 19 20 21 22 23
 */

/*
 * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
 * file for a list of people on the GTK+ Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GTK+ at ftp://ftp.gtk.org/pub/gtk/. 
 */
24

25
#include "config.h"
26

Owen Taylor's avatar
Owen Taylor committed
27 28 29 30 31
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

32
#include <glib/gstdio.h>
Owen Taylor's avatar
Owen Taylor committed
33
#include <gmodule.h>
34
#include "gtkimmoduleprivate.h"
Owen Taylor's avatar
Owen Taylor committed
35
#include "gtkimcontextsimple.h"
36
#include "gtksettings.h"
37
#include "gtkprivate.h"
38
#include "gtkutilsprivate.h"
Owen Taylor's avatar
Owen Taylor committed
39 40
#include "gtkintl.h"

41 42 43 44 45 46 47 48
#ifdef GDK_WINDOWING_X11
#include "x11/gdkx.h"
#endif

#ifdef GDK_WINDOWING_WAYLAND
#include "wayland/gdkwayland.h"
#endif

49 50 51 52
#ifdef GDK_WINDOWING_BROADWAY
#include "broadway/gdkbroadway.h"
#endif

53 54 55 56
#ifdef GDK_WINDOWING_WIN32
#include "win32/gdkwin32.h"
#endif

57 58 59 60
#ifdef G_OS_WIN32
#include <windows.h>
#endif

61 62 63 64 65
#undef GDK_DEPRECATED
#undef GDK_DEPRECATED_FOR
#define GDK_DEPRECATED
#define GDK_DEPRECATED_FOR(f)

Benjamin Otte's avatar
Benjamin Otte committed
66 67
#include "deprecated/gtkrc.h"

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
/* We need to call getc() a lot in a loop. This is suboptimal,
 * as getc() does thread locking on the FILE it is given.
 * To optimize that, lock the file first, then call getc(),
 * then unlock.
 * If locking functions are not present in libc, fall back
 * to the suboptimal getc().
 */
#if !defined(HAVE_FLOCKFILE) && !defined(HAVE__LOCK_FILE)
#  define flockfile(f) (void)1
#  define funlockfile(f) (void)1
#  define getc_unlocked(f) getc(f)
#elif !defined(HAVE_FLOCKFILE) && defined(HAVE__LOCK_FILE)
#  define flockfile(f) _lock_file(f)
#  define funlockfile(f) _unlock_file(f)
#  define getc_unlocked(f) _getc_nolock(f)
#endif

Owen Taylor's avatar
Owen Taylor committed
85
#define SIMPLE_ID "gtk-im-context-simple"
86
#define NONE_ID   "gtk-im-context-none"
Owen Taylor's avatar
Owen Taylor committed
87

88 89 90 91
/**
 * GtkIMContextInfo:
 * @context_id: The unique identification string of the input method.
 * @context_name: The human-readable name of the input method.
Matthias Clasen's avatar
Matthias Clasen committed
92 93
 * @domain: Translation domain to be used with dgettext()
 * @domain_dirname: Name of locale directory for use with bindtextdomain()
94
 * @default_locales: A colon-separated list of locales where this input method
95
 *   should be the default. The asterisk “*” sets the default for all locales.
96 97 98 99
 *
 * Bookkeeping information about a loadable input method.
 */

Owen Taylor's avatar
Owen Taylor committed
100 101 102 103 104 105 106 107 108 109 110
typedef struct _GtkIMModule      GtkIMModule;
typedef struct _GtkIMModuleClass GtkIMModuleClass;

#define GTK_TYPE_IM_MODULE          (gtk_im_module_get_type ())
#define GTK_IM_MODULE(im_module)    (G_TYPE_CHECK_INSTANCE_CAST ((im_module), GTK_TYPE_IM_MODULE, GtkIMModule))
#define GTK_IS_IM_MODULE(im_module) (G_TYPE_CHECK_INSTANCE_TYPE ((im_module), GTK_TYPE_IM_MODULE))

struct _GtkIMModule
{
  GTypeModule parent_instance;
  
111 112
  gboolean builtin;

Owen Taylor's avatar
Owen Taylor committed
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
  GModule *library;

  void          (*list)   (const GtkIMContextInfo ***contexts,
 		           guint                    *n_contexts);
  void          (*init)   (GTypeModule              *module);
  void          (*exit)   (void);
  GtkIMContext *(*create) (const gchar              *context_id);

  GtkIMContextInfo **contexts;
  guint n_contexts;

  gchar *path;
};

struct _GtkIMModuleClass 
{
  GTypeModuleClass parent_class;
};

132
static GType gtk_im_module_get_type (void);
Owen Taylor's avatar
Owen Taylor committed
133

134
static gint n_loaded_contexts = 0;
Owen Taylor's avatar
Owen Taylor committed
135 136 137 138 139 140 141 142
static GHashTable *contexts_hash = NULL;
static GSList *modules_list = NULL;

static gboolean
gtk_im_module_load (GTypeModule *module)
{
  GtkIMModule *im_module = GTK_IM_MODULE (module);
  
143
  if (!im_module->builtin)
Owen Taylor's avatar
Owen Taylor committed
144
    {
145 146 147
      im_module->library = g_module_open (im_module->path, G_MODULE_BIND_LAZY | G_MODULE_BIND_LOCAL);
      if (!im_module->library)
	{
148
	  g_warning ("%s", g_module_error());
149 150
	  return FALSE;
	}
Owen Taylor's avatar
Owen Taylor committed
151
  
152 153 154 155 156 157 158 159 160 161
      /* extract symbols from the lib */
      if (!g_module_symbol (im_module->library, "im_module_init",
			    (gpointer *)&im_module->init) ||
	  !g_module_symbol (im_module->library, "im_module_exit", 
			    (gpointer *)&im_module->exit) ||
	  !g_module_symbol (im_module->library, "im_module_list", 
			    (gpointer *)&im_module->list) ||
	  !g_module_symbol (im_module->library, "im_module_create", 
			    (gpointer *)&im_module->create))
	{
162
	  g_warning ("%s", g_module_error());
163 164 165 166
	  g_module_close (im_module->library);
	  
	  return FALSE;
	}
Owen Taylor's avatar
Owen Taylor committed
167 168
    }
	    
169
  /* call the module's init function to let it */
Owen Taylor's avatar
Owen Taylor committed
170 171 172 173 174 175 176 177 178 179 180 181 182
  /* setup anything it needs to set up. */
  im_module->init (module);

  return TRUE;
}

static void
gtk_im_module_unload (GTypeModule *module)
{
  GtkIMModule *im_module = GTK_IM_MODULE (module);
  
  im_module->exit();

183 184 185 186
  if (!im_module->builtin)
    {
      g_module_close (im_module->library);
      im_module->library = NULL;
Owen Taylor's avatar
Owen Taylor committed
187

188 189 190 191 192
      im_module->init = NULL;
      im_module->exit = NULL;
      im_module->list = NULL;
      im_module->create = NULL;
    }
Owen Taylor's avatar
Owen Taylor committed
193 194
}

195 196
G_DEFINE_TYPE (GtkIMModule, gtk_im_module, G_TYPE_TYPE_MODULE)

Owen Taylor's avatar
Owen Taylor committed
197 198 199 200 201 202 203 204 205 206
/* This only will ever be called if an error occurs during
 * initialization
 */
static void
gtk_im_module_finalize (GObject *object)
{
  GtkIMModule *module = GTK_IM_MODULE (object);

  g_free (module->path);

207
  G_OBJECT_CLASS (gtk_im_module_parent_class)->finalize (object);
Owen Taylor's avatar
Owen Taylor committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221
}

static void
gtk_im_module_class_init (GtkIMModuleClass *class)
{
  GTypeModuleClass *module_class = G_TYPE_MODULE_CLASS (class);
  GObjectClass *gobject_class = G_OBJECT_CLASS (class);

  module_class->load = gtk_im_module_load;
  module_class->unload = gtk_im_module_unload;

  gobject_class->finalize = gtk_im_module_finalize;
}

222 223
static void 
gtk_im_module_init (GtkIMModule* object)
Owen Taylor's avatar
Owen Taylor committed
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
{
}

static void
free_info (GtkIMContextInfo *info)
{
  g_free ((char *)info->context_id);
  g_free ((char *)info->context_name);
  g_free ((char *)info->domain);
  g_free ((char *)info->domain_dirname);
  g_free ((char *)info->default_locales);
  g_free (info);
}

static void
add_module (GtkIMModule *module, GSList *infos)
{
  GSList *tmp_list = infos;
  gint i = 0;
  gint n = g_slist_length (infos);
  module->contexts = g_new (GtkIMContextInfo *, n);

  while (tmp_list)
    {
      GtkIMContextInfo *info = tmp_list->data;
  
      if (g_hash_table_lookup (contexts_hash, info->context_id))
	{
	  free_info (info);	/* Duplicate */
	}
      else
	{
	  g_hash_table_insert (contexts_hash, (char *)info->context_id, module);
	  module->contexts[i++] = tmp_list->data;
	  n_loaded_contexts++;
	}
      
      tmp_list = tmp_list->next;
    }
  g_slist_free (infos);
  module->n_contexts = i;

  modules_list = g_slist_prepend (modules_list, module);
}

Tor Lillqvist's avatar
Tor Lillqvist committed
269
#ifdef G_OS_WIN32
270

271 272 273
static void
correct_libdir_prefix (gchar **path)
{
274
  /* GTK_LIBDIR is the build-time libdir */
275 276 277 278 279 280 281 282 283 284 285
  if (strncmp (*path, GTK_LIBDIR, strlen (GTK_LIBDIR)) == 0)
    {
      /* This is an entry put there by make install on the
       * packager's system. On Windows a prebuilt GTK+
       * package can be installed in a random
       * location. The gtk.immodules file distributed in
       * such a package contains paths from the package
       * builder's machine. Replace the path with the real
       * one on this machine.
       */
      gchar *tem = *path;
286
      *path = g_strconcat (_gtk_get_libdir (), tem + strlen (GTK_LIBDIR), NULL);
287 288 289
      g_free (tem);
    }
}
Tor Lillqvist's avatar
Tor Lillqvist committed
290 291 292 293

static void
correct_localedir_prefix (gchar **path)
{
294
  /* See above */
Tor Lillqvist's avatar
Tor Lillqvist committed
295 296 297 298 299 300 301
  if (strncmp (*path, GTK_LOCALEDIR, strlen (GTK_LOCALEDIR)) == 0)
    {
      gchar *tem = *path;
      *path = g_strconcat (_gtk_get_localedir (), tem + strlen (GTK_LOCALEDIR), NULL);
      g_free (tem);
    }
}
302 303 304
#endif


305
G_GNUC_UNUSED static GtkIMModule *
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
add_builtin_module (const gchar             *module_name,
		    const GtkIMContextInfo **contexts,
		    int                      n_contexts)
{
  GtkIMModule *module = g_object_new (GTK_TYPE_IM_MODULE, NULL);
  GSList *infos = NULL;
  int i;

  for (i = 0; i < n_contexts; i++)
    {
      GtkIMContextInfo *info = g_new (GtkIMContextInfo, 1);
      info->context_id = g_strdup (contexts[i]->context_id);
      info->context_name = g_strdup (contexts[i]->context_name);
      info->domain = g_strdup (contexts[i]->domain);
      info->domain_dirname = g_strdup (contexts[i]->domain_dirname);
#ifdef G_OS_WIN32
      correct_localedir_prefix ((char **) &info->domain_dirname);
#endif
      info->default_locales = g_strdup (contexts[i]->default_locales);
      infos = g_slist_prepend (infos, info);
    }

  module->builtin = TRUE;
  g_type_module_set_name (G_TYPE_MODULE (module), module_name);
  add_module (module, infos);

  return module;
}

Owen Taylor's avatar
Owen Taylor committed
335
static void
336
gtk_im_module_initialize (void)
Owen Taylor's avatar
Owen Taylor committed
337 338 339
{
  GString *line_buf = g_string_new (NULL);
  GString *tmp_buf = g_string_new (NULL);
Owen Taylor's avatar
Owen Taylor committed
340
  gchar *filename = gtk_rc_get_im_module_file();
Owen Taylor's avatar
Owen Taylor committed
341 342 343 344 345 346 347 348
  FILE *file;
  gboolean have_error = FALSE;

  GtkIMModule *module = NULL;
  GSList *infos = NULL;

  contexts_hash = g_hash_table_new (g_str_hash, g_str_equal);

349 350 351 352 353
#define do_builtin(m)							\
  {									\
    const GtkIMContextInfo **contexts;					\
    int n_contexts;							\
    extern void _gtk_immodule_ ## m ## _list (const GtkIMContextInfo ***contexts, \
354
					      int                      *n_contexts); \
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
    extern void _gtk_immodule_ ## m ## _init (GTypeModule *module);	\
    extern void _gtk_immodule_ ## m ## _exit (void);			\
    extern GtkIMContext *_gtk_immodule_ ## m ## _create (const gchar *context_id); \
									\
    _gtk_immodule_ ## m ## _list (&contexts, &n_contexts);		\
    module = add_builtin_module (#m, contexts, n_contexts);		\
    module->init = _gtk_immodule_ ## m ## _init;			\
    module->exit = _gtk_immodule_ ## m ## _exit;			\
    module->create = _gtk_immodule_ ## m ## _create;			\
    module = NULL;							\
  }

#ifdef INCLUDE_IM_am_et
  do_builtin (am_et);
#endif
#ifdef INCLUDE_IM_cedilla
  do_builtin (cedilla);
#endif
#ifdef INCLUDE_IM_cyrillic_translit
  do_builtin (cyrillic_translit);
#endif
#ifdef INCLUDE_IM_ime
  do_builtin (ime);
#endif
#ifdef INCLUDE_IM_inuktitut
  do_builtin (inuktitut);
#endif
#ifdef INCLUDE_IM_ipa
  do_builtin (ipa);
#endif
#ifdef INCLUDE_IM_multipress
  do_builtin (multipress);
#endif
#ifdef INCLUDE_IM_thai
  do_builtin (thai);
#endif
#ifdef INCLUDE_IM_ti_er
  do_builtin (ti_er);
#endif
#ifdef INCLUDE_IM_ti_et
  do_builtin (ti_et);
#endif
#ifdef INCLUDE_IM_viqr
  do_builtin (viqr);
#endif
#ifdef INCLUDE_IM_xim
  do_builtin (xim);
#endif
403 404 405
#ifdef INCLUDE_IM_broadway
  do_builtin (broadway);
#endif
406 407 408
#ifdef INCLUDE_IM_wayland
  do_builtin (wayland);
#endif
409 410 411

#undef do_builtin

412
  file = g_fopen (filename, "r");
Owen Taylor's avatar
Owen Taylor committed
413 414
  if (!file)
    {
415 416 417 418 419 420
      /* In case someone wants only the default input method,
       * we allow no file at all.
       */
      g_string_free (line_buf, TRUE);
      g_string_free (tmp_buf, TRUE);
      g_free (filename);
Owen Taylor's avatar
Owen Taylor committed
421 422 423
      return;
    }

424
  while (!have_error && gtk_read_line (file, line_buf))
Owen Taylor's avatar
Owen Taylor committed
425 426
    {
      const char *p;
427

Owen Taylor's avatar
Owen Taylor committed
428 429
      p = line_buf->str;

430
      if (!gtk_skip_space (&p))
Owen Taylor's avatar
Owen Taylor committed
431 432 433 434 435 436 437 438 439
	{
	  /* Blank line marking the end of a module
	   */
	  if (module && *p != '#')
	    {
	      add_module (module, infos);
	      module = NULL;
	      infos = NULL;
	    }
440

Owen Taylor's avatar
Owen Taylor committed
441 442 443 444 445 446 447 448 449
	  continue;
	}

      if (!module)
	{
	  /* Read a module location
	   */
	  module = g_object_new (GTK_TYPE_IM_MODULE, NULL);

450
	  if (!gtk_scan_string (&p, tmp_buf) || gtk_skip_space (&p))
Owen Taylor's avatar
Owen Taylor committed
451
	    {
452
	      g_warning ("Error parsing context info in '%s'\n  %s", filename, line_buf->str);
Owen Taylor's avatar
Owen Taylor committed
453 454 455 456
	      have_error = TRUE;
	    }

	  module->path = g_strdup (tmp_buf->str);
Tor Lillqvist's avatar
Tor Lillqvist committed
457
#ifdef G_OS_WIN32
458 459
	  correct_libdir_prefix (&module->path);
#endif
Owen Taylor's avatar
Owen Taylor committed
460 461 462 463 464
	  g_type_module_set_name (G_TYPE_MODULE (module), module->path);
	}
      else
	{
	  GtkIMContextInfo *info = g_new0 (GtkIMContextInfo, 1);
465

Owen Taylor's avatar
Owen Taylor committed
466 467
	  /* Read information about a context type
	   */
468
	  if (!gtk_scan_string (&p, tmp_buf))
Owen Taylor's avatar
Owen Taylor committed
469 470 471
	    goto context_error;
	  info->context_id = g_strdup (tmp_buf->str);

472
	  if (!gtk_scan_string (&p, tmp_buf))
Owen Taylor's avatar
Owen Taylor committed
473 474 475
	    goto context_error;
	  info->context_name = g_strdup (tmp_buf->str);

476
	  if (!gtk_scan_string (&p, tmp_buf))
Owen Taylor's avatar
Owen Taylor committed
477 478 479
	    goto context_error;
	  info->domain = g_strdup (tmp_buf->str);

480
	  if (!gtk_scan_string (&p, tmp_buf))
Owen Taylor's avatar
Owen Taylor committed
481
	    goto context_error;
482

Owen Taylor's avatar
Owen Taylor committed
483
	  info->domain_dirname = g_strdup (tmp_buf->str);
Tor Lillqvist's avatar
Tor Lillqvist committed
484 485
#ifdef G_OS_WIN32
	  correct_localedir_prefix ((char **) &info->domain_dirname);
486
#endif
Owen Taylor's avatar
Owen Taylor committed
487

488
	  if (!gtk_scan_string (&p, tmp_buf))
Owen Taylor's avatar
Owen Taylor committed
489 490 491
	    goto context_error;
	  info->default_locales = g_strdup (tmp_buf->str);

492
	  if (gtk_skip_space (&p))
Owen Taylor's avatar
Owen Taylor committed
493 494 495 496 497 498
	    goto context_error;

	  infos = g_slist_prepend (infos, info);
	  continue;

	context_error:
499
	  g_warning ("Error parsing context info in '%s'\n  %s", filename, line_buf->str);
Owen Taylor's avatar
Owen Taylor committed
500 501 502 503 504 505
	  have_error = TRUE;
	}
    }

  if (have_error)
    {
Matthias Clasen's avatar
Matthias Clasen committed
506
      g_slist_free_full (infos, (GDestroyNotify)free_info);
Manish Singh's avatar
Manish Singh committed
507
      g_object_unref (module);
Owen Taylor's avatar
Owen Taylor committed
508 509 510 511 512 513 514
    }
  else if (module)
    add_module (module, infos);

  fclose (file);
  g_string_free (line_buf, TRUE);
  g_string_free (tmp_buf, TRUE);
515
  g_free (filename);
Owen Taylor's avatar
Owen Taylor committed
516 517
}

518
static gint
519 520
compare_gtkimcontextinfo_name (const GtkIMContextInfo **a,
                               const GtkIMContextInfo **b)
521 522 523 524
{
  return g_utf8_collate ((*a)->context_name, (*b)->context_name);
}

Owen Taylor's avatar
Owen Taylor committed
525 526 527 528 529 530 531
/**
 * _gtk_im_module_list:
 * @contexts: location to store an array of pointers to #GtkIMContextInfo
 *            this array should be freed with g_free() when you are finished.
 *            The structures it points are statically allocated and should
 *            not be modified or freed.
 * @n_contexts: the length of the array stored in @contexts
532
 *
Owen Taylor's avatar
Owen Taylor committed
533
 * List all available types of input method context
Matthias Clasen's avatar
Matthias Clasen committed
534
 */
Owen Taylor's avatar
Owen Taylor committed
535 536 537 538 539 540
void
_gtk_im_module_list (const GtkIMContextInfo ***contexts,
		     guint                    *n_contexts)
{
  int n = 0;

Tor Lillqvist's avatar
Tor Lillqvist committed
541 542 543 544 545
  static
#ifndef G_OS_WIN32
	  const
#endif
		GtkIMContextInfo simple_context_info = {
Owen Taylor's avatar
Owen Taylor committed
546
    SIMPLE_ID,
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
    NC_("input method menu", "Simple"),
    GETTEXT_PACKAGE,
#ifdef GTK_LOCALEDIR
    GTK_LOCALEDIR,
#else
    "",
#endif
    ""
  };

  static
#ifndef G_OS_WIN32
	  const
#endif
		GtkIMContextInfo none_context_info = {
    NONE_ID,
    NC_("input method menu", "None"),
564
    GETTEXT_PACKAGE,
565
#ifdef GTK_LOCALEDIR
566
    GTK_LOCALEDIR,
567 568 569
#else
    "",
#endif
Owen Taylor's avatar
Owen Taylor committed
570 571 572
    ""
  };

Tor Lillqvist's avatar
Tor Lillqvist committed
573 574 575 576
#ifdef G_OS_WIN32
  static gboolean beenhere = FALSE;
#endif

Owen Taylor's avatar
Owen Taylor committed
577
  if (!contexts_hash)
578
    gtk_im_module_initialize ();
Owen Taylor's avatar
Owen Taylor committed
579

Tor Lillqvist's avatar
Tor Lillqvist committed
580 581 582 583 584 585 586 587 588
#ifdef G_OS_WIN32
  if (!beenhere)
    {
      beenhere = TRUE;
      /* correct_localedir_prefix() requires its parameter to be a
       * malloced string
       */
      simple_context_info.domain_dirname = g_strdup (simple_context_info.domain_dirname);
      correct_localedir_prefix ((char **) &simple_context_info.domain_dirname);
589 590
      none_context_info.domain_dirname = g_strdup (none_context_info.domain_dirname);
      correct_localedir_prefix ((char **) &none_context_info.domain_dirname);
Tor Lillqvist's avatar
Tor Lillqvist committed
591 592 593
    }
#endif

Owen Taylor's avatar
Owen Taylor committed
594
  if (n_contexts)
595
    *n_contexts = n_loaded_contexts + 2;
Owen Taylor's avatar
Owen Taylor committed
596 597 598 599 600 601

  if (contexts)
    {
      GSList *tmp_list;
      int i;

602 603 604
      *contexts = g_new (const GtkIMContextInfo *, n_loaded_contexts + 2);

      (*contexts)[n++] = &none_context_info;
Owen Taylor's avatar
Owen Taylor committed
605 606 607 608 609 610 611 612 613
      (*contexts)[n++] = &simple_context_info;

      tmp_list = modules_list;
      while (tmp_list)
	{
	  GtkIMModule *module = tmp_list->data;

	  for (i=0; i<module->n_contexts; i++)
	    (*contexts)[n++] = module->contexts[i];
614
  
Owen Taylor's avatar
Owen Taylor committed
615 616
	  tmp_list = tmp_list->next;
	}
617

618 619
      /* first elements (Simple and None) should always be at top */
      qsort ((*contexts)+2, n-2, sizeof (GtkIMContextInfo *), (GCompareFunc)compare_gtkimcontextinfo_name);
Owen Taylor's avatar
Owen Taylor committed
620 621 622 623 624 625 626 627 628 629
    }
}

/**
 * _gtk_im_module_create:
 * @context_id: the context ID for the context type to create
 * 
 * Create an IM context of a type specified by the string
 * ID @context_id.
 * 
630
 * Returns: a newly created input context of or @context_id, or
Matthias Clasen's avatar
Matthias Clasen committed
631 632
 *     if that could not be created, a newly created GtkIMContextSimple.
 */
Owen Taylor's avatar
Owen Taylor committed
633 634 635 636 637
GtkIMContext *
_gtk_im_module_create (const gchar *context_id)
{
  GtkIMModule *im_module;
  GtkIMContext *context = NULL;
638 639 640 641

  if (strcmp (context_id, NONE_ID) == 0)
    return NULL;

Owen Taylor's avatar
Owen Taylor committed
642
  if (!contexts_hash)
643
    gtk_im_module_initialize ();
Owen Taylor's avatar
Owen Taylor committed
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658

  if (strcmp (context_id, SIMPLE_ID) != 0)
    {
      im_module = g_hash_table_lookup (contexts_hash, context_id);
      if (!im_module)
	{
	  g_warning ("Attempt to load unknown IM context type '%s'", context_id);
	}
      else
	{
	  if (g_type_module_use (G_TYPE_MODULE (im_module)))
	    {
	      context = im_module->create (context_id);
	      g_type_module_unuse (G_TYPE_MODULE (im_module));
	    }
659

Owen Taylor's avatar
Owen Taylor committed
660 661 662 663
	  if (!context)
	    g_warning ("Loading IM context type '%s' failed", context_id);
	}
    }
664

Owen Taylor's avatar
Owen Taylor committed
665 666 667 668 669 670 671 672
  if (!context)
     return gtk_im_context_simple_new ();
  else
    return context;
}

/* Match @locale against @against.
 * 
673 674 675 676
 * 'en_US' against “en_US”       => 4
 * 'en_US' against “en”          => 3
 * 'en', “en_UK” against “en_US” => 2
 *  all locales, against “*” 	 => 1
Owen Taylor's avatar
Owen Taylor committed
677 678 679 680 681 682
 */
static gint
match_locale (const gchar *locale,
	      const gchar *against,
	      gint         against_len)
{
683 684 685
  if (strcmp (against, "*") == 0)
    return 1;

686
  if (g_ascii_strcasecmp (locale, against) == 0)
687
    return 4;
Owen Taylor's avatar
Owen Taylor committed
688

689
  if (g_ascii_strncasecmp (locale, against, 2) == 0)
690
    return (against_len == 2) ? 3 : 2;
Owen Taylor's avatar
Owen Taylor committed
691 692 693 694

  return 0;
}

695 696 697 698 699
static gboolean
match_backend (GtkIMContextInfo *context)
{
#ifdef GDK_WINDOWING_WAYLAND
  if (g_strcmp0 (context->context_id, "wayland") == 0)
700 701 702 703 704 705 706
    {
      GdkDisplay *display = gdk_display_get_default ();

      return GDK_IS_WAYLAND_DISPLAY (display) &&
             gdk_wayland_display_query_registry (display,
                                                 "gtk_text_input_manager");
    }
707 708
#endif

709 710 711 712 713
#ifdef GDK_WINDOWING_BROADWAY
  if (g_strcmp0 (context->context_id, "broadway") == 0)
    return GDK_IS_BROADWAY_DISPLAY (gdk_display_get_default ());
#endif

714 715 716 717 718 719 720 721 722 723 724 725 726
#ifdef GDK_WINDOWING_X11
  if (g_strcmp0 (context->context_id, "xim") == 0)
    return GDK_IS_X11_DISPLAY (gdk_display_get_default ());
#endif

#ifdef GDK_WINDOWING_WIN32
  if (g_strcmp0 (context->context_id, "ime") == 0)
    return GDK_IS_WIN32_DISPLAY (gdk_display_get_default ());
#endif

  return TRUE;
}

727 728 729 730 731 732 733
static const gchar *
lookup_immodule (gchar **immodules_list)
{
  while (immodules_list && *immodules_list)
    {
      if (g_strcmp0 (*immodules_list, SIMPLE_ID) == 0)
        return SIMPLE_ID;
734 735
      else if (g_strcmp0 (*immodules_list, NONE_ID) == 0)
        return NONE_ID;
736
      else
737 738 739 740
	{
	  gboolean found;
	  gchar *context_id;
	  found = g_hash_table_lookup_extended (contexts_hash, *immodules_list,
741
						(gpointer *) &context_id, NULL);
742 743 744
	  if (found)
	    return context_id;
	}
745 746 747 748 749 750
      immodules_list++;
    }

  return NULL;
}

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
#ifdef G_OS_WIN32

/* max size for LOCALE_SISO639LANGNAME and LOCALE_SISO3166CTRYNAME is 9 */
#define MAX_NAME_SIZE 9

static gchar *
get_current_input_language (void)
{
  LCID lcid;
  LANGID langid;
  HKL kblayout;
  int name_size;
  wchar_t name[MAX_NAME_SIZE];
  gchar *language;
  gchar *country;
  gchar *full;

  /* Current thread's keyboard layout */
  kblayout = GetKeyboardLayout(0);
  /* lowest word in the HKL is the LANGID */
771
  langid = LOWORD (kblayout);
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
  /* LCID is the LANGID without order */
  lcid = langid;

  /* Get Language ID */
  name_size = GetLocaleInfoW (lcid, LOCALE_SISO639LANGNAME, NULL, 0);
  if (name_size <= 1)
    return NULL;

  g_assert (name_size <= MAX_NAME_SIZE);
  GetLocaleInfoW (lcid, LOCALE_SISO639LANGNAME, name, name_size);

  language = g_utf16_to_utf8 (name, name_size, NULL, NULL, NULL);
  if (!language)
    return NULL;

  if (SUBLANGID (langid) == SUBLANG_NEUTRAL)
    return language;

  /* Get Country ID */
  name_size = GetLocaleInfoW (lcid, LOCALE_SISO3166CTRYNAME, NULL, 0);
  if (name_size <= 1)
    return language;

  g_assert (name_size <= MAX_NAME_SIZE);
  GetLocaleInfoW (lcid, LOCALE_SISO3166CTRYNAME, name, name_size);

  country = g_utf16_to_utf8 (name, name_size, NULL, NULL, NULL);
  if (!country)
    return language;

  full = g_strdup_printf ("%s_%s", language, country);

  g_free (language);
  g_free (country);

  return full;
}

#endif

Owen Taylor's avatar
Owen Taylor committed
812 813 814
/**
 * _gtk_im_module_get_default_context_id:
 * 
815 816
 * Return the context_id of the best IM context type 
 * for the given window.
Owen Taylor's avatar
Owen Taylor committed
817
 * 
818
 * Returns: the context ID (will never be %NULL)
Matthias Clasen's avatar
Matthias Clasen committed
819
 */
Owen Taylor's avatar
Owen Taylor committed
820
const gchar *
821
_gtk_im_module_get_default_context_id (void)
Owen Taylor's avatar
Owen Taylor committed
822 823 824 825 826
{
  GSList *tmp_list;
  const gchar *context_id = NULL;
  gint best_goodness = 0;
  gint i;
827
  gchar *tmp_locale, *tmp, **immodules;
828
  const gchar *envvar;
829 830
  GdkScreen *screen;
  GtkSettings *settings;
831

Owen Taylor's avatar
Owen Taylor committed
832
  if (!contexts_hash)
833
    gtk_im_module_initialize ();
Owen Taylor's avatar
Owen Taylor committed
834

835
  envvar = g_getenv ("GTK_IM_MODULE");
836 837
  if (envvar)
    {
838 839 840
        immodules = g_strsplit (envvar, ":", 0);
        context_id = lookup_immodule (immodules);
        g_strfreev (immodules);
841 842 843 844

        if (context_id)
          return context_id;
    }
845 846 847

  /* Check if the certain immodule is set in XSETTINGS.
   */
848 849 850 851
  screen = gdk_screen_get_default ();
  settings = gtk_settings_get_for_screen (screen);
  g_object_get (G_OBJECT (settings), "gtk-im-module", &tmp, NULL);
  if (tmp)
852
    {
853 854 855 856 857 858 859
      immodules = g_strsplit (tmp, ":", 0);
      context_id = lookup_immodule (immodules);
      g_strfreev (immodules);
      g_free (tmp);

      if (context_id)
        return context_id;
860
    }
Owen Taylor's avatar
Owen Taylor committed
861

862 863 864 865 866 867 868 869 870 871
#ifdef G_OS_WIN32
  /* Read current input locale from the current keyboard info */
  tmp_locale = get_current_input_language ();
  if (!tmp_locale)
    /* Default to system locale when input language is unknown */
    tmp_locale = _gtk_get_lc_ctype ();
#else
  tmp_locale = _gtk_get_lc_ctype ();
#endif

Owen Taylor's avatar
Owen Taylor committed
872 873 874 875 876 877 878 879
  /* Strip the locale code down to the essentials
   */
  tmp = strchr (tmp_locale, '.');
  if (tmp)
    *tmp = '\0';
  tmp = strchr (tmp_locale, '@');
  if (tmp)
    *tmp = '\0';
880

Owen Taylor's avatar
Owen Taylor committed
881 882 883 884
  tmp_list = modules_list;
  while (tmp_list)
    {
      GtkIMModule *module = tmp_list->data;
885

886
      for (i = 0; i < module->n_contexts; i++)
Owen Taylor's avatar
Owen Taylor committed
887
	{
888 889 890 891 892 893
	  const gchar *p;

          if (!match_backend (module->contexts[i]))
            continue;

          p = module->contexts[i]->default_locales;
Owen Taylor's avatar
Owen Taylor committed
894 895 896 897 898 899 900 901 902 903 904 905 906 907
	  while (p)
	    {
	      const gchar *q = strchr (p, ':');
	      gint goodness = match_locale (tmp_locale, p, q ? q - p : strlen (p));

	      if (goodness > best_goodness)
		{
		  context_id = module->contexts[i]->context_id;
		  best_goodness = goodness;
		}

	      p = q ? q + 1 : NULL;
	    }
	}
908

Owen Taylor's avatar
Owen Taylor committed
909 910 911 912
      tmp_list = tmp_list->next;
    }

  g_free (tmp_locale);
913

914
  return context_id ? context_id : SIMPLE_ID;
Owen Taylor's avatar
Owen Taylor committed
915
}