summaryrefslogtreecommitdiff
path: root/libxklavier/xklavier_config.c
blob: 25d006e097ec7ec0a7dca7443ca673227ffca6ef (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
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
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
1183
1184
1185
1186
/*
 * Copyright (C) 2002-2006 Sergey V. Udaltsov <svu@gnome.org>
 *
 * 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, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include <errno.h>
#include <locale.h>
#include <libintl.h>
#include <stdio.h>
#include <string.h>
#include <sys/param.h>
#include <sys/stat.h>

#include "config.h"

#include "xklavier_private.h"

static GObjectClass *parent_class = NULL;

static xmlXPathCompExprPtr models_xpath;
static xmlXPathCompExprPtr layouts_xpath;
static xmlXPathCompExprPtr option_groups_xpath;

static GRegex **xml_encode_regexen = NULL;
static GRegex **xml_decode_regexen = NULL;
static const char *xml_decode_regexen_str[] = { "&lt;", "&gt;", "&amp;" };
static const char *xml_encode_regexen_str[] = { "<", ">", "&" };

/* gettext domain for translations */
#define XKB_DOMAIN "xkeyboard-config"

enum {
	PROP_0,
	PROP_ENGINE
};

typedef struct {
	const gchar *pattern;
	TwoConfigItemsProcessFunc func;
	gpointer data;
	gboolean country_matched;
	gboolean language_matched;
} SearchParamType;

static gboolean
xkl_xml_find_config_item_child(xmlNodePtr iptr, xmlNodePtr * ptr)
{
	/* 
	 * Walking through the 1st level children of iptr
	 * looking for the configItem
	 */
	if (iptr->type != XML_ELEMENT_NODE)
		return FALSE;
	*ptr = iptr->children;
	while (*ptr != NULL) {
		switch ((*ptr)->type) {
		case XML_ELEMENT_NODE:
			return !g_ascii_strcasecmp
			    ((char *) (*ptr)->name, "configItem");
		case XML_TEXT_NODE:
		case XML_COMMENT_NODE:
			(*ptr) = (*ptr)->next;
			continue;
		default:
			return FALSE;
		}
		break;
	}
	return FALSE;
}

static xmlNodePtr
xkl_find_element(xmlNodePtr ptr, const gchar * tag_name)
{
	xmlNodePtr found_element = NULL;

	/* Look through all siblings, trying to find a node with proper name */
	while (ptr != NULL) {
		char *node_name = (char *) ptr->name;
		if (ptr->type != XML_TEXT_NODE) {
			if (!g_ascii_strcasecmp(node_name, tag_name)) {
				found_element = ptr;
				break;
			}
		}
		ptr = ptr->next;
	}
	return found_element;
}

static gboolean
xkl_item_populate_optional_array(XklConfigItem * item, xmlNodePtr ptr,
				 const gchar list_tag[],
				 const gchar element_tag[],
				 const gchar property_name[])
{
	xmlNodePtr top_list_element =
	    xkl_find_element(ptr, list_tag), element_ptr;
	gint n_elements, idx;
	gchar **elements = NULL;

	if (top_list_element == NULL || top_list_element->children == NULL)
		return FALSE;

	n_elements = 0;

	/* First, count countries */
	element_ptr = top_list_element->children;
	while (NULL !=
	       (element_ptr =
		xkl_find_element(element_ptr, element_tag))) {
		n_elements++;
		element_ptr = element_ptr->next;
	}

	if (n_elements == 0)
		return FALSE;

	elements = g_new0(gchar *, n_elements + 1);
	/* Then, actually, populate the list */
	element_ptr = top_list_element->children;
	for (idx = 0;
	     NULL != (element_ptr =
		      xkl_find_element(element_ptr, element_tag));
	     element_ptr = element_ptr->next, idx++) {
		elements[idx] =
		    g_strdup((const char *) element_ptr->children->
			     content);
	}

	g_object_set_data_full(G_OBJECT(item),
			       property_name, elements, (GDestroyNotify)
			       g_strfreev);
	return TRUE;
}

#include "libxml/parserInternals.h"

gboolean
xkl_read_config_item(XklConfigRegistry * config, gint doc_index,
		     xmlNodePtr iptr, XklConfigItem * item)
{
	xmlNodePtr name_element, ptr;
	xmlNodePtr desc_element = NULL, short_desc_element =
	    NULL, vendor_element = NULL;

	gchar *vendor = NULL, *translated = NULL, *escaped =
	    NULL, *unescaped = NULL;

	gint i;

	*item->name = 0;
	*item->short_description = 0;
	*item->description = 0;

	g_object_set_data(G_OBJECT(item), XCI_PROP_VENDOR, NULL);
	g_object_set_data(G_OBJECT(item), XCI_PROP_COUNTRY_LIST, NULL);
	g_object_set_data(G_OBJECT(item), XCI_PROP_LANGUAGE_LIST, NULL);

	if (!xkl_xml_find_config_item_child(iptr, &ptr))
		return FALSE;

	if (doc_index > 0)
		g_object_set_data(G_OBJECT(item), XCI_PROP_EXTRA_ITEM,
				  GINT_TO_POINTER(TRUE));

	ptr = ptr->children;

	if (ptr->type == XML_TEXT_NODE)
		ptr = ptr->next;
	name_element = ptr;
	ptr = ptr->next;

	short_desc_element = xkl_find_element(ptr, XML_TAG_SHORT_DESCR);
	desc_element = xkl_find_element(ptr, XML_TAG_DESCR);
	vendor_element = xkl_find_element(ptr, XML_TAG_VENDOR);

	if (name_element != NULL && name_element->children != NULL)
		strncat(item->name,
			(char *) name_element->children->content,
			XKL_MAX_CI_NAME_LENGTH - 1);

	if (short_desc_element != NULL
	    && short_desc_element->children != NULL) {
		strncat(item->short_description,
			dgettext(XKB_DOMAIN, (const char *)
				 short_desc_element->children->content),
			XKL_MAX_CI_SHORT_DESC_LENGTH - 1);
	}

	if (desc_element != NULL && desc_element->children != NULL) {
		/* Convert all xml-related characters to XML form, otherwise dgettext won't find the translation 
		 * The conversion is not using libxml2, because there are no handy functions in API */
		translated =
		    g_strdup((gchar *) desc_element->children->content);
		for (i =
		     sizeof(xml_encode_regexen_str) /
		     sizeof(xml_encode_regexen_str[0]); --i >= 0;) {
			escaped =
			    g_regex_replace(xml_encode_regexen[i],
					    translated, -1, 0,
					    xml_decode_regexen_str[i], 0,
					    NULL);
			g_free(translated);
			translated = escaped;
		}
		escaped = translated;

		/* Do the translation! */
		translated =
		    g_strdup(dgettext(XKB_DOMAIN, (const char *) escaped));
		g_free(escaped);

		/* Convert all XML entities back to normal form */
		for (i =
		     sizeof(xml_decode_regexen_str) /
		     sizeof(xml_decode_regexen_str[0]); --i >= 0;) {
			unescaped =
			    g_regex_replace(xml_decode_regexen[i],
					    translated, -1, 0,
					    xml_encode_regexen_str[i], 0,
					    NULL);
			g_free(translated);
			translated = unescaped;
		}
		strncat(item->description,
			translated, XKL_MAX_CI_DESC_LENGTH - 1);
		g_free(translated);
	}

	if (vendor_element != NULL && vendor_element->children != NULL) {
		vendor =
		    g_strdup((const char *) vendor_element->
			     children->content);
		g_object_set_data_full(G_OBJECT(item), XCI_PROP_VENDOR,
				       vendor, g_free);
	}

	xkl_item_populate_optional_array(item, ptr, XML_TAG_COUNTRY_LIST,
					 XML_TAG_ISO3166ID,
					 XCI_PROP_COUNTRY_LIST);
	xkl_item_populate_optional_array(item, ptr, XML_TAG_LANGUAGE_LIST,
					 XML_TAG_ISO639ID,
					 XCI_PROP_LANGUAGE_LIST);

	return TRUE;
}

static void
xkl_config_registry_foreach_in_nodeset(XklConfigRegistry * config,
				       GSList ** processed_ids,
				       gint doc_index, xmlNodeSetPtr nodes,
				       ConfigItemProcessFunc func,
				       gpointer data)
{
	gint i;
	if (nodes != NULL) {
		xmlNodePtr *pnode = nodes->nodeTab;
		XklConfigItem *ci = xkl_config_item_new();
		for (i = nodes->nodeNr; --i >= 0;) {
			if (xkl_read_config_item
			    (config, doc_index, *pnode, ci)) {
				if (g_slist_find_custom
				    (*processed_ids, ci->name,
				     (GCompareFunc) g_ascii_strcasecmp) ==
				    NULL) {
					func(config, ci, data);
					*processed_ids =
					    g_slist_append(*processed_ids,
							   g_strdup
							   (ci->name));
				}
			}

			pnode++;
		}
		g_object_unref(G_OBJECT(ci));
	}
}

void
xkl_config_registry_foreach_in_xpath(XklConfigRegistry * config,
				     xmlXPathCompExprPtr
				     xpath_comp_expr,
				     ConfigItemProcessFunc func,
				     gpointer data)
{
	xmlXPathObjectPtr xpath_obj;
	gint di;
	GSList *processed_ids = NULL;

	if (!xkl_config_registry_is_initialized(config))
		return;

	for (di = 0; di < XKL_NUMBER_OF_REGISTRY_DOCS; di++) {
		xmlXPathContextPtr xmlctxt =
		    xkl_config_registry_priv(config, xpath_contexts[di]);
		if (xmlctxt == NULL)
			continue;

		xpath_obj = xmlXPathCompiledEval(xpath_comp_expr, xmlctxt);
		if (xpath_obj == NULL)
			continue;

		xkl_config_registry_foreach_in_nodeset(config,
						       &processed_ids, di,
						       xpath_obj->nodesetval,
						       func, data);
		xmlXPathFreeObject(xpath_obj);
	}
	g_slist_foreach(processed_ids, (GFunc) g_free, NULL);
	g_slist_free(processed_ids);
}

void
xkl_config_registry_foreach_in_xpath_with_param(XklConfigRegistry
						* config,
						const gchar *
						format,
						const gchar *
						value,
						ConfigItemProcessFunc
						func, gpointer data)
{
	char xpath_expr[1024];
	xmlXPathObjectPtr xpath_obj;
	gint di;
	GSList *processed_ids = NULL;

	if (!xkl_config_registry_is_initialized(config))
		return;

	g_snprintf(xpath_expr, sizeof xpath_expr, format, value);

	for (di = 0; di < XKL_NUMBER_OF_REGISTRY_DOCS; di++) {
		xmlXPathContextPtr xmlctxt =
		    xkl_config_registry_priv(config, xpath_contexts[di]);
		if (xmlctxt == NULL)
			continue;

		xpath_obj =
		    xmlXPathEval((unsigned char *) xpath_expr, xmlctxt);
		if (xpath_obj == NULL)
			continue;

		xkl_config_registry_foreach_in_nodeset(config,
						       &processed_ids, di,
						       xpath_obj->nodesetval,
						       func, data);
		xmlXPathFreeObject(xpath_obj);
	}
	g_slist_foreach(processed_ids, (GFunc) g_free, NULL);
	g_slist_free(processed_ids);
}

static gboolean
xkl_config_registry_find_object(XklConfigRegistry * config,
				const gchar * format,
				const gchar * arg1,
				XklConfigItem * pitem /* in/out */ ,
				xmlNodePtr * pnode /* out */ )
{
	xmlXPathObjectPtr xpath_obj;
	xmlNodeSetPtr nodes;
	gboolean rv = FALSE;
	gchar xpath_expr[1024];
	gint di;

	if (!xkl_config_registry_is_initialized(config))
		return FALSE;

	g_snprintf(xpath_expr, sizeof xpath_expr, format, arg1,
		   pitem->name);

	for (di = 0; di < XKL_NUMBER_OF_REGISTRY_DOCS; di++) {
		xmlXPathContextPtr xmlctxt =
		    xkl_config_registry_priv(config, xpath_contexts[di]);
		if (xmlctxt == NULL)
			continue;

		xpath_obj =
		    xmlXPathEval((unsigned char *) xpath_expr, xmlctxt);
		if (xpath_obj == NULL)
			continue;

		nodes = xpath_obj->nodesetval;
		if (nodes != NULL && nodes->nodeTab != NULL
		    && nodes->nodeNr > 0) {
			rv = xkl_read_config_item(config, di,
						  nodes->nodeTab[0],
						  pitem);
			if (pnode != NULL) {
				*pnode = *nodes->nodeTab;
			}
		}

		xmlXPathFreeObject(xpath_obj);
	}
	return rv;
}

gchar *
xkl_config_rec_merge_layouts(const XklConfigRec * data)
{
	return xkl_strings_concat_comma_separated(data->layouts);
}

gchar *
xkl_config_rec_merge_variants(const XklConfigRec * data)
{
	return xkl_strings_concat_comma_separated(data->variants);
}

gchar *
xkl_config_rec_merge_options(const XklConfigRec * data)
{
	return xkl_strings_concat_comma_separated(data->options);
}

gchar *
xkl_strings_concat_comma_separated(gchar ** array)
{
	if (array) {
		return g_strjoinv(",", array);
	} else {
		return g_strdup("");
	}
}

void
xkl_config_rec_split_layouts(XklConfigRec * data, const gchar * merged)
{
	xkl_strings_split_comma_separated(&data->layouts, merged);
}

void
xkl_config_rec_split_variants(XklConfigRec * data, const gchar * merged)
{
	xkl_strings_split_comma_separated(&data->variants, merged);
}

void
xkl_config_rec_split_options(XklConfigRec * data, const gchar * merged)
{
	xkl_strings_split_comma_separated(&data->options, merged);
}

void
xkl_strings_split_comma_separated(gchar *** array, const gchar * merged)
{
	*array = g_strsplit(merged, ",", 0);
}

gchar *
xkl_engine_get_ruleset_name(XklEngine * engine,
			    const gchar default_ruleset[])
{
	static gchar rules_set_name[1024] = "";
	if (!rules_set_name[0]) {
		/* first call */
		gchar *rf = NULL;
		if (!xkl_config_rec_get_from_root_window_property
		    (NULL,
		     xkl_engine_priv(engine, base_config_atom),
		     &rf, engine) || (rf == NULL)) {
			g_strlcpy(rules_set_name, default_ruleset,
				  sizeof rules_set_name);
			xkl_debug(100,
				  "Using default rules set: [%s]\n",
				  rules_set_name);
			return rules_set_name;
		}
		g_strlcpy(rules_set_name, rf, sizeof rules_set_name);
		g_free(rf);
	}
	xkl_debug(100, "Rules set: [%s]\n", rules_set_name);
	return rules_set_name;
}

XklConfigRegistry *
xkl_config_registry_get_instance(XklEngine * engine)
{
	XklConfigRegistry *config;

	if (!engine) {
		xkl_debug(10,
			  "xkl_config_registry_get_instance : engine is NULL ?\n");
		return NULL;
	}

	config =
	    XKL_CONFIG_REGISTRY(g_object_new
				(xkl_config_registry_get_type(),
				 "engine", engine, NULL));

	return config;
}

/* We process descriptions as "leaf" elements - this is ok for base.xml*/
static gboolean skipping_tag = FALSE;

static void
xkl_xml_sax_start_element_ns(void *ctx,
			     const xmlChar * localname,
			     const xmlChar * prefix,
			     const xmlChar * URI,
			     int nb_namespaces,
			     const xmlChar ** namespaces,
			     int nb_attributes,
			     int nb_defaulted, const xmlChar ** attributes)
{
	int i;
	gchar *lang = NULL;
	for (i = 0; i < nb_attributes * 5; i += 5) {
		int len = attributes[i + 4] - attributes[i + 3];
		gchar *value = g_new0(gchar, len + 1);
		memcpy(value, attributes[i + 3], len);
		if (!g_ascii_strcasecmp((gchar *) attributes[i], "lang")
		    /* && ... */
		    ) {
			lang = value;
			break;
		}
		g_free(value);
	}
	if (lang != NULL) {
		g_free(lang);
		skipping_tag = TRUE;
		return;
	}
	xmlSAX2StartElementNs(ctx, localname, prefix, URI,
			      nb_namespaces, namespaces, nb_attributes,
			      nb_defaulted, attributes);
}

static void
xkl_xml_sax_characters(void *ctx, const xmlChar * ch, int len)
{
	if (!skipping_tag) {
		xmlSAX2Characters(ctx, ch, len);
	}
}

static void
xkl_xml_sax_end_element_ns(void *ctx,
			   const xmlChar * localname,
			   const xmlChar * prefix, const xmlChar * URI)
{
	if (skipping_tag) {
		skipping_tag = FALSE;
	} else {
		xmlSAX2EndElementNs(ctx, localname, prefix, URI);
	}
}

gboolean
xkl_config_registry_load_from_file(XklConfigRegistry * config,
				   const gchar * file_name, gint docidx)
{
	xmlParserCtxtPtr ctxt = xmlNewParserCtxt();
	xmlDocPtr doc;

	xkl_debug(100, "Loading XML registry from file %s\n", file_name);

	/* Filter out all unneeded languages! */
	xmlSAX2InitDefaultSAXHandler(ctxt->sax, TRUE);
	ctxt->sax->startElementNs = xkl_xml_sax_start_element_ns;
	ctxt->sax->endElementNs = xkl_xml_sax_end_element_ns;
	ctxt->sax->characters = xkl_xml_sax_characters;

	doc = xkl_config_registry_priv(config, docs[docidx]) =
	    xmlCtxtReadFile(ctxt, file_name, NULL, XML_PARSE_NOBLANKS);
	xmlFreeParserCtxt(ctxt);

	if (doc == NULL) {
		xkl_config_registry_priv(config, xpath_contexts[docidx]) =
		    NULL;
		xkl_last_error_message =
		    "Could not parse primary XKB configuration registry";
		return FALSE;
	}

	xkl_config_registry_priv(config, xpath_contexts[docidx]) =
	    xmlXPathNewContext(doc);

	return TRUE;
}

gboolean
xkl_config_registry_load_helper(XklConfigRegistry * config,
				const char default_ruleset[],
				const char base_dir[],
				gboolean if_extras_needed)
{
	struct stat stat_buf;
	gchar file_name[MAXPATHLEN] = "";
	XklEngine *engine = xkl_config_registry_get_engine(config);
	gchar *rf = xkl_engine_get_ruleset_name(engine, default_ruleset);

	if (rf == NULL || rf[0] == '\0')
		return FALSE;

	g_snprintf(file_name, sizeof file_name, "%s/%s.xml", base_dir, rf);

	if (stat(file_name, &stat_buf) != 0) {
		xkl_debug(0, "Missing registry file %s\n", file_name);
		xkl_last_error_message = "Missing registry file";
		return FALSE;
	}

	if (!xkl_config_registry_load_from_file(config, file_name, 0))
		return FALSE;

	if (!if_extras_needed)
		return TRUE;

	g_snprintf(file_name, sizeof file_name, "%s/%s.extras.xml",
		   base_dir, rf);

	/* no extras - ok, no problem */
	if (stat(file_name, &stat_buf) != 0)
		return TRUE;

	return xkl_config_registry_load_from_file(config, file_name, 1);
}

void
xkl_config_registry_free(XklConfigRegistry * config)
{
	if (xkl_config_registry_is_initialized(config)) {
		gint di;
		for (di = 0; di < XKL_NUMBER_OF_REGISTRY_DOCS; di++) {
			xmlXPathContextPtr xmlctxt =
			    xkl_config_registry_priv(config,
						     xpath_contexts[di]);
			if (xmlctxt == NULL)
				continue;

			xmlXPathFreeContext(xmlctxt);
			xmlFreeDoc(xkl_config_registry_priv
				   (config, docs[di]));
			xkl_config_registry_priv(config,
						 xpath_contexts[di]) =
			    NULL;
			xkl_config_registry_priv(config, docs[di]) = NULL;
		}

	}
}

void
xkl_config_registry_foreach_model(XklConfigRegistry * config,
				  ConfigItemProcessFunc func,
				  gpointer data)
{
	xkl_config_registry_foreach_in_xpath(config, models_xpath,
					     func, data);
}

void
xkl_config_registry_foreach_layout(XklConfigRegistry * config,
				   ConfigItemProcessFunc func,
				   gpointer data)
{
	xkl_config_registry_foreach_in_xpath(config, layouts_xpath,
					     func, data);
}

void
xkl_config_registry_foreach_layout_variant(XklConfigRegistry *
					   config,
					   const gchar *
					   layout_name,
					   ConfigItemProcessFunc
					   func, gpointer data)
{
	xkl_config_registry_foreach_in_xpath_with_param(config,
							XKBCR_VARIANT_PATH
							"[../../configItem/name = '%s']",
							layout_name,
							func, data);
}

void
xkl_config_registry_foreach_option_group(XklConfigRegistry *
					 config,
					 ConfigItemProcessFunc
					 func, gpointer data)
{
	xmlXPathObjectPtr xpath_obj;
	gint di, j;
	GSList *processed_ids = NULL;

	if (!xkl_config_registry_is_initialized(config))
		return;

	for (di = 0; di < XKL_NUMBER_OF_REGISTRY_DOCS; di++) {
		xmlNodeSetPtr nodes;
		xmlNodePtr *pnode;
		XklConfigItem *ci;

		xmlXPathContextPtr xmlctxt =
		    xkl_config_registry_priv(config, xpath_contexts[di]);
		if (xmlctxt == NULL)
			continue;

		xpath_obj =
		    xmlXPathCompiledEval(option_groups_xpath, xmlctxt);
		if (xpath_obj == NULL)
			continue;

		nodes = xpath_obj->nodesetval;
		pnode = nodes->nodeTab;
		ci = xkl_config_item_new();
		for (j = nodes->nodeNr; --j >= 0;) {

			if (xkl_read_config_item(config, di, *pnode, ci)) {
				if (g_slist_find_custom
				    (processed_ids, ci->name,
				     (GCompareFunc) g_ascii_strcasecmp) ==
				    NULL) {
					gboolean allow_multisel = TRUE;
					xmlChar *sallow_multisel =
					    xmlGetProp(*pnode,
						       (unsigned char *)
						       XCI_PROP_ALLOW_MULTIPLE_SELECTION);
					if (sallow_multisel != NULL) {
						allow_multisel =
						    !g_ascii_strcasecmp
						    ("true", (char *)
						     sallow_multisel);
						xmlFree(sallow_multisel);
						g_object_set_data(G_OBJECT
								  (ci),
								  XCI_PROP_ALLOW_MULTIPLE_SELECTION,
								  GINT_TO_POINTER
								  (allow_multisel));
					}

					func(config, ci, data);
					processed_ids =
					    g_slist_append(processed_ids,
							   g_strdup
							   (ci->name));
				}
			}

			pnode++;
		}
		g_object_unref(G_OBJECT(ci));
		xmlXPathFreeObject(xpath_obj);
	}
	g_slist_foreach(processed_ids, (GFunc) g_free, NULL);
	g_slist_free(processed_ids);
}

void
xkl_config_registry_foreach_option(XklConfigRegistry * config,
				   const gchar *
				   option_group_name,
				   ConfigItemProcessFunc func,
				   gpointer data)
{
	xkl_config_registry_foreach_in_xpath_with_param(config,
							XKBCR_OPTION_PATH
							"[../configItem/name = '%s']",
							option_group_name,
							func, data);
}

static void
xkl_config_registry_search_by_pattern_in_layout(XklConfigRegistry * config,
						const XklConfigItem * item,
						SearchParamType *
						search_param)
{
	gchar *upper_name = g_ascii_strup(item->name, -1);
	const gchar *country_desc, *language_desc;

	xkl_debug(200, "Layout to check: [%s]\n", item->name);

	country_desc = xkl_get_country_iso_code(upper_name);
	xkl_debug(200, "Checking layout country: [%s]\n", country_desc);
	search_param->country_matched = FALSE;
	if ((country_desc != NULL)
	    && strcasestr(country_desc, search_param->pattern)) {
		search_param->country_matched = TRUE;
		(search_param->func) (config, item, NULL,
				      search_param->data);
	} else {
		gchar **countries = g_object_get_data(G_OBJECT(item),
						      XCI_PROP_COUNTRY_LIST);
		for (; countries && *countries; countries++) {
			country_desc =
			    xkl_get_country_iso_code(*countries);
			xkl_debug(200, "Checking country: [%s][%s]\n",
				  *countries, country_desc);
			if ((country_desc != NULL) && strcasestr
			    (country_desc, search_param->pattern)) {
				search_param->country_matched = TRUE;
				(search_param->func) (config, item, NULL,
						      search_param->data);
				break;
			}
		}
	}

	if (!search_param->country_matched) {
		language_desc = xkl_get_language_iso_code(item->name);
		xkl_debug(200, "Checking layout language: [%s]\n",
			  language_desc);
		search_param->language_matched = FALSE;
		if ((language_desc != NULL)
		    && strcasestr(language_desc, search_param->pattern)) {
			search_param->language_matched = TRUE;
			(search_param->func) (config, item, NULL,
					      search_param->data);
		} else {
			gchar **languages =
			    g_object_get_data(G_OBJECT(item),
					      XCI_PROP_LANGUAGE_LIST);
			for (; languages && *languages; languages++) {
				language_desc =
				    xkl_get_language_iso_code(*languages);
				xkl_debug(200,
					  "Checking language: [%s][%s]\n",
					  *languages, language_desc);
				if ((language_desc != NULL)
				    && strcasestr(language_desc,
						  search_param->pattern)) {
					search_param->language_matched =
					    TRUE;
					(search_param->func) (config, item,
							      NULL,
							      search_param->
							      data);
					break;
				}
			}
		}
	}

	g_free(upper_name);
}

void
xkl_config_registry_search_by_pattern(XklConfigRegistry * config,
				      const gchar * pattern,
				      TwoConfigItemsProcessFunc func,
				      gpointer data)
{
	xkl_debug(200, "Searching by pattern: [%s]\n", pattern);
	SearchParamType search_param = { pattern, func, data };
	xkl_config_registry_foreach_layout(config, (ConfigItemProcessFunc)
					   xkl_config_registry_search_by_pattern_in_layout,
					   &search_param);
}

gboolean
xkl_config_registry_find_model(XklConfigRegistry * config,
			       XklConfigItem * pitem /* in/out */ )
{
	return xkl_config_registry_find_object(config,
					       XKBCR_MODEL_PATH
					       "[configItem/name = '%s%s']",
					       "", pitem, NULL);
}

gboolean
xkl_config_registry_find_layout(XklConfigRegistry * config,
				XklConfigItem * pitem /* in/out */ )
{
	return xkl_config_registry_find_object(config,
					       XKBCR_LAYOUT_PATH
					       "[configItem/name = '%s%s']",
					       "", pitem, NULL);
}

gboolean
xkl_config_registry_find_variant(XklConfigRegistry * config,
				 const char *layout_name,
				 XklConfigItem * pitem /* in/out */ )
{
	return xkl_config_registry_find_object(config,
					       XKBCR_VARIANT_PATH
					       "[../../configItem/name = '%s' and configItem/name = '%s']",
					       layout_name, pitem, NULL);
}

gboolean
xkl_config_registry_find_option_group(XklConfigRegistry *
				      config,
				      XklConfigItem * pitem /* in/out */ )
{
	xmlNodePtr node = NULL;
	gboolean rv = xkl_config_registry_find_object(config,
						      XKBCR_GROUP_PATH
						      "[configItem/name = '%s%s']",
						      "",
						      pitem,
						      &node);

	if (rv) {
		xmlChar *val = xmlGetProp(node,
					  (unsigned char *)
					  XCI_PROP_ALLOW_MULTIPLE_SELECTION);
		if (val != NULL) {
			gboolean allow_multisel =
			    !g_ascii_strcasecmp("true",
						(char *) val);
			g_object_set_data(G_OBJECT(pitem),
					  XCI_PROP_ALLOW_MULTIPLE_SELECTION,
					  GINT_TO_POINTER(allow_multisel));
			xmlFree(val);
		}
	}
	return rv;
}

gboolean
xkl_config_registry_find_option(XklConfigRegistry * config,
				const char *option_group_name,
				XklConfigItem * pitem /* in/out */ )
{
	return xkl_config_registry_find_object(config,
					       XKBCR_OPTION_PATH
					       "[../configItem/name = '%s' and configItem/name = '%s']",
					       option_group_name,
					       pitem, NULL);
}

/*
 * Calling through vtable
 */
gboolean
xkl_config_rec_activate(const XklConfigRec * data, XklEngine * engine)
{
	xkl_engine_ensure_vtable_inited(engine);
	return xkl_engine_vcall(engine,
				activate_config_rec) (engine, data);
}

gboolean
xkl_config_registry_load(XklConfigRegistry * config,
			 gboolean if_extras_needed)
{
	XklEngine *engine;

	xkl_config_registry_free(config);
	engine = xkl_config_registry_get_engine(config);
	xkl_engine_ensure_vtable_inited(engine);
	return xkl_engine_vcall(engine, load_config_registry) (config,
							       if_extras_needed);
}

gboolean
xkl_config_rec_write_to_file(XklEngine * engine,
			     const gchar * file_name,
			     const XklConfigRec * data,
			     const gboolean binary)
{
	if ((!binary
	     && !(xkl_engine_priv(engine, features) &
		  XKLF_CAN_OUTPUT_CONFIG_AS_ASCII))
	    || (binary
		&& !(xkl_engine_priv(engine, features) &
		     XKLF_CAN_OUTPUT_CONFIG_AS_BINARY))) {
		xkl_last_error_message =
		    "Function not supported at backend";
		return FALSE;
	}
	xkl_engine_ensure_vtable_inited(engine);
	return xkl_engine_vcall(engine,
				write_config_rec_to_file) (engine,
							   file_name,
							   data, binary);
}

void
xkl_config_rec_dump(FILE * file, XklConfigRec * data)
{
	int j;
	fprintf(file, "  model: [%s]\n", data->model);

	fprintf(file, "  layouts:\n");
#define OUTPUT_ARRZ(arrz) \
  { \
    gchar **p = data->arrz; \
    fprintf( file, "  " #arrz ":\n" ); \
    if ( p != NULL ) \
      for( j = 0; *p != NULL; ) \
        fprintf( file, "  %d: [%s]\n", j++, *p++ ); \
  }
	OUTPUT_ARRZ(layouts);
	OUTPUT_ARRZ(variants);
	OUTPUT_ARRZ(options);

}

G_DEFINE_TYPE(XklConfigRegistry, xkl_config_registry, G_TYPE_OBJECT)
static GObject *
xkl_config_registry_constructor(GType type,
				guint
				n_construct_properties,
				GObjectConstructParam
				* construct_properties)
{
	GObject *obj;
	XklConfigRegistry *config;
	XklEngine *engine;

	{
		/* Invoke parent constructor. */
		XklConfigRegistryClass *klass;
		klass =
		    XKL_CONFIG_REGISTRY_CLASS(g_type_class_peek
					      (XKL_TYPE_CONFIG_REGISTRY));
		obj =
		    parent_class->constructor(type,
					      n_construct_properties,
					      construct_properties);
	}

	config = XKL_CONFIG_REGISTRY(obj);

	engine = XKL_ENGINE(g_value_peek_pointer
			    (construct_properties[0].value));
	xkl_config_registry_get_engine(config) = engine;

	xkl_engine_ensure_vtable_inited(engine);
	xkl_engine_vcall(engine, init_config_registry) (config);

	return obj;
}

static void
xkl_config_registry_init(XklConfigRegistry * config)
{
	config->priv = g_new0(XklConfigRegistryPrivate, 1);
}

static void
xkl_config_registry_set_property(GObject * object,
				 guint property_id,
				 const GValue * value, GParamSpec * pspec)
{
}

static void
xkl_config_registry_get_property(GObject * object,
				 guint property_id,
				 GValue * value, GParamSpec * pspec)
{
	XklConfigRegistry *config = XKL_CONFIG_REGISTRY(object);

	switch (property_id) {
	case PROP_ENGINE:
		g_value_set_pointer(value,
				    xkl_config_registry_get_engine
				    (config));
		break;
	}

}

static void
xkl_config_registry_finalize(GObject * obj)
{
	XklConfigRegistry *config = (XklConfigRegistry *) obj;

	xkl_config_registry_free(config);

	g_free(config->priv);

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

/* 
 * This function is actually NEVER called.
 * It is 'extern' just to avoid the compilation warnings
 * TODO: add class cleanup
 */
extern void
xkl_config_registry_class_term(XklConfigRegistryClass * klass)
{
	gint i;

	if (models_xpath != NULL) {
		xmlXPathFreeCompExpr(models_xpath);
		models_xpath = NULL;
	}
	if (layouts_xpath != NULL) {
		xmlXPathFreeCompExpr(layouts_xpath);
		layouts_xpath = NULL;
	}
	if (option_groups_xpath != NULL) {
		xmlXPathFreeCompExpr(option_groups_xpath);
		option_groups_xpath = NULL;
	}
	if (xml_encode_regexen != NULL) {
		for (i =
		     sizeof(xml_encode_regexen_str) /
		     sizeof(xml_encode_regexen_str[0]); --i >= 0;) {
			g_regex_unref(xml_encode_regexen[i]);
		}
		g_free(xml_encode_regexen);
		xml_encode_regexen = NULL;
	}
	if (xml_decode_regexen != NULL) {
		for (i =
		     sizeof(xml_decode_regexen_str) /
		     sizeof(xml_decode_regexen_str[0]); --i >= 0;) {
			g_regex_unref(xml_decode_regexen[i]);
		}
		g_free(xml_decode_regexen);
		xml_decode_regexen = NULL;
	}
}

static void
xkl_config_registry_class_init(XklConfigRegistryClass * klass)
{
	GObjectClass *object_class;
	GParamSpec *engine_param_spec;
	gint i;

	object_class = (GObjectClass *) klass;
	parent_class = g_type_class_peek_parent(object_class);
	object_class->constructor = xkl_config_registry_constructor;
	object_class->finalize = xkl_config_registry_finalize;
	object_class->set_property = xkl_config_registry_set_property;
	object_class->get_property = xkl_config_registry_get_property;

	bind_textdomain_codeset(XKB_DOMAIN, "UTF-8");

	engine_param_spec = g_param_spec_object("engine",
						"Engine",
						"XklEngine",
						XKL_TYPE_ENGINE,
						G_PARAM_CONSTRUCT_ONLY
						| G_PARAM_READWRITE);

	g_object_class_install_property(object_class,
					PROP_ENGINE, engine_param_spec);

	/* static stuff initialized */

	xmlXPathInit();
	models_xpath = xmlXPathCompile((unsigned char *)
				       XKBCR_MODEL_PATH);
	layouts_xpath = xmlXPathCompile((unsigned char *)
					XKBCR_LAYOUT_PATH);
	option_groups_xpath = xmlXPathCompile((unsigned char *)
					      XKBCR_GROUP_PATH);

	xml_encode_regexen =
	    g_new0(GRegex *,
		   sizeof(xml_encode_regexen_str) /
		   sizeof(xml_encode_regexen_str[0]));
	xml_decode_regexen =
	    g_new0(GRegex *,
		   sizeof(xml_decode_regexen_str) /
		   sizeof(xml_decode_regexen_str[0]));
	for (i =
	     sizeof(xml_encode_regexen_str) /
	     sizeof(xml_encode_regexen_str[0]); --i >= 0;) {
		xml_encode_regexen[i] =
		    g_regex_new(xml_encode_regexen_str[i], 0, 0, NULL);
		xml_decode_regexen[i] =
		    g_regex_new(xml_decode_regexen_str[i], 0, 0, NULL);
	}
}