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
|
# Copyright (c) 2012-2013 - The IBus Cangjie authors
#
# This file is part of ibus-cangjie, the IBus Cangjie input method engine.
#
# ibus-cangjie 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 3 of the License, or
# (at your option) any later version.
#
# ibus-cangjie 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 ibus-cangjie. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
__all__ = ["EngineCangjie", "EngineQuick"]
import gettext
from operator import attrgetter
from typing import Any, Union
from pathlib import Path
import subprocess
import sys
import gi # type: ignore
gi.require_version("IBus", "1.0")
from gi.repository import ( # type: ignore
GLib,
Gio,
IBus,
)
import cangjie # type: ignore
from .hotkeys import HotKeyManager, SpecialKeys
from .ibus_helper import IBusPropList, IBusProperty
from .sounds import ErrorSound
# The current settings schema version
#
# This is used to migrate settings from older versions of the engine
# to the current version.
#
# Use integer to represent the schema version.
# 2500 means 2.5.0
CURRENT_SETTINGS_SCHEMA_VERSION = 2500
# FIXME: Find a way to de-hardcode the gettext package
def _(x):
return gettext.dgettext("ibus-cangjie", x)
def is_inputnumber(keyval):
"""Is the `keyval` param a numeric input, e.g to select a candidate."""
return (keyval in range(getattr(IBus, "0"), getattr(IBus, "9") + 1)) or (
keyval in range(IBus.KP_0, IBus.KP_9 + 1)
)
def legacy_schema_migration(
legacy_schema: Gio.SettingsSchema,
old_settings: Gio.Settings,
new_settings: Gio.Settings,
):
"""Migrate legacy schema settings to the new schema.
This is a helper function to migrate settings from the old schema to the new.
For the schema ID migration in v2.5.
"""
for key in legacy_schema.list_keys():
if legacy_schema.has_key(key):
# get the type of the setting key
value_type = legacy_schema.get_key(key).get_value_type()
print(
"migrate old setting key=%s" % key,
file=sys.stderr,
end="",
)
if value_type.equal(GLib.VariantType.new("s")):
print(" (string)", file=sys.stderr)
value = old_settings.get_string(key)
new_settings.set_string(key, value)
elif value_type.equal(GLib.VariantType.new("i")):
print(" (int)", file=sys.stderr)
value = old_settings.get_int(key)
new_settings.set_int(key, value)
elif value_type.equal(GLib.VariantType.new("b")):
print(" (bool)", file=sys.stderr)
value = old_settings.get_boolean(key)
new_settings.set_boolean(key, value)
else:
print(" (unsupported type)", file=sys.stderr)
class Engine(IBus.Engine):
"""The base class for Cangjie and Quick engines."""
__cangjie: cangjie.Cangjie
"""The Cangjie library access object from pycangjie."""
_clear_on_next_input: bool
"""Clear the current input on the next key press."""
_current_input: str
"""The current user input."""
__current_radicals: str
"""The radicals for the current input."""
_engine_prop_symbol: str = ""
"""The display name of the indicator menu when using the engine.
Will be used as symbol in the `icon_prop_key` referred property (i.e.
`InputMode`) when doing Chinese mode.
Note: The symbol shown in GNOME seems to be artifically limited to 2
Unicode characters. And we're have to use 1 other character to indicate
the half-width/full-width mode. This leaves us with only 1 character here.
@see: Engine.__render_icon_prop_symbol()
"""
_direct_mode_prop_symbol: str = "Aa"
"""The display name of the indicator menu when using direct input mode.
Will be used as symbol in the <icon_prop_key> referred property when doing
Direct input mode.
"""
__hotkeys: HotKeyManager
"""The hotkey manager for this engine.
Responsible for handling hotkeys combinations registration and subscription.
"""
_input_max_len: int
"""The maximum length of radical for a character input in this method."""
__prop_list: IBusPropList
"""The list of UI elements in the property dropdown of the indicator."""
__settings: Gio.Settings
"""The Gio.Settings object for this engine."""
__state_mask_ignore: int = (
IBus.ModifierType.CONTROL_MASK # Ctrl+<key>
| IBus.ModifierType.MOD1_MASK # Usually Alt+<key> / Meta_L+<key>
| IBus.ModifierType.MOD4_MASK # Usually Super_L+<key> / Hyper_L+<key>
| IBus.ModifierType.MOD5_MASK # Usually ISO_Level3_Shift+<key> / Mode_switch+<key>
| IBus.ModifierType.HANDLED_MASK # Handled by ibus
)
"""The modifiertype mask to the state of key events that should be ignored.
@see: https://ibus.github.io/docs/ibus-1.5/ibus-ibustypes.html#IBusModifierType-enum
"""
__setup_script_path: Path = Path("/usr/bin/ibus-setup-cangjie")
"""Known path of ibus-cangjie setup UI script.
Will be used to search for and open the preference dialog. It is hard to inspect
the path dynamically. So we opt to simply hardcode the well known path here for
simplicity.
"""
_legacy_schema_id: str = ""
"""Legacy schema ID of the engine
Valid only before v2.5. Only used for migration purposes.
"""
def __init__(self):
super(Engine, self).__init__()
self._input_max_len = 5
self.sounds = ErrorSound()
schema_id = "org.freedesktop.cangjie.ibus.%s" % self.__name__
self.__settings = Gio.Settings(schema_id=schema_id)
self.__settings.connect("changed", self._on_setting_changed)
self.__migrate_settings() # Need to load new settings object before doing migration
self._current_input = ""
self.__current_radicals = ""
self._clear_on_next_input = False
self.lookuptable = IBus.LookupTable()
self.lookuptable.set_page_size(9)
self.lookuptable.set_round(True)
self.lookuptable.set_orientation(IBus.Orientation.VERTICAL)
self.__hotkeys = HotKeyManager()
self.__init_properties()
self.__init_cangjie()
if self.__settings.get_boolean("input-mode-hotkey-shift"):
self.__hotkeys.register_hotkey(
[SpecialKeys.SHIFT_L], self.__do_toggle_direct_input
)
self.__hotkeys.register_hotkey(
[SpecialKeys.SHIFT_R], self.__do_toggle_direct_input
)
def __migrate_settings(self):
try:
schemas = Gio.SettingsSchemaSource.get_default()
settings_schema_version = self.__settings.get_int("schema-version")
if settings_schema_version >= CURRENT_SETTINGS_SCHEMA_VERSION:
return
print(
"setting schema version: %s" % settings_schema_version, file=sys.stderr
)
if settings_schema_version < 2500:
# Do the legacy schema id migration
legacy_schema = schemas.lookup(self._legacy_schema_id, True)
if legacy_schema is None:
return
print("legacy schema migration needed", file=sys.stderr)
old_settings = Gio.Settings(schema_id=self._legacy_schema_id)
legacy_schema_migration(legacy_schema, old_settings, self.__settings)
self.__settings.set_int("schema-version", 2500)
# All migrations are done
print(
"update schema-version to latest" % CURRENT_SETTINGS_SCHEMA_VERSION,
file=sys.stderr,
)
self.__settings.set_int("schema-version", CURRENT_SETTINGS_SCHEMA_VERSION)
except Exception as e:
print("An exception occured while migrating the settings: %s" % e)
return
def __init_properties(self):
"""Initializes the IBus.PropList for the input method's indicator menu.
Helper method.
"""
self.__prop_list = IBusPropList()
self.__prop_list.append(
IBusProperty(
key="InputMode",
label=_("Input Mode"),
symbol=self.__render_icon_prop_symbol(),
sensitive=False,
)
)
self.__prop_list.append(
IBusProperty(
key="direct-input",
prop_type=IBus.PropType.TOGGLE,
label=_("English Input Mode"),
state=self.__propstate_checked(
self.__settings.get_boolean("direct-input")
),
)
)
self.__prop_list.append(
IBusProperty(
key="halfwidth-chars.seperator",
prop_type=IBus.PropType.SEPARATOR,
sensitive=False,
)
)
self.__prop_list.append(
IBusProperty(
key="halfwidth-chars.full",
prop_type=IBus.PropType.RADIO,
label=_("Full-Width Characters"),
state=self.__propstate_checked(
not self.__settings.get_boolean("halfwidth-chars")
),
)
)
self.__prop_list.append(
IBusProperty(
key="halfwidth-chars.half",
prop_type=IBus.PropType.RADIO,
label=_("Half-Width Characters"),
state=self.__propstate_checked(
self.__settings.get_boolean("halfwidth-chars")
),
)
)
# If setting script path in the system is actually a file,
# then show the advanced settings UI.
if self.__setup_script_path.is_file():
name = str(self.__name__).lower()
if name == "cangjie":
label = _("Cangjie Preferences")
elif name == "quick":
label = _("Quick Preferences")
else:
label = _("Input Method Preferences")
self.__prop_list.append(
IBusProperty(
key="engine-setup.seperator",
prop_type=IBus.PropType.SEPARATOR,
sensitive=False,
)
)
self.__prop_list.append(
IBusProperty(
key="engine-setup",
prop_type=IBus.PropType.NORMAL,
label=label,
)
)
def __render_icon_prop_symbol(self):
"""Renders the symbol for the input mode.
Helper method.
"""
state = (
self.__settings.get_boolean("direct-input"),
self.__settings.get_boolean("halfwidth-chars"),
)
match state:
case (True, _):
return self._direct_mode_prop_symbol
case (_, True):
return f"{self._engine_prop_symbol}半" # Halfwidth mode
case (_, False):
return f"{self._engine_prop_symbol}全" # Fullwidth mode
def do_property_activate(self, prop_name, state):
"""Implements property_activate method for IBus.Engine.
Receives and handles the `property-activate` event.
https://ibus.github.io/docs/ibus-1.5/IBusEngine.html#IBusEngine-property-activate
"""
# Note: deal with property menu events by case
match prop_name:
case "InputMode":
"""Do nothing, as this is a read-only property."""
case "direct-input":
self.__settings.set_boolean(prop_name, state == IBus.PropState.CHECKED)
case "halfwidth-chars.full":
self.__settings.set_boolean(
"halfwidth-chars", state == IBus.PropState.CHECKED
)
case "halfwidth-chars.half":
self.__settings.set_boolean(
"halfwidth-chars", state == IBus.PropState.CHECKED
)
case "engine-setup":
# Open the advanced settings dialog with subprocess
name = str(self.__name__).lower()
p = subprocess.Popen([str(self.__setup_script_path.absolute()), name])
def do_focus_in(self):
"""Implements focus_in method for IBus.Engine.
Receives and handles the `focus-in` event.
@see: https://ibus.github.io/docs/ibus-1.5/IBusEngine.html#IBusEngine-focus-in
@see: https://ibus.github.io/docs/ibus-1.5/IBusInputContext.html#ibus-input-context-focus-in
"""
self.register_properties(self.__prop_list.raw())
def __init_cangjie(self):
"""Initializes the Cangjie library object with the current settings.
Helper method.
"""
version = self.__settings.get_int("version")
version = getattr(cangjie.versions, "CANGJIE%d" % version)
filters = (
cangjie.filters.BIG5 | cangjie.filters.HKSCS | cangjie.filters.PUNCTUATION
)
if self.__settings.get_boolean("include-allzh"):
filters |= cangjie.filters.CHINESE
if self.__settings.get_boolean("include-jp"):
filters |= cangjie.filters.KANJI
filters |= cangjie.filters.HIRAGANA
filters |= cangjie.filters.KATAKANA
if self.__settings.get_boolean("include-zhuyin"):
filters |= cangjie.filters.ZHUYIN
if self.__settings.get_boolean("include-symbols"):
filters |= cangjie.filters.SYMBOLS
self.__cangjie = cangjie.Cangjie(version, filters)
def _on_setting_changed(self, settings, key):
"""Event handler for the `changed` signal of the Gio.Settings object.
Helper method.
@see: https://docs.gtk.org/gio/class.Settings.html
@see: https://docs.gtk.org/gio/signal.Settings.change-event.html
"""
# Only recreate the Cangjie object if necessary
match key:
case "halfwidth-chars":
self.__prop_list["InputMode"].symbol = self.__render_icon_prop_symbol()
self.update_property(self.__prop_list["InputMode"].raw())
self.__clear_current_input()
case "direct-input":
self.__prop_list["InputMode"].symbol = self.__render_icon_prop_symbol()
self.update_property(self.__prop_list["InputMode"].raw())
self.__clear_current_input()
case "input-mode-hotkey-shift":
if self.__settings.get_boolean("input-mode-hotkey-shift"):
self.__hotkeys.register_hotkey(
[SpecialKeys.SHIFT_L], self.__do_toggle_direct_input
)
self.__hotkeys.register_hotkey(
[SpecialKeys.SHIFT_R], self.__do_toggle_direct_input
)
else:
self.__hotkeys.deregister_hotkey(
[SpecialKeys.SHIFT_L], self.__do_toggle_direct_input
)
self.__hotkeys.deregister_hotkey(
[SpecialKeys.SHIFT_R], self.__do_toggle_direct_input
)
case _:
self.__init_cangjie()
def do_focus_out(self):
"""Implements focus_out method for IBus.Engine.
Receives and handles the `focus-out` event.
Handles focus out event. This happens, for example, when switching
between application windows or input contexts.
Such events should clear the current input.
@see: https://ibus.github.io/docs/ibus-1.5/IBusEngine.html#IBusEngine-focus-out
"""
self.__clear_current_input()
def __do_cancel_input(self):
"""Cancel the current input.
However, if there isn't any current input, then we shouldn't try to do
anything at all, so that the key can fulfill its original function.
Helper method to do_process_key_event.
"""
if not self._current_input:
return False
self.__clear_current_input()
return True
def __do_page_down(self):
"""Handles the `page-down` event.
Present the next page of candidates. However, if there isn't any current
input, then we shouldn't try to do anything at all, so that the key can
fulfill its original function.
Helper method.
"""
if not self.lookuptable.get_number_of_candidates():
return False
self.lookuptable.page_down()
self.update_lookup_table()
self.update_auxiliary_text()
return True
def __do_page_up(self):
"""Handles the `page-up` event.
Present the previous page of candidates. However, if there isn't any
current input, then we shouldn't try to do anything at all, so that the
key can fulfill its original function.
Helper method.
"""
if not self.lookuptable.get_number_of_candidates():
return False
self.lookuptable.page_up()
self.update_lookup_table()
self.update_auxiliary_text()
return True
def __do_backspace(self):
"""Go back from one input character.
This doesn't cancel the current input, only removes the last
user-inputted character from the current input, and clear the list of
candidates.
However, if there isn't any pre-edit, then we shouldn't handle the
backspace key at all, so that it can fulfill its original function:
deleting characters backwards.
Helper method to do_process_key_event.
"""
if not self._current_input:
return False
self._update_current_input(drop=1)
self.lookuptable.clear()
self.update_lookup_table()
return True
def __do_space(self):
"""Handle the space key.
This is our "power key". It implements most of the behaviour behind
Cangjie and Quick.
It can be used to fetch the candidates if there are none, scroll to
the next page of candidates if appropriate or just commit the first
candidate when we have only one page.
Of course, it can also be used to input a "space" character.
Helper method to do_process_key_event.
"""
if not self._current_input:
return self.__do_fullwidth_char(" ")
if not self.lookuptable.get_number_of_candidates():
try:
self._get_candidates()
except (
cangjie.errors.CangjieNoCharsError,
cangjie.errors.CangjieInvalidInputError,
):
self._play_error_bell()
self._clear_on_next_input = True
return True
if self.lookuptable.get_number_of_candidates() <= 9:
self._do_select_candidate(1)
return True
self.__do_page_down()
return True
def __do_number(self, keyval):
"""Handle numeric input.
Helper method to do_process_key_event.
"""
if self.lookuptable.get_number_of_candidates():
return self._do_select_candidate(int(IBus.keyval_to_unicode(keyval)))
return self.__do_fullwidth_char(IBus.keyval_to_unicode(keyval))
def _do_other_key(self, keyval):
"""Handle all otherwise unhandled key presses.
Helper method to do_process_key_event.
"""
c = IBus.keyval_to_unicode(keyval)
if not c or c == "\n" or c == "\r":
return False
if not self.lookuptable.get_number_of_candidates() and self._current_input:
# FIXME: This is really ugly
if len(self._current_input) == 1 and not self.__cangjie.is_input_key(
self._current_input
):
self._get_candidates(by_shortcode=True)
else:
try:
self._get_candidates()
except cangjie.errors.CangjieNoCharsError:
self._play_error_bell()
return True
if self.lookuptable.get_number_of_candidates():
self._do_select_candidate(1)
return self.__do_fullwidth_char(IBus.keyval_to_unicode(keyval))
def __do_fullwidth_char(self, inputchar):
"""Commit the full-width version of an input character.
Helper method to do_space, do_number, do_other_key, etc."""
if self.__settings.get_boolean("halfwidth-chars"):
return False
self._update_current_input(append=inputchar)
try:
self._get_candidates(code=inputchar, by_shortcode=True)
except cangjie.errors.CangjieNoCharsError:
self.__clear_current_input()
return False
return True
def _do_select_candidate(self, index):
"""Commit the selected candidate.
Parameter `index` is the number entered by the user corresponding to
the character she wishes to select on the current page.
Note: user-visible index starts at 1, but start at 0 in the lookup
table.
Helper method.
"""
if index == 0:
# Do nothing if the index is zero
# but still return True to indicate that the key was handled
return True
page_pos = self.lookuptable.get_cursor_pos()
total = self.lookuptable.get_number_of_candidates()
select_pos = page_pos + index - 1
if select_pos >= total:
# Do nothing if the selection is out of bounds
# but still return True to indicate that the key was handled
return True
selected = self.lookuptable.get_candidate(select_pos).get_text()[0]
self.commit_text(IBus.Text.new_from_unichar(selected))
self.__clear_current_input()
return True
def __do_toggle_direct_input(self, keys=[]):
"""Toggle direct input mode.
This is not used by Cangjie or Quick, so we just return False to
indicate that we didn't handle the event.
"""
result = not self.__settings.get_boolean("direct-input")
self.__settings.set_boolean("direct-input", result)
self.__prop_list["direct-input"].state = self.__propstate_checked(result)
self.update_property(self.__prop_list["direct-input"].raw())
return result
def do_process_key_event(self, keyval, keycode, state):
"""Implements process_key_event method for IBus.Engine.
Receives and handles the `process-key-event` event.
This event is fired when the user presses a key.
@see: https://ibus.github.io/docs/ibus-1.5/IBusEngine.html#IBusEngine-process-key-event
"""
# Handle hotkeys before any input
self.__hotkeys.do_process_key_event(keyval, keycode, state)
# Ignore key events in direct input mode
if self.__settings.get_boolean("direct-input"):
return False
# Ignore key release events
if state & IBus.ModifierType.RELEASE_MASK:
return False
# Work around integer overflow bug on 32 bits systems:
# https://bugzilla.gnome.org/show_bug.cgi?id=693121
# The bug is fixed in pygobject 3.7.91, but many distributions will
# ship the previous version for some time. (e.g Fedora 18)
if state & 1073741824:
return False
if state & self.__state_mask_ignore:
return False
if keyval == IBus.Escape:
return self.__do_cancel_input()
if keyval == IBus.space:
return self.__do_space()
if keyval == IBus.Page_Down:
return self.__do_page_down()
if keyval == IBus.Page_Up:
return self.__do_page_up()
if keyval == IBus.BackSpace:
return self.__do_backspace()
if is_inputnumber(keyval):
return self.__do_number(keyval)
c = IBus.keyval_to_unicode(keyval)
if c and c == "*":
return self._do_star()
if c and self.__cangjie.is_input_key(c):
return self._do_inputchar(c)
return self._do_other_key(keyval)
def __clear_current_input(self):
"""Clear the current input.
Helper method.
"""
self._current_input = ""
self.__current_radicals = ""
self._clear_on_next_input = False
self.update_lookup_table()
self.update_auxiliary_text()
def _update_current_input(self, append=None, drop=None):
"""Update the current input.
Helper method.
"""
if append is not None:
if self._clear_on_next_input:
self.__clear_current_input()
if len(self._current_input) < self._input_max_len:
self._current_input += append
try:
self.__current_radicals += self.__cangjie.get_radical(append)
except cangjie.errors.CangjieInvalidInputError:
# That character doesn't have a radical
self.__current_radicals += append
else:
self._play_error_bell()
elif drop is not None:
self._clear_on_next_input = False
self._current_input = self._current_input[:-drop]
self.__current_radicals = self.__current_radicals[:-drop]
else:
raise ValueError("You must specify either 'append' or 'drop'")
self.update_auxiliary_text()
def _get_candidates(self, code=None, by_shortcode=False):
"""Get the candidates based on the user input.
If the optional `code` parameter is not specified, then use the
current input instead.
Helper
"""
self.lookuptable.clear()
num_candidates = 0
if not code:
code = self._current_input
if not by_shortcode:
chars = self.__cangjie.get_characters(code)
else:
chars = self.__cangjie.get_characters_by_shortcode(code)
# Finding an element in a dict is **much** faster than in a list
seen = {}
for candidate in sorted(chars, key=attrgetter("frequency"), reverse=True):
if candidate.chchar in seen:
continue
if self.__name__ in ("Cangjie", "Quick") and "*" in code:
cangjie_code = ""
try:
cangjie_code = "".join(
[self.__cangjie.get_radical(key) for key in candidate.code[:]]
)
if self.__settings.get_boolean("star-helps-learners"):
self.lookuptable.append_candidate(
IBus.Text.new_from_string(
candidate.chchar + " (%s)" % cangjie_code
)
)
else:
self.lookuptable.append_candidate(
IBus.Text.new_from_string(candidate.chchar)
)
except cangjie.errors.CangjieInvalidInputError:
self.lookuptable.append_candidate(
IBus.Text.new_from_string(candidate.chchar)
)
else:
self.lookuptable.append_candidate(
IBus.Text.new_from_string(candidate.chchar)
)
num_candidates += 1
seen[candidate.chchar] = True
if num_candidates == 1:
self._do_select_candidate(1)
else:
# More than one candidate, display them
self.update_lookup_table()
def update_preedit_text(self):
"""Overrides update_preedit_text method for IBus.Engine.
Update the preedit text.
This is never used with Cangjie and Quick, so let's nullify it
completely, in case something else in the IBus machinery calls it.
@see: https://ibus.github.io/docs/ibus-1.5/IBusEngine.html#ibus-engine-update-preedit-text
"""
pass
def update_auxiliary_text(self):
"""Overrides update_auxiliary_text method for IBus.Engine.
Update the auxiliary text.
This should contain the radicals for the current input.
@see: https://ibus.github.io/docs/ibus-1.5/IBusEngine.html#ibus-engine-update-auxiliary-text
"""
text = IBus.Text.new_from_string(self.__current_radicals)
super(Engine, self).update_auxiliary_text(
text, len(self.__current_radicals) > 0
)
# We don't use pre-edit at all for Cangjie or Quick
#
# However, some applications (most notably Firefox) fail to correctly
# position the candidate popup, as if they got confused by the absence
# of a pre-edit text. :(
#
# This is a horrible hack, but it fixes the immediate problem.
if self.__current_radicals:
super(Engine, self).update_preedit_text(
IBus.Text.new_from_string("\u200B"), 0, True
)
else:
super(Engine, self).update_preedit_text(
IBus.Text.new_from_string(""), 0, False
)
# End of the horrible workaround
def update_lookup_table(self):
"""Overrides update_lookup_table method for IBus.Engine.
Update the lookup table.
@see: https://ibus.github.io/docs/ibus-1.5/IBusEngine.html#ibus-engine-update-lookup-table
"""
if not self._current_input:
self.lookuptable.clear()
num_candidates = self.lookuptable.get_number_of_candidates()
super(Engine, self).update_lookup_table(self.lookuptable, num_candidates > 0)
def _play_error_bell(self):
"""Play an error sound, to notify the user of invalid input.
Helper method.
"""
self.sounds.play_error()
def _do_inputchar(self, inputchar):
"""Handle user input of valid Cangjie input characters.
This is the main method that should be implemented by subclasses.
Helper method.
"""
raise NotImplementedError
def _do_star(self):
"""Handle the star key (*)
This is the main method that should be implemented by subclasses.
Helper method.
"""
raise NotImplementedError
def __propstate_checked(self, value: bool):
"""Returns the property state for a given boolean property name.
Helper method.
"""
return IBus.PropState.CHECKED if value else IBus.PropState.UNCHECKED
class EngineCangjie(Engine):
"""The Cangjie engine."""
__gtype_name__ = "EngineCangjie"
__name__ = "Cangjie"
_engine_prop_symbol = "倉"
_legacy_schema_id = "org.cangjians.ibus.cangjie"
def _do_inputchar(self, inputchar):
"""Handle user input of valid Cangjie input characters."""
if self.lookuptable.get_number_of_candidates():
self._do_select_candidate(1)
self._update_current_input(append=inputchar)
return True
def _do_star(self):
"""Handle the star key (*)
For Cangjie, this can in some cases be a wildcard key.
"""
if self._current_input:
return self._do_inputchar("*")
return self._do_other_key(IBus.asterisk)
class EngineQuick(Engine):
"""The Quick engine."""
__gtype_name__ = "EngineQuick"
__name__ = "Quick"
_engine_prop_symbol = "速"
_legacy_schema_id = "org.cangjians.ibus.quick"
def __init__(self):
super(EngineQuick, self).__init__()
self._input_max_len = 2
def _do_inputchar(self, inputchar):
"""Handle user input of valid Cangjie input characters."""
if self.lookuptable.get_number_of_candidates():
self._do_select_candidate(1)
if len(self._current_input) < self._input_max_len:
self._update_current_input(append=inputchar)
# Now that we appended/committed, let's check the new length
if len(self._current_input) == self._input_max_len:
current_input = "*".join(self._current_input)
try:
self._get_candidates(current_input)
except cangjie.errors.CangjieNoCharsError:
self._play_error_bell()
self._clear_on_next_input = True
return True
def _do_star(self):
"""Handle the star key (*)
For Quick, this should just be considered as any other key.
"""
return self._do_other_key(IBus.asterisk)
|