Debian Codegraph @

im/pinyin/pinyin.h

raw symbols SCIP
1 /*
2 * SPDX-FileCopyrightText: 2017-2017 CSSlayer <[email protected]>
3 *
4 * SPDX-License-Identifier: LGPL-2.1-or-later
5 *
6 */
7 #ifndef _PINYIN_PINYIN_H_
8 #define _PINYIN_PINYIN_H_
9
10 #include "customphrase.h"
11 #include "symboldictionary.h"
12 #include "workerthread.h"
13 #include <cstddef>
14 #include <cstdint>
15 #include <fcitx-config/configuration.h>
16 #include <fcitx-config/enum.h>
17 #include <fcitx-config/iniparser.h>
18 #include <fcitx-config/option.h>
19 #include <fcitx-config/rawconfig.h>
20 #include <fcitx-utils/event.h>
21 #include <fcitx-utils/eventloopinterface.h>
22 #include <fcitx-utils/handlertable.h>
23 #include <fcitx-utils/i18n.h>
24 #include <fcitx-utils/inputbuffer.h>
25 #include <fcitx-utils/key.h>
26 #include <fcitx-utils/keysym.h>
27 #include <fcitx-utils/misc.h>
28 #include <fcitx-utils/standardpaths.h>
29 #include <fcitx-utils/trackableobject.h>
30 #include <fcitx-utils/unixfd.h>
31 #include <fcitx/action.h>
32 #include <fcitx/addoninstance.h>
33 #include <fcitx/addonmanager.h>
34 #include <fcitx/event.h>
35 #include <fcitx/inputcontext.h>
36 #include <fcitx/inputcontextproperty.h>
37 #include <fcitx/inputmethodengine.h>
38 #include <fcitx/instance.h>
39 #include <fcitx/text.h>
40 #include <filesystem>
41 #include <future>
42 #include <libime/core/historybigram.h>
43 #include <libime/pinyin/pinyincontext.h>
44 #include <libime/pinyin/pinyinime.h>
45 #include <libime/pinyin/pinyinprediction.h>
46 #include <list>
47 #include <memory>
48 #include <optional>
49 #include <regex>
50 #include <string>
51 #include <string_view>
52 #include <unordered_set>
53 #include <utility>
54 #include <vector>
55
56 namespace fcitx {
57
58 template <typename Base = NoAnnotation>
59 struct OptionalHideInDescriptionBase : public Base {
60 void setHidden(bool hidden) { hidden_ = hidden; }
61
62 bool skipDescription() { return hidden_; }
63 using Base::dumpDescription;
64 using Base::skipSave;
65
66 private:
67 bool hidden_ = false;
68 };
69
70 using OptionalHideInDescription = OptionalHideInDescriptionBase<>;
71
72 class OptionalHiddenSubConfigOption : public SubConfigOption {
73 public:
74 using SubConfigOption::SubConfigOption;
75
76 void setHidden(bool hidden) { hidden_ = hidden; }
77
78 bool skipDescription() const override { return hidden_; }
79
80 private:
81 bool hidden_ = false;
82 };
83
84 enum class SwitchInputMethodBehavior { Clear, CommitPreedit, CommitDefault };
85
86 FCITX_CONFIG_ENUM_NAME_WITH_I18N(SwitchInputMethodBehavior, N_("Clear"),
87 N_("Commit current preedit"),
88 N_("Commit default selection"))
89
90 enum class ShuangpinProfileEnum {
91 Ziranma,
92 MS,
93 Ziguang,
94 ABC,
95 Zhongwenzhixing,
96 PinyinJiajia,
97 Xiaohe,
98 GB,
99 Custom
100 };
101
102 FCITX_CONFIG_ENUM_NAME_WITH_I18N(ShuangpinProfileEnum, N_("Ziranma"), N_("MS"),
103 N_("Ziguang"), N_("ABC"),
104 N_("Zhongwenzhixing"), N_("PinyinJiajia"),
105 N_("Xiaohe"), N_("GB Standard"), N_("Custom"))
106
107 enum class PreeditMode { No, ComposingPinyin, CommitPreview };
108
109 FCITX_CONFIG_ENUM_NAME_WITH_I18N(PreeditMode, N_("Do not show"),
110 N_("Composing pinyin"), N_("Commit preview"))
111
112 enum class BackspaceBehaviorOnPrediction {
113 OnlyClearCandidates,
114 ClearCandidatesAndBackspace,
115 BackspaceWhenNotUsingOnScreenKeyboard
116 };
117
118 FCITX_CONFIG_ENUM_NAME_WITH_I18N(
119 BackspaceBehaviorOnPrediction, N_("Only Clear candidates"),
120 N_("Clear candidates & backspace"),
121 N_("Backspace when not using on-screen keyboard"))
122
123 enum class CorrectionLayout {
124 None,
125 Qwerty,
126 };
127
128 FCITX_CONFIG_ENUM_NAME_WITH_I18N(CorrectionLayout, N_("None"), N_("QWERTY"))
129
130 FCITX_CONFIGURATION(
131 FuzzyConfig, Option<bool> ue{this, "VE_UE", _("ue -> ve"), true};
132 Option<bool> commonTypo{this, "NG_GN", _("Common Typo"), true};
133 Option<bool> lowerCaseMatchLetter{this, "LowerCaseMatchLetter",
134 _("Match Letter in lower case"), true};
135 Option<bool> inner{this, "Inner", _("Inner Segment (xian -> xi'an)"), true};
136 Option<bool> innerShort{this, "InnerShort",
137 _("Inner Segment for Short Pinyin (qie -> qi'e)"),
138 true};
139 Option<bool> partialFinal{this, "PartialFinal",
140 _("Match partial finals (e -> en, eng, ei)"),
141 true};
142 OptionWithAnnotation<bool, OptionalHideInDescription> partialSp{
143 this, "PartialSp",
144 _("Match partial shuangpin if input length is longer than 4"), false};
145 Option<bool> v{this, "V_U", _("u <-> v"), false};
146 Option<bool> an{this, "AN_ANG", _("an <-> ang"), false};
147 Option<bool> en{this, "EN_ENG", _("en <-> eng"), false};
148 Option<bool> ian{this, "IAN_IANG", _("ian <-> iang"), false};
149 Option<bool> in{this, "IN_ING", _("in <-> ing"), false};
150 Option<bool> ou{this, "U_OU", _("u <-> ou"), false};
151 Option<bool> uan{this, "UAN_UANG", _("uan <-> uang"), false};
152 Option<bool> c{this, "C_CH", _("c <-> ch"), false};
153 Option<bool> f{this, "F_H", _("f <-> h"), false};
154 Option<bool> l{this, "L_N", _("l <-> n"), false};
155 Option<bool> r{this, "L_R", _("l <-> r"), false};
156 Option<bool> s{this, "S_SH", _("s <-> sh"), false};
157 Option<bool> z{this, "Z_ZH", _("z <-> zh"), false};
158 OptionWithAnnotation<CorrectionLayout, CorrectionLayoutI18NAnnotation>
159 correction{this, "Correction", _("Correction Layout"),
160 isAndroid() ? CorrectionLayout::Qwerty
161 : CorrectionLayout::None};)
162
163 FCITX_CONFIGURATION(
164 PinyinEngineConfig,
165 OptionWithAnnotation<
166 ShuangpinProfileEnum,
167 OptionalHideInDescriptionBase<ShuangpinProfileEnumI18NAnnotation>>
168 shuangpinProfile{this, "ShuangpinProfile", _("Shuangpin Profile"),
169 ShuangpinProfileEnum::Ziranma};
170 OptionWithAnnotation<bool, OptionalHideInDescription> showShuangpinMode{
171 this, "ShowShuangpinMode", _("Show current shuangpin mode"), true};
172 Option<int, IntConstrain> pageSize{
173 this, "PageSize", _("Candidates Per Page"), 7, IntConstrain(3, 10)};
174 Option<bool> spellEnabled{this, "SpellEnabled",
175 _("Show English Candidates"), true};
176 Option<bool> symbolsEnabled{this, "SymbolsEnabled",
177 _("Show symbol candidates"), true};
178 Option<bool> chaiziEnabled{this, "ChaiziEnabled",
179 _("Show Chaizi candidates"), true};
180 Option<bool> extBEnabled{
181 this, "ExtBEnabled",
182 _("Enable more Characters after Unicode CJK Extension B"),
183 !isAndroid()};
184 Option<bool> strokeCandidateEnabled{
185 this, "StrokeCandidateEnabled",
186 _("Show stroke candidates when typing with h(一), s(丨), p(丿), n(㇏), "
187 "z(𠃍)"),
188 true};
189 OptionWithAnnotation<bool, OptionalHideInDescription> cloudPinyinEnabled{
190 this, "CloudPinyinEnabled", _("Enable Cloud Pinyin"), false};
191 OptionalHiddenSubConfigOption cloudpinyin{
192 this, "CloudPinyin", _("Configure Cloud Pinyin"),
193 "fcitx://config/addon/cloudpinyin"};
194 Option<int, IntConstrain, DefaultMarshaller<int>, OptionalHideInDescription>
195 cloudPinyinIndex{this, "CloudPinyinIndex",
196 _("Cloud Pinyin Candidate Order"), 2,
197 IntConstrain(1, 10)};
198 OptionWithAnnotation<bool, OptionalHideInDescription> cloudPinyinAnimation{
199 this, "CloudPinyinAnimation",
200 _("Show animation when Cloud Pinyin is loading"), true};
201 OptionWithAnnotation<bool, OptionalHideInDescription>
202 keepCloudPinyinPlaceHolder{this, "KeepCloudPinyinPlaceHolder",
203 _("Always show Cloud Pinyin place holder"),
204 false};
205 OptionWithAnnotation<PreeditMode, PreeditModeI18NAnnotation> preeditMode{
206 this, "PreeditMode", _("Preedit Mode"),
207 isAndroid() ? PreeditMode::No : PreeditMode::ComposingPinyin};
208 Option<bool> preeditCursorPositionAtBeginning{
209 this, "PreeditCursorPositionAtBeginning",
210 _("Fix embedded preedit cursor at the beginning of the preedit"),
211 !isAndroid() && !isApple() && !isEmscripten()};
212 Option<bool> showActualPinyinInPreedit{
213 this, "PinyinInPreedit", _("Show complete pinyin in preedit"), false};
214 Option<bool> predictionEnabled{this, "Prediction", _("Enable Prediction"),
215 isAndroid()};
216 OptionWithAnnotation<bool, ToolTipAnnotation> keepCurrentContext{
217 this,
218 "KeepCurrentContext",
219 _("Keep the current typed text for next input prediction"),
220 true,
221 {},
222 {},
223 {_("Keep the current typed text for future prediction.")}};
224 Option<int, IntConstrain> predictionSize{this, "PredictionSize",
225 _("Number of Predictions"), 49,
226 IntConstrain(3, 100)};
227 OptionWithAnnotation<BackspaceBehaviorOnPrediction,
228 BackspaceBehaviorOnPredictionI18NAnnotation>
229 backspaceBehaviorOnPrediction{
230 this, "BackspaceBehaviorOnPrediction",
231 _("Backspace behavior on prediction"),
232 BackspaceBehaviorOnPrediction::
233 BackspaceWhenNotUsingOnScreenKeyboard};
234 OptionWithAnnotation<SwitchInputMethodBehavior,
235 SwitchInputMethodBehaviorI18NAnnotation>
236 switchInputMethodBehavior{this, "SwitchInputMethodBehavior",
237 _("Action when switching input method"),
238 SwitchInputMethodBehavior::CommitPreedit};
239 KeyListOption forgetWord{this,
240 "ForgetWord",
241 _("Forget word"),
242 {Key("Control+7")},
243 KeyListConstrain()};
244 KeyListOption prevPage{
245 this,
246 "PrevPage",
247 _("Previous Page"),
248 {Key(FcitxKey_minus), Key(FcitxKey_Up), Key(FcitxKey_KP_Up),
249 Key(FcitxKey_Page_Up)},
250 KeyListConstrain({KeyConstrainFlag::AllowModifierLess})};
251 KeyListOption nextPage{
252 this,
253 "NextPage",
254 _("Next Page"),
255 {Key(FcitxKey_equal), Key(FcitxKey_Down), Key(FcitxKey_KP_Down),
256 Key(FcitxKey_Page_Down)},
257 KeyListConstrain({KeyConstrainFlag::AllowModifierLess})};
258 KeyListOption prevCandidate{
259 this,
260 "PrevCandidate",
261 _("Previous Candidate"),
262 {Key("Shift+Tab")},
263 KeyListConstrain({KeyConstrainFlag::AllowModifierLess})};
264 KeyListOption nextCandidate{
265 this,
266 "NextCandidate",
267 _("Next Candidate"),
268 {Key("Tab")},
269 KeyListConstrain({KeyConstrainFlag::AllowModifierLess})};
270 KeyListOption currentCandidate{
271 this,
272 "CurrentCandidate",
273 _("Select Current Candidate"),
274 {Key(FcitxKey_space), Key(FcitxKey_KP_Space)},
275 KeyListConstrain({KeyConstrainFlag::AllowModifierLess})};
276 KeyListOption commitRawInput{
277 this,
278 "CommitRawInput",
279 _("Commit Raw Input"),
280 {Key("Return"), Key("KP_Enter"), Key("Control+Return"),
281 Key("Control+KP_Enter"), Key("Shift+Return"), Key("Shift+KP_Enter"),
282 Key("Control+Shift+Return"), Key("Control+Shift+KP_Enter")},
283 KeyListConstrain({KeyConstrainFlag::AllowModifierLess})};
284 KeyListOption secondCandidate{
285 this,
286 "SecondCandidate",
287 _("Select Second Candidate"),
288 {},
289 KeyListConstrain({KeyConstrainFlag::AllowModifierLess,
290 KeyConstrainFlag::AllowModifierOnly})};
291 KeyListOption thirdCandidate{
292 this,
293 "ThirdCandidate",
294 _("Select Third Candidate"),
295 {},
296 KeyListConstrain({KeyConstrainFlag::AllowModifierLess,
297 KeyConstrainFlag::AllowModifierOnly})};
298 Option<bool> useKeypadAsSelectionKey{
299 this, "UseKeypadAsSelection", _("Use Keypad as Selection key"), false};
300 KeyListOptionWithAnnotation<ToolTipAnnotation> selectCharFromPhrase{
301 this,
302 "ChooseCharFromPhrase",
303 _("Choose Character from Phrase"),
304 {Key("[")},
305 KeyListConstrain({KeyConstrainFlag::AllowModifierLess}),
306 {},
307 {_("N-th key in the option will select the N-th character in the "
308 "current candidate.")}};
309 Option<Key, KeyConstrain> selectLastCharFromPhrase{
310 this, "ChooseLastCharFromPhrase",
311 _("Choose Last Character from Phrase"), Key("]"),
312 KeyConstrain{KeyConstrainFlag::AllowModifierLess}};
313 Option<bool> useBackSpaceToUnselect{
314 this, "BackSpaceToUnselect", _("Use BackSpace to cancel the selection"),
315 true};
316 KeyListOption selectByStroke{
317 this,
318 "FilterByStroke",
319 _("Filter by stroke"),
320 {Key("grave")},
321 KeyListConstrain({KeyConstrainFlag::AllowModifierLess})};
322 Option<int, IntConstrain> nbest{this, "Number of sentence",
323 _("Number of Sentences"), 2,
324 IntConstrain(1, 3)};
325 Option<int, IntConstrain, DefaultMarshaller<int>, ToolTipAnnotation>
326 wordCandidateLimit{this,
327 "WordCandidateLimit",
328 _("Number of Phrase Candidates"),
329 15,
330 IntConstrain(0),
331 {},
332 {_("Set to 0 will show all candidates.")}};
333 Option<int, IntConstrain> longWordLimit{
334 this, "LongWordLengthLimit",
335 _("Prompt long word length when input length over (0 for disable)"), 4,
336 IntConstrain(0, 10)};
337 ExternalOption dictmanager{this, "DictManager", _("Manage Dictionaries"),
338 "fcitx://config/addon/pinyin/dictmanager"};
339 ExternalOption customphrase{this, "CustomPhrase", _("Manage Custom Phrase"),
340 "fcitx://config/addon/pinyin/customphrase"};
341 SubConfigOption punctuationMap{
342 this, "Punctuation", _("Punctuation"),
343 "fcitx://config/addon/punctuation/punctuationmap/zh_CN"};
344 SubConfigOption chttrans{
345 this, "Chttrans",
346 _("Configure Simplified/Traditional Chinese Conversion"),
347 "fcitx://config/addon/chttrans"};
348 Option<Key, KeyConstrain> quickphraseKey{
349 this,
350 "QuickPhraseKey",
351 _("Key to trigger quickphrase"),
352 Key{FcitxKey_semicolon},
353 {KeyConstrainFlag::AllowModifierLess}};
354 Option<bool> useVAsQuickphrase{this, "VAsQuickphrase",
355 _("Use V to trigger quickphrase"), true};
356 ExternalOption quickphrase{this, "QuickPhrase", _("Quick Phrase"),
357 "fcitx://config/addon/quickphrase/editor"};
358 OptionWithAnnotation<std::vector<std::string>, ToolTipAnnotation>
359 quickphraseTriggerRegex{
360 this,
361 "QuickPhraseTriggerRegex",
362 _("Regular expression to trigger quick phrase"),
363 {".(/|@)$", "^(www|bbs|forum|mail|bbs)\\.",
364 "^(http|https|ftp|telnet|mailto):"},
365 {},
366 {},
367 {_("Enter quickphrase mode when current input matches any regular "
368 "expression from the list.")}};
369 Option<FuzzyConfig> fuzzyConfig{this, "Fuzzy", _("Fuzzy Pinyin")};
370 HiddenOption<bool> firstRun{this, "FirstRun", "FirstRun", true};)
371
372 struct EventSourceTime;
373 class CandidateList;
374 class PinyinEngine;
375
376 enum class PinyinMode { Normal, StrokeFilter, ForgetCandidate, Punctuation };
377
378 class PinyinState : public InputContextProperty {
379 public:
380 PinyinState(PinyinEngine *engine);
381
382 libime::PinyinContext context_;
383 bool lastIsPunc_ = false;
384
385 PinyinMode mode_ = PinyinMode::Normal;
386
387 // Stroke filter
388 InputBuffer strokeBuffer_;
389
390 // Forget candidate
391 std::shared_ptr<CandidateList> forgetCandidateList_;
392
393 std::unique_ptr<EventSourceTime> cancelLastEvent_;
394
395 std::optional<std::vector<libime::HistoryBigram::WordWithCode>>
396 predictWords_;
397
398 int keyReleased_ = -1;
399 int keyReleasedIndex_ = -2;
400 uint64_t lastKeyPressedTime_ = 0;
401 };
402
403 class PinyinEngine final : public InputMethodEngineV3,
404 public TrackableObject<PinyinEngine> {
405 public:
406 PinyinEngine(Instance *instance);
407 ~PinyinEngine() override;
408 Instance *instance() { return instance_; }
409 void activate(const InputMethodEntry &entry,
410 InputContextEvent &event) override;
411 void deactivate(const InputMethodEntry &entry,
412 InputContextEvent &event) override;
413 void keyEvent(const InputMethodEntry &entry, KeyEvent &keyEvent) override;
414 void reloadConfig() override;
415 void reset(const InputMethodEntry &entry,
416 InputContextEvent &event) override;
417 void doReset(InputContext *inputContext) const;
418 void save() override;
419 auto &factory() { return factory_; }
420 std::string subMode(const InputMethodEntry &entry,
421 InputContext &inputContext) override;
422 void invokeActionImpl(const InputMethodEntry &entry,
423 InvokeActionEvent &event) override;
424
425 const Configuration *getConfig() const override;
426 const Configuration *
427 getConfigForInputMethod(const InputMethodEntry &entry) const override;
428
429 void setConfig(const RawConfig &config) override {
430 config_.load(config, true);
431 safeSaveAsIni(config_, "conf/pinyin.conf");
432 populateConfig();
433 }
434
435 void setSubConfig(const std::string &path,
436 const fcitx::RawConfig &config) override;
437
438 libime::PinyinIME *ime() { return ime_.get(); }
439 const auto &config() const { return config_; }
440
441 void initPredict(InputContext *inputContext);
442 void updatePredict(InputContext *inputContext);
443
444 void updateUI(InputContext *inputContext);
445 void updateFilter(InputContext *inputContext);
446
447 void resetStroke(InputContext *inputContext) const;
448 void resetForgetCandidate(InputContext *inputContext) const;
449 void forgetCandidate(InputContext *inputContext, size_t index);
450 void pinCustomPhrase(InputContext *inputContext,
451 const std::string &customPhrase);
452 void deleteCustomPhrase(InputContext *inputContext,
453 const std::string &customPhrase);
454
455 FCITX_ADDON_DEPENDENCY_LOADER(cloudpinyin, instance_->addonManager());
456
457 const auto &selectionKeys() const { return selectionKeys_; }
458
459 private:
460 void cloudPinyinSelected(InputContext *inputContext,
461 const std::string &selected,
462 const std::string &word);
463
464 bool handleCloudpinyinTrigger(KeyEvent &event);
465 bool handle2nd3rdSelection(KeyEvent &event);
466 bool handleCandidateList(KeyEvent &event,
467 const std::shared_future<uint32_t> &keyChr);
468 bool handleNextPage(KeyEvent &event) const;
469 bool handleStrokeFilter(KeyEvent &event,
470 const std::shared_future<uint32_t> &keyChr);
471 bool handleForgetCandidate(KeyEvent &event);
472 bool handlePunc(KeyEvent &event,
473 const std::shared_future<uint32_t> &keyChr);
474 bool handlePuncCandidate(KeyEvent &event);
475 bool handleCompose(KeyEvent &event);
476 void resetPredict(InputContext *inputContext);
477
478 std::string evaluateCustomPhrase(InputContext *inputContext,
479 std::string_view key);
480
481 void populateConfig();
482
483 void updateForgetCandidate(InputContext *inputContext);
484
485 void updatePreedit(InputContext *inputContext) const;
486 void updatePuncCandidate(InputContext *inputContext,
487 const std::string &original,
488 const std::vector<std::string> &candidates) const;
489 void updatePuncPreedit(InputContext *inputContext) const;
490
491 std::pair<Text, Text> preedit(InputContext *inputContext) const;
492 std::string preeditCommitString(InputContext *inputContext) const;
493
494 #ifdef FCITX_HAS_LUA
495 std::vector<std::string>
496 luaCandidateTrigger(InputContext *ic, const std::string &candidateString);
497 #endif
498 void loadBuiltInDict();
499 void loadExtraDict();
500 void loadCustomPhrase();
501 void loadSymbols(const UnixFD &file);
502 void loadDict(const std::string &fullPath,
503 std::list<std::unique_ptr<TaskToken>> &taskTokens);
504 void saveCustomPhrase();
505
506 Instance *instance_;
507 PinyinEngineConfig config_;
508 PinyinEngineConfig pyConfig_;
509 std::unique_ptr<libime::PinyinIME> ime_;
510 std::vector<std::regex> quickphraseTriggerRegex_;
511 KeyList selectionKeys_;
512 KeyList numpadSelectionKeys_;
513 FactoryFor<PinyinState> factory_;
514 SimpleAction predictionAction_;
515 libime::PinyinPrediction prediction_;
516 std::unique_ptr<EventSource> deferEvent_;
517 std::unique_ptr<EventSource> deferredPreload_;
518 std::unique_ptr<HandlerTableEntry<EventHandler>> event_;
519 CustomPhraseDict customPhrase_;
520 SymbolDict symbols_;
521 WorkerThread worker_;
522 std::list<std::unique_ptr<TaskToken>> persistentTask_;
523 std::list<std::unique_ptr<TaskToken>> tasks_;
524
525 FCITX_ADDON_DEPENDENCY_LOADER(quickphrase, instance_->addonManager());
526 FCITX_ADDON_DEPENDENCY_LOADER(fullwidth, instance_->addonManager());
527 FCITX_ADDON_DEPENDENCY_LOADER(chttrans, instance_->addonManager());
528 FCITX_ADDON_DEPENDENCY_LOADER(punctuation, instance_->addonManager());
529 FCITX_ADDON_DEPENDENCY_LOADER(notifications, instance_->addonManager());
530 FCITX_ADDON_DEPENDENCY_LOADER(pinyinhelper, instance_->addonManager());
531 FCITX_ADDON_DEPENDENCY_LOADER(spell, instance_->addonManager());
532 FCITX_ADDON_DEPENDENCY_LOADER(imeapi, instance_->addonManager());
533
534 static constexpr size_t NumBuiltInDict = 2;
535 };
536
537 } // namespace fcitx
538
539 #endif // _PINYIN_PINYIN_H_