forked from fujiwarat/ibus-anthy
-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.py
1705 lines (1533 loc) · 68 KB
/
main.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
# vim:set noet ts=4:
#
# ibus-anthy - The Anthy engine for IBus
#
# Copyright (c) 2007-2008 Peng Huang <shawn.p.huang@gmail.com>
# Copyright (c) 2009 Hideaki ABE <abe.sendai@gmail.com>
# Copyright (c) 2010-2021 Takao Fujiwara <takao.fujiwara1@gmail.com>
# Copyright (c) 2007-2019 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from os import environ, getuid, path
import binascii
import codecs
import functools
import locale
import os, sys
import xml.dom.minidom
import gettext
from gettext import dgettext
from gi import require_version as gi_require_version
gi_require_version('Gio', '2.0')
gi_require_version('GLib', '2.0')
gi_require_version('Gtk', '3.0')
gi_require_version('Gdk', '3.0')
gi_require_version('GdkX11', '3.0')
gi_require_version('Pango', '1.0')
gi_require_version('IBus', '1.0')
from gi.repository import Gio
from gi.repository import GLib
# set_prgname before importing other modules to show the name in warning
# messages when import modules are failed. E.g. Gtk.
GLib.set_prgname('ibus-setup-anthy')
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GdkX11
from gi.repository import Pango
from gi.repository import IBus
import _config as config
from anthyprefs import AnthyPrefs
DOMAINNAME = 'ibus-anthy'
_ = lambda a : dgettext('ibus-anthy', a)
def l_to_s(l):
return str(sorted([str(s) for s in l])).replace('\'', '')
def s_to_l(s):
return [] if s == '[]' else s[1:-1].replace(' ', '').split(',')
class AnthySetup(object):
def __init__(self):
# Python's locale module doesn't provide all methods on some
# operating systems like FreeBSD
try:
locale.bindtextdomain(DOMAINNAME, config.LOCALEDIR)
locale.bind_textdomain_codeset(DOMAINNAME, 'UTF-8')
except AttributeError:
pass
gettext.bindtextdomain(DOMAINNAME, config.LOCALEDIR)
self.__prefs = AnthyPrefs()
builder_file = path.join(path.dirname(__file__), 'setup.ui')
self.__builder = builder = Gtk.Builder()
builder.set_translation_domain(DOMAINNAME)
builder.add_from_file(builder_file)
toplevel = builder.get_object('main')
parent_xid = 0
parent_wmname = None
parent_wmclass = None
try:
parent_xid = int(environ['IBUS_SETUP_XID'])
if parent_xid != 0:
parent_wmname = 'ibus-setup'
parent_wmclass = 'Ibus-setup'
except:
pass
try:
if parent_xid == 0:
parent_xid = int(environ['GNOME_CONTROL_CENTER_XID'])
if parent_xid != 0:
parent_wmname = 'gnome-conrol-center'
parent_wmclass = 'Gnome-conrol-center'
except:
pass
if parent_xid != 0:
def set_transient(obj, pspec):
window = toplevel.get_window()
if window == None:
return
parent_window = GdkX11.X11Window.foreign_new_for_display(Gdk.Display.get_default(),
parent_xid)
if parent_window != None:
window.set_transient_for(parent_window)
toplevel.set_wmclass(parent_wmname, parent_wmclass)
toplevel.set_modal(True)
toplevel.set_type_hint(Gdk.WindowTypeHint.DIALOG)
toplevel.connect('notify::window', set_transient)
toplevel.show()
self.__init_bus_connected()
def __init_bus_connected(self):
builder = self.__builder
prefs = self.__prefs
self.__thumb_kb_layout_mode = None
self.__thumb_kb_layout = None
self.__japanese_ordered_dict = {}
# glade 'icon_name' property has a custom scaling and it seems
# to be difficult to show the complicated small icon in metacity.
# This can add the pixbuf without scaling.
anthydir = path.dirname(path.dirname(__file__))
if not anthydir:
anthydir = '/usr/share/ibus-anthy'
icon_path = path.join(anthydir, 'icons', 'ibus-anthy.png')
if path.exists(icon_path):
builder.get_object('main').set_icon_from_file(icon_path)
else:
icon_path = 'ibus-anthy'
builder.get_object('main').set_icon_name(icon_path)
for name in ['input-mode', 'typing-method', 'conversion-segment-mode',
'period-style', 'symbol-style', 'ten-key-mode',
'behavior-on-focus-out', 'behavior-on-period',
'half-width-symbol', 'half-width-number', 'half-width-space',
'latin-with-shift',
'thumb:keyboard-layout-mode', 'thumb:keyboard-layout',
'thumb:fmv-extension', 'thumb:handakuten']:
section, key = self.__get_section_key(name)
prefs.bind(section, key,
builder.get_object(name),
'active',
Gio.SettingsBindFlags.DEFAULT)
prefs.bind('thumb', 'keyboard-layout-mode',
builder.get_object('thumb:keyboard-layout'),
'sensitive',
Gio.SettingsBindFlags.INVERT_BOOLEAN)
tv = builder.get_object('menu-visible:treeview')
ls = Gtk.ListStore(str, bool, str)
tv.set_model(ls)
column = Gtk.TreeViewColumn(' ')
renderer = Gtk.CellRendererToggle()
renderer.set_radio(False)
renderer.connect('toggled', self.__renderer_toggled_cb, ls)
column.pack_start(renderer, False)
column.set_cell_data_func(renderer,
self.__toggle_menu_visible_cell_cb,
1)
tv.append_column(column)
column = Gtk.TreeViewColumn(_("Menu label"))
renderer = Gtk.CellRendererText()
column.pack_start(renderer, False)
column.set_cell_data_func(renderer,
self.__text_menu_visible_cell_cb,
2)
tv.append_column(column)
self.__append_menus_in_model()
l = ['default', 'atok', 'wnn']
s_type = prefs.get_value('common', 'shortcut-type')
s_type = s_type if s_type in l else 'default'
builder.get_object('shortcut-type').set_active(l.index(s_type))
prefs.bind('common', 'page-size',
builder.get_object('page-size').get_adjustment(),
'value',
Gio.SettingsBindFlags.DEFAULT)
tv = builder.get_object('shortcut')
tv.append_column(Gtk.TreeViewColumn(_("Command"),
Gtk.CellRendererText(), text=0))
renderer = Gtk.CellRendererText()
renderer.set_property('ellipsize', Pango.EllipsizeMode.END)
tv.append_column(Gtk.TreeViewColumn(_("Shortcut"),
renderer, text=1))
tv.get_selection().connect_after('changed',
self.on_selection_changed, 0)
ls = Gtk.ListStore(str, str)
shortcuts = self.__prefs.get_value('shortcut', s_type)
for k in shortcuts.keys():
ls.append([k, l_to_s(shortcuts[k])])
tv.set_model(ls)
self.__keymap = None
GLib.idle_add(self.__update_keymap_label,
priority = GLib.PRIORITY_LOW)
self.__thumb_kb_layout_mode = builder.get_object('thumb:keyboard-layout-mode')
self.__thumb_kb_layout = builder.get_object('thumb:keyboard-layout')
self.__set_thumb_kb_label()
for name in ['thumb:ls', 'thumb:rs']:
section, key = self.__get_section_key(name)
builder.get_object(name).set_text(prefs.get_value(section, key))
tv = builder.get_object('es:treeview')
tv.append_column(Gtk.TreeViewColumn('', Gtk.CellRendererText(), text=0))
tv.get_selection().connect_after('changed',
self.on_selection_changed, 1)
tv.set_model(Gtk.ListStore(str))
key = 'dict-admin-command'
cli = self.__get_dict_cli_from_list(prefs.get_value('common', key))
name = 'dict:entry-edit-dict-command'
builder.get_object(name).set_text(cli)
key = 'add-word-command'
cli = self.__get_dict_cli_from_list(prefs.get_value('common', key))
name = 'dict:entry-add-word-command'
builder.get_object(name).set_text(cli)
tv = builder.get_object('dict:view')
column = Gtk.TreeViewColumn(' ')
renderer = Gtk.CellRendererText()
column.pack_start(renderer, False)
column.set_cell_data_func(renderer, self.__text_cell_data_cb, 1)
tv.append_column(column)
column = Gtk.TreeViewColumn(_("Description"))
renderer = Gtk.CellRendererText()
column.pack_start(renderer, False)
column.set_cell_data_func(renderer, self.__text_cell_data_cb, 2)
column.set_expand(True)
tv.append_column(column)
# Translators: "Embd" is an abbreviation of "embedded".
column = Gtk.TreeViewColumn(_("Embd"))
renderer = Gtk.CellRendererToggle()
renderer.set_radio(False)
column.pack_start(renderer, False)
column.set_cell_data_func(renderer, self.__toggle_cell_data_cb, 3)
tv.append_column(column)
# Translators: "Sgl" is an abbreviation of "single".
column = Gtk.TreeViewColumn(_("Sgl"))
renderer = Gtk.CellRendererToggle()
renderer.set_radio(False)
column.pack_start(renderer, False)
column.set_cell_data_func(renderer, self.__toggle_cell_data_cb, 4)
tv.append_column(column)
'''
Unfortunately reverse conversion is too slow.
# Translators: "Rev" is an abbreviation of "reverse".
column = Gtk.TreeViewColumn(_("Rev"))
renderer = Gtk.CellRendererToggle()
renderer.set_radio(False)
column.pack_start(renderer, False)
column.set_cell_data_func(renderer, self.__toggle_cell_data_cb, 5)
tv.append_column(column)
'''
ls = Gtk.ListStore(str, str, str, bool, bool, bool)
tv.set_model(ls)
self.__append_dicts_in_model()
self.__init_japanese_sort()
self.__init_about_vbox(icon_path)
builder.connect_signals(self)
def __init_japanese_sort(self):
japanese_ordered_dict = {}
japanese_ordered_list = self.__prefs.get_japanese_ordered_list()
for index, c in enumerate(japanese_ordered_list):
japanese_ordered_dict[c] = index
self.__japanese_ordered_dict = japanese_ordered_dict;
def __init_about_vbox(self, icon_path):
about_dialog = self.__builder.get_object('about_dialog')
about_vbox = self.__builder.get_object('about_vbox')
about_dialog.set_version(self.__prefs.get_version())
if icon_path != None:
if icon_path[0] == '/':
image = Gtk.Image.new_from_file(icon_path)
about_dialog.set_logo(image.get_pixbuf())
else:
icon_theme = Gtk.IconTheme.get_default()
try:
pixbuf = icon_theme.load_icon(icon_path, 48, 0)
about_dialog.set_logo(pixbuf)
except Exception as err:
print('Not found icon', str(err), file=sys.stderr)
print('Need to run gtk-update-icon-cache', file=sys.stderr)
content_area = about_dialog.get_content_area()
list = content_area.get_children()
vbox = list[0]
for w in vbox.get_children():
old_parent = w.props.parent
w.unparent()
w.emit('parent-set', old_parent)
about_vbox.pack_start(w, False, False, 0)
def __get_userhome(self):
if 'HOME' not in environ:
import pwd
userhome = pwd.getpwuid(getuid()).pw_dir
else:
userhome = environ['HOME']
userhome = userhome.rstrip('/')
return userhome
def __get_section_key(self, name):
i = name.find(':')
if i > 0:
section = name[:i]
key = name[i + 1:]
else:
section = 'common'
key = name
return (section, key)
def __run_message_dialog(self, message, type=Gtk.MessageType.INFO):
dlg = Gtk.MessageDialog(
transient_for=self.__builder.get_object('main'),
message_type=type,
buttons=Gtk.ButtonsType.OK,
text=message)
dlg.run()
dlg.destroy()
def _get_shortcut_sec(self):
l = ['default', 'atok', 'wnn']
iter = self.__builder.get_object('shortcut-type').get_active_iter()
model = self.__builder.get_object('shortcut-type').get_model()
s_type = model[iter][0].lower()
return 'shortcut/' + (s_type if s_type in l else 'default')
def __get_shortcut_group(self):
l = ['default', 'atok', 'wnn']
iter = self.__builder.get_object('shortcut-type').get_active_iter()
model = self.__builder.get_object('shortcut-type').get_model()
s_type = model[iter][0].lower()
return s_type if s_type in l else 'default'
def __japanese_tuple_sort(self, a, b):
if a[1] == b[1]:
# http://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons
return (a[0] > b[0]) - (a[0] < b[0])
elif a[1] in self.__japanese_ordered_dict and \
b[1] in self.__japanese_ordered_dict:
return self.__japanese_ordered_dict[a[1]] - \
self.__japanese_ordered_dict[b[1]]
elif a[1] not in self.__japanese_ordered_dict and \
b[1] in self.__japanese_ordered_dict:
return 1
elif a[1] in self.__japanese_ordered_dict and \
b[1] not in self.__japanese_ordered_dict:
return -1
else:
return (a[1] > b[1]) - (a[1] < b[1])
def __japanese_thumb_sort(self, a, b):
# http://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons
return (a[0] > b[0]) - (a[0] < b[0])
def __renderer_toggled_cb(self, renderer, path, model):
prefs = self.__prefs
enabled = not model[path][1]
model[path][1] = enabled
key = model[path][0]
prefs.set_value('common', key, enabled)
def __toggle_menu_visible_cell_cb(self, column, renderer, model, iter, id):
l = self.__builder.get_object('menu-visible:treeview').get_model()
active = l.get_value(iter, id)
renderer.set_property('active', active)
def __text_menu_visible_cell_cb(self, column, renderer, model, iter, id):
l = self.__builder.get_object('menu-visible:treeview').get_model()
text = l.get_value(iter, id)
renderer.set_property('text', text)
def __append_menus_in_model(self):
prefs = self.__prefs
l = self.__builder.get_object('menu-visible:treeview').get_model()
l.append(['show-input-mode',
prefs.get_value('common', 'show-input-mode'),
_("Input mode")])
l.append(['show-typing-method',
prefs.get_value('common', 'show-typing-method'),
_("Typing method")])
l.append(['show-segment-mode',
prefs.get_value('common', 'show-segment-mode'),
_("Segment mode")])
l.append(['show-dict-mode',
prefs.get_value('common', 'show-dict-mode'),
_("Dictionary mode")])
l.append(['show-dict-config',
prefs.get_value('common', 'show-dict-config'),
_("Dictionary - Anthy")])
l.append(['show-preferences',
prefs.get_value('common', 'show-preferences'),
_("Preferences - Anthy")])
def __get_romaji_treeview_custom_key_table(self, method):
prefs = self.__prefs
rule = {}
ls = Gtk.ListStore(str, str, str)
tv = self.__builder.get_object('treeview_custom_key_table')
section = 'romaji-typing-rule'
keymap = prefs.get_value(section, 'list')[method]
for key in keymap.keys():
value = keymap[key]
ch = prefs.typing_from_config_key(key)
if ch == '':
continue
# config.set_value(key, None) is not supported.
if value != None and value != '':
rule[ch] = value
for key, value in sorted(list(rule.items()), \
key = functools.cmp_to_key(self.__japanese_tuple_sort)):
ls.append(['romaji', key, value])
tv.set_model(None)
tv.append_column(Gtk.TreeViewColumn(_(_("Input Chars")),
Gtk.CellRendererText(), text=1))
tv.append_column(Gtk.TreeViewColumn(_(_("Output Chars")),
Gtk.CellRendererText(), text=2))
tv.set_model(ls)
return tv
def __get_kana_treeview_custom_key_table(self, method):
prefs = self.__prefs
rule = {}
ls = Gtk.ListStore(str, str, str)
tv = self.__builder.get_object('treeview_custom_key_table')
section = 'kana-typing-rule'
keymap = prefs.get_value(section, 'list')[method]
for key in keymap.keys():
value = keymap[key]
ch = prefs.typing_from_config_key(key)
if ch == '':
continue
# config.set_value(key, None) is not supported.
if value != None and value != '':
rule[ch] = value
for key, value in sorted(list(rule.items()), \
key = functools.cmp_to_key(self.__japanese_tuple_sort)):
ls.append(['kana', key, value])
tv.set_model(None)
tv.append_column(Gtk.TreeViewColumn(_(_("Input Chars")),
Gtk.CellRendererText(), text=1))
tv.append_column(Gtk.TreeViewColumn(_(_("Output Chars")),
Gtk.CellRendererText(), text=2))
tv.set_model(ls)
return tv
def __get_thumb_treeview_custom_key_table(self, method):
prefs = self.__prefs
rule = {}
ls = Gtk.ListStore(str, str, str, str, str)
tv = self.__builder.get_object('treeview_custom_key_table')
section = 'thumb-typing-rule'
keymap = prefs.get_value(section, 'list')[method]
for key in keymap.keys():
value = keymap[key]
ch = prefs.typing_from_config_key(key)
if ch == '':
continue
# config.set_value(key, None) is not supported.
if value != None and len(value) == 3 and \
((value[0] != None and value[0] != '') or \
(value[1] != None and value[1] != '') or \
(value[2] != None and value[2] != '')):
rule[ch] = {}
rule[ch][0] = value[0]
rule[ch][1] = value[1]
rule[ch][2] = value[2]
for key, value in sorted(list(rule.items()), \
key = functools.cmp_to_key(self.__japanese_thumb_sort)):
ls.append(['thumb', key, value[0], value[2], value[1]])
tv.set_model(None)
tv.append_column(Gtk.TreeViewColumn(_(_("Input")),
Gtk.CellRendererText(), text=1))
tv.append_column(Gtk.TreeViewColumn(_(_("Single")),
Gtk.CellRendererText(), text=2))
tv.append_column(Gtk.TreeViewColumn(_(_("Left")),
Gtk.CellRendererText(), text=3))
tv.append_column(Gtk.TreeViewColumn(_(_("Right")),
Gtk.CellRendererText(), text=4))
tv.set_model(ls)
return tv
def __show_dialog_custom_key_table_extention(self, mode):
hbox_combo = self.__builder.get_object('hbox_for_combobox_custom_key_table')
label_left = self.__builder.get_object('label_left_thumb_shift_custom_key')
entry_left = self.__builder.get_object('entry_left_thumb_shift_custom_key')
label_right = self.__builder.get_object('label_right_thumb_shift_custom_key')
entry_right = self.__builder.get_object('entry_right_thumb_shift_custom_key')
if mode == 'thumb':
hbox_combo.show()
label_left.show()
entry_left.show()
label_right.show()
entry_right.show()
elif mode == 'kana':
hbox_combo.show()
label_left.hide()
entry_left.hide()
label_right.hide()
entry_right.hide()
else:
hbox_combo.hide()
label_left.hide()
entry_left.hide()
label_right.hide()
entry_right.hide()
def __connect_dialog_custom_key_table_buttons(self, mode):
tv = self.__builder.get_object('treeview_custom_key_table')
tv.get_selection().connect_after('changed',
self.on_selection_custom_key_table_changed, 0)
entry = self.__builder.get_object('entry_input_custom_key')
entry.connect('changed', self.on_entry_custom_key_changed, mode)
entry = self.__builder.get_object('entry_output_custom_key')
entry.connect('changed', self.on_entry_custom_key_changed, mode)
entry = self.__builder.get_object('entry_left_thumb_shift_custom_key')
entry.connect('changed', self.on_entry_custom_key_changed, mode)
entry = self.__builder.get_object('entry_right_thumb_shift_custom_key')
entry.connect('changed', self.on_entry_custom_key_changed, mode)
button = self.__builder.get_object('button_add_custom_key')
button.set_sensitive(False)
button.connect('clicked', self.on_btn_add_custom_key, mode)
button = self.__builder.get_object('button_remove_custom_key')
button.set_sensitive(False)
button.connect('clicked', self.on_btn_remove_custom_key, tv)
def __disconnect_dialog_custom_key_table_buttons(self):
tv = self.__builder.get_object('treeview_custom_key_table')
combobox = self.__builder.get_object('combobox_custom_key_table')
if tv != None:
for column in tv.get_columns():
tv.remove_column(column)
for child in tv.get_children():
tv.remove(child)
entry = self.__builder.get_object('entry_input_custom_key')
entry.disconnect_by_func(self.on_entry_custom_key_changed)
entry.set_text('')
entry = self.__builder.get_object('entry_output_custom_key')
entry.disconnect_by_func(self.on_entry_custom_key_changed)
entry.set_text('')
entry = self.__builder.get_object('entry_left_thumb_shift_custom_key')
entry.disconnect_by_func(self.on_entry_custom_key_changed)
entry = self.__builder.get_object('entry_right_thumb_shift_custom_key')
entry.disconnect_by_func(self.on_entry_custom_key_changed)
button = self.__builder.get_object('button_add_custom_key')
button.disconnect_by_func(self.on_btn_add_custom_key)
button = self.__builder.get_object('button_remove_custom_key')
button.disconnect_by_func(self.on_btn_remove_custom_key)
combobox.clear()
combobox.disconnect_by_func(self.on_cb_custom_key_table_changed)
def __run_dialog_custom_key_table(self, widget, mode):
prefs = self.__prefs
dlg = self.__builder.get_object('dialog_custom_key_table')
dlg.set_transient_for(widget.get_toplevel())
label = self.__builder.get_object('label_custom_key_table')
label_output = self.__builder.get_object('label_output_custom_key')
list_labels = []
if mode == 'romaji':
dlg.set_title(_("Customize Romaji Key Table"))
label.set_label(_("_Romaji Key Table:"))
label_output.set_label(_("_Output Chars"))
list_labels = [['default', _("Default")]]
self.__show_dialog_custom_key_table_extention(mode)
elif mode == 'kana':
dlg.set_title(_("Customize Kana Key Table"))
label.set_label(_("_Kana Key Table:"))
label_output.set_label(_("_Output Chars"))
list_labels = [['jp', _("Japanese Keyboard Layout")],
['us', _("U.S. Keyboard Layout")]]
self.__show_dialog_custom_key_table_extention(mode)
elif mode == 'thumb':
dlg.set_title(_("Customize Thumb Shift Key Table"))
label.set_label(_("_Thumb Shift Key Table:"))
label_output.set_label(_("Single _Output Chars"))
list_labels = [['base', _("Base")],
['nicola-j-table', _("NICOLA-J key extension")],
['nicola-a-table', _("NICOLA-A key extension")],
['nicola-f-table', _("NICOLA-F key extension")],
['kb231-j-fmv-table', _("FMV KB231-J key extension")],
['kb231-a-fmv-table', _("FMV KB231-A key extension")],
['kb231-f-fmv-table', _("FMV KB231-F key extension")],
['kb611-j-fmv-table', _("FMV KB611-J key extension")],
['kb611-a-fmv-table', _("FMV KB611-A key extension")],
['kb611-f-fmv-table', _("FMV KB611-F key extension")],
]
self.__show_dialog_custom_key_table_extention(mode)
ls = Gtk.ListStore(str, str)
for s in list_labels:
ls.append([s[1], s[0]])
renderer = Gtk.CellRendererText()
combobox = self.__builder.get_object('combobox_custom_key_table')
combobox.pack_start(renderer, True)
combobox.add_attribute(renderer, 'text', 0)
combobox.set_model(ls)
tv = None
if mode == 'romaji':
method = prefs.get_value('romaji-typing-rule', 'method')
if method == None:
method = 'default'
tv = self.__get_romaji_treeview_custom_key_table(method)
if mode == 'kana':
method = prefs.get_value('kana-typing-rule', 'method')
if method == None:
method = 'jp'
tv = self.__get_kana_treeview_custom_key_table(method)
if mode == 'thumb':
method = prefs.get_value('thumb-typing-rule', 'method')
if method == None:
method = 'base'
tv = self.__get_thumb_treeview_custom_key_table(method)
self.__connect_dialog_custom_key_table_buttons(mode)
id = 0
# thumb uses all tables so the default is always 0.
if mode != 'thumb':
id = -1
for index, labels in enumerate(list_labels):
if labels[0] == method:
id = index
break
if id == -1:
ls.append([method, method])
combobox.set_model(ls)
id = len(list_labels)
combobox.set_active(id)
combobox.connect('changed', self.on_cb_custom_key_table_changed, mode)
id = dlg.run()
dlg.hide()
self.__disconnect_dialog_custom_key_table_buttons()
def __set_thumb_kb_label(self):
if self.__thumb_kb_layout_mode == None or \
self.__thumb_kb_layout == None:
return
section, key = self.__get_section_key(
Gtk.Buildable.get_name(self.__thumb_kb_layout_mode))
layout_mode = self.__prefs.get_value(section, key)
if layout_mode:
self.__thumb_kb_layout.set_sensitive(False)
else:
self.__thumb_kb_layout.set_sensitive(True)
def __get_dict_cli_from_list(self, cli_list):
cli_str = cli_list[0]
if len(cli_list) <= 2:
return cli_str
cli_str = cli_str + ' ' + ' '.join(cli_list[2:])
return cli_str
def __get_quoted_id(self, file):
id = file
has_mbcs = False
for i in range(0, len(id)):
if ord(id[i]) >= 0x7f:
has_mbcs = True
break
if has_mbcs:
id = str(binascii.hexlify(id.encode()), 'ascii')
if id.find('/') >=0:
id = id[id.rindex('/') + 1:]
if id.find('.') >=0:
id = id[:id.rindex('.')]
if id.startswith('0x'):
id = str(binascii.hexlify(id.encode()), 'ascii')
has_mbcs = True
if has_mbcs:
id = '0x' + id
return id
def __get_dict_file_from_id(self, selected_id):
files = self.__prefs.get_value('dict', 'files')
return files.get(selected_id, None)
def __is_system_dict_file_from_id(self, selected_id):
prefs = self.__prefs
dict_item = prefs.get_value('dict', 'list')[selected_id]
return dict_item.is_system
def __append_dict_id_in_model(self, id):
prefs = self.__prefs
section = 'dict/file/' + id
dicts = prefs.get_value('dict', 'list')
dict_item = dicts[id]
short_label = dict_item.short_label
long_label = dict_item.long_label
embed = dict_item.embed
single = dict_item.single
reverse = dict_item.reverse
if dict_item.is_system:
long_label = _(long_label)
l = self.__builder.get_object('dict:view').get_model()
l.append([id, short_label, long_label, embed, single, reverse])
def __append_dicts_in_model(self):
prefs = self.__prefs
order = prefs.get_value('dict', 'order')
dict_files = prefs.get_value('dict', 'files')
if len(order) == 0:
order = list(dict_files.keys())
for id in order:
if id == 'embedded':
continue
files = dict_files[id]
for file in files:
if not path.exists(file):
continue
self.__append_dict_id_in_model(id)
def __append_user_dict_from_dialog(self, file, id, new):
files_dict = self.__prefs.get_value('dict', 'files')
if new:
files = []
for v in files_dict.values():
for f in v:
files.append(f)
if file in files:
self.__run_message_dialog(_("Your choosed file has already been added: ") + file,
Gtk.MessageType.ERROR)
return
if not path.exists(file):
self.__run_message_dialog(_("The file you have chosen does not exist: ") + file,
Gtk.MessageType.ERROR)
return
if path.isdir(file):
self.__run_message_dialog(_("Your choosed file is a directory: " + file),
Gtk.MessageType.ERROR)
return
if file.startswith(self.__get_userhome() + '/.anthy'):
self.__run_message_dialog(_("You cannot add dictionaries in the anthy private directory: " + file),
Gtk.MessageType.ERROR)
return
else:
file = files_dict[id][0]
if new:
id = self.__get_quoted_id(file)
if id == None or id == '':
self.__run_message_dialog(_("Your file path is not good: ") + file,
Gtk.MessageType.ERROR)
return
single = self.__builder.get_object('dict:single').get_active()
embed = self.__builder.get_object('dict:embed').get_active()
reverse = self.__builder.get_object('dict:reverse').get_active()
short_label = self.__builder.get_object('dict:short_entry').get_text()
if len(short_label) > 1:
short_label = short_label[0]
long_label = self.__builder.get_object('dict:long_entry').get_text()
if new:
order = self.__prefs.get_value('dict', 'order')
if len(order) == 0:
order = list(self.__prefs.get_value('dict', 'files').keys())
order.append(id)
self.__prefs.set_value('dict', 'order', order)
self.__prefs.set_list_item('dict', 'files', id, [file])
filename = file
if filename.find('/') >=0:
filename = filename[filename.rindex('/') + 1:]
if filename.find('.') >=0:
filname = filename[:filename.rindex('.')]
if short_label == None or short_label == '':
short_label = filename[0]
if long_label == None or long_label == '':
long_label = filename
self.__update_dict_values(new, id, short_label, long_label, embed, single, reverse)
files = []
def __init_dict_chooser_dialog(self):
self.__builder.get_object('dict:single').set_active(True)
self.__builder.get_object('dict:embed').set_active(False)
self.__builder.get_object('dict:reverse').set_active(False)
short_entry = self.__builder.get_object('dict:short_entry')
short_entry.set_text('')
short_entry.set_editable(True)
long_entry = self.__builder.get_object('dict:long_entry')
long_entry.set_text('')
long_entry.set_editable(True)
def __get_selected_dict_id(self):
l, it = self.__builder.get_object('dict:view').get_selection().get_selected()
if not it:
return None
return l.get_value(it, 0)
def __set_selected_dict_to_dialog(self):
selected_id = self.__get_selected_dict_id()
if selected_id == None:
return None
dict_item = self.__prefs.get_value('dict', 'list')[selected_id]
short_label = dict_item.short_label
long_label = dict_item.long_label
embed = dict_item.embed
single = dict_item.single
reverse = dict_item.reverse
is_system_dict = dict_item.is_system
if len(short_label) > 1:
short_label = short_label[0]
self.__builder.get_object('dict:single').set_active(single)
self.__builder.get_object('dict:embed').set_active(embed)
self.__builder.get_object('dict:reverse').set_active(reverse)
short_entry = self.__builder.get_object('dict:short_entry')
short_entry.set_text(short_label)
long_entry = self.__builder.get_object('dict:long_entry')
if is_system_dict:
short_entry.set_editable(False)
long_entry.set_text(_(long_label))
long_entry.set_editable(False)
else:
short_entry.set_editable(True)
long_entry.set_text(long_label)
long_entry.set_editable(True)
return selected_id
def __update_dict_values(self, new, id, short_label, long_label, embed, single, reverse):
prefs = self.__prefs
if new:
dict_item = prefs.get_value('dict', 'template')
dict_item.id = id
dict_item.short_label = short_label
dict_item.long_label = long_label
dict_item.embed = embed
dict_item.single = single
dict_item.reverse = reverse
l = self.__builder.get_object('dict:view').get_model()
l.append([id, short_label, long_label, embed, single, reverse])
else:
dict_item = prefs.get_value('dict', 'list')[id]
if not dict_item.is_system:
dict_item.short_label = short_label
dict_item.long_label = long_label
dict_item.embed = embed
dict_item.single = single
dict_item.reverse = reverse
l, i = self.__builder.get_object('dict:view').get_selection().get_selected()
if i :
l[i] = [id, short_label, long_label, embed, single, reverse]
prefs.set_list_item('dict', 'list', id, dict_item)
def __text_cell_data_cb(self, column, renderer, model, iter, id):
l = self.__builder.get_object('dict:view').get_model()
text = l.get_value(iter, id)
renderer.set_property('text', text)
def __toggle_cell_data_cb(self, column, renderer, model, iter, id):
l = self.__builder.get_object('dict:view').get_model()
active = l.get_value(iter, id)
renderer.set_property('active', active)
def __resync_engine_file(self):
user_config = path.join(self.__get_userhome(), '.config',
'ibus-anthy', 'engines.xml')
system_config = path.join(config.PKGDATADIR, 'engine', 'default.xml')
if not path.exists(user_config):
return
if not path.exists(system_config):
os.unlink(user_config)
return
# path.getmtime depends on the build time rather than install time.
def __get_engine_file_version(engine_file):
version_str = ''
dom = xml.dom.minidom.parse(engine_file)
elements = dom.getElementsByTagName('version')
nodes = []
if len(elements) > 0:
nodes = elements[0].childNodes
if len(nodes) > 0:
version_str = nodes[0].data
if version_str != '':
version_str = version_str.strip()
return version_str
user_config_version = __get_engine_file_version(user_config)
system_config_version = __get_engine_file_version(system_config)
if system_config_version > user_config_version:
import shutil
shutil.copyfile(system_config, user_config)
def __get_engine_file(self):
user_config = path.join(self.__get_userhome(), '.config',
'ibus-anthy', 'engines.xml')
system_config = path.join(config.PKGDATADIR, 'engine', 'default.xml')
engine_file = None
for f in [user_config, system_config]:
if path.exists(f):
engine_file = f
break
if engine_file == None:
self.__run_message_dialog(_("The engine xml file does not exist: ") + system_config,
Gtk.MessageType.ERROR)
return None
return engine_file
def __get_keymap(self):
keymap = ''
layout = ''
variant = ''
option = ''
engine_file = self.__get_engine_file()
if engine_file == None:
return None
dom = xml.dom.minidom.parse(engine_file)
nodes = dom.getElementsByTagName('layout')[0].childNodes
if len(nodes) > 0:
layout = nodes[0].data
if layout != '':
keymap = layout.strip()
nodes = dom.getElementsByTagName('layout_variant')[0].childNodes
if len(nodes) > 0:
variant = nodes[0].data
if variant != '':
keymap += '(' + varaint.strip() + ')'
nodes = dom.getElementsByTagName('layout_option')[0].childNodes
if len(nodes) > 0:
option = nodes[0].data
if option != '':
keymap += '[' + option.strip() + ']'
return keymap
def __parse_keymap(self, keymap):
layout = None
variant = None
option = None
length = keymap.find('(')
if length >= 0:
if layout == None:
layout = keymap[0:length]
keymap = keymap[length + 1:]
length = keymap.find(')')
if length > 0:
variant = keymap[0:length]
keymap = keymap[length + 1:]
else:
print('Invalid keymap', keymap, file=sys.stderr)
return ('', '', '')
length = keymap.find('[')
if length >= 0:
if layout == None:
layout = keymap[0:length]
keymap = keymap[length + 1:]
length = keymap.find(']')
if length > 0:
option = keymap[0:length]
keymap = keymap[length + 1:]
else:
print('Invalid keymap', keymap, file=sys.stderr)
return ('', '', '')
if layout == None:
layout = keymap