Debian Codegraph @

im/pinyin/pinyin.cpp

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
8 #include "pinyin.h"
9
10 // Use relative path so we don't need import export target.
11 // We want to keep cloudpinyin logic but don't call it.
12 #include "../../modules/cloudpinyin/cloudpinyin_public.h"
13 #include "config.h"
14 #include "customphrase.h"
15 #include "notifications_public.h"
16 #include "pinyincandidate.h"
17 #include "pinyinhelper_public.h"
18 #include "punctuation_public.h"
19 #include "spell_public.h"
20 #include "workerthread.h"
21 #include <algorithm>
22 #include <cassert>
23 #include <cstddef>
24 #include <cstdint>
25 #include <ctime>
26 #include <exception>
27 #include <fcitx-config/iniparser.h>
28 #include <fcitx-config/rawconfig.h>
29 #include <fcitx-utils/capabilityflags.h>
30 #include <fcitx-utils/charutils.h>
31 #include <fcitx-utils/event.h>
32 #include <fcitx-utils/eventloopinterface.h>
33 #include <fcitx-utils/fdstreambuf.h>
34 #include <fcitx-utils/i18n.h>
35 #include <fcitx-utils/key.h>
36 #include <fcitx-utils/keysym.h>
37 #include <fcitx-utils/log.h>
38 #include <fcitx-utils/macros.h>
39 #include <fcitx-utils/misc.h>
40 #include <fcitx-utils/standardpaths.h>
41 #include <fcitx-utils/stringutils.h>
42 #include <fcitx-utils/textformatflags.h>
43 #include <fcitx-utils/unixfd.h>
44 #include <fcitx-utils/utf8.h>
45 #include <fcitx/action.h>
46 #include <fcitx/addoninstance.h>
47 #include <fcitx/candidatelist.h>
48 #include <fcitx/event.h>
49 #include <fcitx/inputcontext.h>
50 #include <fcitx/inputcontextmanager.h>
51 #include <fcitx/inputcontextproperty.h>
52 #include <fcitx/inputmethodengine.h>
53 #include <fcitx/inputmethodentry.h>
54 #include <fcitx/inputpanel.h>
55 #include <fcitx/instance.h>
56 #include <fcitx/statusarea.h>
57 #include <fcitx/text.h>
58 #include <fcitx/userinterface.h>
59 #include <fcitx/userinterfacemanager.h>
60 #include <fcntl.h>
61 #include <filesystem>
62 #include <fstream>
63 #include <functional>
64 #include <future>
65 #include <ios>
66 #include <istream>
67 #include <iterator>
68 #include <libime/core/historybigram.h>
69 #include <libime/core/languagemodel.h>
70 #include <libime/core/lattice.h>
71 #include <libime/core/triedictionary.h>
72 #include <libime/core/userlanguagemodel.h>
73 #include <libime/pinyin/pinyincontext.h>
74 #include <libime/pinyin/pinyincorrectionprofile.h>
75 #include <libime/pinyin/pinyindecoder.h>
76 #include <libime/pinyin/pinyindictionary.h>
77 #include <libime/pinyin/pinyinencoder.h>
78 #include <libime/pinyin/pinyinime.h>
79 #include <libime/pinyin/pinyinprediction.h>
80 #include <libime/pinyin/shuangpinprofile.h>
81 #include <list>
82 #include <memory>
83 #include <optional>
84 #include <ostream>
85 #include <quickphrase_public.h>
86 #include <ranges>
87 #include <regex>
88 #include <stdexcept>
89 #include <string>
90 #include <string_view>
91 #include <tuple>
92 #include <unordered_map>
93 #include <unordered_set>
94 #include <utility>
95 #include <vector>
96
97 #ifdef FCITX_HAS_LUA
98 #include <luaaddon_public.h>
99 #endif
100
101 namespace fcitx {
102
103 namespace {
104
105 FCITX_DEFINE_LOG_CATEGORY(pinyin, "pinyin");
106
107 #define PINYIN_DEBUG() FCITX_LOGC(pinyin, Debug)
108 #define PINYIN_ERROR() FCITX_LOGC(pinyin, Error)
109
110 template <typename T>
111 std::unique_ptr<CandidateList>
112 predictCandidateList(PinyinEngine *engine, const std::vector<T> &words) {
113 if (words.empty()) {
114 return nullptr;
115 }
116 auto candidateList = std::make_unique<CommonCandidateList>();
117 for (const auto &word : words) {
118 if constexpr (std::is_same_v<T, std::string>) {
119 candidateList->append<PinyinPredictCandidateWord>(engine, word);
120 } else if constexpr (std::is_same_v<
121 T,
122 std::pair<std::string,
123 libime::PinyinPredictionSource>>) {
124
125 if (word.second == libime::PinyinPredictionSource::Model) {
126 candidateList->append<PinyinPredictCandidateWord>(engine,
127 word.first);
128 } else if (word.second ==
129 libime::PinyinPredictionSource::Dictionary) {
130 candidateList->append<PinyinPredictDictCandidateWord>(
131 engine, word.first);
132 }
133 }
134 }
135 candidateList->setSelectionKey(engine->selectionKeys());
136 candidateList->setPageSize(*engine->config().pageSize);
137 if (!candidateList->empty()) {
138 candidateList->setGlobalCursorIndex(0);
139 }
140 return candidateList;
141 }
142
143 std::tuple<bool, int> englishNess(const std::string &input, bool sp) {
144 const auto pys = stringutils::split(input, " ");
145 constexpr int fullWeight = -2;
146 constexpr int shortWeight = 3;
147 constexpr int invalidWeight = 6;
148 constexpr int defaultWeight = shortWeight;
149 int weight = 0;
150 if (std::ranges::any_of(input, charutils::isupper)) {
151 return {true,
152 std::max<size_t>(1, ((invalidWeight * pys.size()) + 7) / 10)};
153 }
154
155 for (const auto &py : pys) {
156 if (sp) {
157 if (py.size() == 2) {
158 weight += fullWeight / 2;
159 } else {
160 weight += invalidWeight;
161 }
162 } else {
163 if (py == "ng") {
164 weight += fullWeight;
165 } else {
166 auto firstChr = py[0];
167 if (firstChr == '\'') {
168 return {false, 0};
169 }
170 if (firstChr == 'i' || firstChr == 'u' || firstChr == 'v') {
171 weight += invalidWeight;
172 } else if (py.size() <= 2) {
173 weight += shortWeight;
174 } else if (py.find_first_of("aeiou") != std::string::npos) {
175 weight += fullWeight;
176 } else {
177 weight += defaultWeight;
178 }
179 }
180 }
181 }
182
183 if (weight < 0) {
184 return {false, 0};
185 }
186 return {false, (weight + 7) / 10};
187 }
188
189 bool isStroke(const std::string &input) {
190 static const std::unordered_set<char> py{'h', 'p', 's', 'z', 'n'};
191 return std::all_of(input.begin(), input.end(),
192 [](char c) { return py.count(c); });
193 }
194
195 std::string getEncodedPinyin(const libime::SentenceResult &result) {
196 std::string encodedPinyin;
197 bool validPinyin = std::all_of(
198 result.sentence().begin(), result.sentence().end(),
199 [](const libime::LatticeNode *node) {
200 if (node->word().empty()) {
201 return true;
202 }
203 const auto *pinyinNode =
204 static_cast<const libime::PinyinLatticeNode *>(node);
205 return !pinyinNode->encodedPinyin().empty() &&
206 pinyinNode->encodedPinyin().size() % 2 == 0;
207 });
208 if (validPinyin) {
209 for (const auto *node : result.sentence()) {
210 const auto *pinyinNode =
211 static_cast<const libime::PinyinLatticeNode *>(node);
212 encodedPinyin.insert(encodedPinyin.end(),
213 pinyinNode->encodedPinyin().begin(),
214 pinyinNode->encodedPinyin().end());
215 }
216 }
217 return encodedPinyin;
218 }
219
220 std::optional<int> selectCharFromCandidateIndex(const Key &key,
221 PinyinEngineConfig &config) {
222 if (key.check(*config.selectLastCharFromPhrase)) {
223 return -1;
224 }
225 if (int idx = key.keyListIndex(*config.selectCharFromPhrase); idx >= 0) {
226 return idx;
227 }
228 return std::nullopt;
229 }
230
231 } // namespace
232
233 PinyinState::PinyinState(PinyinEngine *engine) : context_(engine->ime()) {
234 context_.setMaxSentenceLength(35);
235 }
236
237 void PinyinEngine::initPredict(InputContext *inputContext) {
238 auto *state = inputContext->propertyFor(&factory_);
239 // clear state no matter what.
240 state->predictWords_.reset();
241 auto &context = state->context_;
242 auto lmState = context.state();
243 auto selected = context.selectedWordsWithPinyin();
244 if (*config_.keepCurrentContext) {
245 context.appendContextWordsWithPinyin(context.selectedWordsWithPinyin());
246 }
247 if (selected.empty()) {
248 return;
249 }
250 if (!*config_.predictionEnabled) {
251 return;
252 }
253
254 const auto selectPinyin = context.selectedWordsWithPinyin();
255
256 auto words =
257 prediction_.predict(lmState, selected, *config_.predictionSize);
258 if (auto candidateList = predictCandidateList(this, words)) {
259 auto &inputPanel = inputContext->inputPanel();
260 state->predictWords_ = std::move(selected);
261 inputPanel.setCandidateList(std::move(candidateList));
262 } else {
263 return;
264 }
265 inputContext->updatePreedit();
266 inputContext->updateUserInterface(UserInterfaceComponent::InputPanel);
267 }
268
269 void PinyinEngine::updatePredict(InputContext *inputContext) {
270 inputContext->inputPanel().reset();
271
272 auto *state = inputContext->propertyFor(&factory_);
273 assert(state->predictWords_.has_value());
274 if (*config_.keepCurrentContext) {
275 state->context_.setContextWordsWithPinyin(*state->predictWords_);
276 }
277 auto words =
278 prediction_.predict(ime_->model()->nullState(), *state->predictWords_,
279 *config_.predictionSize);
280 if (auto candidateList = predictCandidateList(this, words)) {
281 auto &inputPanel = inputContext->inputPanel();
282 inputPanel.setCandidateList(std::move(candidateList));
283 } else {
284 // Clear if we can't do predict.
285 // This help other code to detect whether we are in predict.
286 state->predictWords_.reset();
287 }
288 inputContext->updatePreedit();
289 inputContext->updateUserInterface(UserInterfaceComponent::InputPanel);
290 }
291
292 #ifdef FCITX_HAS_LUA
293 std::vector<std::string>
294 PinyinEngine::luaCandidateTrigger(InputContext *ic,
295 const std::string &candidateString) {
296 std::vector<std::string> result;
297 RawConfig arg;
298 arg.setValue(candidateString);
299 auto ret = imeapi()->call<ILuaAddon::invokeLuaFunction>(
300 ic, "candidateTrigger", arg);
301 const auto *length = ret.valueByPath("Length");
302 try {
303 if (length) {
304 auto n = std::stoi(*length);
305 for (int i = 0; i < n; i++) {
306 const auto *candidate = ret.valueByPath(std::to_string(i));
307 if (candidate && !candidate->empty()) {
308 result.push_back(*candidate);
309 }
310 }
311 }
312 } catch (...) {
313 }
314 return result;
315 }
316 #endif
317
318 std::pair<Text, Text> PinyinEngine::preedit(InputContext *inputContext) const {
319 auto *state = inputContext->propertyFor(&factory_);
320 PreeditMode mode =
321 inputContext->capabilityFlags().test(CapabilityFlag::Preedit)
322 ? *config_.preeditMode
323 : PreeditMode::No;
324 // Use const ref to avoid accidentally change anything.
325 const auto &context = state->context_;
326 auto preeditWithCursor = context.preeditWithCursor();
327 // client preedit can be empty/pinyin/preview depends on config
328 Text clientPreedit;
329 Text preedit;
330 switch (mode) {
331 case PreeditMode::ComposingPinyin:
332 if (*config_.preeditCursorPositionAtBeginning) {
333 clientPreedit.append(
334 preeditWithCursor.first.substr(0, preeditWithCursor.second),
335 {TextFormatFlag::HighLight, TextFormatFlag::Underline});
336 clientPreedit.append(
337 preeditWithCursor.first.substr(preeditWithCursor.second),
338 TextFormatFlag::Underline);
339 clientPreedit.setCursor(0);
340 } else {
341 clientPreedit.append(preeditWithCursor.first,
342 TextFormatFlag::Underline);
343 clientPreedit.setCursor(preeditWithCursor.second);
344 }
345 break;
346 case PreeditMode::CommitPreview:
347 clientPreedit.append(context.sentence(), TextFormatFlag::Underline);
348 if (*config_.preeditCursorPositionAtBeginning) {
349 clientPreedit.setCursor(0);
350 } else {
351 clientPreedit.setCursor(context.selectedSentence().size());
352 }
353 [[fallthrough]];
354 case PreeditMode::No:
355 preedit.append(preeditWithCursor.first);
356 preedit.setCursor(preeditWithCursor.second);
357 break;
358 }
359 return {std::move(clientPreedit), std::move(preedit)};
360 }
361
362 std::string
363 PinyinEngine::preeditCommitString(InputContext *inputContext) const {
364 auto *state = inputContext->propertyFor(&factory_);
365 // Use const ref to avoid accidentally change anything.
366 const auto &context = state->context_;
367
368 const auto &userInput = context.userInput();
369 const auto selectedLength = context.selectedLength();
370
371 return context.selectedSentence() +
372 userInput.substr(selectedLength,
373 userInput.length() - selectedLength);
374 }
375
376 void PinyinEngine::updatePreedit(InputContext *inputContext) const {
377 auto &inputPanel = inputContext->inputPanel();
378 auto [clientPreedit, preedit] = this->preedit(inputContext);
379 inputPanel.setClientPreedit(clientPreedit);
380 inputPanel.setPreedit(preedit);
381 }
382
383 void PinyinEngine::updatePuncPreedit(InputContext *inputContext) const {
384 auto candidateList = inputContext->inputPanel().candidateList();
385
386 if (inputContext->capabilityFlags().test(CapabilityFlag::Preedit)) {
387 if (candidateList->cursorIndex() >= 0) {
388 Text preedit;
389
390 const auto &candidate =
391 candidateList->candidate(candidateList->cursorIndex());
392 if (const auto *puncCandidate =
393 dynamic_cast<const PinyinPunctuationCandidateWord *>(
394 &candidate)) {
395 preedit.append(puncCandidate->word());
396 }
397
398 preedit.setCursor(preedit.textLength());
399 inputContext->inputPanel().setClientPreedit(preedit);
400 }
401 inputContext->updatePreedit();
402 }
403 }
404
405 void PinyinEngine::updatePuncCandidate(
406 InputContext *inputContext, const std::string &original,
407 const std::vector<std::string> &candidates) const {
408 inputContext->inputPanel().reset();
409 auto *state = inputContext->propertyFor(&factory_);
410 auto puncCandidateList = std::make_unique<CommonCandidateList>();
411 puncCandidateList->setPageSize(*config_.pageSize);
412 puncCandidateList->setCursorPositionAfterPaging(
413 CursorPositionAfterPaging::ResetToFirst);
414 for (const auto &result : candidates) {
415 puncCandidateList->append<PinyinPunctuationCandidateWord>(
416 this, result, original == result);
417 }
418 puncCandidateList->setCursorIncludeUnselected(false);
419 puncCandidateList->setCursorKeepInSamePage(false);
420 puncCandidateList->setGlobalCursorIndex(0);
421 puncCandidateList->setSelectionKey(selectionKeys_);
422 state->mode_ = PinyinMode::Punctuation;
423 inputContext->inputPanel().setCandidateList(std::move(puncCandidateList));
424 updatePuncPreedit(inputContext);
425 inputContext->updateUserInterface(UserInterfaceComponent::InputPanel);
426 }
427
428 void PinyinEngine::updateUI(InputContext *inputContext) {
429 auto *state = inputContext->propertyFor(&factory_);
430 if (state->mode_ == PinyinMode::StrokeFilter) {
431 resetStroke(inputContext);
432 }
433 inputContext->inputPanel().reset();
434 // Use const ref to avoid accidentally change anything.
435 const auto &context = state->context_;
436 if (context.selected()) {
437 auto sentence = context.sentence();
438 if (!inputContext->capabilityFlags().testAny(
439 CapabilityFlag::PasswordOrSensitive)) {
440 state->context_.learn();
441 }
442 inputContext->commitString(sentence);
443 inputContext->updatePreedit();
444 inputContext->updateUserInterface(UserInterfaceComponent::InputPanel);
445 initPredict(inputContext);
446 state->context_.clear();
447 return;
448 }
449
450 do {
451 if (context.userInput().empty()) {
452 break;
453 }
454 // Update Preedit.
455 updatePreedit(inputContext);
456 auto &inputPanel = inputContext->inputPanel();
457 // Update candidate
458 const auto &pinyinCandidates = context.candidatesToCursor();
459 if (pinyinCandidates.empty()) {
460 break;
461 }
462
463 // Setup candidate list.
464 auto candidateList = std::make_unique<CommonCandidateList>();
465 candidateList->setPageSize(*config_.pageSize);
466 candidateList->setCursorPositionAfterPaging(
467 CursorPositionAfterPaging::ResetToFirst);
468
469 // Precompute some values.
470 const auto selectedLength = context.selectedLength();
471 const auto selectedSentence = context.selectedSentence();
472
473 const bool fullResult = (context.cursor() == context.size() ||
474 context.cursor() == context.selectedLength());
475
476 const auto pyLength = context.cursor() > selectedLength
477 ? context.cursor() - selectedLength
478 : std::string::npos;
479 const auto pyBeforeCursor =
480 context.userInput().substr(selectedLength, pyLength);
481
482 std::unordered_map<std::string,
483 std::unique_ptr<PinyinAbstractCandidateWord>>
484 customCandidateMap;
485 /// Create custom phrase candidate {{{
486 do {
487 const auto *results = customPhrase_.lookup(pyBeforeCursor);
488 if (!results) {
489 break;
490 }
491 for (const auto &result : *results) {
492 if (result.order() <= 0) {
493 continue;
494 }
495 auto phrase =
496 result.evaluate([this, inputContext](std::string_view key) {
497 return evaluateCustomPhrase(inputContext, key);
498 });
499 if (customCandidateMap.contains(phrase)) {
500 continue;
501 }
502 std::string customPhrase =
503 result.isDynamic() ? result.value() : phrase;
504 customCandidateMap.emplace(
505 phrase, std::make_unique<CustomPhraseCandidateWord>(
506 this, pyBeforeCursor.size(),
507 CandidateOrder{result.order() - 1,
508 customCandidateMap.size()},
509 phrase, std::move(customPhrase)));
510 }
511 } while (false);
512 /// }}}
513
514 /// Create cloud candidate. {{{
515 if (*config_.cloudPinyinEnabled && cloudpinyin() &&
516 !inputContext->capabilityFlags().testAny(
517 CapabilityFlag::PasswordOrSensitive) &&
518 fullResult) {
519 using namespace std::placeholders;
520 auto fullPinyin = context.useShuangpin()
521 ? context.candidateFullPinyin(0)
522 : context.userInput().substr(selectedLength);
523 auto cand = std::make_unique<CustomCloudPinyinCandidateWord>(
524 this, fullPinyin, selectedSentence, inputContext,
525 [this](InputContext *ic, const std::string &selected,
526 const std::string &word) {
527 cloudPinyinSelected(ic, selected, word);
528 },
529 CandidateOrder{*config_.cloudPinyinIndex - 1,
530 customCandidateMap.size()});
531 if (!cand->filled() ||
532 (!cand->word().empty() &&
533 !customCandidateMap.contains(cand->word()) &&
534 !context.candidatesToCursorSet().contains(cand->word()))) {
535 customCandidateMap.emplace(cand->word(), std::move(cand));
536 }
537 }
538 /// }}}
539
540 /// Create spell candidate {{{
541 auto [parsedPy, parsedPyCursor] = state->context_.preeditWithCursor(
542 libime::PinyinPreeditMode::RawText);
543 if (*config_.spellEnabled && spell() &&
544 parsedPyCursor >= selectedSentence.size() &&
545 selectedLength <= context.cursor()) {
546 auto [hasUpper, engNess] =
547 englishNess(parsedPy, context.useShuangpin());
548 if (engNess) {
549 parsedPyCursor -= selectedSentence.length();
550 parsedPy = parsedPy.substr(
551 selectedSentence.size(),
552 parsedPyCursor > selectedSentence.length()
553 ? parsedPyCursor - selectedSentence.length()
554 : std::string::npos);
555 auto results = spell()->call<ISpell::hintWithProvider>(
556 "en", SpellProvider::Custom, pyBeforeCursor, engNess);
557
558 // Our hint doesn't work well with mixed case, so, always put a
559 // word as is.
560 if (hasUpper && !pyBeforeCursor.empty()) {
561 if (std::find(results.begin(), results.end(),
562 pyBeforeCursor) == results.end()) {
563 if (!charutils::isupper(pyBeforeCursor[0])) {
564 results.insert(results.begin(), pyBeforeCursor);
565 } else {
566 results.push_back(pyBeforeCursor);
567 }
568 }
569 }
570
571 int position = hasUpper ? 0 : 1;
572 for (const auto &result : results) {
573 if (customCandidateMap.contains(result)) {
574 continue;
575 }
576 customCandidateMap.emplace(
577 result, std::make_unique<SpellCandidateWord>(
578 this, result, pyBeforeCursor.size(),
579 CandidateOrder{position++,
580 customCandidateMap.size()}));
581 }
582 }
583 }
584 /// }}}
585
586 /// Create stroke candidate {{{
587 if (*config_.strokeCandidateEnabled && pinyinhelper() &&
588 context.selectedLength() == 0 && fullResult &&
589 isStroke(context.userInput())) {
590 int limit = (context.userInput().size() + 4) / 5;
591 limit = std::min(limit, 3);
592 auto results = pinyinhelper()->call<IPinyinHelper::lookupStroke>(
593 context.userInput(), limit);
594
595 int strokeCandsPos =
596 *config_.pageSize - static_cast<int>(results.size());
597 if (strokeCandsPos < 0) {
598 strokeCandsPos = *config_.pageSize - 1;
599 }
600 for (auto &result : results) {
601 utf8::getChar(result.first);
602 auto py = pinyinhelper()->call<IPinyinHelper::lookup>(
603 utf8::getChar(result.first));
604 auto pystr = stringutils::join(py, " ");
605 customCandidateMap.try_emplace(
606 result.first,
607 std::make_unique<StrokeCandidateWord>(
608 this, result.first, pystr, context.userInput().size(),
609 CandidateOrder{strokeCandsPos++,
610 customCandidateMap.size()}));
611 }
612 }
613 /// }}}
614
615 const auto candidateCompare = [](const auto &lhs, const auto &rhs) {
616 return lhs->sortOrder() < rhs->sortOrder();
617 };
618
619 // Save the middle point for inplace_merge.
620 std::vector<std::unique_ptr<PinyinAbstractCandidateWord>> candidates;
621 std::unordered_map<std::string,
622 std::unordered_set<PinyinCandidateWord *>>
623 candidateSet;
624
625 for (size_t idx = 0; idx < pinyinCandidates.size(); ++idx) {
626 const auto &candidate = pinyinCandidates[idx];
627 auto candidateString = candidate.toString();
628 auto iter = customCandidateMap.find(candidateString);
629 CandidateOrder order{idx, customCandidateMap.size()};
630 if (iter != customCandidateMap.end()) {
631 if (iter->second->selectLength() !=
632 candidate.sentence().back()->to()->index()) {
633 continue;
634 }
635 order = iter->second->sortOrder();
636 }
637 auto pinyinCandidate = std::make_unique<PinyinCandidateWord>(
638 this, inputContext, Text(std::move(candidateString)),
639 candidate.sentence().back()->to()->index(), idx, order);
640 candidateSet[pinyinCandidate->text().toString()].insert(
641 pinyinCandidate.get());
642 if (iter != customCandidateMap.end()) {
643 if (dynamic_cast<CustomPhraseCandidateWord *>(
644 iter->second.get())) {
645 pinyinCandidate->setCustomPhrase();
646 }
647 iter->second = std::move(pinyinCandidate);
648 } else {
649 candidates.push_back(std::move(pinyinCandidate));
650 }
651 }
652 for (const auto &[_, candidates] : candidateSet) {
653 if (candidates.size() > 1) {
654 for (auto *candidate : candidates) {
655 candidate->setPinyinInComment();
656 }
657 }
658 }
659 size_t middle = candidates.size();
660 for (auto &[_, candidate] : customCandidateMap) {
661 candidates.push_back(std::move(candidate));
662 }
663 // We expect stable sort here.
664 // Real pinyin candidate is always in order, so we have small N here.
665 std::stable_sort(std::ranges::next(candidates.begin(), middle),
666 candidates.end(), candidateCompare);
667 std::ranges::inplace_merge(
668 candidates, std::ranges::next(candidates.begin(), middle),
669 candidateCompare);
670
671 // Apply the candidate to candidate generation.
672 for (auto &candidatePtr : candidates) {
673 // Candidate pointer shall still valid here.
674 auto *candidate = candidatePtr.get();
675 auto candidateString = candidate->text().toString();
676
677 std::vector<std::string> luaExtraCandidates;
678 #ifdef FCITX_HAS_LUA
679 // Only trigger lua for top N candidates to avoid too much overhead.
680 if (candidate->order() <
681 std::max<size_t>(*config_.nbest, *config_.pageSize) &&
682 imeapi()) {
683 luaExtraCandidates =
684 luaCandidateTrigger(inputContext, candidateString);
685 }
686 #endif
687
688 // use candidateString before it is moved.
689 const std::vector<std::string> *symbols = nullptr;
690 if (*config_.symbolsEnabled) {
691 symbols = symbols_.lookup(candidateString);
692 }
693
694 candidateList->append(std::move(candidatePtr));
695 for (auto &extraCandidate : luaExtraCandidates) {
696 candidateList->append<LuaCandidateWord>(
697 this, candidate->selectLength(), std::move(extraCandidate));
698 }
699
700 if (symbols) {
701 std::string encodedPinyin;
702 int pinyinCandidateIndex = -1;
703 if (candidate->isPinyinCandidate()) {
704 auto *pinyinCandidate =
705 static_cast<PinyinCandidateWord *>(candidate);
706 pinyinCandidateIndex = pinyinCandidate->candidateIndex();
707 encodedPinyin = getEncodedPinyin(
708 pinyinCandidates[pinyinCandidateIndex]);
709 }
710 for (const auto &symbol : *symbols) {
711 const bool isFull =
712 candidate->selectLength() == pyBeforeCursor.size();
713 candidateList->append<SymbolCandidateWord>(
714 this, symbol, encodedPinyin, candidate->selectLength(),
715 isFull, pinyinCandidateIndex);
716 }
717 }
718 }
719
720 candidateList->setSelectionKey(selectionKeys_);
721 if (!candidateList->empty()) {
722 candidateList->setGlobalCursorIndex(0);
723 }
724 candidateList->setActionableImpl(
725 std::make_unique<PinyinActionableCandidateList>(this,
726 inputContext));
727 candidateList->setTabbedImpl(
728 std::make_unique<PinyinTabbedCandidateList>(this, inputContext,
729 candidateList.get()));
730 inputPanel.setCandidateList(std::move(candidateList));
731 } while (0);
732 inputContext->updatePreedit();
733 inputContext->updateUserInterface(UserInterfaceComponent::InputPanel);
734 }
735
736 std::string PinyinEngine::evaluateCustomPhrase(InputContext *inputContext,
737 std::string_view key) {
738 FCITX_UNUSED(inputContext);
739 auto result = CustomPhrase::builtinEvaluator(key);
740 if (!result.empty()) {
741 return result;
742 }
743
744 #ifdef FCITX_HAS_LUA
745 if (key.starts_with("lua:")) {
746 RawConfig config;
747 auto ret = imeapi()->call<ILuaAddon::invokeLuaFunction>(
748 inputContext, std::string(key.substr(4)), config);
749 if (!ret.value().empty()) {
750 return ret.value();
751 }
752 }
753 #endif
754 return "";
755 }
756
757 PinyinEngine::PinyinEngine(Instance *instance)
758 : instance_(instance),
759 factory_([this](InputContext &) { return new PinyinState(this); }),
760 worker_(instance->eventDispatcher()) {
761 ime_ = std::make_unique<libime::PinyinIME>(
762 std::make_unique<libime::PinyinDictionary>(),
763 std::make_unique<libime::UserLanguageModel>(
764 libime::DefaultLanguageModelResolver::instance()
765 .languageModelFileForLanguage("zh_CN")));
766
767 const auto &standardPath = StandardPaths::global();
768 auto systemDictFile =
769 standardPath.open(StandardPathsType::Data, "libime/sc.dict");
770 if (systemDictFile.isValid()) {
771 IFDStreamBuf buffer(systemDictFile.fd());
772 std::istream in(&buffer);
773 ime_->dict()->load(libime::PinyinDictionary::SystemDict, in,
774 libime::PinyinDictFormat::Binary);
775 } else {
776 ime_->dict()->load(libime::PinyinDictionary::SystemDict,
777 LIBIME_INSTALL_PKGDATADIR "/sc.dict",
778 libime::PinyinDictFormat::Binary);
779 }
780 prediction_.setUserLanguageModel(ime_->model());
781 prediction_.setPinyinDictionary(ime_->dict());
782
783 do {
784 auto file =
785 standardPath.open(StandardPathsType::PkgData, "pinyin/user.dict");
786
787 if (!file.isValid()) {
788 break;
789 }
790
791 try {
792 IFDStreamBuf buffer(file.fd());
793 std::istream in(&buffer);
794 ime_->dict()->load(libime::PinyinDictionary::UserDict, in,
795 libime::PinyinDictFormat::Binary);
796 } catch (const std::exception &e) {
797 PINYIN_ERROR() << "Failed to load pinyin dict: " << e.what();
798 }
799 } while (0);
800 do {
801 auto file =
802 standardPath.open(StandardPathsType::PkgData, "pinyin/user.history",
803 StandardPathsMode::User);
804
805 try {
806 IFDStreamBuf buffer(file.fd());
807 std::istream in(&buffer);
808 ime_->model()->load(in);
809 } catch (const std::exception &e) {
810 PINYIN_ERROR() << "Failed to load pinyin history: " << e.what();
811 }
812 } while (0);
813
814 ime_->setScoreFilter(1);
815 loadBuiltInDict();
816 reloadConfig();
817 loadExtraDict();
818 loadCustomPhrase();
819 instance_->inputContextManager().registerProperty("pinyinState", &factory_);
820 KeySym syms[] = {
821 FcitxKey_1, FcitxKey_2, FcitxKey_3, FcitxKey_4, FcitxKey_5,
822 FcitxKey_6, FcitxKey_7, FcitxKey_8, FcitxKey_9, FcitxKey_0,
823 };
824
825 KeyStates states;
826 for (auto sym : syms) {
827 selectionKeys_.emplace_back(sym, states);
828 }
829
830 KeySym numpadsyms[] = {
831 FcitxKey_KP_1, FcitxKey_KP_2, FcitxKey_KP_3, FcitxKey_KP_4,
832 FcitxKey_KP_5, FcitxKey_KP_6, FcitxKey_KP_7, FcitxKey_KP_8,
833 FcitxKey_KP_9, FcitxKey_KP_0,
834 };
835
836 KeyStates numpadStates;
837 for (auto sym : numpadsyms) {
838 numpadSelectionKeys_.emplace_back(sym, numpadStates);
839 }
840
841 predictionAction_.setShortText(*config_.predictionEnabled
842 ? _("Prediction Enabled")
843 : _("Prediction Disabled"));
844 predictionAction_.setLongText(_("Show prediction words"));
845 predictionAction_.setIcon(*config_.predictionEnabled
846 ? "fcitx-remind-active"
847 : "fcitx-remind-inactive");
848 predictionAction_.connect<SimpleAction::Activated>(
849 [this](InputContext *ic) {
850 config_.predictionEnabled.setValue(!(*config_.predictionEnabled));
851 predictionAction_.setShortText(*config_.predictionEnabled
852 ? _("Prediction Enabled")
853 : _("Prediction Disabled"));
854 predictionAction_.setIcon(*config_.predictionEnabled
855 ? "fcitx-remind-active"
856 : "fcitx-remind-inactive");
857 predictionAction_.update(ic);
858 });
859 instance_->userInterfaceManager().registerAction("pinyin-prediction",
860 &predictionAction_);
861 event_ = instance_->watchEvent(
862 EventType::InputContextKeyEvent, EventWatcherPhase::PreInputMethod,
863 [this](Event &event) {
864 auto &keyEvent = static_cast<KeyEvent &>(event);
865 auto *inputContext = keyEvent.inputContext();
866 const auto *entry = instance_->inputMethodEntry(inputContext);
867 if (!entry || entry->addon() != "pinyin") {
868 return;
869 }
870 handle2nd3rdSelection(keyEvent);
871 });
872
873 pyConfig_.shuangpinProfile.annotation().setHidden(true);
874 pyConfig_.showShuangpinMode.annotation().setHidden(true);
875 pyConfig_.fuzzyConfig->partialSp.annotation().setHidden(true);
876
877 deferredPreload_ = instance_->eventLoop().addDeferEvent([this](
878 EventSource *) {
879 bool hasCloudPinyin = cloudpinyin() != nullptr;
880 for (auto *configPtr : {&config_, &pyConfig_}) {
881 configPtr->cloudPinyinEnabled.annotation().setHidden(
882 !hasCloudPinyin);
883 configPtr->cloudPinyinIndex.annotation().setHidden(!hasCloudPinyin);
884 configPtr->cloudPinyinAnimation.annotation().setHidden(
885 !hasCloudPinyin);
886 configPtr->keepCloudPinyinPlaceHolder.annotation().setHidden(
887 !hasCloudPinyin);
888 configPtr->cloudpinyin.setHidden(!hasCloudPinyin);
889 }
890 deferredPreload_.reset();
891 return true;
892 });
893 }
894
895 PinyinEngine::~PinyinEngine() {}
896
897 void PinyinEngine::loadSymbols(const UnixFD &file) {
898 if (!file.isValid()) {
899 return;
900 }
901 IFDStreamBuf buffer(file.fd());
902 std::istream in(&buffer);
903 try {
904 PINYIN_DEBUG() << "Loading symbol dict.";
905 symbols_.load(in);
906 } catch (const std::exception &e) {
907 PINYIN_ERROR() << "Failed to load symbol dict: " << e.what();
908 }
909 }
910
911 void PinyinEngine::loadDict(const std::string &fullPath,
912 std::list<std::unique_ptr<TaskToken>> &taskTokens) {
913 if (fullPath.empty()) {
914 return;
915 }
916 ime_->dict()->addEmptyDict();
917 PINYIN_DEBUG() << "Loading pinyin dict " << fullPath;
918 std::packaged_task<libime::PinyinDictionary::TrieType()> task([fullPath]() {
919 std::ifstream in(fullPath, std::ios::in | std::ios::binary);
920 auto trie = libime::PinyinDictionary::load(
921 in, libime::PinyinDictFormat::Binary);
922 return trie;
923 });
924 taskTokens.push_back(worker_.addTask(
925 std::move(task),
926 [this, index = ime_->dict()->dictSize() - 1, fullPath](
927 std::shared_future<libime::PinyinDictionary::TrieType> &future) {
928 try {
929 PINYIN_DEBUG()
930 << "Load pinyin dict " << fullPath << " finished.";
931 ime_->dict()->setTrie(index, future.get());
932 } catch (const std::exception &e) {
933 PINYIN_ERROR() << "Failed to load pinyin dict " << fullPath
934 << ": " << e.what();
935 }
936 }));
937 }
938
939 void PinyinEngine::loadBuiltInDict() {
940 const auto &standardPath = StandardPaths::global();
941 {
942 auto file =
943 standardPath.open(StandardPathsType::PkgData, "pinyin/symbols");
944 loadSymbols(file);
945 }
946 {
947 auto file = standardPath.locate(StandardPathsType::PkgData,
948 "pinyin/chaizi.dict");
949 loadDict(file, persistentTask_);
950 }
951 {
952 auto file =
953 standardPath.locate(StandardPathsType::Data, "libime/extb.dict");
954 // Try again with absolute libime path.
955 if (file.empty()) {
956 file = standardPath.locate(StandardPathsType::Data,
957 LIBIME_INSTALL_PKGDATADIR "/extb.dict");
958 }
959 loadDict(file, persistentTask_);
960 }
961 if (ime_->dict()->dictSize() !=
962 libime::TrieDictionary::UserDict + 1 + NumBuiltInDict) {
963 throw std::runtime_error("Failed to load built-in dictionary");
964 }
965 }
966
967 void PinyinEngine::loadExtraDict() {
968 const auto &standardPath = StandardPaths::global();
969 auto files =
970 standardPath.locate(StandardPathsType::PkgData, "pinyin/dictionaries",
971 pathfilter::extension(".dict"));
972 std::unordered_set<std::filesystem::path> disableFilesSet;
973 for (const auto &item :
974 standardPath.locate(StandardPathsType::PkgData, "pinyin/dictionaries",
975 pathfilter::extension(".disable")) |
976 std::views::transform(
977 [](const auto &item) { return item.first.stem(); })) {
978 disableFilesSet.insert(item);
979 }
980 FCITX_ASSERT(ime_->dict()->dictSize() >=
981 libime::TrieDictionary::UserDict + NumBuiltInDict + 1)
982 << "Dict size: " << ime_->dict()->dictSize();
983 tasks_.clear();
984 ime_->dict()->removeFrom(libime::TrieDictionary::UserDict + NumBuiltInDict +
985 1);
986 for (auto &file : files) {
987 if (disableFilesSet.contains(file.first)) {
988 PINYIN_DEBUG() << "Dictionary: " << file.first << " is disabled.";
989 continue;
990 }
991 PINYIN_DEBUG() << "Loading extra dictionary: " << file.first;
992 loadDict(file.second, tasks_);
993 }
994 }
995
996 void PinyinEngine::loadCustomPhrase() {
997 const auto &standardPath = StandardPaths::global();
998 auto file =
999 standardPath.open(StandardPathsType::PkgData, "pinyin/customphrase");
1000 if (!file.isValid()) {
1001 customPhrase_.clear();
1002 return;
1003 }
1004
1005 try {
1006 IFDStreamBuf buffer(file.fd());
1007 std::istream in(&buffer);
1008 customPhrase_.load(in, true);
1009 } catch (const std::exception &e) {
1010 PINYIN_ERROR() << e.what();
1011 }
1012 }
1013
1014 void PinyinEngine::populateConfig() {
1015 if (*config_.firstRun) {
1016 config_.firstRun.setValue(false);
1017 safeSaveAsIni(config_, "conf/pinyin.conf");
1018 deferEvent_ = instance_->eventLoop().addDeferEvent([this](
1019 EventSource *) {
1020 if (cloudpinyin() && !*config_.cloudPinyinEnabled &&
1021 notifications()) {
1022 const auto &key =
1023 cloudpinyin()->call<ICloudPinyin::toggleKey>();
1024
1025 std::string msg;
1026 if (key.empty()) {
1027 msg = _("Do you want to enable cloudpinyin now for better "
1028 "prediction? You can always toggle it later in "
1029 "configuration.");
1030 } else {
1031 msg = _(
1032 "Do you want to enable cloudpinyin now for better "
1033 "prediction? You can always toggle it later in "
1034 "configuration or by pressing {}.",
1035 Key::keyListToString(key, KeyStringFormat::Localized));
1036 }
1037 std::vector<std::string> actions = {"yes", _("Yes"), "no",
1038 _("No")};
1039
1040 notifications()->call<INotifications::sendNotification>(
1041 _("Pinyin"), 0, "fcitx-pinyin", _("Enable Cloudpinyin"),
1042 msg, actions, -1,
1043 [this](const std::string &action) {
1044 if (action == "yes") {
1045 for (auto *configPtr : {&config_, &pyConfig_}) {
1046 configPtr->cloudPinyinEnabled.setValue(true);
1047 }
1048 save();
1049 }
1050 },
1051 nullptr);
1052 }
1053 deferEvent_.reset();
1054 return true;
1055 });
1056 }
1057 ime_->setNBest(*config_.nbest);
1058 ime_->setWordCandidateLimit(*config_.wordCandidateLimit);
1059 ime_->setPartialLongWordLimit(*config_.longWordLimit);
1060 ime_->setPreeditMode(*config_.showActualPinyinInPreedit
1061 ? libime::PinyinPreeditMode::Pinyin
1062 : libime::PinyinPreeditMode::RawText);
1063
1064 // Setup fuzzy flags.
1065 libime::PinyinFuzzyFlags flags;
1066 const auto &fuzzyConfig = *config_.fuzzyConfig;
1067 #define SET_FUZZY_FLAG(VAR, ENUM) \
1068 if (*fuzzyConfig.VAR) { \
1069 flags |= libime::PinyinFuzzyFlag::ENUM; \
1070 }
1071 SET_FUZZY_FLAG(ue, VE_UE)
1072 SET_FUZZY_FLAG(commonTypo, CommonTypo)
1073 SET_FUZZY_FLAG(commonTypo, AdvancedTypo)
1074 SET_FUZZY_FLAG(lowerCaseMatchLetter, Letter)
1075 SET_FUZZY_FLAG(inner, Inner)
1076 SET_FUZZY_FLAG(innerShort, InnerShort)
1077 SET_FUZZY_FLAG(partialFinal, PartialFinal)
1078 SET_FUZZY_FLAG(partialSp, PartialSp)
1079 SET_FUZZY_FLAG(v, V_U)
1080 SET_FUZZY_FLAG(an, AN_ANG)
1081 SET_FUZZY_FLAG(en, EN_ENG)
1082 SET_FUZZY_FLAG(ian, IAN_IANG)
1083 SET_FUZZY_FLAG(in, IN_ING)
1084 SET_FUZZY_FLAG(ou, U_OU)
1085 SET_FUZZY_FLAG(uan, UAN_UANG)
1086 SET_FUZZY_FLAG(c, C_CH)
1087 SET_FUZZY_FLAG(f, F_H)
1088 SET_FUZZY_FLAG(l, L_N)
1089 SET_FUZZY_FLAG(r, L_R)
1090 SET_FUZZY_FLAG(s, S_SH)
1091 SET_FUZZY_FLAG(z, Z_ZH)
1092
1093 {
1094 std::shared_ptr<libime::PinyinCorrectionProfile> correctionProfile;
1095 switch (*fuzzyConfig.correction) {
1096 case CorrectionLayout::None:
1097 break;
1098 case CorrectionLayout::Qwerty:
1099 correctionProfile =
1100 std::make_shared<libime::PinyinCorrectionProfile>(
1101 libime::BuiltinPinyinCorrectionProfile::Qwerty);
1102 break;
1103 }
1104 ime_->setCorrectionProfile(std::move(correctionProfile));
1105 }
1106
1107 if (ime_->correctionProfile()) {
1108 flags |= libime::PinyinFuzzyFlag::Correction;
1109 }
1110 ime_->setFuzzyFlags(flags);
1111
1112 if (*config_.shuangpinProfile == ShuangpinProfileEnum::Custom) {
1113 auto file = StandardPaths::global().open(StandardPathsType::PkgConfig,
1114 "pinyin/sp.dat");
1115 if (file.isValid()) {
1116 try {
1117 IFDStreamBuf buffer(file.fd());
1118 std::istream in(&buffer);
1119 ime_->setShuangpinProfile(
1120 std::make_shared<libime::ShuangpinProfile>(
1121 in, ime_->correctionProfile().get()));
1122 } catch (const std::exception &e) {
1123 PINYIN_ERROR() << e.what();
1124 }
1125 } else {
1126 PINYIN_ERROR() << "Failed to open shuangpin profile.";
1127 }
1128 } else {
1129 libime::ShuangpinBuiltinProfile profile;
1130 #define TRANS_SP_PROFILE(PROFILE) \
1131 case ShuangpinProfileEnum::PROFILE: \
1132 profile = libime::ShuangpinBuiltinProfile::PROFILE; \
1133 break;
1134 switch (*config_.shuangpinProfile) {
1135 TRANS_SP_PROFILE(Ziranma)
1136 TRANS_SP_PROFILE(MS)
1137 TRANS_SP_PROFILE(Ziguang)
1138 TRANS_SP_PROFILE(ABC)
1139 TRANS_SP_PROFILE(Zhongwenzhixing)
1140 TRANS_SP_PROFILE(PinyinJiajia)
1141 TRANS_SP_PROFILE(Xiaohe)
1142 TRANS_SP_PROFILE(GB)
1143 default:
1144 profile = libime::ShuangpinBuiltinProfile::Ziranma;
1145 break;
1146 }
1147 ime_->setShuangpinProfile(std::make_shared<libime::ShuangpinProfile>(
1148 profile, ime_->correctionProfile().get()));
1149 }
1150
1151 // Always set a profile to avoid crash.
1152 if (!ime_->shuangpinProfile()) {
1153 ime_->setShuangpinProfile(std::make_shared<libime::ShuangpinProfile>(
1154 libime::ShuangpinBuiltinProfile::Ziranma,
1155 ime_->correctionProfile().get()));
1156 }
1157
1158 quickphraseTriggerRegex_.clear();
1159 for (const std::string &regStr : *config_.quickphraseTriggerRegex) {
1160 try {
1161 std::regex reg{regStr};
1162 quickphraseTriggerRegex_.push_back(std::move(reg));
1163 } catch (const std::exception &e) {
1164 PINYIN_DEBUG() << "Invalid regular expression: \"" << regStr
1165 << "\", " << e.what();
1166 }
1167 }
1168 PINYIN_DEBUG() << "Quick Phrase Trigger Regex size: "
1169 << quickphraseTriggerRegex_.size();
1170
1171 ime_->dict()->setFlags(libime::TrieDictionary::UserDict + 1,
1172 *config_.chaiziEnabled
1173 ? libime::PinyinDictFlag::FullMatch
1174 : libime::PinyinDictFlag::Disabled);
1175 ime_->dict()->setFlags(libime::TrieDictionary::UserDict + 2,
1176 *config_.extBEnabled
1177 ? libime::PinyinDictFlag::NoFlag
1178 : libime::PinyinDictFlag::Disabled);
1179
1180 pyConfig_ = config_;
1181 }
1182
1183 void PinyinEngine::reloadConfig() {
1184 PINYIN_DEBUG() << "Reload pinyin config.";
1185 readAsIni(config_, "conf/pinyin.conf");
1186 populateConfig();
1187 }
1188 void PinyinEngine::activate(const fcitx::InputMethodEntry &entry,
1189 fcitx::InputContextEvent &event) {
1190 auto *inputContext = event.inputContext();
1191 // Request addons that gonna be used but not listed in optional
1192 // dependencies.
1193 fullwidth();
1194 chttrans();
1195 if (*config_.spellEnabled) {
1196 spell();
1197 }
1198 if (pinyinhelper()) {
1199 // Preload stroke data, since we gonna use it anyway.
1200 pinyinhelper()->call<IPinyinHelper::loadStroke>();
1201 }
1202 for (const auto *actionName : {"chttrans", "punctuation", "fullwidth"}) {
1203 if (auto *action =
1204 instance_->userInterfaceManager().lookupAction(actionName)) {
1205 inputContext->statusArea().addAction(StatusGroup::InputMethod,
1206 action);
1207 }
1208 }
1209 inputContext->statusArea().addAction(StatusGroup::InputMethod,
1210 &predictionAction_);
1211 auto *state = inputContext->propertyFor(&factory_);
1212 state->context_.setUseShuangpin(entry.uniqueName() == "shuangpin");
1213 // TODO: use surrouding to re-build context.
1214 state->context_.clearContextWords();
1215 }
1216
1217 void PinyinEngine::deactivate(const fcitx::InputMethodEntry &entry,
1218 fcitx::InputContextEvent &event) {
1219 auto *inputContext = event.inputContext();
1220 do {
1221 if (event.type() != EventType::InputContextSwitchInputMethod) {
1222 break;
1223 }
1224 auto *state = inputContext->propertyFor(&factory_);
1225 if (state->mode_ == PinyinMode::Punctuation) {
1226 auto candidateList = inputContext->inputPanel().candidateList();
1227 if (!candidateList) {
1228 break;
1229 }
1230 auto index = candidateList->cursorIndex();
1231 if (index >= 0) {
1232 candidateList->candidate(index).select(inputContext);
1233 }
1234 break;
1235 }
1236
1237 if (state->context_.empty()) {
1238 break;
1239 }
1240
1241 switch (*config_.switchInputMethodBehavior) {
1242 case SwitchInputMethodBehavior::CommitPreedit:
1243 inputContext->commitString(preeditCommitString(inputContext));
1244 break;
1245 case SwitchInputMethodBehavior::CommitDefault: {
1246 inputContext->commitString(state->context_.sentence());
1247 break;
1248 }
1249 case SwitchInputMethodBehavior::Clear:
1250 break;
1251 }
1252 } while (0);
1253 reset(entry, event);
1254 }
1255
1256 bool PinyinEngine::handlePuncCandidate(KeyEvent &event) {
1257 auto *inputContext = event.inputContext();
1258 auto *state = inputContext->propertyFor(&factory_);
1259 if (state->mode_ != PinyinMode::Punctuation) {
1260 return false;
1261 }
1262 auto candidateList = inputContext->inputPanel().candidateList();
1263 if (!candidateList) {
1264 doReset(inputContext);
1265 return false;
1266 }
1267 if (event.key().check(FcitxKey_BackSpace)) {
1268 event.filterAndAccept();
1269 doReset(inputContext);
1270 return true;
1271 }
1272 if (!event.isVirtual()) {
1273 int idx = event.key().keyListIndex(selectionKeys_);
1274 if (idx == -1 && *config_.useKeypadAsSelectionKey) {
1275 idx = event.key().keyListIndex(numpadSelectionKeys_);
1276 }
1277 if (idx >= 0) {
1278 event.filterAndAccept();
1279 if (idx < candidateList->size()) {
1280 candidateList->candidate(idx).select(inputContext);
1281 }
1282 return true;
1283 }
1284
1285 if (auto *movable = candidateList->toCursorMovable()) {
1286 if (event.key().checkKeyList(*config_.nextCandidate)) {
1287 movable->nextCandidate();
1288 updatePuncPreedit(inputContext);
1289 inputContext->updateUserInterface(
1290 UserInterfaceComponent::InputPanel);
1291 event.filterAndAccept();
1292 return true;
1293 }
1294 if (event.key().checkKeyList(*config_.prevCandidate)) {
1295 movable->prevCandidate();
1296 updatePuncPreedit(inputContext);
1297 inputContext->updateUserInterface(
1298 UserInterfaceComponent::InputPanel);
1299 event.filterAndAccept();
1300 return true;
1301 }
1302 }
1303 }
1304
1305 auto index = candidateList->cursorIndex();
1306 if (index >= 0) {
1307 candidateList->candidate(index).select(inputContext);
1308 }
1309
1310 doReset(inputContext);
1311 return false;
1312 }
1313
1314 bool PinyinEngine::handleCloudpinyinTrigger(KeyEvent &event) {
1315 if (cloudpinyin() && event.key().checkKeyList(
1316 cloudpinyin()->call<ICloudPinyin::toggleKey>())) {
1317 config_.cloudPinyinEnabled.setValue(!*config_.cloudPinyinEnabled);
1318 safeSaveAsIni(config_, "conf/pinyin.conf");
1319
1320 if (notifications()) {
1321 notifications()->call<INotifications::showTip>(
1322 "fcitx-cloudpinyin-toggle", _("Pinyin"), "",
1323 _("Cloud Pinyin Status"),
1324 *config_.cloudPinyinEnabled ? _("Cloud Pinyin is enabled.")
1325 : _("Cloud Pinyin is disabled."),
1326 1000);
1327 }
1328 if (*config_.cloudPinyinEnabled) {
1329 cloudpinyin()->call<ICloudPinyin::resetError>();
1330 }
1331 event.filterAndAccept();
1332 return true;
1333 }
1334 return false;
1335 }
1336
1337 bool PinyinEngine::handle2nd3rdSelection(KeyEvent &event) {
1338 auto *inputContext = event.inputContext();
1339 auto candidateList = inputContext->inputPanel().candidateList();
1340 if (!candidateList) {
1341 return false;
1342 }
1343
1344 struct {
1345 const KeyList &list;
1346 int selection;
1347 } keyHandlers[] = {
1348 // Index starts with 0
1349 {.list = *config_.secondCandidate, .selection = 1},
1350 {.list = *config_.thirdCandidate, .selection = 2},
1351 };
1352
1353 auto *state = inputContext->propertyFor(&factory_);
1354 int keyReleased = state->keyReleased_;
1355 int keyReleasedIndex = state->keyReleasedIndex_;
1356 // Keep these two values, and reset them in the state
1357 state->keyReleased_ = -1;
1358 state->keyReleasedIndex_ = -2;
1359 const bool isModifier = event.key().isModifier();
1360 if (event.isRelease()) {
1361 int idx = 0;
1362 for (auto &keyHandler : keyHandlers) {
1363 if (keyReleased == idx &&
1364 keyReleasedIndex == event.key().keyListIndex(keyHandler.list)) {
1365 if (isModifier) {
1366 if (instance_->globalConfig().checkModifierOnlyKeyTimeout(
1367 state->lastKeyPressedTime_) &&
1368 keyHandler.selection < candidateList->size()) {
1369 candidateList->candidate(keyHandler.selection)
1370 .select(inputContext);
1371 }
1372 state->lastKeyPressedTime_ = 0;
1373 event.filterAndAccept();
1374 return true;
1375 }
1376 event.filter();
1377 return true;
1378 }
1379 idx++;
1380 }
1381 }
1382
1383 if (!event.filtered() && !event.isRelease()) {
1384 int idx = 0;
1385 for (auto &keyHandler : keyHandlers) {
1386 auto keyIdx = event.key().keyListIndex(keyHandler.list);
1387 if (keyIdx >= 0) {
1388 state->keyReleased_ = idx;
1389 state->keyReleasedIndex_ = keyIdx;
1390 if (isModifier) {
1391 state->lastKeyPressedTime_ = now(CLOCK_MONOTONIC);
1392 // don't forward to input method, but make it pass
1393 // through to client.
1394 event.filter();
1395 return true;
1396 }
1397 if (keyHandler.selection < candidateList->size()) {
1398 candidateList->candidate(keyHandler.selection)
1399 .select(inputContext);
1400 }
1401 event.filterAndAccept();
1402 return true;
1403 }
1404 idx++;
1405 }
1406 }
1407 return false;
1408 }
1409
1410 bool PinyinEngine::handleCandidateList(
1411 KeyEvent &event, const std::shared_future<uint32_t> &keyChr) {
1412 auto *inputContext = event.inputContext();
1413 auto candidateList = inputContext->inputPanel().candidateList();
1414 if (!candidateList) {
1415 return false;
1416 }
1417 auto *state = inputContext->propertyFor(&factory_);
1418 if (event.key().checkKeyList(*config_.currentCandidate) &&
1419 !state->predictWords_) {
1420 if (!candidateList->empty()) {
1421 event.filterAndAccept();
1422 int idx = std::max(candidateList->cursorIndex(), 0);
1423 candidateList->candidate(idx).select(inputContext);
1424 return true;
1425 }
1426 }
1427
1428 if (event.isVirtual()) {
1429 return false;
1430 }
1431
1432 int idx = event.key().keyListIndex(selectionKeys_);
1433 if (idx == -1 && *config_.useKeypadAsSelectionKey) {
1434 idx = event.key().keyListIndex(numpadSelectionKeys_);
1435 }
1436 if (idx >= 0) {
1437 event.filterAndAccept();
1438 if (idx < candidateList->size()) {
1439 candidateList->candidate(idx).select(inputContext);
1440 }
1441 return true;
1442 }
1443
1444 if (event.key().checkKeyList(*config_.prevPage)) {
1445 auto *pageable = candidateList->toPageable();
1446 if (!pageable->hasPrev()) {
1447 if (pageable->usedNextBefore()) {
1448 event.filterAndAccept();
1449 return true;
1450 }
1451 // Only let key go through if it can reach handlePunc.
1452 auto c = keyChr.get();
1453 if (event.key().hasModifier() || !c) {
1454 event.filterAndAccept();
1455 return true;
1456 }
1457 } else {
1458 event.filterAndAccept();
1459 pageable->prev();
1460 inputContext->updateUserInterface(
1461 UserInterfaceComponent::InputPanel);
1462 return true;
1463 }
1464 }
1465
1466 if (handleNextPage(event)) {
1467 return true;
1468 }
1469
1470 if (auto *movable = candidateList->toCursorMovable()) {
1471 if (event.key().checkKeyList(*config_.nextCandidate)) {
1472 movable->nextCandidate();
1473 inputContext->updateUserInterface(
1474 UserInterfaceComponent::InputPanel);
1475 event.filterAndAccept();
1476 return true;
1477 }
1478 if (event.key().checkKeyList(*config_.prevCandidate)) {
1479 movable->prevCandidate();
1480 inputContext->updateUserInterface(
1481 UserInterfaceComponent::InputPanel);
1482 event.filterAndAccept();
1483 return true;
1484 }
1485 }
1486 return false;
1487 }
1488
1489 bool PinyinEngine::handleNextPage(KeyEvent &event) const {
1490 auto *inputContext = event.inputContext();
1491 auto candidateList = inputContext->inputPanel().candidateList();
1492 if (event.key().checkKeyList(*config_.nextPage)) {
1493 event.filterAndAccept();
1494 candidateList->toPageable()->next();
1495 inputContext->updateUserInterface(UserInterfaceComponent::InputPanel);
1496 return true;
1497 }
1498 return false;
1499 }
1500
1501 void PinyinEngine::updateFilter(InputContext *inputContext) {
1502 auto *state = inputContext->propertyFor(&factory_);
1503 auto &inputPanel = inputContext->inputPanel();
1504
1505 updatePreedit(inputContext);
1506 Text aux;
1507 if (state->mode_ == PinyinMode::StrokeFilter) {
1508 aux.append(_("[Stroke Filtering]"));
1509 aux.append(pinyinhelper()->call<IPinyinHelper::prettyStrokeString>(
1510 state->strokeBuffer_.userInput()));
1511 }
1512 inputPanel.setAuxUp(aux);
1513 inputPanel.setAuxDown(Text());
1514
1515 auto *candidateList =
1516 dynamic_cast<CommonCandidateList *>(inputPanel.candidateList().get());
1517 if (candidateList) {
1518 auto *pinyinTabbed = dynamic_cast<PinyinTabbedCandidateList *>(
1519 candidateList->toTabbed());
1520 if (state->strokeBuffer_.empty() &&
1521 (!pinyinTabbed || !pinyinTabbed->checked())) {
1522 candidateList->clearFilter();
1523 } else {
1524 candidateList->setFilter([this, pinyinTabbed,
1525 state](const CandidateWord &candidate)
1526 -> bool {
1527 if (pinyinTabbed && !pinyinTabbed->filter(candidate)) {
1528 return false;
1529 }
1530 if (!state->strokeBuffer_.empty()) {
1531 // For stroke candidate, skip if we are doing stroke filter.
1532 if (dynamic_cast<const StrokeCandidateWord *>(&candidate)) {
1533 return false;
1534 }
1535 auto str = candidate.text().toStringForCommit();
1536 if (auto length = utf8::lengthValidated(str);
1537 length != utf8::INVALID_LENGTH && length >= 1) {
1538 auto charRange = utf8::MakeUTF8CharRange(str);
1539 for (auto iter = std::begin(charRange),
1540 end = std::end(charRange);
1541 iter != end; ++iter) {
1542 std::string chr(iter.charRange().first,
1543 iter.charRange().second);
1544 auto stroke =
1545 pinyinhelper()
1546 ->call<IPinyinHelper::reverseLookupStroke>(
1547 chr);
1548 if (stroke.starts_with(
1549 state->strokeBuffer_.userInput())) {
1550 return true;
1551 }
1552 }
1553 }
1554 return false;
1555 }
1556 return true;
1557 });
1558 }
1559
1560 if (!candidateList->empty()) {
1561 candidateList->setGlobalCursorIndex(0);
1562 }
1563 }
1564 inputContext->updatePreedit();
1565 inputContext->updateUserInterface(UserInterfaceComponent::InputPanel);
1566 }
1567
1568 void PinyinEngine::updateForgetCandidate(InputContext *inputContext) {
1569 auto *state = inputContext->propertyFor(&factory_);
1570 auto &inputPanel = inputContext->inputPanel();
1571 inputPanel.reset();
1572
1573 updatePreedit(inputContext);
1574 Text aux(_("[Select the word to remove from history]"));
1575 inputPanel.setAuxUp(aux);
1576
1577 auto candidateList = std::make_unique<CommonCandidateList>();
1578 candidateList->setPageSize(*config_.pageSize);
1579 candidateList->setCursorPositionAfterPaging(
1580 CursorPositionAfterPaging::ResetToFirst);
1581
1582 auto *origCandidateList = state->forgetCandidateList_->toBulk();
1583 for (int i = 0; i < origCandidateList->totalSize(); i++) {
1584 const auto &candidate = origCandidateList->candidateFromAll(i);
1585 if (const auto *pyCandidate =
1586 dynamic_cast<const PinyinCandidateWord *>(&candidate)) {
1587 if (static_cast<size_t>(pyCandidate->candidateIndex()) >=
1588 state->context_.candidatesToCursor().size() ||
1589 state->context_
1590 .candidateFullPinyin(state->context_.candidatesToCursor()
1591 [pyCandidate->candidateIndex()])
1592 .empty()) {
1593 continue;
1594 }
1595
1596 candidateList->append<ForgetCandidateWord>(
1597 this, pyCandidate->text(), pyCandidate->candidateIndex());
1598 }
1599 }
1600 candidateList->setSelectionKey(selectionKeys_);
1601 if (!candidateList->empty()) {
1602 candidateList->setGlobalCursorIndex(0);
1603 }
1604 inputContext->inputPanel().setCandidateList(std::move(candidateList));
1605 inputContext->updatePreedit();
1606 inputContext->updateUserInterface(UserInterfaceComponent::InputPanel);
1607 }
1608
1609 void PinyinEngine::resetStroke(InputContext *inputContext) const {
1610 auto *state = inputContext->propertyFor(&factory_);
1611 state->strokeBuffer_.clear();
1612 if (state->mode_ == PinyinMode::StrokeFilter) {
1613 state->mode_ = PinyinMode::Normal;
1614 }
1615 }
1616
1617 void PinyinEngine::resetForgetCandidate(InputContext *inputContext) const {
1618 auto *state = inputContext->propertyFor(&factory_);
1619 state->forgetCandidateList_.reset();
1620 if (state->mode_ == PinyinMode::ForgetCandidate) {
1621 state->mode_ = PinyinMode::Normal;
1622 }
1623 }
1624
1625 void PinyinEngine::forgetCandidate(InputContext *inputContext, size_t index) {
1626 auto *state = inputContext->propertyFor(&factory_);
1627
1628 const std::string currentInput = state->context_.userInput();
1629
1630 if (index < state->context_.candidatesToCursor().size()) {
1631 const auto &sentence = state->context_.candidatesToCursor()[index];
1632 // If this is a word, remove it from user dict.
1633 if (sentence.size() == 1) {
1634 auto py = state->context_.candidateFullPinyin(index);
1635 state->context_.ime()->dict()->removeWord(
1636 libime::PinyinDictionary::UserDict, py, sentence.toString());
1637 }
1638 for (const auto &word : sentence.sentence()) {
1639 state->context_.ime()->model()->history().forget(word->word());
1640 }
1641 }
1642 resetForgetCandidate(inputContext);
1643 doReset(inputContext);
1644
1645 state->context_.type(currentInput);
1646 updateUI(inputContext);
1647 }
1648
1649 void PinyinEngine::saveCustomPhrase() {
1650 instance_->eventDispatcher().scheduleWithContext(watch(), [this]() {
1651 StandardPaths::global().safeSave(
1652 StandardPathsType::PkgData, "pinyin/customphrase", [this](int fd) {
1653 OFDStreamBuf buffer(fd);
1654 std::ostream out(&buffer);
1655 try {
1656 customPhrase_.save(out);
1657 return static_cast<bool>(out);
1658 } catch (const std::exception &e) {
1659 PINYIN_ERROR()
1660 << "Failed to save custom phrase: " << e.what();
1661 return false;
1662 }
1663 });
1664 });
1665 }
1666
1667 void PinyinEngine::pinCustomPhrase(InputContext *inputContext,
1668 const std::string &customPhrase) {
1669 auto *state = inputContext->propertyFor(&factory_);
1670 auto &context = state->context_;
1671 // Precompute some values.
1672 const auto selectedLength = context.selectedLength();
1673 const auto pyLength = context.cursor() > selectedLength
1674 ? context.cursor() - selectedLength
1675 : std::string::npos;
1676 const auto py = context.userInput().substr(selectedLength, pyLength);
1677 customPhrase_.pinPhrase(py, customPhrase);
1678
1679 resetStroke(inputContext);
1680 updateUI(inputContext);
1681 saveCustomPhrase();
1682 }
1683
1684 void PinyinEngine::deleteCustomPhrase(InputContext *inputContext,
1685 const std::string &customPhrase) {
1686 auto *state = inputContext->propertyFor(&factory_);
1687 auto &context = state->context_;
1688 // Precompute some values.
1689 const auto selectedLength = context.selectedLength();
1690 const auto pyLength = context.cursor() > selectedLength
1691 ? context.cursor() - selectedLength
1692 : std::string::npos;
1693 const auto py = context.userInput().substr(selectedLength, pyLength);
1694 customPhrase_.removePhrase(py, customPhrase);
1695
1696 resetStroke(inputContext);
1697 updateUI(inputContext);
1698 saveCustomPhrase();
1699 }
1700
1701 bool PinyinEngine::handleStrokeFilter(
1702 KeyEvent &event, const std::shared_future<uint32_t> &keyChr) {
1703 auto *inputContext = event.inputContext();
1704 auto candidateList = inputContext->inputPanel().candidateList();
1705 auto *state = inputContext->propertyFor(&factory_);
1706 if (state->mode_ == PinyinMode::Normal) {
1707 if (candidateList && !candidateList->empty() &&
1708 candidateList->toBulk() &&
1709 event.key().checkKeyList(*config_.selectByStroke) &&
1710 pinyinhelper()) {
1711 resetStroke(inputContext);
1712 state->mode_ = PinyinMode::StrokeFilter;
1713 updateFilter(inputContext);
1714 handleNextPage(event);
1715
1716 event.filterAndAccept();
1717 return true;
1718 }
1719 return false;
1720 }
1721
1722 if (state->mode_ != PinyinMode::StrokeFilter) {
1723 return false;
1724 }
1725
1726 event.filterAndAccept();
1727 // A special case that allow prev page to quit stroke filtering.
1728 if ((state->strokeBuffer_.empty() &&
1729 event.key().checkKeyList(*config_.prevPage))) {
1730 auto candidateList = inputContext->inputPanel().candidateList();
1731 if (candidateList && candidateList->toPageable() &&
1732 candidateList->toPageable()->currentPage() <= 1) {
1733 resetStroke(inputContext);
1734 updateUI(inputContext);
1735 return true;
1736 }
1737 }
1738
1739 if (handleCandidateList(event, keyChr)) {
1740 return true;
1741 }
1742 // Skip all key combination.
1743 if (event.key().states().testAny(KeyState::SimpleMask)) {
1744 return true;
1745 }
1746
1747 if (event.key().check(FcitxKey_Escape)) {
1748 resetStroke(inputContext);
1749 updateUI(inputContext);
1750 return true;
1751 }
1752 if (event.key().check(FcitxKey_BackSpace)) {
1753 // Do backspace is stroke is not empty.
1754 if (!state->strokeBuffer_.empty()) {
1755 state->strokeBuffer_.backspace();
1756 updateFilter(inputContext);
1757 } else {
1758 // Exit stroke mode when stroke buffer is empty.
1759 resetStroke(inputContext);
1760 updateUI(inputContext);
1761 }
1762 return true;
1763 }
1764 // if it gonna commit something
1765 auto c = keyChr.get();
1766 if (!c) {
1767 return true;
1768 }
1769
1770 if (event.key().check(FcitxKey_h) || event.key().check(FcitxKey_p) ||
1771 event.key().check(FcitxKey_s) || event.key().check(FcitxKey_n) ||
1772 event.key().check(FcitxKey_z)) {
1773 static const std::unordered_map<FcitxKeySym, char> strokeMap{
1774 {FcitxKey_h, '1'},
1775 {FcitxKey_s, '2'},
1776 {FcitxKey_p, '3'},
1777 {FcitxKey_n, '4'},
1778 {FcitxKey_z, '5'}};
1779 if (auto iter = strokeMap.find(event.key().sym());
1780 iter != strokeMap.end()) {
1781 state->strokeBuffer_.type(iter->second);
1782 updateFilter(inputContext);
1783 }
1784 }
1785
1786 return true;
1787 }
1788
1789 bool PinyinEngine::handleForgetCandidate(KeyEvent &event) {
1790 auto *inputContext = event.inputContext();
1791 auto candidateList = inputContext->inputPanel().candidateList();
1792 auto *state = inputContext->propertyFor(&factory_);
1793 if (state->mode_ == PinyinMode::Normal) {
1794 if (!state->predictWords_ && candidateList && !candidateList->empty() &&
1795 candidateList->toBulk() &&
1796 event.key().checkKeyList(*config_.forgetWord)) {
1797 resetForgetCandidate(inputContext);
1798 state->forgetCandidateList_ = std::move(candidateList);
1799 state->mode_ = PinyinMode::ForgetCandidate;
1800 updateForgetCandidate(inputContext);
1801 event.filterAndAccept();
1802 return true;
1803 }
1804 return false;
1805 }
1806
1807 if (state->mode_ != PinyinMode::ForgetCandidate) {
1808 return false;
1809 }
1810
1811 event.filterAndAccept();
1812 // Skip all key combination.
1813 if (event.key().states().testAny(KeyState::SimpleMask)) {
1814 return true;
1815 }
1816
1817 if (event.key().check(FcitxKey_Escape)) {
1818 resetForgetCandidate(inputContext);
1819 updateUI(inputContext);
1820 return true;
1821 }
1822 return true;
1823 }
1824
1825 bool PinyinEngine::handlePunc(KeyEvent &event,
1826 const std::shared_future<uint32_t> &keyChr) {
1827 auto *inputContext = event.inputContext();
1828 auto candidateList = inputContext->inputPanel().candidateList();
1829 auto *state = inputContext->propertyFor(&factory_);
1830 if (event.filtered()) {
1831 return false;
1832 }
1833 // if it gonna commit something
1834 auto c = keyChr.get();
1835 if (event.key().hasModifier() || !c) {
1836 // Handle quick phrase with modifier
1837 if (event.key().check(*config_.quickphraseKey) && quickphrase()) {
1838 quickphrase()->call<IQuickPhrase::trigger>(inputContext, "", "", "",
1839 "", Key());
1840 event.filterAndAccept();
1841 return true;
1842 }
1843 return false;
1844 }
1845 if (candidateList && !candidateList->empty()) {
1846 int idx = std::max(candidateList->cursorIndex(), 0);
1847 candidateList->candidate(idx).select(inputContext);
1848 }
1849
1850 // We can't emit punctuation right now, since it's not yet fully selected.
1851 // There is an option to split the current input, however, it may not be
1852 // sane to do so based on the partial input and cursor location. E.g.
1853 // current input is n|i hao, and you press ",". Candidate will be filtered
1854 // until "ni", instead of "n". which means you are not inserting "," between
1855 // n & i. Thus, let's just make it select the default candidate.
1856 // Also, it can not work with punctuation candidate, or type punc in pair.
1857 if (!state->context_.empty()) {
1858 event.filterAndAccept();
1859 return true;
1860 }
1861 // It's a key not handled by engine, just clear the word context.
1862 // Need to do after candidate selection, so the context is properly reset.
1863 state->context_.clearContextWords();
1864
1865 std::string punc;
1866 std::string puncAfter;
1867 // skip key pad
1868 if (c && !event.key().isKeyPad()) {
1869 auto candidates =
1870 punctuation()->call<IPunctuation::getPunctuationCandidates>("zh_CN",
1871 c);
1872 auto pushResult = punctuation()->call<IPunctuation::pushPunctuationV2>(
1873 "zh_CN", inputContext, c);
1874 if (candidates.size() == 1) {
1875 std::tie(punc, puncAfter) = pushResult;
1876 } else if (candidates.size() > 1) {
1877 updatePuncCandidate(inputContext, utf8::UCS4ToUTF8(c), candidates);
1878 event.filterAndAccept();
1879 return true;
1880 }
1881 }
1882 if (!event.isVirtual() && event.key().check(*config_.quickphraseKey) &&
1883 quickphrase()) {
1884 auto keyString = utf8::UCS4ToUTF8(c);
1885 // s is punc or key
1886 auto output = !punc.empty() ? (punc + puncAfter) : keyString;
1887 // alt is key or empty
1888 auto altOutput = !punc.empty() ? keyString : "";
1889 // if no punc: key -> key (s = key, alt = empty)
1890 // if there's punc: key -> punc, return -> key (s = punc, alt =
1891 // key)
1892 std::string text;
1893 if (!output.empty()) {
1894 if (!altOutput.empty()) {
1895 text = _("Press {} for {} and Return for {}", keyString, output,
1896 altOutput);
1897 } else {
1898 text = _("Press {} for {}", keyString, output);
1899 }
1900 }
1901 quickphrase()->call<IQuickPhrase::trigger>(
1902 inputContext, text, "", output, altOutput, *config_.quickphraseKey);
1903 event.filterAndAccept();
1904 return true;
1905 }
1906 if (!punc.empty()) {
1907 event.filterAndAccept();
1908 auto paired = punc + puncAfter;
1909 if (inputContext->capabilityFlags().test(
1910 CapabilityFlag::CommitStringWithCursor)) {
1911 if (size_t length = utf8::lengthValidated(punc);
1912 length != 0 && length != utf8::INVALID_LENGTH) {
1913 inputContext->commitStringWithCursor(paired, length);
1914 } else {
1915 inputContext->commitString(paired);
1916 }
1917 } else {
1918 inputContext->commitString(paired);
1919 if (size_t length = utf8::lengthValidated(puncAfter);
1920 length != 0 && length != utf8::INVALID_LENGTH) {
1921 for (size_t i = 0; i < length; i++) {
1922 inputContext->forwardKey(Key(FcitxKey_Left));
1923 }
1924 }
1925 }
1926 }
1927 state->lastIsPunc_ = true;
1928 return false;
1929 }
1930
1931 bool PinyinEngine::handleCompose(KeyEvent &event) {
1932 auto *inputContext = event.inputContext();
1933 auto *state = inputContext->propertyFor(&factory_);
1934 if (event.key().states().testAny(
1935 KeyStates{KeyState::Ctrl, KeyState::Super}) ||
1936 state->mode_ != PinyinMode::Normal) {
1937 return false;
1938 }
1939 auto candidateList = inputContext->inputPanel().candidateList();
1940 if (event.filtered()) {
1941 return false;
1942 }
1943 auto compose =
1944 instance_->processComposeString(inputContext, event.key().sym());
1945 if (!compose) {
1946 // invalid compose or in the middle of compose.
1947 event.filterAndAccept();
1948 return true;
1949 }
1950 // Handle the key just like punc select.
1951 if (!compose->empty()) {
1952 // Reset predict in case we are in predict.
1953 resetPredict(inputContext);
1954 // punc like auto selection.
1955 auto candidateList = inputContext->inputPanel().candidateList();
1956 if (candidateList && !candidateList->empty()) {
1957 candidateList->candidate(0).select(inputContext);
1958 }
1959 inputContext->commitString(*compose);
1960 event.filterAndAccept();
1961 return true;
1962 }
1963 return false;
1964 }
1965
1966 void PinyinEngine::resetPredict(InputContext *inputContext) {
1967 auto *state = inputContext->propertyFor(&factory_);
1968 if (!state->predictWords_) {
1969 return;
1970 }
1971 state->predictWords_.reset();
1972 inputContext->inputPanel().reset();
1973 inputContext->updatePreedit();
1974 inputContext->updateUserInterface(UserInterfaceComponent::InputPanel);
1975 }
1976
1977 void PinyinEngine::keyEvent(const InputMethodEntry &entry, KeyEvent &event) {
1978 FCITX_UNUSED(entry);
1979 PINYIN_DEBUG() << "Pinyin receive key: " << event.key() << " "
1980 << event.isRelease();
1981 auto *inputContext = event.inputContext();
1982 auto *state = inputContext->propertyFor(&factory_);
1983
1984 std::shared_future<uint32_t> keyChr =
1985 std::async(std::launch::deferred, [sym = event.key().sym()] {
1986 return Key::keySymToUnicode(sym);
1987 }).share();
1988 std::shared_future<std::string> keyStr =
1989 std::async(std::launch::deferred, [&keyChr] {
1990 return utf8::UCS4ToUTF8(keyChr.get());
1991 }).share();
1992
1993 // 2nd/3rd selection is allowed to be modifier only, handle them before we
1994 // skip the release.
1995 if (handle2nd3rdSelection(event)) {
1996 return;
1997 }
1998
1999 // by pass all key release
2000 if (event.isRelease()) {
2001 return;
2002 }
2003
2004 // Small hack to debug tabbed candidate on desktop.
2005 #if 0
2006 KeyList list;
2007 list.push_back(Key(FcitxKey_1, KeyState::Alt));
2008 list.push_back(Key(FcitxKey_2, KeyState::Alt));
2009 list.push_back(Key(FcitxKey_3, KeyState::Alt));
2010 list.push_back(Key(FcitxKey_4, KeyState::Alt));
2011 list.push_back(Key(FcitxKey_5, KeyState::Alt));
2012 list.push_back(Key(FcitxKey_6, KeyState::Alt));
2013 if (auto candidateList = inputContext->inputPanel().candidateList()) {
2014 if (auto *tabbed = candidateList->toTabbed()) {
2015 auto actions = tabbed->tabActions();
2016 if (auto idx = event.key().keyListIndex(list); idx >= 0 && idx < actions.size()) {
2017 tabbed->triggerTabAction(actions[idx].id());
2018 event.filterAndAccept();
2019 return;
2020 }
2021 }
2022 }
2023 #endif
2024
2025 if (handlePuncCandidate(event)) {
2026 return;
2027 }
2028
2029 // and by pass all modifier
2030 if (event.key().isModifier()) {
2031 return;
2032 }
2033
2034 if (handleCloudpinyinTrigger(event)) {
2035 return;
2036 }
2037
2038 auto candidateList = inputContext->inputPanel().candidateList();
2039 bool lastIsPunc = state->lastIsPunc_;
2040 state->lastIsPunc_ = false;
2041
2042 if (handleStrokeFilter(event, keyChr)) {
2043 return;
2044 }
2045
2046 if (handleCompose(event)) {
2047 return;
2048 }
2049
2050 // handle number key selection and prev/next page/candidate.
2051 if (handleCandidateList(event, keyChr)) {
2052 return;
2053 }
2054
2055 if (handleForgetCandidate(event)) {
2056 return;
2057 }
2058
2059 // In prediction, as long as it's not candidate selection, clear, then
2060 // fallback
2061 // to remaining operation.
2062 if (state->predictWords_) {
2063 resetPredict(inputContext);
2064 if (event.key().check(FcitxKey_Escape) ||
2065 (event.key().check(FcitxKey_BackSpace) &&
2066 (*config_.backspaceBehaviorOnPrediction ==
2067 BackspaceBehaviorOnPrediction::OnlyClearCandidates ||
2068 (*config_.backspaceBehaviorOnPrediction ==
2069 BackspaceBehaviorOnPrediction::
2070 BackspaceWhenNotUsingOnScreenKeyboard &&
2071 event.isVirtual()))) ||
2072 event.key().check(FcitxKey_Delete)) {
2073 event.filterAndAccept();
2074 return;
2075 }
2076 }
2077
2078 auto checkSp = [this, &keyChr](const KeyEvent &event, PinyinState *state) {
2079 auto shuangpinProfile = ime_->shuangpinProfile();
2080 if (!state->context_.useShuangpin() || !shuangpinProfile ||
2081 !event.key().isSimple()) {
2082 return false;
2083 }
2084 // event.key().isSimple() make sure the return value is within range of
2085 // char.
2086 char chr = keyChr.get();
2087 return (!state->context_.empty() &&
2088 shuangpinProfile->validInput().contains(chr)) ||
2089 (state->context_.empty() &&
2090 shuangpinProfile->validInitial().contains(chr));
2091 };
2092
2093 if (!event.key().hasModifier() && quickphrase() &&
2094 !quickphraseTriggerRegex_.empty() && !keyStr.get().empty() &&
2095 state->context_.selectedLength() == 0 &&
2096 state->context_.cursor() == state->context_.size()) {
2097 std::string text =
2098 stringutils::concat(state->context_.userInput(), keyStr.get());
2099 for (const auto &reg : quickphraseTriggerRegex_) {
2100 if (std::regex_search(text, reg,
2101 std::regex_constants::match_default)) {
2102 // Keep the current state before reset.
2103 const std::string origin = state->context_.userInput();
2104 doReset(inputContext);
2105 quickphrase()->call<IQuickPhrase::trigger>(inputContext, "", "",
2106 "", "", Key());
2107 quickphrase()->call<IQuickPhrase::setBufferWithRestoreCallback>(
2108 inputContext, text, origin,
2109 [this](InputContext *ic, const std::string &origin) {
2110 if (this->instance()->inputMethodEngine(ic) == this) {
2111 auto *state = ic->propertyFor(&factory_);
2112 doReset(ic);
2113 state->context_.type(origin);
2114 updateUI(ic);
2115 }
2116 });
2117 event.filterAndAccept();
2118 return;
2119 }
2120 }
2121 }
2122
2123 if (event.key().isLAZ() || event.key().isUAZ() ||
2124 (event.key().check(FcitxKey_apostrophe) && !state->context_.empty()) ||
2125 checkSp(event, state)) {
2126 // first v, use it to trigger quickphrase
2127 if (*config_.useVAsQuickphrase && quickphrase() &&
2128 state->context_.empty()) {
2129 const bool isSp = state->context_.useShuangpin();
2130 if ((event.key().check(FcitxKey_v) && !isSp) ||
2131 (event.key().check(FcitxKey_V) && isSp)) {
2132 const std::string leadingString =
2133 Key::keySymToUTF8(event.key().sym());
2134
2135 quickphrase()->call<IQuickPhrase::trigger>(
2136 inputContext, "", leadingString, "", "",
2137 Key(FcitxKey_None));
2138 event.filterAndAccept();
2139 return;
2140 }
2141 }
2142 event.filterAndAccept();
2143 if (!state->context_.type(keyStr.get())) {
2144 return;
2145 }
2146 } else if (!state->context_.empty()) {
2147 // key to handle when it is not empty.
2148 if (event.key().check(FcitxKey_BackSpace)) {
2149 if (*config_.useBackSpaceToUnselect &&
2150 state->context_.selectedLength()) {
2151 state->context_.cancel();
2152 } else {
2153 state->context_.backspace();
2154 }
2155 event.filterAndAccept();
2156 } else if (event.key().check(FcitxKey_Delete) ||
2157 event.key().check(FcitxKey_KP_Delete)) {
2158 state->context_.del();
2159 event.filterAndAccept();
2160 } else if (event.key().check(FcitxKey_BackSpace, KeyState::Ctrl)) {
2161 if (state->context_.cursor() == state->context_.selectedLength()) {
2162 state->context_.cancel();
2163 }
2164 auto cursor = state->context_.pinyinBeforeCursor();
2165 if (cursor >= 0) {
2166 state->context_.erase(cursor, state->context_.cursor());
2167 }
2168 event.filterAndAccept();
2169 } else if (event.key().check(FcitxKey_Delete, KeyState::Ctrl) ||
2170 event.key().check(FcitxKey_KP_Delete, KeyState::Ctrl)) {
2171 auto cursor = state->context_.pinyinAfterCursor();
2172 if (cursor >= 0 &&
2173 static_cast<size_t>(cursor) <= state->context_.size()) {
2174 state->context_.erase(state->context_.cursor(), cursor);
2175 }
2176 event.filterAndAccept();
2177 } else if (event.key().check(FcitxKey_Home) ||
2178 event.key().check(FcitxKey_KP_Home)) {
2179 state->context_.setCursor(state->context_.selectedLength());
2180 event.filterAndAccept();
2181 } else if (event.key().check(FcitxKey_End) ||
2182 event.key().check(FcitxKey_KP_End)) {
2183 state->context_.setCursor(state->context_.size());
2184 event.filterAndAccept();
2185 } else if (event.key().check(FcitxKey_Left) ||
2186 event.key().check(FcitxKey_KP_Left)) {
2187 if (state->context_.cursor() == state->context_.selectedLength()) {
2188 state->context_.cancel();
2189 }
2190 auto cursor = state->context_.cursor();
2191 if (cursor > 0) {
2192 state->context_.setCursor(cursor - 1);
2193 }
2194 event.filterAndAccept();
2195 } else if (event.key().check(FcitxKey_Right) ||
2196 event.key().check(FcitxKey_KP_Right)) {
2197 auto cursor = state->context_.cursor();
2198 if (cursor < state->context_.size()) {
2199 state->context_.setCursor(cursor + 1);
2200 }
2201 event.filterAndAccept();
2202 } else if (event.key().check(FcitxKey_Left, KeyState::Ctrl) ||
2203 event.key().check(FcitxKey_KP_Left, KeyState::Ctrl)) {
2204 if (state->context_.cursor() == state->context_.selectedLength()) {
2205 state->context_.cancel();
2206 }
2207 auto cursor = state->context_.pinyinBeforeCursor();
2208 if (cursor >= 0) {
2209 state->context_.setCursor(cursor);
2210 }
2211 event.filterAndAccept();
2212 } else if (event.key().check(FcitxKey_Right, KeyState::Ctrl) ||
2213 event.key().check(FcitxKey_KP_Right, KeyState::Ctrl)) {
2214 auto cursor = state->context_.pinyinAfterCursor();
2215 if (cursor >= 0 &&
2216 static_cast<size_t>(cursor) <= state->context_.size()) {
2217 state->context_.setCursor(cursor);
2218 }
2219 event.filterAndAccept();
2220 } else if (event.key().check(FcitxKey_Escape)) {
2221 state->context_.clear();
2222 event.filterAndAccept();
2223 } else if (event.key().checkKeyList(*config_.commitRawInput)) {
2224 inputContext->commitString(preeditCommitString(inputContext));
2225 state->context_.clear();
2226 state->context_.clearContextWords();
2227 event.filterAndAccept();
2228 } else if (auto maybeIdx =
2229 selectCharFromCandidateIndex(event.key(), config_)) {
2230 do {
2231 if (!candidateList || candidateList->empty() ||
2232 candidateList->cursorIndex() < 0) {
2233 break;
2234 }
2235 auto idx = maybeIdx.value();
2236 const auto &candidate =
2237 candidateList->candidate(candidateList->cursorIndex());
2238 auto str = candidate.text().toStringForCommit();
2239 // Validate string and length.
2240 auto len = utf8::lengthValidated(str);
2241 if (len == utf8::INVALID_LENGTH || len == 0) {
2242 break;
2243 }
2244 if (idx < 0) {
2245 idx = len - 1;
2246 }
2247 if (static_cast<size_t>(idx) >= len) {
2248 break;
2249 }
2250 // Get idx-th char.
2251 const std::string_view chr =
2252 std::next(utf8::MakeUTF8CharRange(str).begin(), idx).view();
2253 auto segmentLength =
2254 state->context_.size() - state->context_.selectedLength();
2255 const auto *pyCandidate =
2256 dynamic_cast<const PinyinCandidateWord *>(&candidate);
2257 if (pyCandidate) {
2258 const auto &contextCandidates =
2259 state->context_.candidatesToCursor();
2260 if (static_cast<size_t>(pyCandidate->candidateIndex()) <
2261 contextCandidates.size()) {
2262 const auto &sentence =
2263 contextCandidates[pyCandidate->candidateIndex()]
2264 .sentence();
2265 const auto candidateSegmentLength =
2266 sentence.back()->to()->index();
2267 segmentLength =
2268 std::min(segmentLength, candidateSegmentLength);
2269 }
2270 }
2271 state->context_.selectCustom(segmentLength, chr);
2272 event.filterAndAccept();
2273 } while (false);
2274 }
2275 } else if (event.key().check(FcitxKey_BackSpace)) {
2276 if (lastIsPunc) {
2277 const std::string &puncStr =
2278 punctuation()->call<IPunctuation::cancelLast>("zh_CN",
2279 inputContext);
2280 if (!puncStr.empty()) {
2281 // forward the original key is the best choice.
2282 state->cancelLastEvent_ = instance()->eventLoop().addTimeEvent(
2283 CLOCK_MONOTONIC, now(CLOCK_MONOTONIC) + 3000, 1,
2284 [this, ref = inputContext->watch(),
2285 puncStr = puncStr](EventSourceTime *, uint64_t) {
2286 if (auto *inputContext = ref.get()) {
2287 inputContext->commitString(puncStr);
2288 auto *state = inputContext->propertyFor(&factory_);
2289 state->cancelLastEvent_.reset();
2290 }
2291 return true;
2292 });
2293 event.filter();
2294 return;
2295 }
2296 }
2297 }
2298 if (handlePunc(event, keyChr)) {
2299 return;
2300 }
2301
2302 if (event.filtered() && event.accepted()) {
2303 updateUI(inputContext);
2304 }
2305 }
2306
2307 void PinyinEngine::setSubConfig(const std::string &path,
2308 const RawConfig &config) {
2309 FCITX_UNUSED(config);
2310 if (path == "dictmanager") {
2311 loadExtraDict();
2312 } else if (path == "clearuserdict") {
2313 ime_->dict()->clear(libime::PinyinDictionary::UserDict);
2314 } else if (path == "clearalldict") {
2315 ime_->dict()->clear(libime::PinyinDictionary::UserDict);
2316 ime_->model()->history().clear();
2317 } else if (path == "customphrase") {
2318 loadCustomPhrase();
2319 }
2320 }
2321
2322 void PinyinEngine::reset(const InputMethodEntry & /*entry*/,
2323 InputContextEvent &event) {
2324 auto *inputContext = event.inputContext();
2325 doReset(inputContext);
2326 }
2327
2328 void PinyinEngine::doReset(InputContext *inputContext) const {
2329 auto *state = inputContext->propertyFor(&factory_);
2330 resetStroke(inputContext);
2331 resetForgetCandidate(inputContext);
2332 state->mode_ = PinyinMode::Normal;
2333 state->context_.clear();
2334 state->context_.clearContextWords();
2335 state->predictWords_.reset();
2336 inputContext->inputPanel().reset();
2337 inputContext->updatePreedit();
2338 inputContext->updateUserInterface(UserInterfaceComponent::InputPanel);
2339 // state->lastIsPunc_ = false;
2340
2341 state->keyReleased_ = -1;
2342 state->keyReleasedIndex_ = -2;
2343 instance_->resetCompose(inputContext);
2344 }
2345
2346 void PinyinEngine::save() {
2347 safeSaveAsIni(config_, "conf/pinyin.conf");
2348 const auto &standardPath = StandardPaths::global();
2349 standardPath.safeSave(
2350 StandardPathsType::PkgData, "pinyin/user.dict", [this](int fd) {
2351 OFDStreamBuf buffer(fd);
2352 std::ostream out(&buffer);
2353 try {
2354 ime_->dict()->save(libime::PinyinDictionary::UserDict, out,
2355 libime::PinyinDictFormat::Binary);
2356 return static_cast<bool>(out);
2357 } catch (const std::exception &e) {
2358 PINYIN_ERROR() << "Failed to save pinyin dict: " << e.what();
2359 return false;
2360 }
2361 });
2362 standardPath.safeSave(
2363 StandardPathsType::PkgData, "pinyin/user.history", [this](int fd) {
2364 OFDStreamBuf buffer(fd);
2365 std::ostream out(&buffer);
2366 try {
2367 ime_->model()->save(out);
2368 return true;
2369 } catch (const std::exception &e) {
2370 PINYIN_ERROR() << "Failed to save pinyin history: " << e.what();
2371 return false;
2372 }
2373 });
2374 }
2375
2376 std::string PinyinEngine::subMode(const InputMethodEntry &entry,
2377 InputContext &inputContext) {
2378 FCITX_UNUSED(inputContext);
2379 if (entry.uniqueName() == "shuangpin" && *config_.showShuangpinMode &&
2380 *config_.shuangpinProfile != ShuangpinProfileEnum::Custom) {
2381 return ShuangpinProfileEnumI18NAnnotation::toString(
2382 *config_.shuangpinProfile);
2383 }
2384 return {};
2385 }
2386
2387 const Configuration *PinyinEngine::getConfig() const { return &config_; }
2388
2389 const Configuration *
2390 PinyinEngine::getConfigForInputMethod(const InputMethodEntry &entry) const {
2391 // Hide shuangpin options.
2392 if (entry.uniqueName() == "pinyin") {
2393 return &pyConfig_;
2394 }
2395 return &config_;
2396 }
2397
2398 void PinyinEngine::invokeActionImpl(const InputMethodEntry &entry,
2399 InvokeActionEvent &event) {
2400 auto *inputContext = event.inputContext();
2401 auto *state = inputContext->propertyFor(&factory_);
2402 auto &context = state->context_;
2403 auto &inputPanel = inputContext->inputPanel();
2404 if (event.cursor() < 0 ||
2405 event.action() != InvokeActionEvent::Action::LeftClick ||
2406 !inputContext->capabilityFlags().test(CapabilityFlag::Preedit)) {
2407 InputMethodEngineV3::invokeActionImpl(entry, event);
2408 return;
2409 }
2410 auto [clientPreedit, _] = this->preedit(inputContext);
2411
2412 auto preedit = clientPreedit.toString();
2413 size_t cursor = event.cursor();
2414 if (inputPanel.clientPreedit().toString() != clientPreedit.toString() ||
2415 inputPanel.clientPreedit().cursor() != clientPreedit.cursor() ||
2416 cursor > utf8::length(preedit)) {
2417 InputMethodEngineV3::invokeActionImpl(entry, event);
2418 return;
2419 }
2420
2421 event.filter();
2422
2423 auto preeditWithCursor = context.preeditWithCursor();
2424 auto selectedSentence = context.selectedSentence();
2425 // The logic here need to match ::preedit()
2426 switch (*config_.preeditMode) {
2427 case PreeditMode::No:
2428 break;
2429 case PreeditMode::ComposingPinyin:
2430 if (utf8::length(selectedSentence) > cursor) {
2431 // If cursor is with in selected sentence range, cancel until cursor
2432 // is covered.
2433 do {
2434 context.cancel();
2435 } while (utf8::length(context.selectedSentence()) > cursor);
2436 context.setCursor(context.selectedLength());
2437 } else {
2438 // If cursor is with in the pinyin range, move to the left most and
2439 // then move it around. This is a easy way to cover Shuangpin and
2440 // Preedit Mode difference. setCursor should be cheap operation if
2441 // it does not cancel any selection.
2442 context.setCursor(context.selectedLength());
2443 while (context.cursor() < context.size()) {
2444 auto [preeditText, preeditCursor] = context.preeditWithCursor();
2445 if (utf8::length(preeditText.begin(),
2446 preeditText.begin() + preeditCursor) <
2447 cursor) {
2448 state->context_.setCursor(context.cursor() + 1);
2449 } else {
2450 break;
2451 }
2452 }
2453 auto [preeditText, preeditCursor] = context.preeditWithCursor();
2454 if (utf8::length(preeditText.begin(),
2455 preeditText.begin() + preeditCursor) > cursor) {
2456 state->context_.setCursor(context.cursor() - 1);
2457 }
2458 }
2459 break;
2460 case PreeditMode::CommitPreview:
2461 if (utf8::length(selectedSentence) > cursor) {
2462 do {
2463 context.cancel();
2464 } while (utf8::length(context.selectedSentence()) > cursor);
2465 }
2466 break;
2467 }
2468 updateUI(inputContext);
2469 }
2470
2471 void PinyinEngine::cloudPinyinSelected(InputContext *inputContext,
2472 const std::string &selected,
2473 const std::string &word) {
2474 auto *state = inputContext->propertyFor(&factory_);
2475 auto words = state->context_.selectedWordsWithPinyin();
2476 // This ensure us to convert pinyin to the right one.
2477 auto preedit = state->context_.preedit(libime::PinyinPreeditMode::RawText);
2478 // preedit is "selected sentence" + Pinyin.
2479 do {
2480 // Validate selected is still the same.
2481 if (!preedit.starts_with(selected)) {
2482 words.clear();
2483 break;
2484 }
2485 // Get segmented pinyin.
2486 preedit = preedit.substr(selected.size());
2487 auto pinyins = stringutils::split(preedit, " '");
2488 std::string_view wordView = word;
2489 // Check word length matches pinyin length.
2490 if (pinyins.empty() || pinyins.size() != utf8::length(word)) {
2491 break;
2492 }
2493 const auto &candidates = state->context_.candidates();
2494 auto pinyinsIter = pinyins.begin();
2495 auto pinyinsEnd = pinyins.end();
2496 if (!candidates.empty()) {
2497 const auto &bestSentence = candidates[0].sentence();
2498 auto iter = bestSentence.begin();
2499 auto end = bestSentence.end();
2500 while (iter != end) {
2501 auto consumed = wordView;
2502 if (!stringutils::consumePrefix(consumed, (*iter)->word())) {
2503 break;
2504 }
2505 if (!(*iter)->word().empty()) {
2506 PINYIN_DEBUG()
2507 << "Cloud Pinyin can reuse segment " << (*iter)->word();
2508 const auto *pinyinNode =
2509 static_cast<const libime::PinyinLatticeNode *>(*iter);
2510 words.push_back(libime::HistoryBigram::WordWithCode{
2511 (*iter)->word(), pinyinNode->encodedPinyin()});
2512 auto pinyinSize = pinyinNode->encodedPinyin().size() / 2;
2513 if (pinyinSize &&
2514 static_cast<size_t>(std::distance(
2515 pinyinsIter, pinyinsEnd)) >= pinyinSize) {
2516 pinyinsIter += pinyinSize;
2517 } else {
2518 break;
2519 }
2520 }
2521 wordView = consumed;
2522 iter++;
2523 }
2524 }
2525 // if pinyin is not valid, it may throw
2526 try {
2527 if (utf8::length(wordView) == 1 &&
2528 std::ranges::all_of(
2529 words, [](const libime::HistoryBigram::WordWithCode &w) {
2530 return utf8::length(w.first) == 1;
2531 })) {
2532 words = state->context_.selectedWordsWithPinyin();
2533 auto joined =
2534 stringutils::join(pinyins.begin(), pinyins.end(), "'");
2535 auto encodedPinyin =
2536 libime::PinyinEncoder::encodeFullPinyinWithFlags(
2537 joined, libime::PinyinFuzzyFlag::VE_UE);
2538 words.push_back(libime::HistoryBigram::WordWithCode{
2539 std::string(word),
2540 std::string(encodedPinyin.data(), encodedPinyin.size())});
2541 ime_->dict()->addWord(libime::PinyinDictionary::UserDict,
2542 joined, word);
2543 } else {
2544 if (state->context_.useShuangpin()) {
2545 bool end = false;
2546 for (auto &sppinyin :
2547 MakeIterRange(pinyinsIter, pinyinsEnd)) {
2548 // Likely something goes wrong.
2549 if (sppinyin.size() > 2) {
2550 end = true;
2551 break;
2552 }
2553 sppinyin = libime::PinyinEncoder::shuangpinToPinyin(
2554 sppinyin, *ime_->shuangpinProfile());
2555 if (sppinyin.empty()) {
2556 end = true;
2557 break;
2558 }
2559 }
2560 if (end) {
2561 break;
2562 }
2563 }
2564 auto joined = stringutils::join(pinyinsIter, pinyinsEnd, "'");
2565 PINYIN_DEBUG()
2566 << "Cloud pinyin saves word: " << wordView << " " << joined;
2567 auto encodedPinyin =
2568 libime::PinyinEncoder::encodeFullPinyinWithFlags(
2569 joined, libime::PinyinFuzzyFlag::VE_UE);
2570 ime_->dict()->addWord(libime::PinyinDictionary::UserDict,
2571 joined, wordView);
2572 words.push_back(libime::HistoryBigram::WordWithCode{
2573 std::string(wordView),
2574 std::string(encodedPinyin.data(), encodedPinyin.size())});
2575 }
2576 ime_->model()->history().addWithCode(words);
2577 } catch (const std::exception &e) {
2578 PINYIN_DEBUG() << "Failed to save cloudpinyin: " << e.what();
2579 }
2580 } while (0);
2581 state->context_.clear();
2582 inputContext->commitString(selected + word);
2583 inputContext->inputPanel().reset();
2584 if (*config_.keepCurrentContext) {
2585 state->context_.appendContextWordsWithPinyin(words);
2586 }
2587 if (*config_.predictionEnabled) {
2588 state->predictWords_ = std::move(words);
2589 updatePredict(inputContext);
2590 }
2591 inputContext->updatePreedit();
2592 inputContext->updateUserInterface(UserInterfaceComponent::InputPanel);
2593 }
2594
2595 } // namespace fcitx