forked from acevery/ibus-table
/
table.py
4507 lines (4051 loc) · 181 KB
/
table.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
# -*- coding: utf-8 -*-
# vim:et sts=4 sw=4
#
# ibus-table - The Tables engine for IBus
#
# Copyright (c) 2008-2009 Yu Yuwei <acevery@gmail.com>
# Copyright (c) 2009-2014 Caius "kaio" CHANCE <me@kaio.net>
# Copyright (c) 2012-2022 Mike FABIAN <mfabian@redhat.com>
# Copyright (c) 2019 Peng Wu <alexepico@gmail.com>
#
# 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.1 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 program. If not, see <http://www.gnu.org/licenses/>
'''
This file implements the ibus engine for ibus-table
'''
__all__ = (
"TabEngine",
)
from typing import Any
from typing import List
from typing import Tuple
from typing import Iterable
from typing import Dict
from typing import Union
from typing import Optional
from typing import Callable
import sys
import os
import re
import copy
import time
import logging
IMPORT_SIMPLEAUDIO_SUCCESSFUL = False
try:
import simpleaudio # type: ignore
IMPORT_SIMPLEAUDIO_SUCCESSFUL = True
except (ImportError,):
IMPORT_SIMPLEAUDIO_SUCCESSFUL = False
from gettext import dgettext
_: Callable[[str], str] = lambda a: dgettext('ibus-table', a)
N_: Callable[[str], str] = lambda a: a
from gi import require_version # type: ignore
require_version('IBus', '1.0')
from gi.repository import IBus # type: ignore
require_version('Gio', '2.0')
from gi.repository import Gio
require_version('GLib', '2.0')
from gi.repository import GLib
#import tabsqlitedb
from gi.repository import GObject
import it_util
import it_active_window
import it_sound
LOGGER = logging.getLogger('ibus-table')
DEBUG_LEVEL = int(0)
def ascii_ispunct(character: str) -> bool:
'''
Use our own function instead of ascii.ispunct()
from “from curses import ascii” because the behaviour
of the latter is kind of weird. In Python 3.3.2 it does
for example:
# >>> from curses import ascii
# >>> ascii.ispunct('.')
# True
# >>> ascii.ispunct(u'.')
# True
# >>> ascii.ispunct('a')
# False
# >>> ascii.ispunct(u'a')
# False
# >>>
# >>> ascii.ispunct(u'あ')
# True
# >>> ascii.ispunct('あ')
# True
# >>>
あ isn’t punctuation. ascii.ispunct() only really works
in the ascii range, it returns weird results when used
over the whole unicode range. Maybe we should better use
unicodedata.category(), which works fine to figure out
what is punctuation for all of unicode. But at the moment
I am only porting from Python2 to Python3 and just want to
preserve the original behaviour for the moment.
By the way, Python 3.6.6 does not seem the above bug
anymore, in Python 3.6.6 we get
# >>> from curses import ascii
# >>> ascii.ispunct('あ')
# False
# >>>
Examples:
>>> ascii_ispunct('.')
True
>>> ascii_ispunct('a')
False
>>> ascii_ispunct('あ')
False
'''
return bool(character in '''!"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~''')
THEME: Dict[str, Union[bool, int]] = {
"dark": False,
"candidate_text": it_util.color_string_to_argb('#1973a2'),
"system_phrase": it_util.color_string_to_argb('#000000'),
"user_phrase": it_util.color_string_to_argb('#7700c3'),
"system_phrase_unused": it_util.color_string_to_argb('#000000'),
"debug_text": it_util.color_string_to_argb('#00ff00'),
"preedit_left": it_util.color_string_to_argb('#f90f0f'), # bright red
"preedit_right": it_util.color_string_to_argb('#1edc1a'), # light green
"preedit_invalid": it_util.color_string_to_argb('#ff00ff'), # magenta
"aux_text": it_util.color_string_to_argb('#9515b5'),
}
THEME_DARK: Dict[str, Union[bool, int]] = {
"dark": True,
"candidate_text": it_util.color_string_to_argb('#7bc8f0'),
"system_phrase": it_util.color_string_to_argb('#ffffff'),
"user_phrase": it_util.color_string_to_argb('#c078ee'),
"system_phrase_unused": it_util.color_string_to_argb('#f0f0f0'),
"debug_text": it_util.color_string_to_argb('#00ff00'),
"preedit_left": it_util.color_string_to_argb('#f9f90f'),
"preedit_right": it_util.color_string_to_argb('#1edc1a'),
"preedit_invalid": it_util.color_string_to_argb('#ff00ff'),
"aux_text": it_util.color_string_to_argb('#dd70f9'),
}
__HALF_FULL_TABLE: List[Tuple[int, int, int]] = [
(0x0020, 0x3000, 1),
(0x0021, 0xFF01, 0x5E),
(0x00A2, 0xFFE0, 2),
(0x00A5, 0xFFE5, 1),
(0x00A6, 0xFFE4, 1),
(0x00AC, 0xFFE2, 1),
(0x00AF, 0xFFE3, 1),
(0x20A9, 0xFFE6, 1),
(0xFF61, 0x3002, 1),
(0xFF62, 0x300C, 2),
(0xFF64, 0x3001, 1),
(0xFF65, 0x30FB, 1),
(0xFF66, 0x30F2, 1),
(0xFF67, 0x30A1, 1),
(0xFF68, 0x30A3, 1),
(0xFF69, 0x30A5, 1),
(0xFF6A, 0x30A7, 1),
(0xFF6B, 0x30A9, 1),
(0xFF6C, 0x30E3, 1),
(0xFF6D, 0x30E5, 1),
(0xFF6E, 0x30E7, 1),
(0xFF6F, 0x30C3, 1),
(0xFF70, 0x30FC, 1),
(0xFF71, 0x30A2, 1),
(0xFF72, 0x30A4, 1),
(0xFF73, 0x30A6, 1),
(0xFF74, 0x30A8, 1),
(0xFF75, 0x30AA, 2),
(0xFF77, 0x30AD, 1),
(0xFF78, 0x30AF, 1),
(0xFF79, 0x30B1, 1),
(0xFF7A, 0x30B3, 1),
(0xFF7B, 0x30B5, 1),
(0xFF7C, 0x30B7, 1),
(0xFF7D, 0x30B9, 1),
(0xFF7E, 0x30BB, 1),
(0xFF7F, 0x30BD, 1),
(0xFF80, 0x30BF, 1),
(0xFF81, 0x30C1, 1),
(0xFF82, 0x30C4, 1),
(0xFF83, 0x30C6, 1),
(0xFF84, 0x30C8, 1),
(0xFF85, 0x30CA, 6),
(0xFF8B, 0x30D2, 1),
(0xFF8C, 0x30D5, 1),
(0xFF8D, 0x30D8, 1),
(0xFF8E, 0x30DB, 1),
(0xFF8F, 0x30DE, 5),
(0xFF94, 0x30E4, 1),
(0xFF95, 0x30E6, 1),
(0xFF96, 0x30E8, 6),
(0xFF9C, 0x30EF, 1),
(0xFF9D, 0x30F3, 1),
(0xFFA0, 0x3164, 1),
(0xFFA1, 0x3131, 30),
(0xFFC2, 0x314F, 6),
(0xFFCA, 0x3155, 6),
(0xFFD2, 0x315B, 9),
(0xFFE9, 0x2190, 4),
(0xFFED, 0x25A0, 1),
(0xFFEE, 0x25CB, 1)]
def unichar_half_to_full(char: str) -> str:
'''
Convert a character to full width if possible.
:param char: A character to convert to full width
Examples:
>>> unichar_half_to_full('a')
'a'
>>> unichar_half_to_full('a')
'a'
>>> unichar_half_to_full('☺')
'☺'
'''
code = ord(char)
for half, full, size in __HALF_FULL_TABLE:
if half <= code < half + size:
return chr(full + code - half)
return char
def unichar_full_to_half(char: str) -> str:
'''
Convert a character to half width if possible.
:param char: A character to convert to half width
:type char: String
:rtype: String
Examples:
>>> unichar_full_to_half('a')
'a'
>>> unichar_full_to_half('a')
'a'
>>> unichar_full_to_half('☺')
'☺'
'''
code = ord(char)
for half, full, size in __HALF_FULL_TABLE:
if full <= code < full + size:
return chr(half + code - full)
return char
SAVE_USER_COUNT_MAX = 16
SAVE_USER_TIMEOUT = 30 # in seconds
IBUS_VERSION = (IBus.MAJOR_VERSION, IBus.MINOR_VERSION, IBus.MICRO_VERSION)
class TabEngine(IBus.EngineSimple): # type: ignore
'''The IM Engine for Tables'''
def __init__(
self,
bus: IBus.Bus,
obj_path: str,
database: Any, # tabsqlitedb.TabSqliteDb
unit_test: bool = False) -> None:
global DEBUG_LEVEL
try:
DEBUG_LEVEL = int(str(os.getenv('IBUS_TABLE_DEBUG_LEVEL')))
except (TypeError, ValueError):
DEBUG_LEVEL = int(0)
if DEBUG_LEVEL > 1:
LOGGER.debug(
'TabEngine.__init__(bus=%s, obj_path=%s, database=%s)',
bus, obj_path, database)
LOGGER.info('ibus version = %s', '.'.join(map(str, IBUS_VERSION)))
if hasattr(IBus.Engine.props, 'has_focus_id'):
super().__init__(
connection=bus.get_connection(),
object_path=obj_path,
has_focus_id=True)
LOGGER.info('This ibus version has focus id.')
else:
super().__init__(
connection=bus.get_connection(),
object_path=obj_path)
LOGGER.info('This ibus version does *not* have focus id.')
# Load $HOME/.XCompose file:
self.add_table_by_locale(None)
self._unit_test = unit_test
self._input_purpose: int = 0
self._input_hints: int = 0
self._bus = bus
# this is the backend sql db we need for our IME
# we receive this db from IMEngineFactory
#self.db = tabsqlitedb.TabSqliteDb( name = dbname )
self.database = database
self._setup_pid = 0
self._icon_dir = '%s%s%s%s' % (os.getenv('IBUS_TABLE_LOCATION'),
os.path.sep, 'icons', os.path.sep)
self._engine_name = os.path.basename(
self.database.filename).replace('.db', '').replace(' ', '_')
if DEBUG_LEVEL > 1:
LOGGER.debug(
'self._engine_name = %s', self._engine_name)
self._gsettings: Gio.Settings = Gio.Settings(
schema='org.freedesktop.ibus.engine.table',
path='/org/freedesktop/ibus/engine/table/%s/' %self._engine_name)
self._gsettings.connect('changed', self.on_gsettings_value_changed)
self._prop_dict: Dict[str, IBus.Property] = {}
self._sub_props_dict: Dict[str, IBus.PropList] = {}
self.main_prop_list: List[IBus.Property] = []
self.chinese_mode_menu: Dict[str, Any] = {}
self.chinese_mode_properties: Dict[str, Any] = {}
self.input_mode_menu: Dict[str, Any] = {}
self.input_mode_properties: Dict[str, Any] = {}
self.letter_width_menu: Dict[str, Any] = {}
self.letter_width_properties: Dict[str, Any] = {}
self.punctuation_width_menu: Dict[str, Any] = {}
self.punctuation_width_properties: Dict[str, Any] = {}
self.pinyin_mode_menu: Dict[str, Any] = {}
self.pinyin_mode_properties: Dict[str, Any] = {}
self.suggestion_mode_menu: Dict[str, Any] = {}
self.suggestion_mode_properties: Dict[str, Any] = {}
self.onechar_mode_menu: Dict[str, Any] = {}
self.onechar_mode_properties: Dict[str, Any] = {}
self.autocommit_mode_menu: Dict[str, Any] = {}
self.autocommit_mode_properties: Dict[str, Any] = {}
self._setup_property: Optional[IBus.Property] = None
self._im_client: str = ''
self.theme = THEME
self._keybindings: Dict[str, List[str]] = {}
self._hotkeys: Optional[it_util.HotKeys] = None
# self._ime_py: Indicates whether this table supports pinyin mode
self._ime_py = self.database.ime_properties.get('pinyin_mode')
if self._ime_py:
self._ime_py = bool(self._ime_py.lower() == u'true')
else:
LOGGER.info('We could not find "pinyin_mode" entry in database, '
'is it an outdated database?')
self._ime_py = False
# self._ime_sg: Indicates whether this table supports suggestion mode
self._ime_sg = self.database.ime_properties.get('suggestion_mode')
if self._ime_sg:
self._ime_sg = bool(self._ime_sg.lower() == u'true')
else:
LOGGER.info(
'We could not find "suggestion_mode" entry in database, '
'is it an outdated database?')
self._ime_sg = False
self._symbol = self.database.ime_properties.get('symbol')
if self._symbol is None or self._symbol == u'':
self._symbol = self.database.ime_properties.get('status_prompt')
if self._symbol is None:
self._symbol = u''
# some Chinese tables have “STATUS_PROMPT = CN” replace it
# with the shorter and nicer “中”:
if self._symbol == u'CN':
self._symbol = u'中'
# workaround for the translit and translit-ua tables which
# have 2 character symbols. '☑' + self._symbol then is
# 3 characters and currently gnome-shell ignores symbols longer
# than 3 characters:
if self._symbol == u'Ya':
self._symbol = u'Я'
if self._symbol == u'Yi':
self._symbol = u'Ї'
# now we check and update the valid input characters
self._valid_input_chars = self.database.ime_properties.get(
'valid_input_chars')
self._pinyin_valid_input_chars = u'abcdefghijklmnopqrstuvwxyz!@#$%'
self._debug_level: int = it_util.variant_to_value(
self._gsettings.get_value('debuglevel'))
if self._debug_level < 0:
self._debug_level = 0 # minimum
if self._debug_level > 255:
self._debug_level = 255 # maximum
DEBUG_LEVEL = self._debug_level
dynamic_adjust: Optional[bool] = it_util.variant_to_value(
self._gsettings.get_user_value('dynamicadjust'))
if dynamic_adjust is None:
if self.database.ime_properties.get('dynamic_adjust'):
dynamic_adjust = self.database.ime_properties.get(
'dynamic_adjust').lower() == u'true'
LOGGER.info('Got "dynamic_adjust" entry from database.')
else:
LOGGER.info(
'Could not find "dynamic_adjust" entry from database, '
'is it an outdated database?')
if dynamic_adjust is None:
dynamic_adjust = it_util.variant_to_value(
self._gsettings.get_value('dynamicadjust'))
self._dynamic_adjust: bool = dynamic_adjust
single_wildcard_char: Optional[str] = it_util.variant_to_value(
self._gsettings.get_user_value('singlewildcardchar'))
if single_wildcard_char is None:
if self.database.ime_properties.get('single_wildcard_char'):
single_wildcard_char = self.database.ime_properties.get(
'single_wildcard_char')
else:
single_wildcard_char = it_util.variant_to_value(
self._gsettings.get_value('singlewildcardchar'))
self._single_wildcard_char: str = single_wildcard_char
if len(self._single_wildcard_char) > 1:
self._single_wildcard_char = self._single_wildcard_char[0]
multi_wildcard_char: Optional[str] = it_util.variant_to_value(
self._gsettings.get_user_value('multiwildcardchar'))
if multi_wildcard_char is None:
if self.database.ime_properties.get('multi_wildcard_char'):
multi_wildcard_char = self.database.ime_properties.get(
'multi_wildcard_char')
else:
multi_wildcard_char = it_util.variant_to_value(
self._gsettings.get_value('multiwildcardchar'))
self._multi_wildcard_char: str = multi_wildcard_char
if len(self._multi_wildcard_char) > 1:
self._multi_wildcard_char = self._multi_wildcard_char[0]
auto_wildcard: Optional[bool] = it_util.variant_to_value(
self._gsettings.get_user_value('autowildcard'))
if auto_wildcard is None:
if self.database.ime_properties.get('auto_wildcard'):
auto_wildcard = self.database.ime_properties.get(
'auto_wildcard').lower() == u'true'
LOGGER.info('Got "auto_wildcard" entry from database.')
else:
auto_wildcard = it_util.variant_to_value(
self._gsettings.get_value('autowildcard'))
self._auto_wildcard: bool = auto_wildcard
self._max_key_length = int(
self.database.ime_properties.get('max_key_length'))
self._max_key_length_pinyin = 7
self._remember_input_mode: bool = it_util.variant_to_value(
self._gsettings.get_value('rememberinputmode'))
# 0 = Direct input, i.e. table input OFF (aka “English input mode”),
# most characters are just passed through to the application
# (but some fullwidth ↔ halfwidth conversion may be done even
# in this mode, depending on the settings)
# 1 = Table input ON (aka “Table input mode”, “Chinese mode”)
self._input_mode: int = 1
if self._remember_input_mode:
self._input_mode = it_util.variant_to_value(
self._gsettings.get_value('inputmode'))
self._sound_backend: str = it_util.variant_to_value(
self._gsettings.get_value('soundbackend'))
self._error_sound_object: Optional[it_sound.SoundObject] = None
self._error_sound_file: str = ''
self._error_sound: bool = it_util.variant_to_value(
self._gsettings.get_value('errorsound'))
self.set_error_sound_file(
it_util.variant_to_value(
self._gsettings.get_value('errorsoundfile')),
update_gsettings=False)
# self._prev_key: hold the key event last time.
self._prev_key: Optional[it_util.KeyEvent] = None
self._prev_char: Optional[str] = None
self._double_quotation_state = False
self._single_quotation_state = False
# self._prefix: the previous commit character or phrase
self._prefix = u''
self._py_mode = False
# suggestion mode
self._sg_mode = False
self._sg_mode_active = False
self._full_width_letter: List[Optional[bool]] = [None, None]
self._full_width_letter = [
it_util.variant_to_value(
self._gsettings.get_value('endeffullwidthletter')),
it_util.variant_to_value(
self._gsettings.get_user_value('tabdeffullwidthletter'))
]
if self._full_width_letter[1] is None:
if self.database.ime_properties.get('def_full_width_letter'):
self._full_width_letter[1] = self.database.ime_properties.get(
'def_full_width_letter').lower() == u'true'
if self._full_width_letter[1] is None:
self._full_width_letter[1] = it_util.variant_to_value(
self._gsettings.get_value('tabdeffullwidthletter'))
self._full_width_punct: List[Optional[bool]] = [None, None]
self._full_width_punct = [
it_util.variant_to_value(
self._gsettings.get_value('endeffullwidthpunct')),
it_util.variant_to_value(
self._gsettings.get_user_value('tabdeffullwidthpunct'))
]
if self._full_width_punct[1] is None:
if self.database.ime_properties.get('def_full_width_punct'):
self._full_width_punct[1] = self.database.ime_properties.get(
'def_full_width_punct').lower() == u'true'
if self._full_width_punct[1] is None:
self._full_width_punct[1] = it_util.variant_to_value(
self._gsettings.get_value('tabdeffullwidthpunct'))
auto_commit: Optional[bool] = it_util.variant_to_value(
self._gsettings.get_user_value('autocommit'))
if auto_commit is None:
if self.database.ime_properties.get('auto_commit'):
auto_commit = self.database.ime_properties.get(
'auto_commit').lower() == u'true'
else:
auto_commit = it_util.variant_to_value(
self._gsettings.get_value('autocommit'))
self._auto_commit: bool = auto_commit
# self._commit_invalid_mode: This selects what is committed
# when a character which is not in the set of valid input
# characters for the current table is typed.
#
# 0 means to commit the current candidate
# 1 means to commit the raw characters typed so far
self._commit_invalid_mode: int = it_util.variant_to_value(
self._gsettings.get_value('commitinvalidmode'))
# If auto select is true, then the first candidate phrase will
# be selected automatically during typing. Auto select is true
# by default for the stroke5 table for example.
auto_select: Optional[bool] = it_util.variant_to_value(
self._gsettings.get_user_value('autoselect'))
if auto_select is None:
if self.database.ime_properties.get('auto_select'):
auto_select = self.database.ime_properties.get(
'auto_select').lower() == u'true'
LOGGER.info('Got "auto_select" entry from database.')
else:
auto_select = it_util.variant_to_value(
self._gsettings.get_value('autoselect'))
self._auto_select: bool = auto_select
always_show_lookup: Optional[bool] = it_util.variant_to_value(
self._gsettings.get_user_value('alwaysshowlookup'))
if always_show_lookup is None:
if self.database.ime_properties.get('always_show_lookup'):
always_show_lookup = self.database.ime_properties.get(
'always_show_lookup').lower() == u'true'
LOGGER.info('Got "always_show_lookup" entry from database.')
else:
always_show_lookup = it_util.variant_to_value(
self._gsettings.get_value('alwaysshowlookup'))
self._always_show_lookup: bool = always_show_lookup
# The values below will be reset in
# self.clear_input_not_committed_to_preedit()
self._chars_valid = u'' # valid user input in table mode
self._chars_invalid = u'' # invalid user input in table mode
self._chars_valid_update_candidates_last = u''
self._chars_invalid_update_candidates_last = u''
# self._candidates holds the “best” candidates matching the user input
# [(tabkeys, phrase, freq, user_freq), ...]
self._candidates: List[Tuple[str, str, int, int]] = []
self._candidates_previous: List[Tuple[str, str, int, int]] = []
# self._u_chars: holds the user input of the phrases which
# have been automatically committed to preedit (but not yet
# “really” committed).
self._u_chars: List[str] = []
# self._strings: holds the phrases which have been
# automatically committed to preedit (but not yet “really”
# committed).
#
# self._u_chars and self._strings should always have the same
# length, if I understand it correctly.
#
# Example when using the wubi-jidian86 table:
#
# self._u_chars = ['gaaa', 'gggg', 'ihty']
# self._strings = ['形式', '王', '小']
#
# I.e. after typing 'gaaa', '形式' is in the preedit and
# both self._u_chars and self._strings are empty. When typing
# another 'g', the maximum key length of the wubi table (which is 4)
# is exceeded and '形式' is automatically committed to the preedit
# (but not yet “really” committed, i.e. not yet committed into
# the application). The key 'gaaa' and the matching phrase '形式'
# are stored in self._u_chars and self._strings respectively
# and 'gaaa' is removed from self._chars_valid. Now self._chars_valid
# contains only the 'g' which starts a new search for candidates ...
# When removing the 'g' with backspace, the 'gaaa' is moved
# back from self._u_chars into self._chars_valid again and
# the same candidate list is shown as before the last 'g' had
# been entered.
self._strings: List[str] = []
# self._cursor_precommit: The cursor
# position in the array of strings which have already been
# committed to preëdit but not yet “really” committed.
self._cursor_precommit = 0
self._prompt_characters = eval(
self.database.ime_properties.get('char_prompts'))
# self._onechar: whether we only select single character
self._onechar: bool = it_util.variant_to_value(
self._gsettings.get_value('onechar'))
# self._chinese_mode: the candidate filter mode,
# 0 means to show simplified Chinese only
# 1 means to show traditional Chinese only
# 2 means to show all characters but show simplified Chinese first
# 3 means to show all characters but show traditional Chinese first
# 4 means to show all characters
# we use LC_CTYPE or LANG to determine which one to use if
# no default comes from the user GSettings.
chinese_mode: Optional[int] = it_util.variant_to_value(
self._gsettings.get_user_value('chinesemode'))
if chinese_mode is None:
chinese_mode = it_util.get_default_chinese_mode(
self.database)
elif DEBUG_LEVEL > 1:
LOGGER.debug(
'Chinese mode found in Gsettings, mode=%s', chinese_mode)
self._chinese_mode: int = chinese_mode
# If auto select is true, then the first candidate phrase will
# be selected automatically during typing. Auto select is true
# by default for the stroke5 table for example.
self._auto_select = it_util.variant_to_value(
self._gsettings.get_user_value('autoselect'))
if self._auto_select is None:
if self.database.ime_properties.get('auto_select') is not None:
self._auto_select = self.database.ime_properties.get(
'auto_select').lower() == u'true'
if self._auto_select is None:
self._auto_select = it_util.variant_to_value(
self._gsettings.get_value('autoselect'))
self._default_keybindings: Dict[str, List[str]] = {}
self._default_keybindings = it_util.get_default_keybindings(
self._gsettings, self.database)
self._page_size: int = it_util.variant_to_value(
self._gsettings.get_default_value('lookuptablepagesize'))
for index in range(1, 10):
if not self._default_keybindings[
'commit_candidate_%s' % (index + 1)]:
self._page_size = min(index, self._page_size)
break
user_page_size: Optional[int] = it_util.variant_to_value(
self._gsettings.get_user_value('lookuptablepagesize'))
if not user_page_size is None:
self._page_size = user_page_size
orientation: Optional[int] = it_util.variant_to_value(
self._gsettings.get_user_value('lookuptableorientation'))
if orientation is None:
orientation = self.database.get_orientation()
self._orientation: int = orientation
user_keybindings = it_util.variant_to_value(
self._gsettings.get_user_value('keybindings'))
if not user_keybindings:
user_keybindings = {}
self.set_keybindings(user_keybindings, update_gsettings=False)
use_dark_theme = it_util.variant_to_value(
self._gsettings.get_user_value('darktheme'))
if use_dark_theme:
self.set_dark_theme(True, update_gsettings=False)
self._lookup_table = self.get_new_lookup_table()
self.chinese_mode_properties = {
'ChineseMode.Simplified': {
'number': 0,
'symbol': '簡',
'icon': 'sc-mode.svg',
# Translators: This is the menu entry to select
# when one wants to input only Simplified Chinese.
'label': _('Simplified Chinese'),
'tooltip':
_('Switch to “Simplified Chinese only”.')},
'ChineseMode.Traditional': {
'number': 1,
'symbol': '繁',
'icon': 'tc-mode.svg',
# Translators: This is the menu entry to select
# when one wants to input only Traditonal Chinese
'label': _('Traditional Chinese'),
'tooltip':
_('Switch to “Traditional Chinese only”.')},
'ChineseMode.SimplifiedFirst': {
'number': 2,
'symbol': '簡/大',
'icon': 'scb-mode.svg',
# Translators: This is the menu entry to select when
# one wants to input both Simplified and Traditional
# Chinese but wants the Simplified Chinese to be
# preferred, i.e. shown higher up in the candidate
# lists.
'label': _('Simplified Chinese first'),
'tooltip':
_('Switch to “Simplified Chinese before traditional”.')},
'ChineseMode.TraditionalFirst': {
'number': 3,
'symbol': '繁/大',
'icon': 'tcb-mode.svg',
# Translators: This is the menu entry to select when
# one wants to input both Simplified and Traditional
# Chinese but wants the Traditional Chinese to be
# preferred, i.e. shown higher up in the candidate
# lists.
'label': _('Traditional Chinese first'),
'tooltip':
_('Switch to “Traditional Chinese before simplified”.')},
'ChineseMode.All': {
'number': 4,
'symbol': '大',
'icon': 'cb-mode.svg',
# Translators: This is the menu entry to select when
# one wants to input both Simplified and Traditional
# Chinese and has no particular preference whether
# simplified or traditional characters should be higher
# up in the candidate lists.
'label': _('All Chinese characters'),
'tooltip': _('Switch to “All Chinese characters”.')}
}
self.chinese_mode_menu = {
'key': 'ChineseMode',
'label': _('Chinese mode'),
'tooltip': _('Switch Chinese mode'),
'shortcut_hint': repr(
self._keybindings['switch_to_next_chinese_mode']),
'sub_properties': self.chinese_mode_properties
}
if self.database._is_chinese:
self.input_mode_properties = {
'InputMode.Direct': {
'number': 0,
'symbol': '英',
'icon': 'english.svg',
'label': _('English'),
'tooltip': _('Switch to English input')},
'InputMode.Table': {
'number': 1,
'symbol': '中',
'symbol_table': '中',
'symbol_pinyin': '拼音',
'icon': 'chinese.svg',
'label': _('Chinese'),
'tooltip': _('Switch to Chinese input')}
}
else:
self.input_mode_properties = {
'InputMode.Direct': {
'number': 0,
'symbol': '☐' + self._symbol,
'icon': 'english.svg',
'label': _('Direct'),
'tooltip': _('Switch to direct input')},
'InputMode.Table': {
'number': 1,
'symbol': '☑' + self._symbol,
'icon': 'ibus-table.svg',
'label': _('Table'),
'tooltip': _('Switch to table input')}
}
# The symbol of the property “InputMode” is displayed
# in the input method indicator of the Gnome3 panel.
# This depends on the property name “InputMode” and
# is case sensitive!
self.input_mode_menu = {
'key': 'InputMode',
'label': _('Input mode'),
'tooltip': _('Switch Input mode'),
'shortcut_hint': repr(
self._keybindings['toggle_input_mode_on_off']),
'sub_properties': self.input_mode_properties
}
self.letter_width_properties = {
'LetterWidth.Half': {
'number': 0,
'symbol': '◑',
'icon': 'half-letter.svg',
'label': _('Half'),
'tooltip': _('Switch to halfwidth letters')},
'LetterWidth.Full': {
'number': 1,
'symbol': '●',
'icon': 'full-letter.svg',
'label': _('Full'),
'tooltip': _('Switch to fullwidth letters')}
}
self.letter_width_menu = {
'key': 'LetterWidth',
'label': _('Letter width'),
'tooltip': _('Switch letter width'),
'shortcut_hint': repr(
self._keybindings['toggle_letter_width']),
'sub_properties': self.letter_width_properties
}
self.punctuation_width_properties = {
'PunctuationWidth.Half': {
'number': 0,
'symbol': ',.',
'icon': 'half-punct.svg',
'label': _('Half'),
'tooltip': _('Switch to halfwidth punctuation')},
'PunctuationWidth.Full': {
'number': 1,
'symbol': '、。',
'icon': 'full-punct.svg',
'label': _('Full'),
'tooltip': _('Switch to fullwidth punctuation')}
}
self.punctuation_width_menu = {
'key': 'PunctuationWidth',
'label': _('Punctuation width'),
'tooltip': _('Switch punctuation width'),
'shortcut_hint': repr(
self._keybindings['toggle_punctuation_width']),
'sub_properties': self.punctuation_width_properties
}
self.pinyin_mode_properties = {
'PinyinMode.Table': {
'number': 0,
'symbol': '☐ 拼音',
'icon': 'tab-mode.svg',
'label': _('Table'),
'tooltip': _('Switch to table mode')},
'PinyinMode.Pinyin': {
'number': 1,
'symbol': '☑ 拼音',
'icon': 'py-mode.svg',
'label': _('Pinyin'),
'tooltip': _('Switch to pinyin mode')}
}
self.pinyin_mode_menu = {
'key': 'PinyinMode',
'label': _('Pinyin mode'),
'tooltip': _('Switch pinyin mode'),
'shortcut_hint': repr(
self._keybindings['toggle_pinyin_mode']),
'sub_properties': self.pinyin_mode_properties
}
self.suggestion_mode_properties = {
'SuggestionMode.Disabled': {
'number': 0,
'symbol': '☐ 联想',
'icon': 'tab-mode.svg',
'label': _('Suggestion disabled'),
'tooltip': _('Switch to suggestion mode')},
'SuggestionMode.Enabled': {
'number': 1,
'symbol': '☑ 联想',
'icon': 'tab-mode.svg',
'label': _('Suggestion enabled'),
'tooltip': _('Switch to suggestion mode')}
}
self.suggestion_mode_menu = {
'key': 'SuggestionMode',
'label': _('Suggestion mode'),
'tooltip': _('Switch suggestion mode'),
'shortcut_hint': repr(
self._keybindings['toggle_suggestion_mode']),
'sub_properties': self.suggestion_mode_properties
}
self.onechar_mode_properties = {
'OneCharMode.Phrase': {
'number': 0,
'symbol': '☐ 1',
'icon': 'phrase.svg',
'label': _('Multiple character match'),
'tooltip':
_('Switch to matching multiple characters at once')},
'OneCharMode.OneChar': {
'number': 1,
'symbol': '☑ 1',
'icon': 'onechar.svg',
'label': _('Single character match'),
'tooltip':
_('Switch to matching only single characters')}
}
self.onechar_mode_menu = {
'key': 'OneCharMode',
'label': _('Onechar mode'),
'tooltip': _('Switch onechar mode'),
'shortcut_hint': repr(
self._keybindings['toggle_onechar_mode']),
'sub_properties': self.onechar_mode_properties
}
self.autocommit_mode_properties = {
'AutoCommitMode.Direct': {
'number': 0,
'symbol': '☐ ↑',
'icon': 'ncommit.svg',
'label': _('Normal'),
'tooltip':
_('Switch to normal commit mode '
+ '(automatic commits go into the preedit '
+ 'instead of into the application. '
+ 'This enables automatic definitions of new shortcuts)')},
'AutoCommitMode.Normal': {
'number': 1,
'symbol': '☑ ↑',
'icon': 'acommit.svg',
'label': _('Direct'),
'tooltip':
_('Switch to direct commit mode '
+ '(automatic commits go directly into the application)')}
}
self.autocommit_mode_menu = {
'key': 'AutoCommitMode',
'label': _('Auto commit mode'),
'tooltip': _('Switch autocommit mode'),
'shortcut_hint': repr(
self._keybindings['toggle_autocommit_mode']),
'sub_properties': self.autocommit_mode_properties
}
self._init_properties()
self._save_user_count = 0
self._save_user_start = time.time()
self._save_user_count_max = SAVE_USER_COUNT_MAX
self._save_user_timeout = SAVE_USER_TIMEOUT
self.reset()
self.sync_timeout_id = GObject.timeout_add_seconds(
1, self._sync_user_db)
self.connect('process-key-event', self.__do_process_key_event)
LOGGER.info(
'********** Initialized and ready for input: **********')
def get_new_lookup_table(self) -> IBus.LookupTable:
'''
Get a new lookup table
'''
lookup_table = IBus.LookupTable()
lookup_table.clear()
lookup_table.set_page_size(self._page_size)
lookup_table.set_orientation(self._orientation)
lookup_table.set_cursor_visible(True)
lookup_table.set_round(True)
for index in range(0, 10):
label = ''
if self._keybindings['commit_candidate_%s' % (index + 1)]:
keybinding = self._keybindings[
'commit_candidate_%s' % (index + 1)][0]
key = it_util.keybinding_to_keyevent(keybinding)
label = keybinding
if key.unicode and not key.name.startswith('KP_'):
label = key.unicode
lookup_table.append_label(IBus.Text.new_from_string(label))
return lookup_table
def clear_all_input_and_preedit(self) -> None:
'''
Clear all input, whether committed to preëdit or not.
'''
if DEBUG_LEVEL > 1:
LOGGER.debug('clear_all_input_and_preedit()')
self.clear_input_not_committed_to_preedit()
self._u_chars = []
self._strings = []
self._cursor_precommit = 0
self._prefix = u''
self._sg_mode_active = False
self.update_candidates()
def is_empty(self) -> bool:
'''Checks whether the preëdit is empty
Returns True if the preëdit is empty, False if not.
'''
return self._chars_valid + self._chars_invalid == u''
def clear_input_not_committed_to_preedit(self) -> None:
'''
Clear the input which has not yet been committed to preëdit.
'''
if DEBUG_LEVEL > 1:
LOGGER.debug('clear_input_not_committed_to_preedit()')
self._chars_valid = u''
self._chars_invalid = u''
self._chars_valid_update_candidates_last = u''
self._chars_invalid_update_candidates_last = u''
self._lookup_table.clear()
self._lookup_table.set_cursor_visible(True)
self._candidates = []
self._candidates_previous = []