This repository has been archived by the owner on May 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompose-parse.py
executable file
·1348 lines (1231 loc) · 47.4 KB
/
compose-parse.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# compose-parse.py, version 1.3
#
# multifunction script that helps manage the compose sequence table in GTK+ (gtk/gtkimcontextsimple.c)
# the script produces statistics and information about the whole process, run with --help for more.
#
# You may need to switch your python installation to utf-8, if you get 'ascii' codec errors.
#
# Complain to Simos Xenitellis ([email protected], http://simos.info/blog) for this craft.
from re import findall, match, split, sub
from string import atoi
from unicodedata import normalize, decimal
from urllib import urlretrieve
from os.path import isfile, getsize
from copy import copy
import sys
import getopt
# We grab files off the web, left and right.
URL_COMPOSE = 'http://gitweb.freedesktop.org/?p=xorg/lib/libX11.git;a=blob_plain;f=nls/en_US.UTF-8/Compose.pre'
URL_KEYSYMSTXT = 'http://www.cl.cam.ac.uk/~mgk25/ucs/keysyms.txt'
URL_GDKKEYSYMSH = 'http://svn.gnome.org/svn/gtk%2B/trunk/gdk/gdkkeysyms.h'
URL_UNICODEDATATXT = 'http://www.unicode.org/Public/5.0.0/ucd/UnicodeData.txt'
URL_GTKOLDSEQUENCES = 'http://simos.info/pub/GTKOLDSEQUENCES.txt'
FILENAME_COMPOSE_LOOKASIDE = 'gtk-compose-lookaside.txt'
FILENAME_COMPOSE_WIN32 = 'gtk-win32-sequences.txt'
# We currently support keysyms of size 2; once upstream xorg gets sorted,
# we might produce some tables with size 2 and some with size 4.
SIZEOFINT = 2
# Current max compose sequence length; in case it gets increased.
WIDTHOFCOMPOSETABLE = 5
keysymdatabase = {}
keysymunicodedatabase = {}
unicodedatabase = {}
gtkoldsequences = {}
multisequences = {}
multisequence_maxseqlen = 0
multisequence_maxvallen = 0
headerfile_start = """/* GTK - The GIMP Tool Kit
* Copyright (C) 2007, 2008, 2009 GNOME Foundation
*
* 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.
*/
/*
* File auto-generated from script found at http://bugzilla.gnome.org/show_bug.cgi?id=321896
* using the input files
* Input : http://gitweb.freedesktop.org/?p=xorg/lib/libX11.git;a=blob_plain;f=nls/en_US.UTF-8/Compose.pre
* Input : http://www.cl.cam.ac.uk/~mgk25/ucs/keysyms.txt
* Input : http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
*
* This table is optimised for space and requires special handling to access the content.
* This table is used solely by http://svn.gnome.org/viewcvs/gtk%2B/trunk/gtk/gtkimcontextsimple.c
*
* The resulting file is placed at http://svn.gnome.org/viewcvs/gtk%2B/trunk/gtk/gtkimcontextsimpleseqs.h
* This file is described in bug report http://bugzilla.gnome.org/show_bug.cgi?id=321896
*/
/*
* Modified by the GTK+ Team and others 2007, 2008, 2009. 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/.
*/
#ifndef __GTK_IM_CONTEXT_SIMPLE_SEQS_H__
#define __GTK_IM_CONTEXT_SIMPLE_SEQS_H__
/* === These are the original comments of the file; we keep for historical purposes ===
*
* The following table was generated from the X compose tables include with
* XFree86 4.0 using a set of Perl scripts. Contact Owen Taylor <[email protected]>
* to obtain the relevant perl scripts.
*
* The following compose letter letter sequences confliced
* Dstroke/dstroke and ETH/eth; resolved to Dstroke (Croation, Vietnamese, Lappish), over
* ETH (Icelandic, Faroese, old English, IPA) [ D- -D d- -d ]
* Amacron/amacron and ordfeminine; resolved to ordfeminine [ _A A_ a_ _a ]
* Amacron/amacron and Atilde/atilde; resolved to atilde [ -A A- a- -a ]
* Omacron/Omacron and masculine; resolved to masculine [ _O O_ o_ _o ]
* Omacron/omacron and Otilde/atilde; resolved to otilde [ -O O- o- -o ]
*
* [ Amacron and Omacron are in Latin-4 (Baltic). ordfeminine and masculine are used for
* spanish. atilde and otilde are used at least for Portuguese ]
*
* at and Aring; resolved to Aring [ AA ]
* guillemotleft and caron; resolved to guillemotleft [ << ]
* ogonek and cedilla; resolved to cedilla [ ,, ]
*
* This probably should be resolved by first checking an additional set of compose tables
* that depend on the locale or selected input method.
*/
static const guint16 gtk_compose_seqs_compact[] = {"""
headerfile_end = """};
#endif /* __GTK_IM_CONTEXT_SIMPLE_SEQS_H__ */
"""
multipleseqs_file_start = """/* GTK - The GIMP Tool Kit
* Copyright (C) 2007, 2008, 2009 GNOME Foundation
*
* 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.
*/
/* This file is gtkimcontextsimplemultiseqs.h.
* This table is for compose sequences that produce two or more characters.
* These sequences where extracted from the upstream Compose file from X.Org.
* This file was generated with http://svn.gnome.org/svn/gtk+/trunk/gtk/compose-parse.py
*
* The table is composed of two parts, $compose_max_sequence_len columns for
* the sequence, and $compose_max_codepoint_len columns for the printed character.
* We pad with 0 for any missing keys or characters.
* The number of sequences is $compose_multi_index_size.
*/
"""
multipleseqs_file_middle = """
static const guint16 gtk_compose_seqs_multi[] = {"""
multipleseqs_file_end = """};
"""
win32seqs_file_start = """/* GTK - The GIMP Tool Kit
* Copyright (C) 2007, 2008, 2009 GNOME Foundation
*
* 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.
*/
/* This file is gtkimcontextsimplewin32seqs.h.
* This table is for compose sequences to be used on Win32 systems.
* These sequences where extracted from the file gtk-win32-sequences.txt
* This file was generated with http://svn.gnome.org/svn/gtk+/trunk/gtk/compose-parse.py
*/
"""
win32seqs_file_middle = """static const guint16 gtk_compose_seqs_win32[] = {"""
win32seqs_file_end = """};
"""
def stringtohex(str): return atoi(str, 16)
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)
def uniq(*args) :
""" Performs a uniq operation on a list or lists """
theInputList = []
for theList in args:
theInputList += theList
theFinalList = []
for elem in theInputList:
if elem not in theFinalList:
theFinalList.append(elem)
return theFinalList
def all_permutations(seq):
""" Borrowed from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252178 """
""" Produces all permutations of the items of a list """
if len(seq) <=1:
yield seq
else:
for perm in all_permutations(seq[1:]):
for i in range(len(perm)+1):
#nb str[0:1] works in both string and list contexts
yield perm[:i] + seq[0:1] + perm[i:]
def usage():
print """compose-parse available parameters:
-a, --algorithmic show sequences saved with algorithmic optimisation
-e, --gtk-expanded when used with --gtk, create file that repeats first column; not usable in GTK+
-g, --gtk show entries that go to GTK+
-h, --help this craft
-m, --multiple shows compose sequences that result to >1 unicode characters
-n, --numeric when used with --gtk, create file with numeric values only
-p, --plane1 show plane1 compose sequences
-q, --quiet do not show verbose output (default is verbose)
-r, --regression shows compose sequences that used to exist in pre-update, but are not found in Xorg's Compose.
-s, --statistics show overall statistics (both algorithmic, non-algorithmic)
-u, --unicodedatatxt show compose sequences derived from UnicodeData.txt (from unicode.org)
-w, --warnings show some non-fatal warnings (useful for maintainer)
--win32 process gtk-win32-sequences.txt and produce gtkimcontextsimplewin32seqs.h
Default is to show statistics.
"""
try:
opts, args = getopt.getopt(sys.argv[1:], "aeghmnpqrsuw",
[ "algorithmic", "gtk-expanded", "gtk", "help", "multiple",
"numeric", "plane1", "quiet", "regression",
"stats", "statistics", "unicodedatatxt", "warnings", "win32"])
except:
usage()
sys.exit(2)
opt_algorithmic = False
opt_gtkexpanded = False
opt_gtk = False
opt_multiple = False
opt_numeric = False
opt_plane1 = False
opt_quiet = False
opt_regression = False
opt_statistics = False
opt_unicodedatatxt = False
opt_warnings = False
opt_win32 = False
no_options = True
for o, a in opts:
if o in ("-a", "--algorithmic"):
opt_algorithmic = True
no_options = False
if o in ("-e", "--gtk-expanded"):
opt_gtkexpanded = True
no_options = False
if o in ("-g", "--gtk"):
opt_gtk = True
no_options = False
if o in ("-h", "--help"):
usage()
sys.exit()
if o in ("-m", "--multiple"):
opt_multiple = True
no_options = False
if o in ("-n", "--numeric"):
opt_numeric = True
no_options = False
if o in ("-p", "--plane1"):
opt_plane1 = True
no_options = False
if o in ("-q", "--quiet"):
opt_quiet = True
no_options = False
if o in ("-r", "--regression"):
opt_regression = True
no_options = False
if o in ("-s", "--statistics"):
opt_statistics = True
if o in ("-u", "--unicodedatatxt"):
opt_unicodedatatxt = True
no_options = False
if o in ("-w", "--warnings"):
opt_warnings = True
if o in ("--win32"):
opt_win32 = True
no_options = False
if no_options:
opt_statistics = True
def download_hook(blocks_transferred, block_size, file_size):
""" A download hook to provide some feedback when downloading """
if blocks_transferred == 0:
if file_size > 0:
if not opt_quiet:
print "Downloading", file_size, "bytes: ",
else:
if not opt_quiet:
print "Downloading: ",
sys.stdout.write('#')
sys.stdout.flush()
def download_file(url):
""" Downloads a file provided a URL. Returns the filename. """
""" Borks on failure """
localfilename = url.split('/')[-1]
if not isfile(localfilename) or getsize(localfilename) <= 0:
if not opt_quiet:
print "Downloading ", url, "..."
try:
urlretrieve(url, localfilename, download_hook)
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
sys.exit(-1)
except:
print "Unexpected error: ", sys.exc_info()[0]
sys.exit(-1)
print " done."
else:
if not opt_quiet:
print "Using cached file for ", url
return localfilename
def process_gdkkeysymsh():
""" Opens the gdkkeysyms.h file from GTK+/gdk/gdkkeysyms.h """
""" Fills up keysymdb with contents """
filename_gdkkeysymsh = download_file(URL_GDKKEYSYMSH)
try:
gdkkeysymsh = open(filename_gdkkeysymsh, 'r')
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
sys.exit(-1)
except:
print "Unexpected error: ", sys.exc_info()[0]
sys.exit(-1)
""" Parse the gdkkeysyms.h file and place contents in keysymdb """
linenum_gdkkeysymsh = 0
keysymdb = {}
for line in gdkkeysymsh.readlines():
linenum_gdkkeysymsh += 1
line = line.strip()
if line == "" or not match('^#define GDK_', line):
continue
components = split('\s+', line)
if len(components) < 3:
print "Invalid line %(linenum)d in %(filename)s: %(line)s"\
% {'linenum': linenum_gdkkeysymsh, 'filename': filename_gdkkeysymsh, 'line': line}
print "Was expecting 3 items in the line"
sys.exit(-1)
if not match('^GDK_', components[1]):
print "Invalid line %(linenum)d in %(filename)s: %(line)s"\
% {'linenum': linenum_gdkkeysymsh, 'filename': filename_gdkkeysymsh, 'line': line}
print "Was expecting a keysym starting with GDK_"
sys.exit(-1)
if components[2][:2] == '0x' and match('[0-9a-fA-F]+$', components[2][2:]):
unival = atoi(components[2][2:], 16)
if unival == 0:
continue
keysymdb[components[1][4:]] = unival
else:
print "Invalid line %(linenum)d in %(filename)s: %(line)s"\
% {'linenum': linenum_gdkkeysymsh, 'filename': filename_gdkkeysymsh, 'line': line}
print "Was expecting a hexadecimal number at the end of the line"
sys.exit(-1)
gdkkeysymsh.close()
""" Patch up the keysymdb with some of our own stuff """
""" This is for a missing keysym from the currently upstream file """
#keysymdb['dead_stroke'] = 0x338
""" This is for a missing keysym from the currently upstream file """
keysymdb['dead_belowdiaeresis'] = 0x324
keysymdb['dead_belowring'] = 0x325
keysymdb['dead_belowcomma'] = 0x326
keysymdb['dead_belowcircumflex']= 0x32d
keysymdb['dead_belowbreve'] = 0x32e
keysymdb['dead_belowtilde'] = 0x330
keysymdb['dead_belowmacron'] = 0x331
"""
keysymdb['KP_Multiply'] = 0x02a
keysymdb['KP_Add'] = 0x02b
keysymdb['KP_Separator'] = 0x02c
keysymdb['KP_Subtract'] = 0x02d
keysymdb['KP_Decimal'] = 0x02e
keysymdb['KP_Divide'] = 0x02f
keysymdb['KP_0'] = 0x030
keysymdb['KP_1'] = 0x031
keysymdb['KP_2'] = 0x032
keysymdb['KP_3'] = 0x033
keysymdb['KP_4'] = 0x034
keysymdb['KP_5'] = 0x035
keysymdb['KP_6'] = 0x036
keysymdb['KP_7'] = 0x037
keysymdb['KP_8'] = 0x038
keysymdb['KP_9'] = 0x039
keysymdb['KP_Equal'] = 0x03d
"""
""" This is^Wwas preferential treatment for Greek """
# keysymdb['dead_tilde'] = 0x342
""" This is^was preferential treatment for Greek """
#keysymdb['combining_tilde'] = 0x342
""" Fixing VoidSymbol """
keysymdb['VoidSymbol'] = 0xFFFF
return keysymdb
def process_keysymstxt():
""" Grabs and opens the keysyms.txt file that Markus Kuhn maintains """
""" This file keeps a record between keysyms <-> unicode chars """
filename_keysymstxt = download_file(URL_KEYSYMSTXT)
try:
keysymstxt = open(filename_keysymstxt, 'r')
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
sys.exit(-1)
except:
print "Unexpected error: ", sys.exc_info()[0]
sys.exit(-1)
""" Parse the keysyms.txt file and place content in keysymdb """
linenum_keysymstxt = 0
keysymdb = {}
for line in keysymstxt.readlines():
linenum_keysymstxt += 1
line = line.strip()
if line == "" or match('^#', line):
continue
components = split('\s+', line)
if len(components) < 5:
print "Invalid line %(linenum)d in %(filename)s: %(line)s'"\
% {'linenum': linenum_keysymstxt, 'filename': filename_keysymstxt, 'line': line}
print "Was expecting 5 items in the line"
sys.exit(-1)
if components[1][0] == 'U' and match('[0-9a-fA-F]+$', components[1][1:]):
unival = atoi(components[1][1:], 16)
if unival == 0:
continue
keysymdb[components[4]] = unival
keysymstxt.close()
""" Patch up the keysymdb with some of our own stuff """
""" This is for a missing keysym from the currently upstream file """
keysymdb['dead_belowdiaeresis'] = 0x324
keysymdb['dead_belowring'] = 0x325
keysymdb['dead_belowcomma'] = 0x326
keysymdb['dead_belowcircumflex']= 0x32d
keysymdb['dead_belowbreve'] = 0x32e
keysymdb['dead_belowtilde'] = 0x330
keysymdb['dead_belowmacron'] = 0x331
"""
keysymdb['KP_Multiply'] = 0x02a
keysymdb['KP_Add'] = 0x02b
keysymdb['KP_Separator'] = 0x02c
keysymdb['KP_Subtract'] = 0x02d
keysymdb['KP_Decimal'] = 0x02e
keysymdb['KP_Divide'] = 0x02f
keysymdb['KP_0'] = 0x030
keysymdb['KP_1'] = 0x031
keysymdb['KP_2'] = 0x032
keysymdb['KP_3'] = 0x033
keysymdb['KP_4'] = 0x034
keysymdb['KP_5'] = 0x035
keysymdb['KP_6'] = 0x036
keysymdb['KP_7'] = 0x037
keysymdb['KP_8'] = 0x038
keysymdb['KP_9'] = 0x039
keysymdb['KP_Equal'] = 0x03d
"""
""" This is preferential treatment for Greek """
""" => we get more savings if used for Greek """
# keysymdb['dead_tilde'] = 0x342
""" This is preferential treatment for Greek """
# keysymdb['combining_tilde'] = 0x342
keysymdb['zerosubscript'] = 0x2080
keysymdb['onesubscript'] = 0x2081
keysymdb['twosubscript'] = 0x2082
keysymdb['threesubscript'] = 0x2083
keysymdb['foursubscript'] = 0x2084
keysymdb['fivesubscript'] = 0x2085
keysymdb['sixsubscript'] = 0x2086
keysymdb['sevensubscript'] = 0x2087
keysymdb['eightsubscript'] = 0x2088
keysymdb['ninesubscript'] = 0x2089
""" This is for a missing keysym from Markus Kuhn's db """
keysymdb['dead_stroke'] = 0xFE63
""" This is for a missing keysym from Markus Kuhn's db """
keysymdb['Oslash'] = 0x0d8
""" This is for a missing (recently added) keysym """
keysymdb['dead_psili'] = 0x313
""" This is for a missing (recently added) keysym """
keysymdb['dead_dasia'] = 0x314
""" Allows to import Multi_key sequences """
keysymdb['Multi_key'] = 0xff20
""" New keysym (no corresponding Unicode character) """
#keysymdb['dead_currency'] = 0xfe6f
return keysymdb
def process_gtkoldsequences():
""" Grabs and opens the keysyms.txt file that Markus Kuhn maintains """
""" This file keeps a record between keysyms <-> unicode chars """
filename_gtkoldsequences = download_file(URL_GTKOLDSEQUENCES)
try:
gtkoldsequencestxt = open(filename_gtkoldsequences, 'r')
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
sys.exit(-1)
except:
print "Unexpected error: ", sys.exc_info()[0]
sys.exit(-1)
""" Parse the gtkoldsequences.txt file and place content in gtkoldsequences """
linenum = 0
for line in gtkoldsequencestxt.readlines():
line = line.strip()
components = split('\s+', line)
if len(components) < 6:
print "Invalid line in %(filename)s: %(line)s'"\
% {'line': line, 'filename': filename_keysymstxt }
print "Was expecting 6 items in the line"
sys.exit(-1)
components[5] = atoi(components[5], 16)
sequence = components[0:6]
sequence.append(False)
if not gtkoldsequences.has_key(components[5]):
gtkoldsequences[components[5]] = []
gtkoldsequences[components[5]].append(sequence)
gtkoldsequencestxt.close()
return gtkoldsequences
def keysymvalue(keysym, file = "n/a", linenum = 0):
""" Extracts a value from the keysym """
""" Find the value of keysym, using the data from keysyms """
""" Use file and linenum to when reporting errors """
if keysym == "":
return 0
if keysymdatabase.has_key(keysym):
return keysymdatabase[keysym]
elif keysym[0] == 'U' and match('[0-9a-fA-F]+$', keysym[1:]):
return atoi(keysym[1:], 16)
elif keysym[:2] == '0x' and match('[0-9a-fA-F]+$', keysym[2:]):
return atoi(keysym[2:], 16)
else:
print 'keysymvalue: UNKNOWN{%(keysym)s}' % { "keysym": keysym }
sys.exit(-1)
def keysymunicodevalue(keysym, file = "n/a", linenum = 0):
""" Extracts a value from the keysym """
""" Find the value of keysym, using the data from keysyms """
""" Use file and linenum to when reporting errors """
if keysym == "":
return 0
if keysymunicodedatabase.has_key(keysym):
return keysymunicodedatabase[keysym]
elif keysym[0] == 'U' and match('[0-9a-fA-F]+$', keysym[1:]):
return atoi(keysym[1:], 16)
elif keysym[:2] == '0x' and match('[0-9a-fA-F]+$', keysym[2:]):
return atoi(keysym[2:], 16)
else:
print 'keysymunicodevalue: UNKNOWN{%(keysym)s}' % { "keysym": keysym }
sys.exit(-1)
def rename_combining(seq):
filtered_sequence = []
for ks in seq:
if findall('^combining_', ks):
filtered_sequence.append(sub('^combining_', 'dead_', ks))
else:
filtered_sequence.append(ks)
return filtered_sequence
def check_if_sequence_exists(allsequences, seq):
seq_len = len(seq)
for s in allsequences:
if seq_len == len(s):
for i in range(seq_len - 1):
if seq[i] != s[i]:
return False
if i == seq_len - 2:
return True
return False
keysymunicodedatabase = process_keysymstxt()
keysymdatabase = process_gdkkeysymsh()
gtkoldsequences = process_gtkoldsequences()
print
if opt_win32:
""" Process the compose sequences in gtk-win32-sequences.txt
"""
try:
composefile_win32 = open(FILENAME_COMPOSE_WIN32, 'r')
except IOError, (errno, strerror):
if not opt_quiet:
print "I/O error(%s): %s" % (errno, strerror)
print "Did not find the win32 compose file %s. Exiting..." % (FILENAME_COMPOSE_WIN32)
except:
print "Unexpected error: ", sys.exc_info()[0]
sys.exit(-1)
""" Parse the compose file in xorg_compose_sequences_win32 """
xorg_compose_sequences_win32 = []
xorg_compose_sequences_win32_algorithmic = []
linenum_compose = 0
for line in composefile_win32.readlines():
linenum_compose += 1
line = line.strip()
if line is "" or match("^XCOMM", line) or match("^#", line):
continue
components = split(':', line)
if len(components) != 2:
print "Invalid line %(linenum_compose)d in %(filename)s: No sequence\
/value pair found" % { "linenum_compose": linenum_compose, "filename": FILENAME_COMPOSE_WIN32 }
exit(-1)
(seq, val ) = split(':', line)
seq = seq.strip()
val = val.strip()
raw_sequence = findall('\w+', seq)
values = split('\s+', val)
unichar_temp = split('"', values[0])
unichar = unichar_temp[1]
try:
codepointstr = values[1]
except IndexError:
codepointstr = 'U' + str(ord(unichar.decode('utf-8')[0]))
if raw_sequence[0][0] == 'U' and match('[0-9a-fA-F]+$', raw_sequence[0][1:]):
raw_sequence[0] = '0x' + raw_sequence[0][1:]
if codepointstr[0] == 'U' and match('[0-9a-fA-F]+$', codepointstr[1:]):
codepoint = atoi(codepointstr[1:], 16)
elif keysymunicodedatabase.has_key(codepointstr):
try:
if keysymdatabase[codepointstr] != keysymunicodedatabase[codepointstr]:
if opt_warnings:
print "DIFFERENCE (nonfatal): 0x%(a)X 0x%(b)X" % { "a": keysymdatabase[codepointstr],
"b": keysymunicodedatabase[codepointstr]},
print raw_sequence, codepointstr
else:
codepoint = keysymunicodedatabase[codepointstr]
except KeyError:
if opt_warnings:
print "KEYERROR (nonfatal): ", codepointstr
codepoint = keysymunicodedatabase[codepointstr]
else:
print
print "Invalid codepoint %(cp)s at line %(linenum_compose)d in %(filename)s:\
%(line)s" % { "cp": codepointstr, "linenum_compose": linenum_compose, "filename": FILENAME_COMPOSE_WIN32, "line": line }
exit(-1)
sequence = rename_combining(raw_sequence)
""" This is temporary filtering, because we need to get an updated Compose file with less sequences """
if "Multi_key" not in sequence:
""" Ignore for now >0xFFFF keysyms """
if codepoint < 0xFFFF:
original_sequence = copy(sequence)
stats_sequence = copy(sequence)
base = sequence.pop()
basechar = keysymvalue(base, FILENAME_COMPOSE_WIN32, linenum_compose)
if basechar < 0xFFFF:
counter = 1
unisequence = []
not_normalised = True
skipping_this = False
for i in range(0, len(sequence)):
bc = basechar
unisequence.append(unichr(keysymunicodevalue(sequence.pop(), FILENAME_COMPOSE_WIN32, linenum_compose)))
if skipping_this:
unisequence = []
for perm in all_permutations(unisequence):
# print counter, original_sequence, unichr(basechar) + "".join(perm)
# print counter, map(unichr, perm)
normalized = normalize('NFC', unichr(basechar) + "".join(perm))
if len(normalized) == 1:
# print 'Base: %(base)s [%(basechar)s], produces [%(unichar)s] (0x%(codepoint)04X)' \
# % { "base": base, "basechar": unichr(basechar), "unichar": unichar, "codepoint": codepoint },
# print "Normalized: [%(normalized)s] SUCCESS %(c)d" % { "normalized": normalized, "c": counter }
stats_sequence_data = map(keysymunicodevalue, stats_sequence)
stats_sequence_data.append(normalized)
xorg_compose_sequences_win32_algorithmic.append(stats_sequence_data)
not_normalised = False
break;
counter += 1
if not_normalised:
original_sequence.append(codepoint)
if check_if_sequence_exists(xorg_compose_sequences_win32, original_sequence):
if not opt_quiet:
print "WARNING: Got duplicate sequence:", original_sequence
xorg_compose_sequences_win32.append(original_sequence)
else:
print "INFO: Sequence was normalised, thus not including:", original_sequence
else:
print "Error in base char !?!"
exit(-2)
else:
print "OVER", sequence
exit(-1)
else:
sequence.append(codepoint)
if check_if_sequence_exists(xorg_compose_sequences_win32, sequence):
if not opt_quiet:
print "WARNING: Got duplicate sequence:", sequence
else:
xorg_compose_sequences_win32.append(sequence)
print win32seqs_file_start
print win32seqs_file_middle
for seq in xorg_compose_sequences_win32:
for sym in seq[:-1]:
print "%18s" % ("GDK_%(sym)s, " % { "sym": sym }),
for i in range(len(seq[:-1]), 5):
print "%18s" % "",
print "0x%(codepoint)04d, " % { "codepoint": seq[-1] }
print win32seqs_file_end
exit(0)
""" Grab and open the compose file from upstream """
filename_compose = download_file(URL_COMPOSE)
try:
composefile = open(filename_compose, 'r')
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
sys.exit(-1)
except:
print "Unexpected error: ", sys.exc_info()[0]
sys.exit(-1)
""" Look if there is a lookaside compose file in the current
directory, and if so, open, then merge with upstream Compose file.
"""
try:
composefile_lookaside = open(FILENAME_COMPOSE_LOOKASIDE, 'r')
except IOError, (errno, strerror):
if not opt_quiet:
print "I/O error(%s): %s" % (errno, strerror)
print "Did not find the lookaside compose file %s. Continuing..." % (FILENAME_LOOKASIDE)
except:
print "Unexpected error: ", sys.exc_info()[0]
sys.exit(-1)
xorg_compose_sequences_raw = []
for seq in composefile.readlines():
xorg_compose_sequences_raw.append(seq)
for seq in composefile_lookaside.readlines():
xorg_compose_sequences_raw.append(seq)
""" Parse the compose file in xorg_compose_sequences"""
xorg_compose_sequences = []
xorg_compose_sequences_algorithmic = []
linenum_compose = 0
for line in xorg_compose_sequences_raw:
linenum_compose += 1
line = line.strip()
if line is "" or match("^XCOMM", line) or match("^#", line):
continue
components = split(':', line)
if len(components) != 2:
print "Invalid line %(linenum_compose)d in %(filename)s: No sequence\
/value pair found" % { "linenum_compose": linenum_compose, "filename": filename_compose }
exit(-1)
(seq, val ) = split(':', line)
seq = seq.strip()
val = val.strip()
raw_sequence = findall('\w+', seq)
values = split('\s+', val)
unichar_temp = split('"', values[0])
unichar = unichar_temp[1]
if len(unichar.decode('utf-8')) > 1:
if unichar[0] != '\\': # Ignore escaped characters.
# No codepoints that are >1 characters yet.
# plane1 multiple
multiseq = []
# print 'Multiple:',
for item in raw_sequence:
# print item,
multiseq.append(item)
if multisequence_maxseqlen < len(raw_sequence):
multisequence_maxseqlen = len(raw_sequence)
# print len(unichar.decode('utf-8')),
multicodepoint = []
for item in unichar.decode('utf-8'):
# print "U%04X " % ord(item),
multicodepoint.append("U%04X" % ord(item))
if multisequence_maxvallen < len(unichar.decode('utf-8')):
multisequence_maxvallen = len(unichar.decode('utf-8'))
# print
multisequences[unichar.decode('utf-8')] = [multiseq, multicodepoint]
continue
#if len(values) == 1:
# print "SKIPPING PLANE1:", len(unichar.decode('utf-8')), tuple(values[0])
# continue
#print values, tuple(unichar)
try:
codepointstr = values[1]
except IndexError:
codepointstr = 'U' + str(ord(unichar.decode('utf-8')[0]))
if raw_sequence[0][0] == 'U' and match('[0-9a-fA-F]+$', raw_sequence[0][1:]):
raw_sequence[0] = '0x' + raw_sequence[0][1:]
if codepointstr[0] == 'U' and match('[0-9a-fA-F]+$', codepointstr[1:]):
codepoint = atoi(codepointstr[1:], 16)
elif keysymunicodedatabase.has_key(codepointstr):
try:
if keysymdatabase[codepointstr] != keysymunicodedatabase[codepointstr]:
if opt_warnings:
print "DIFFERENCE (nonfatal): 0x%(a)X 0x%(b)X" % { "a": keysymdatabase[codepointstr],
"b": keysymunicodedatabase[codepointstr]},
print raw_sequence, codepointstr
else:
codepoint = keysymunicodedatabase[codepointstr]
except KeyError:
if opt_warnings:
print "KEYERROR (nonfatal): ", codepointstr
codepoint = keysymunicodedatabase[codepointstr]
else:
print
print "Invalid codepoint %(cp)s at line %(linenum_compose)d in %(filename)s:\
%(line)s" % { "cp": codepointstr, "linenum_compose": linenum_compose, "filename": filename_compose, "line": line }
exit(-1)
sequence = rename_combining(raw_sequence)
if "dead_currency" in sequence:
continue
reject_this = False
for i in sequence:
if keysymvalue(i) > 0xFFFF:
reject_this = True
if opt_plane1:
print 'Plane1:', sequence
break
if reject_this:
continue
for i in range(len(sequence)):
if sequence[i] == "0x0342":
sequence[i] = "dead_tilde"
if "U0313" in sequence or "U0314" in sequence or "0x0313" in sequence or "0x0314" in sequence:
continue
""" This is temporary filtering, because we need to get an updated Compose file with less sequences """
if "Multi_key" not in sequence:
""" Ignore for now >0xFFFF keysyms """
if codepoint < 0xFFFF:
original_sequence = copy(sequence)
stats_sequence = copy(sequence)
base = sequence.pop()
basechar = keysymvalue(base, filename_compose, linenum_compose)
if basechar < 0xFFFF:
counter = 1
unisequence = []
not_normalised = True
skipping_this = False
for i in range(0, len(sequence)):
bc = basechar
unisequence.append(unichr(keysymunicodevalue(sequence.pop(), filename_compose, linenum_compose)))
if skipping_this:
unisequence = []
for perm in all_permutations(unisequence):
# print counter, original_sequence, unichr(basechar) + "".join(perm)
# print counter, map(unichr, perm)
normalized = normalize('NFC', unichr(basechar) + "".join(perm))
if len(normalized) == 1:
# print 'Base: %(base)s [%(basechar)s], produces [%(unichar)s] (0x%(codepoint)04X)' \
# % { "base": base, "basechar": unichr(basechar), "unichar": unichar, "codepoint": codepoint },
# print "Normalized: [%(normalized)s] SUCCESS %(c)d" % { "normalized": normalized, "c": counter }
stats_sequence_data = map(keysymunicodevalue, stats_sequence)
stats_sequence_data.append(normalized)
xorg_compose_sequences_algorithmic.append(stats_sequence_data)
not_normalised = False
break;
counter += 1
if not_normalised:
original_sequence.append(codepoint)
if check_if_sequence_exists(xorg_compose_sequences, original_sequence):
if not opt_quiet:
print "WARNING: Got duplicate sequence:", original_sequence
xorg_compose_sequences.append(original_sequence)
""" print xorg_compose_sequences[-1] """
else:
print "Error in base char !?!"
exit(-2)
else:
print "OVER", sequence
exit(-1)
else:
sequence.append(codepoint)
if check_if_sequence_exists(xorg_compose_sequences, sequence):
if not opt_quiet:
print "WARNING: Got duplicate sequence:", sequence
xorg_compose_sequences.append(sequence)
""" print xorg_compose_sequences[-1] """
def sequence_cmp(x, y):
if keysymvalue(x[0]) > keysymvalue(y[0]):
return 1
elif keysymvalue(x[0]) < keysymvalue(y[0]):
return -1
elif len(x) > len(y):
return 1
elif len(x) < len(y):
return -1
elif keysymvalue(x[1]) > keysymvalue(y[1]):
return 1
elif keysymvalue(x[1]) < keysymvalue(y[1]):
return -1
elif len(x) < 4:
return 0
elif keysymvalue(x[2]) > keysymvalue(y[2]):
return 1
elif keysymvalue(x[2]) < keysymvalue(y[2]):
return -1
elif len(x) < 5:
return 0
elif keysymvalue(x[3]) > keysymvalue(y[3]):
return 1
elif keysymvalue(x[3]) < keysymvalue(y[3]):
return -1
elif len(x) < 6:
return 0
elif keysymvalue(x[4]) > keysymvalue(y[4]):
return 1
elif keysymvalue(x[4]) < keysymvalue(y[4]):
return -1
else:
return 0
def sequence_unicode_cmp(x, y):
if keysymunicodevalue(x[0]) > keysymunicodevalue(y[0]):
return 1
elif keysymunicodevalue(x[0]) < keysymunicodevalue(y[0]):
return -1
elif len(x) > len(y):
return 1
elif len(x) < len(y):
return -1
elif keysymunicodevalue(x[1]) > keysymunicodevalue(y[1]):
return 1
elif keysymunicodevalue(x[1]) < keysymunicodevalue(y[1]):
return -1
elif len(x) < 4:
return 0
elif keysymunicodevalue(x[2]) > keysymunicodevalue(y[2]):
return 1
elif keysymunicodevalue(x[2]) < keysymunicodevalue(y[2]):
return -1
elif len(x) < 5:
return 0
elif keysymunicodevalue(x[3]) > keysymunicodevalue(y[3]):
return 1
elif keysymunicodevalue(x[3]) < keysymunicodevalue(y[3]):
return -1
elif len(x) < 6:
return 0
elif keysymunicodevalue(x[4]) > keysymunicodevalue(y[4]):
return 1
elif keysymunicodevalue(x[4]) < keysymunicodevalue(y[4]):
return -1
else:
return 0
def sequence_algorithmic_cmp(x, y):
if len(x) < len(y):
return -1
elif len(x) > len(y):
return 1
else:
for i in range(len(x)):
if x[i] < y[i]: