| 1 | /* |
| 2 | * SPDX-FileCopyrightText: 2017-2017 CSSlayer <[email protected]> |
| 3 | * |
| 4 | * SPDX-License-Identifier: LGPL-2.1-or-later |
| 5 | * |
| 6 | */ |
| 7 | #include "state.h" |
| 8 | #include "candidate.h" |
| 9 | #include "context.h" |
| 10 | #include "engine.h" |
| 11 | #include "ime.h" |
| 12 | #include "pinyinhelper_public.h" |
| 13 | #include "punctuation_public.h" |
| 14 | #include "quickphrase_public.h" |
| 15 | #include <algorithm> |
| 16 | #include <cstddef> |
| 17 | #include <cstdint> |
| 18 | #include <ctime> |
| 19 | #include <fcitx-utils/capabilityflags.h> |
| 20 | #include <fcitx-utils/event.h> |
| 21 | #include <fcitx-utils/eventloopinterface.h> |
| 22 | #include <fcitx-utils/i18n.h> |
| 23 | #include <fcitx-utils/key.h> |
| 24 | #include <fcitx-utils/keysym.h> |
| 25 | #include <fcitx-utils/stringutils.h> |
| 26 | #include <fcitx-utils/utf8.h> |
| 27 | #include <fcitx/candidatelist.h> |
| 28 | #include <fcitx/event.h> |
| 29 | #include <fcitx/inputcontext.h> |
| 30 | #include <fcitx/inputmethodentry.h> |
| 31 | #include <fcitx/inputpanel.h> |
| 32 | #include <fcitx/text.h> |
| 33 | #include <fcitx/userinterface.h> |
| 34 | #include <initializer_list> |
| 35 | #include <iterator> |
| 36 | #include <libime/core/historybigram.h> |
| 37 | #include <libime/pinyin/pinyinencoder.h> |
| 38 | #include <libime/pinyin/shuangpinprofile.h> |
| 39 | #include <libime/table/tablebaseddictionary.h> |
| 40 | #include <map> |
| 41 | #include <memory> |
| 42 | #include <string> |
| 43 | #include <string_view> |
| 44 | #include <tuple> |
| 45 | #include <utility> |
| 46 | #include <vector> |
| 47 | |
| 48 | namespace fcitx { |
| 49 | |
| 50 | TableContext *TableState::updateContext(const InputMethodEntry *entry) { |
| 51 | if (!entry || lastContext_ == entry->uniqueName()) { |
| 52 | return context_.get(); |
| 53 | } |
| 54 | |
| 55 | auto dict = engine_->ime()->requestDict(entry->uniqueName()); |
| 56 | if (!std::get<0>(dict)) { |
| 57 | return nullptr; |
| 58 | } |
| 59 | context_ = std::make_unique<TableContext>( |
| 60 | *std::get<0>(dict), *std::get<2>(dict), *std::get<1>(dict)); |
| 61 | lastContext_ = entry->uniqueName(); |
| 62 | return context_.get(); |
| 63 | } |
| 64 | |
| 65 | void TableState::release() { |
| 66 | reset(); |
| 67 | lastContext_.clear(); |
| 68 | context_.reset(); |
| 69 | } |
| 70 | |
| 71 | std::string TableState::commitSegements(size_t from, size_t to) { |
| 72 | auto *context = context_.get(); |
| 73 | if (!context) { |
| 74 | return ""; |
| 75 | } |
| 76 | |
| 77 | std::string sentence; |
| 78 | const auto &config = context->config(); |
| 79 | for (size_t i = from; i < to; i++) { |
| 80 | auto seg = context->selectedSegment(i); |
| 81 | if (std::get<bool>(seg) || *config.commitInvalidSegment) { |
| 82 | std::string code; |
| 83 | const auto &word = std::get<std::string>(seg); |
| 84 | if (utf8::length(word) == 1) { |
| 85 | code = context->selectedCode(i); |
| 86 | } |
| 87 | pushLastCommit(code, word); |
| 88 | sentence += word; |
| 89 | } |
| 90 | } |
| 91 | return sentence; |
| 92 | } |
| 93 | |
| 94 | void TableState::pushLastCommit(const std::string &code, |
| 95 | const std::string &lastSegment) { |
| 96 | if (lastSegment.empty() || |
| 97 | ic_->capabilityFlags().testAny(CapabilityFlag::PasswordOrSensitive)) { |
| 98 | return; |
| 99 | } |
| 100 | |
| 101 | TABLE_DEBUG() << "TableState::pushLastCommit " << lastSegment |
| 102 | << " code: " << code; |
| 103 | constexpr size_t limit = 10; |
| 104 | const auto length = utf8::lengthValidated(lastSegment); |
| 105 | // Sanity check. |
| 106 | if (length <= 0 || length == utf8::INVALID_LENGTH) { |
| 107 | return; |
| 108 | } |
| 109 | |
| 110 | if (length == 1 || *context_->config().autoPhraseWithPhrase) { |
| 111 | // Single character is with code as hint |
| 112 | if (length == 1) { |
| 113 | autoPhraseBuffer_.emplace_back(code, lastSegment); |
| 114 | } else { |
| 115 | auto range = fcitx::utf8::MakeUTF8CharRange(lastSegment); |
| 116 | for (auto iter = std::begin(range); iter != std::end(range); |
| 117 | iter++) { |
| 118 | autoPhraseBuffer_.emplace_back("", iter.view()); |
| 119 | } |
| 120 | } |
| 121 | while (autoPhraseBuffer_.size() > limit) { |
| 122 | autoPhraseBuffer_.pop_front(); |
| 123 | } |
| 124 | |
| 125 | std::string singleCharString; |
| 126 | std::vector<std::string> codeHints; |
| 127 | for (const auto &[code, chr] : autoPhraseBuffer_) { |
| 128 | singleCharString += chr; |
| 129 | codeHints.push_back(code); |
| 130 | } |
| 131 | TABLE_DEBUG() << "learnAutoPhrase " << autoPhraseBuffer_ << " " |
| 132 | << singleCharString << codeHints; |
| 133 | context_->learnAutoPhrase(singleCharString, codeHints); |
| 134 | } else { |
| 135 | autoPhraseBuffer_.clear(); |
| 136 | } |
| 137 | |
| 138 | if (length == 1) { |
| 139 | lastCommit_.emplace_back(code, lastSegment); |
| 140 | } else { |
| 141 | auto range = fcitx::utf8::MakeUTF8CharRange(lastSegment); |
| 142 | for (auto iter = std::begin(range); iter != std::end(range); iter++) { |
| 143 | lastCommit_.emplace_back("", iter.view()); |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | if (lastCommit_.size() > limit) { |
| 148 | while (lastCommit_.size() > limit) { |
| 149 | lastCommit_.pop_front(); |
| 150 | } |
| 151 | } |
| 152 | lastSegment_ = lastSegment; |
| 153 | } |
| 154 | |
| 155 | void TableState::reset(const InputMethodEntry *entry) { |
| 156 | auto *context = updateContext(entry); |
| 157 | if (context) { |
| 158 | context->clear(); |
| 159 | } |
| 160 | ic_->inputPanel().reset(); |
| 161 | ic_->updatePreedit(); |
| 162 | ic_->updateUserInterface(UserInterfaceComponent::InputPanel); |
| 163 | // lastIsPunc_ = false; |
| 164 | mode_ = TableMode::Normal; |
| 165 | pinyinModePrefix_.clear(); |
| 166 | pinyinModeBuffer_.clear(); |
| 167 | |
| 168 | keyReleased_ = -1; |
| 169 | keyReleasedIndex_ = -2; |
| 170 | // Since we also to compose, just reset compose all together |
| 171 | engine_->instance()->resetCompose(ic_); |
| 172 | } |
| 173 | |
| 174 | std::unique_ptr<CandidateList> |
| 175 | TableState::predictCandidateList(const std::vector<std::string> &words) { |
| 176 | if (words.empty() || isComposeTableMode()) { |
| 177 | return nullptr; |
| 178 | } |
| 179 | auto candidateList = std::make_unique<CommonCandidateList>(); |
| 180 | for (const auto &word : words) { |
| 181 | candidateList->append<TablePredictCandidateWord>(this, word); |
| 182 | } |
| 183 | candidateList->setSelectionKey(*context_->config().selection); |
| 184 | candidateList->setPageSize(*context_->config().pageSize); |
| 185 | if (!candidateList->empty()) { |
| 186 | candidateList->setGlobalCursorIndex(0); |
| 187 | } |
| 188 | return candidateList; |
| 189 | } |
| 190 | |
| 191 | void TableState::resetAndPredict() { |
| 192 | reset(); |
| 193 | predict(); |
| 194 | } |
| 195 | |
| 196 | void TableState::predict() { |
| 197 | if (!context_ || !context_->prediction() || |
| 198 | !*engine_->config().predictionEnabled) { |
| 199 | return; |
| 200 | } |
| 201 | |
| 202 | std::string predictWord; |
| 203 | if (*context_->config().commitAfterSelect) { |
| 204 | predictWord = lastSegment_; |
| 205 | } else { |
| 206 | if (context_->selected()) { |
| 207 | auto [segment, valid] = |
| 208 | context_->selectedSegment(context_->selectedSize() - 1); |
| 209 | if (!valid) { |
| 210 | return; |
| 211 | } |
| 212 | predictWord = segment; |
| 213 | } else if (context_->empty()) { |
| 214 | predictWord = lastSegment_; |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | if (predictWord.empty()) { |
| 219 | return; |
| 220 | } |
| 221 | const std::vector<std::string> predictWords{std::move(predictWord)}; |
| 222 | auto words = context_->prediction()->predict( |
| 223 | predictWords, *engine_->config().predictionSize); |
| 224 | if (auto candidateList = predictCandidateList(words)) { |
| 225 | auto &inputPanel = ic_->inputPanel(); |
| 226 | inputPanel.setCandidateList(std::move(candidateList)); |
| 227 | } |
| 228 | ic_->updateUserInterface(UserInterfaceComponent::InputPanel); |
| 229 | } |
| 230 | |
| 231 | bool TableState::isContextEmpty() const { |
| 232 | if (!context_) { |
| 233 | return true; |
| 234 | } |
| 235 | |
| 236 | if (*context_->config().commitAfterSelect) { |
| 237 | return context_->empty() || context_->selected(); |
| 238 | } |
| 239 | return context_->empty(); |
| 240 | } |
| 241 | |
| 242 | bool TableState::isComposeTableMode() const { |
| 243 | |
| 244 | if (!context_) { |
| 245 | return false; |
| 246 | } |
| 247 | |
| 248 | return *context_->config().pageSize == 0; |
| 249 | } |
| 250 | |
| 251 | bool TableState::autoSelectCandidate() const { |
| 252 | auto candidateList = ic_->inputPanel().candidateList(); |
| 253 | if (candidateList && !candidateList->empty()) { |
| 254 | int idx = std::max(candidateList->cursorIndex(), 0); |
| 255 | candidateList->candidate(idx).select(ic_); |
| 256 | return true; |
| 257 | } |
| 258 | if (isComposeTableMode() && !context_->candidates().empty()) { |
| 259 | // Create a dummy candidate word to reuse the logic in |
| 260 | // TableCandidateWord::select |
| 261 | TableCandidateWord candidate(engine_, Text{}, Text{}, true, 0); |
| 262 | candidate.select(ic_); |
| 263 | return true; |
| 264 | } |
| 265 | return false; |
| 266 | } |
| 267 | |
| 268 | bool TableState::handleCandidateList(const TableConfig &config, |
| 269 | KeyEvent &event) { |
| 270 | if (event.isVirtual()) { |
| 271 | return false; |
| 272 | } |
| 273 | auto *inputContext = event.inputContext(); |
| 274 | // check if we can select candidate. |
| 275 | auto candidateList = inputContext->inputPanel().candidateList(); |
| 276 | if (!candidateList) { |
| 277 | return false; |
| 278 | } |
| 279 | |
| 280 | const int idx = event.key().keyListIndex(*config.selection); |
| 281 | if (idx >= 0) { |
| 282 | event.filterAndAccept(); |
| 283 | if (idx < candidateList->size()) { |
| 284 | candidateList->candidate(idx).select(inputContext); |
| 285 | } |
| 286 | return true; |
| 287 | } |
| 288 | |
| 289 | if (event.key().checkKeyList(*config.prevPage)) { |
| 290 | auto *pageable = candidateList->toPageable(); |
| 291 | if (!pageable->hasPrev()) { |
| 292 | if (pageable->usedNextBefore()) { |
| 293 | event.filterAndAccept(); |
| 294 | return true; |
| 295 | } |
| 296 | // Only let key go through if it can reach handlePunc. |
| 297 | auto c = Key::keySymToUnicode(event.key().sym()); |
| 298 | if (event.key().hasModifier() || !c) { |
| 299 | event.filterAndAccept(); |
| 300 | return true; |
| 301 | } |
| 302 | } else { |
| 303 | event.filterAndAccept(); |
| 304 | pageable->prev(); |
| 305 | inputContext->updateUserInterface( |
| 306 | UserInterfaceComponent::InputPanel); |
| 307 | return true; |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | if (event.key().checkKeyList(*config.nextPage)) { |
| 312 | event.filterAndAccept(); |
| 313 | candidateList->toPageable()->next(); |
| 314 | inputContext->updateUserInterface(UserInterfaceComponent::InputPanel); |
| 315 | return true; |
| 316 | } |
| 317 | if (auto *movable = candidateList->toCursorMovable()) { |
| 318 | if (event.key().checkKeyList(*config.nextCandidate)) { |
| 319 | movable->nextCandidate(); |
| 320 | inputContext->updateUserInterface( |
| 321 | UserInterfaceComponent::InputPanel); |
| 322 | event.filterAndAccept(); |
| 323 | return true; |
| 324 | } |
| 325 | if (event.key().checkKeyList(*config.prevCandidate)) { |
| 326 | movable->prevCandidate(); |
| 327 | inputContext->updateUserInterface( |
| 328 | UserInterfaceComponent::InputPanel); |
| 329 | event.filterAndAccept(); |
| 330 | return true; |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | return false; |
| 335 | } |
| 336 | |
| 337 | bool TableState::handlePinyinMode(KeyEvent &event) { |
| 338 | auto *context = context_.get(); |
| 339 | const auto &config = context_->config(); |
| 340 | const auto &pinyinKey = *config.pinyinKey; |
| 341 | if (pinyinKey.sym() == FcitxKey_None) { |
| 342 | return false; |
| 343 | } |
| 344 | bool needUpdate = false; |
| 345 | if (mode_ == TableMode::Normal && event.key().check(pinyinKey)) { |
| 346 | auto chr = Key::keySymToUnicode(event.key().sym()); |
| 347 | if (!isContextEmpty()) { |
| 348 | if (context->isValidInput(chr)) { |
| 349 | return false; |
| 350 | } |
| 351 | } |
| 352 | // This is to flush all the pending buffer. |
| 353 | commitBuffer(true); |
| 354 | mode_ = TableMode::Pinyin; |
| 355 | event.filterAndAccept(); |
| 356 | |
| 357 | if (!event.key().hasModifier()) { |
| 358 | pinyinModePrefix_ = Key::keySymToUTF8(event.key().sym()); |
| 359 | needUpdate = true; |
| 360 | } |
| 361 | } else if (mode_ != TableMode::Pinyin) { |
| 362 | return false; |
| 363 | } else { |
| 364 | if (event.key().isLAZ() || event.key().check(FcitxKey_apostrophe)) { |
| 365 | event.filterAndAccept(); |
| 366 | pinyinModeBuffer_.type(Key::keySymToUTF8(event.key().sym())); |
| 367 | needUpdate = true; |
| 368 | } else if (event.key().check(FcitxKey_BackSpace)) { |
| 369 | event.filterAndAccept(); |
| 370 | if (!pinyinModeBuffer_.empty()) { |
| 371 | pinyinModeBuffer_.backspace(); |
| 372 | needUpdate = true; |
| 373 | } else { |
| 374 | reset(); |
| 375 | return true; |
| 376 | } |
| 377 | } else if (event.key().checkKeyList(*config.defaultCandidate)) { |
| 378 | event.filterAndAccept(); |
| 379 | if (autoSelectCandidate()) { |
| 380 | return true; |
| 381 | } |
| 382 | if (pinyinModeBuffer_.empty()) { |
| 383 | if (!lastSegment_.empty()) { |
| 384 | ic_->commitString(lastSegment_); |
| 385 | } |
| 386 | reset(); |
| 387 | } |
| 388 | return true; |
| 389 | } else if (event.key().check(FcitxKey_Return) || |
| 390 | event.key().check(FcitxKey_KP_Enter)) { |
| 391 | event.filterAndAccept(); |
| 392 | auto commit = pinyinModePrefix_ + pinyinModeBuffer_.userInput(); |
| 393 | if (!commit.empty()) { |
| 394 | ic_->commitString(commit); |
| 395 | } |
| 396 | reset(); |
| 397 | return true; |
| 398 | } |
| 399 | } |
| 400 | if (!needUpdate) { |
| 401 | return false; |
| 402 | } |
| 403 | auto &inputPanel = ic_->inputPanel(); |
| 404 | ic_->inputPanel().reset(); |
| 405 | |
| 406 | if (!pinyinModeBuffer_.empty() && !isComposeTableMode()) { |
| 407 | const auto &dict = engine_->pinyinDict(); |
| 408 | const auto &lm = engine_->pinyinModel(); |
| 409 | auto pinyin = libime::PinyinEncoder::encodeOneUserPinyin( |
| 410 | pinyinModeBuffer_.userInput()); |
| 411 | |
| 412 | auto candidateList = std::make_unique<CommonCandidateList>(); |
| 413 | candidateList->setLayoutHint(*config.candidateLayoutHint); |
| 414 | candidateList->setCursorPositionAfterPaging( |
| 415 | CursorPositionAfterPaging::ResetToFirst); |
| 416 | candidateList->setSelectionKey(*config.selection); |
| 417 | candidateList->setPageSize(*config.pageSize); |
| 418 | |
| 419 | std::vector<std::pair<std::string, float>> pinyinWords; |
| 420 | |
| 421 | dict.matchWords(pinyin.data(), pinyin.size(), |
| 422 | [&pinyinWords, &lm](std::string_view, |
| 423 | std::string_view hanzi, float) { |
| 424 | pinyinWords.emplace_back(hanzi, |
| 425 | lm.singleWordScore(hanzi)); |
| 426 | return true; |
| 427 | }); |
| 428 | |
| 429 | std::sort(pinyinWords.begin(), pinyinWords.end(), |
| 430 | [](const auto &lhs, const auto &rhs) { |
| 431 | return lhs.second > rhs.second; |
| 432 | }); |
| 433 | |
| 434 | for (auto &p : pinyinWords) { |
| 435 | candidateList->append<TablePinyinCandidateWord>( |
| 436 | engine_, std::move(p.first), context_->dict(), |
| 437 | *config.displayCustomHint, *config.hintSeparator, |
| 438 | *config.spaceBeforeHint); |
| 439 | } |
| 440 | |
| 441 | if (!candidateList->empty()) { |
| 442 | candidateList->setGlobalCursorIndex(0); |
| 443 | inputPanel.setCandidateList(std::move(candidateList)); |
| 444 | } |
| 445 | } else { |
| 446 | if (!lastSegment_.empty()) { |
| 447 | inputPanel.setAuxDown(Text(lastSegment_)); |
| 448 | } |
| 449 | } |
| 450 | Text preeditText; |
| 451 | preeditText.append(pinyinModePrefix_); |
| 452 | preeditText.append(pinyinModeBuffer_.userInput()); |
| 453 | if (ic_->capabilityFlags().test(CapabilityFlag::Preedit)) { |
| 454 | if (*config.preeditCursorPositionAtBeginning) { |
| 455 | preeditText.setCursor(0); |
| 456 | } else { |
| 457 | preeditText.setCursor(preeditText.textLength()); |
| 458 | } |
| 459 | inputPanel.setClientPreedit(preeditText); |
| 460 | } else { |
| 461 | preeditText.setCursor(preeditText.textLength()); |
| 462 | inputPanel.setPreedit(preeditText); |
| 463 | } |
| 464 | ic_->updatePreedit(); |
| 465 | ic_->updateUserInterface(UserInterfaceComponent::InputPanel); |
| 466 | return true; |
| 467 | } |
| 468 | |
| 469 | bool TableState::handleForgetWord(KeyEvent &event) { |
| 470 | auto *inputContext = event.inputContext(); |
| 471 | auto candidateList = inputContext->inputPanel().candidateList(); |
| 472 | if (!candidateList || candidateList->empty() || |
| 473 | !dynamic_cast<const TableCandidateWord *>( |
| 474 | &candidateList->candidate(0))) { |
| 475 | return false; |
| 476 | } |
| 477 | if (mode_ == TableMode::Normal && |
| 478 | event.key().checkKeyList(*engine_->config().forgetWord)) { |
| 479 | mode_ = TableMode::ForgetWord; |
| 480 | event.filterAndAccept(); |
| 481 | updateUI(/*keepOldCursor=*/true, /*maybePredict=*/false); |
| 482 | return true; |
| 483 | } |
| 484 | if (mode_ == TableMode::ForgetWord && event.key().check(FcitxKey_Escape)) { |
| 485 | mode_ = TableMode::Normal; |
| 486 | event.filterAndAccept(); |
| 487 | updateUI(/*keepOldCursor=*/true, /*maybePredict=*/false); |
| 488 | return true; |
| 489 | } |
| 490 | |
| 491 | if (mode_ == TableMode::ForgetWord) { |
| 492 | event.filterAndAccept(); |
| 493 | return true; |
| 494 | } |
| 495 | return false; |
| 496 | } |
| 497 | |
| 498 | bool TableState::handleLookupPinyinOrModifyDictionaryMode(KeyEvent &event) { |
| 499 | // Lookup pinyin and addPhrase may share some code. |
| 500 | bool needUpdate = false; |
| 501 | if (mode_ == TableMode::Normal) { |
| 502 | if (event.key().checkKeyList(*engine_->config().lookupPinyin)) { |
| 503 | mode_ = TableMode::LookupPinyin; |
| 504 | } else if (event.key().checkKeyList( |
| 505 | *engine_->config().modifyDictionary)) { |
| 506 | mode_ = TableMode::ModifyDictionary; |
| 507 | } |
| 508 | if (mode_ == TableMode::Normal) { |
| 509 | return false; |
| 510 | } |
| 511 | |
| 512 | // Flush pending buffer. |
| 513 | commitBuffer(false); |
| 514 | lookupPinyinIndex_ = 0; |
| 515 | lookupPinyinString_.assign(lastCommit_.begin(), lastCommit_.end()); |
| 516 | if (ic_->capabilityFlags().test(CapabilityFlag::SurroundingText) && |
| 517 | ic_->surroundingText().isValid()) { |
| 518 | auto text = ic_->surroundingText().selectedText(); |
| 519 | if (!text.empty()) { |
| 520 | lookupPinyinString_.clear(); |
| 521 | auto range = utf8::MakeUTF8CharRange(text); |
| 522 | for (auto iter = std::begin(range), end = std::end(range); |
| 523 | iter != end; ++iter) { |
| 524 | lookupPinyinString_.emplace_back("", iter.view()); |
| 525 | } |
| 526 | } |
| 527 | } |
| 528 | if (mode_ == TableMode::ModifyDictionary) { |
| 529 | if (lookupPinyinIndex_ + 1 < lookupPinyinString_.size()) { |
| 530 | lookupPinyinIndex_ = 1; |
| 531 | } |
| 532 | } |
| 533 | needUpdate = true; |
| 534 | } else if (mode_ != TableMode::LookupPinyin && |
| 535 | mode_ != TableMode::ModifyDictionary && |
| 536 | mode_ != TableMode::ForgetWord) { |
| 537 | return false; |
| 538 | } |
| 539 | |
| 540 | event.filterAndAccept(); |
| 541 | if (event.key().check(FcitxKey_Left) || |
| 542 | event.key().check(FcitxKey_KP_Left)) { |
| 543 | needUpdate = true; |
| 544 | if (!lookupPinyinString_.empty()) { |
| 545 | lookupPinyinIndex_ += 1; |
| 546 | if (lookupPinyinIndex_ >= lookupPinyinString_.size()) { |
| 547 | lookupPinyinIndex_ = lookupPinyinString_.size() - 1; |
| 548 | } |
| 549 | } |
| 550 | } else if (event.key().check(FcitxKey_Right) || |
| 551 | event.key().check(FcitxKey_KP_Right)) { |
| 552 | needUpdate = true; |
| 553 | if (!lookupPinyinString_.empty()) { |
| 554 | if (lookupPinyinIndex_ >= lookupPinyinString_.size()) { |
| 555 | lookupPinyinIndex_ = lookupPinyinString_.size() - 1; |
| 556 | } else if (lookupPinyinIndex_ > 0) { |
| 557 | lookupPinyinIndex_ -= 1; |
| 558 | } |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | auto getSubString = [&]() { |
| 563 | if (lookupPinyinIndex_ >= lookupPinyinString_.size()) { |
| 564 | lookupPinyinIndex_ = lookupPinyinString_.size() - 1; |
| 565 | } |
| 566 | std::string str; |
| 567 | std::vector<std::string> hints; |
| 568 | for (auto idx = lookupPinyinString_.size() - lookupPinyinIndex_ - 1; |
| 569 | idx < lookupPinyinString_.size(); ++idx) { |
| 570 | str += lookupPinyinString_[idx].second; |
| 571 | hints.push_back(lookupPinyinString_[idx].first); |
| 572 | } |
| 573 | return std::make_pair(str, hints); |
| 574 | }; |
| 575 | |
| 576 | if (!lookupPinyinString_.empty()) { |
| 577 | if ((event.key().check(FcitxKey_space) || |
| 578 | event.key().check(FcitxKey_Return) || |
| 579 | event.key().check(FcitxKey_KP_Space) || |
| 580 | event.key().check(FcitxKey_KP_Enter)) && |
| 581 | mode_ == TableMode::ModifyDictionary) { |
| 582 | auto subString = getSubString(); |
| 583 | std::string result; |
| 584 | if (context_->dict().generateWithHint(subString.first, |
| 585 | subString.second, result)) { |
| 586 | auto wordFlag = |
| 587 | context_->dict().wordExists(result, subString.first); |
| 588 | if (wordFlag == libime::PhraseFlag::Invalid) { |
| 589 | context_->mutableDict().insert(result, subString.first, |
| 590 | libime::PhraseFlag::User); |
| 591 | reset(); |
| 592 | return true; |
| 593 | } |
| 594 | if (wordFlag == libime::PhraseFlag::Auto) { |
| 595 | context_->mutableDict().removeWord(result, subString.first); |
| 596 | context_->mutableDict().insert(result, subString.first, |
| 597 | libime::PhraseFlag::User); |
| 598 | reset(); |
| 599 | } |
| 600 | } |
| 601 | } else if (event.key().checkKeyList(std::initializer_list<Key>{ |
| 602 | Key(FcitxKey_BackSpace), Key(FcitxKey_Delete), |
| 603 | Key(FcitxKey_KP_Delete)}) && |
| 604 | mode_ == TableMode::ModifyDictionary) { |
| 605 | auto subString = getSubString(); |
| 606 | std::string result; |
| 607 | if (context_->dict().generateWithHint(subString.first, |
| 608 | subString.second, result)) { |
| 609 | auto flag = |
| 610 | context_->dict().wordExists(result, subString.first); |
| 611 | if (flag != libime::PhraseFlag::Invalid) { |
| 612 | if ((flag == libime::PhraseFlag::User || |
| 613 | flag == libime::PhraseFlag::None || |
| 614 | flag == libime::PhraseFlag::Auto) && |
| 615 | event.key().check(FcitxKey_Delete)) { |
| 616 | context_->mutableDict().removeWord(result, |
| 617 | subString.first); |
| 618 | } |
| 619 | context_->mutableModel().history().forget(subString.first); |
| 620 | reset(); |
| 621 | return true; |
| 622 | } |
| 623 | } |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | if (needUpdate) { |
| 628 | auto &inputPanel = ic_->inputPanel(); |
| 629 | inputPanel.reset(); |
| 630 | if (lookupPinyinString_.empty()) { |
| 631 | inputPanel.setAuxUp(Text( |
| 632 | _("Please use this functionality after typing some text."))); |
| 633 | } else { |
| 634 | auto subString = getSubString(); |
| 635 | auto chr = utf8::getChar(subString.first); |
| 636 | |
| 637 | if (mode_ == TableMode::LookupPinyin) { |
| 638 | Text auxUp(_("Use Left and Right to select character: ")); |
| 639 | auxUp.append(utf8::UCS4ToUTF8(chr)); |
| 640 | inputPanel.setAuxUp(auxUp); |
| 641 | auto result = |
| 642 | engine_->pinyinhelper()->call<IPinyinHelper::fullLookup>( |
| 643 | chr); |
| 644 | if (!result.empty()) { |
| 645 | std::string text; |
| 646 | bool first = true; |
| 647 | std::map<std::string, std::vector<std::string>> resultMap; |
| 648 | for (const auto &[toned, fullPinyin, _] : result) { |
| 649 | resultMap[fullPinyin].push_back(toned); |
| 650 | } |
| 651 | |
| 652 | for (const auto &[fullPinyin, tones] : resultMap) { |
| 653 | if (first) { |
| 654 | first = false; |
| 655 | } else { |
| 656 | text.append(C_("Pinyin lookup delimeter", ", ")); |
| 657 | } |
| 658 | |
| 659 | std::vector<std::string_view> sp; |
| 660 | if (const auto *reverseShuangPinTable = |
| 661 | engine_->reverseShuangPinTable()) { |
| 662 | const auto normalizedFullPinyin = |
| 663 | stringutils::replaceAll(fullPinyin, "ü", "v"); |
| 664 | auto [iter, end] = |
| 665 | reverseShuangPinTable->equal_range( |
| 666 | normalizedFullPinyin); |
| 667 | for (; iter != end; ++iter) { |
| 668 | sp.push_back(iter->second); |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | const auto allTones = stringutils::join(tones, " "); |
| 673 | if (sp.empty()) { |
| 674 | text.append(allTones); |
| 675 | } else { |
| 676 | text.append(C_("Pinyin & Shuangpin", "{0} ({1})", |
| 677 | allTones, |
| 678 | stringutils::join(sp, " "))); |
| 679 | } |
| 680 | } |
| 681 | inputPanel.setAuxDown(Text(std::move(text))); |
| 682 | } else { |
| 683 | inputPanel.setAuxDown(Text(_("Could not find pinyin."))); |
| 684 | } |
| 685 | } else { |
| 686 | Text auxUp(_("Use Left and Right to select text. ")); |
| 687 | Text auxDown; |
| 688 | if (lookupPinyinIndex_ >= 1) { |
| 689 | std::string result; |
| 690 | if (context_->dict().generateWithHint( |
| 691 | subString.first, subString.second, result)) { |
| 692 | auxDown.append(_("{0}: {1}", subString.first, |
| 693 | context_->customHint(result))); |
| 694 | auto flag = context_->dict().wordExists( |
| 695 | result, subString.first); |
| 696 | if (flag == libime::PhraseFlag::Invalid || |
| 697 | flag == libime::PhraseFlag::Auto) { |
| 698 | auxUp.append(_("Press space or enter to insert.")); |
| 699 | } |
| 700 | if (flag != libime::PhraseFlag::Invalid) { |
| 701 | auxUp.append(_("Press Backspace to forget.")); |
| 702 | } |
| 703 | if (flag == libime::PhraseFlag::User) { |
| 704 | auxUp.append(_("Press Delete to remove.")); |
| 705 | } |
| 706 | } else { |
| 707 | auxDown.append( |
| 708 | _("{0}: No corresponding code.", subString.first)); |
| 709 | } |
| 710 | auxDown.append(" "); |
| 711 | } |
| 712 | auto chrString = utf8::UCS4ToUTF8(chr); |
| 713 | auto chrCode = context_->dict().reverseLookup(chrString); |
| 714 | if (!chrCode.empty()) { |
| 715 | auxDown.append(_("{0}: {1}", chrString, chrCode)); |
| 716 | } else { |
| 717 | auxDown.append(_("{0} is not in table.", chrString)); |
| 718 | } |
| 719 | inputPanel.setAuxUp(auxUp); |
| 720 | inputPanel.setAuxDown(auxDown); |
| 721 | } |
| 722 | } |
| 723 | ic_->updatePreedit(); |
| 724 | ic_->updateUserInterface(UserInterfaceComponent::InputPanel); |
| 725 | } |
| 726 | |
| 727 | return true; |
| 728 | } |
| 729 | |
| 730 | void TableState::forgetCandidateWord(size_t idx) { |
| 731 | mode_ = TableMode::Normal; |
| 732 | // Make a copy of old code since it will be cleared later. |
| 733 | const std::string oldCode = context_->currentCode(); |
| 734 | auto code = TableContext::code(context_->candidates()[idx]); |
| 735 | if (!code.empty()) { |
| 736 | auto word = context_->candidates()[idx].toString(); |
| 737 | commitBuffer(false); |
| 738 | context_->mutableDict().removeWord(code, word); |
| 739 | context_->mutableModel().history().forget(word); |
| 740 | } else { |
| 741 | return; |
| 742 | } |
| 743 | context_->clear(); |
| 744 | { |
| 745 | const CommitAfterSelectWrapper commitAfterSelectRAII(this); |
| 746 | context_->type(oldCode); |
| 747 | } |
| 748 | |
| 749 | updateUI(/*keepOldCursor=*/true, /*maybePredict=*/false); |
| 750 | } |
| 751 | |
| 752 | void TableState::keyEvent(const InputMethodEntry &entry, KeyEvent &event) { |
| 753 | bool needUpdate = false; |
| 754 | auto *inputContext = event.inputContext(); |
| 755 | const bool lastIsPunc = lastIsPunc_; |
| 756 | auto *context = updateContext(&entry); |
| 757 | if (!context) { |
| 758 | return; |
| 759 | } |
| 760 | |
| 761 | const auto &config = context->config(); |
| 762 | // 2nd/3rd selection is allowed to be modifier only, handle them before we |
| 763 | // skip the release. |
| 764 | if (handle2nd3rdCandidate(config, event)) { |
| 765 | return; |
| 766 | } |
| 767 | |
| 768 | // by pass all key release and by pass all modifier |
| 769 | if (event.isRelease() || event.key().isModifier()) { |
| 770 | return; |
| 771 | } |
| 772 | |
| 773 | if (handlePuncCandidate(config, event)) { |
| 774 | return; |
| 775 | } |
| 776 | |
| 777 | if ((mode_ == TableMode::Normal || mode_ == TableMode::Pinyin) && |
| 778 | !event.key().states().testAny( |
| 779 | KeyStates{KeyState::Ctrl, KeyState::Super})) { |
| 780 | auto compose = engine_->instance()->processComposeString( |
| 781 | inputContext, event.key().sym()); |
| 782 | if (!compose) { |
| 783 | // invalid compose or in the middle of compose. |
| 784 | event.filterAndAccept(); |
| 785 | return; |
| 786 | } |
| 787 | // Handle the key just like punc select. |
| 788 | if (!compose->empty()) { |
| 789 | // if current key will produce some string, select the candidate. |
| 790 | if (!autoSelectCandidate()) { |
| 791 | commitBuffer(true); |
| 792 | } |
| 793 | inputContext->commitString(*compose); |
| 794 | reset(); |
| 795 | event.filterAndAccept(); |
| 796 | return; |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | lastIsPunc_ = false; |
| 801 | |
| 802 | if (handleCandidateList(config, event)) { |
| 803 | return; |
| 804 | } |
| 805 | |
| 806 | // Non candidate key for predict candidate should clear it. |
| 807 | if (inputContext->inputPanel().candidateList() && |
| 808 | dynamic_cast<const TablePredictCandidateWord *>( |
| 809 | &inputContext->inputPanel().candidateList()->candidate(0))) { |
| 810 | inputContext->inputPanel().setCandidateList(nullptr); |
| 811 | needUpdate = true; |
| 812 | } |
| 813 | |
| 814 | // We have special handling of escape here. |
| 815 | if (handleForgetWord(event)) { |
| 816 | return; |
| 817 | } |
| 818 | |
| 819 | if (event.key().check(FcitxKey_Escape)) { |
| 820 | if (mode_ != TableMode::Normal) { |
| 821 | event.filterAndAccept(); |
| 822 | } |
| 823 | if (!isContextEmpty()) { |
| 824 | event.filterAndAccept(); |
| 825 | } |
| 826 | reset(); |
| 827 | if (event.accepted()) { |
| 828 | return; |
| 829 | } |
| 830 | } |
| 831 | |
| 832 | if (handlePinyinMode(event)) { |
| 833 | return; |
| 834 | } |
| 835 | |
| 836 | if (handleLookupPinyinOrModifyDictionaryMode(event)) { |
| 837 | return; |
| 838 | } |
| 839 | |
| 840 | bool maybePredict = false; |
| 841 | auto chr = Key::keySymToUnicode(event.key().sym()); |
| 842 | auto str = utf8::UCS4ToUTF8(chr); |
| 843 | |
| 844 | if (engine_->quickphrase() && !event.key().hasModifier() && |
| 845 | !config.quickphraseText->empty() && !str.empty() && |
| 846 | config.quickphraseText->find(str) != std::string::npos) { |
| 847 | std::string text = context_->currentCode(); |
| 848 | // Need to flush buffer before entering quick phrase. |
| 849 | commitBuffer(false); |
| 850 | text.append(str); |
| 851 | reset(); |
| 852 | engine_->quickphrase()->call<IQuickPhrase::trigger>(inputContext, "", |
| 853 | "", "", "", Key()); |
| 854 | engine_->quickphrase()->call<IQuickPhrase::setBuffer>(inputContext, |
| 855 | text); |
| 856 | event.filterAndAccept(); |
| 857 | return; |
| 858 | } |
| 859 | if (mode_ == TableMode::Normal) { |
| 860 | if (!event.key().hasModifier() && chr && context->isValidInput(chr) && |
| 861 | (!event.key().isKeyPad() || *config.keypadAsInput)) { |
| 862 | auto candidateList = ic_->inputPanel().candidateList(); |
| 863 | auto autoSelectHint = 0; |
| 864 | if (candidateList && !candidateList->empty()) { |
| 865 | const int idx = candidateList->cursorIndex(); |
| 866 | if (idx >= 0) { |
| 867 | const auto *cand = dynamic_cast<const TableCandidateWord *>( |
| 868 | &candidateList->candidate(idx)); |
| 869 | if (cand) { |
| 870 | autoSelectHint = cand->idx_; |
| 871 | } |
| 872 | } |
| 873 | } |
| 874 | context->setAutoSelectIndex(autoSelectHint); |
| 875 | { |
| 876 | const CommitAfterSelectWrapper commitAfterSelectRAII(this); |
| 877 | context->type(str); |
| 878 | } |
| 879 | if (!context->dict().hasMatchingWords(context->currentCode()) && |
| 880 | ((*config.commitAfterSelect && context->currentCode() == str) || |
| 881 | (!*config.commitAfterSelect && context->userInput() == str))) { |
| 882 | // This means it is not a valid start, make it go through the |
| 883 | // punc. |
| 884 | context->backspace(); |
| 885 | // This should clear all candidates. |
| 886 | inputContext->inputPanel().reset(); |
| 887 | needUpdate = true; |
| 888 | } else { |
| 889 | event.filterAndAccept(); |
| 890 | maybePredict = true; |
| 891 | } |
| 892 | } else if (!isContextEmpty() && !isComposeTableMode()) { |
| 893 | if (event.key().check(FcitxKey_Return, KeyState::Shift) || |
| 894 | event.key().check(FcitxKey_KP_Enter, KeyState::Shift)) { |
| 895 | // This key is used to type long auto select buffer. |
| 896 | if (*config.commitAfterSelect) { |
| 897 | commitBuffer(true); |
| 898 | } else { |
| 899 | inputContext->commitString(context->userInput()); |
| 900 | context->clear(); |
| 901 | } |
| 902 | event.filterAndAccept(); |
| 903 | } else if (event.key().check(FcitxKey_Tab) || |
| 904 | event.key().check(FcitxKey_KP_Tab)) { |
| 905 | { |
| 906 | const CommitAfterSelectWrapper commitAfterSelectRAII(this); |
| 907 | (void)autoSelectCandidate(); |
| 908 | } |
| 909 | event.filterAndAccept(); |
| 910 | if (context->selected()) { |
| 911 | commitBuffer(false); |
| 912 | maybePredict = true; |
| 913 | } |
| 914 | } else if (event.key().sym() == FcitxKey_Return || |
| 915 | event.key().sym() == FcitxKey_KP_Enter) { |
| 916 | if (*config.commitAfterSelect) { |
| 917 | if (!context->selected()) { |
| 918 | event.filterAndAccept(); |
| 919 | } |
| 920 | commitBuffer(true); |
| 921 | } else { |
| 922 | inputContext->commitString(context->userInput()); |
| 923 | context->clear(); |
| 924 | event.filterAndAccept(); |
| 925 | } |
| 926 | } else if (event.key().check(FcitxKey_BackSpace) || |
| 927 | event.key().check(FcitxKey_BackSpace, KeyState::Ctrl)) { |
| 928 | // Commit the last segment if it is selected. |
| 929 | if (*config.commitAfterSelect && context->selected() && |
| 930 | (std::get<bool>(context->selectedSegment( |
| 931 | context->selectedSize() - 1)) || |
| 932 | *config.commitInvalidSegment)) { |
| 933 | commitBuffer(false); |
| 934 | updateUI(/*keepOldCursor=*/false, /*maybePredict=*/false); |
| 935 | return; |
| 936 | } |
| 937 | if (event.key().check(FcitxKey_BackSpace, KeyState::Ctrl)) { |
| 938 | // For non-commitAfterSelect, remove the whole segment, or |
| 939 | // the current code. |
| 940 | if (!*config.commitAfterSelect && context->selected()) { |
| 941 | auto cursor = context->cursor(); |
| 942 | context_->erase(cursor - |
| 943 | context->selectedSegmentLength( |
| 944 | context->selectedSize() - 1), |
| 945 | cursor); |
| 946 | } else { |
| 947 | auto cursor = context->cursor(); |
| 948 | context_->erase( |
| 949 | cursor - utf8::length(context_->currentCode()), |
| 950 | cursor); |
| 951 | } |
| 952 | } else { |
| 953 | context->backspace(); |
| 954 | } |
| 955 | event.filterAndAccept(); |
| 956 | } else if (event.key().isCursorMove() || |
| 957 | event.key().check(FcitxKey_Delete)) { |
| 958 | // if it gonna commit something |
| 959 | commitBuffer(true); |
| 960 | needUpdate = true; |
| 961 | } else if (!context->selected()) { |
| 962 | // key to handle when it is not empty. |
| 963 | if (event.key().checkKeyList(*config.defaultCandidate)) { |
| 964 | event.filterAndAccept(); |
| 965 | if (autoSelectCandidate()) { |
| 966 | // Update UI is called in candidate::select |
| 967 | return; |
| 968 | } |
| 969 | commitBuffer(true); |
| 970 | needUpdate = true; |
| 971 | } |
| 972 | } |
| 973 | } else if (event.key().check(FcitxKey_BackSpace) && lastIsPunc) { |
| 974 | const std::string &puncStr = |
| 975 | engine_->punctuation()->call<IPunctuation::cancelLast>( |
| 976 | entry.languageCode(), inputContext); |
| 977 | if (!puncStr.empty()) { |
| 978 | // forward the original key is the best choice. |
| 979 | cancelLastEvent_ = |
| 980 | engine_->instance()->eventLoop().addTimeEvent( |
| 981 | CLOCK_MONOTONIC, now(CLOCK_MONOTONIC) + 3000, 1, |
| 982 | [this, ref = inputContext->watch(), |
| 983 | puncStr = puncStr](EventSourceTime *, uint64_t) { |
| 984 | if (auto *inputContext = ref.get()) { |
| 985 | inputContext->commitString(puncStr); |
| 986 | } |
| 987 | cancelLastEvent_.reset(); |
| 988 | return true; |
| 989 | }); |
| 990 | event.filter(); |
| 991 | return; |
| 992 | } |
| 993 | } |
| 994 | } |
| 995 | |
| 996 | do { |
| 997 | if (event.filtered()) { |
| 998 | break; |
| 999 | } |
| 1000 | |
| 1001 | // no reason to keep buffer if we move cursor. |
| 1002 | if (*context->config().commitAfterSelect && isContextEmpty() && |
| 1003 | mode_ == TableMode::Normal) { |
| 1004 | if (event.key().check(FcitxKey_Delete) || |
| 1005 | event.key().check(FcitxKey_BackSpace) || |
| 1006 | event.key().check(FcitxKey_Delete, KeyState::Ctrl) || |
| 1007 | event.key().check(FcitxKey_BackSpace, KeyState::Ctrl) || |
| 1008 | event.key().isCursorMove() || |
| 1009 | event.key().sym() == FcitxKey_Return || |
| 1010 | event.key().sym() == FcitxKey_KP_Enter) { |
| 1011 | commitBuffer(false); |
| 1012 | } |
| 1013 | } |
| 1014 | |
| 1015 | if (event.key().hasModifier() || !chr) { |
| 1016 | // Handle quick phrase with modifier |
| 1017 | if (event.key().check(*config.quickphrase) && |
| 1018 | engine_->quickphrase()) { |
| 1019 | engine_->quickphrase()->call<IQuickPhrase::trigger>( |
| 1020 | inputContext, "", "", "", "", Key()); |
| 1021 | event.filterAndAccept(); |
| 1022 | return; |
| 1023 | } |
| 1024 | |
| 1025 | if (isComposeTableMode()) { |
| 1026 | if (!autoSelectCandidate()) { |
| 1027 | commitBuffer(true); |
| 1028 | needUpdate = true; |
| 1029 | } |
| 1030 | } |
| 1031 | |
| 1032 | break; |
| 1033 | } |
| 1034 | // if current key will produce some string, select the candidate. |
| 1035 | if (!autoSelectCandidate()) { |
| 1036 | commitBuffer(true); |
| 1037 | needUpdate = true; |
| 1038 | } |
| 1039 | std::string punc; |
| 1040 | std::string puncAfter; |
| 1041 | if (!*context->config().ignorePunc && !event.key().isKeyPad()) { |
| 1042 | auto candidates = |
| 1043 | engine_->punctuation() |
| 1044 | ->call<IPunctuation::getPunctuationCandidates>( |
| 1045 | entry.languageCode(), chr); |
| 1046 | auto pushResult = |
| 1047 | engine_->punctuation()->call<IPunctuation::pushPunctuationV2>( |
| 1048 | entry.languageCode(), inputContext, chr); |
| 1049 | if (candidates.size() == 1 || isComposeTableMode()) { |
| 1050 | std::tie(punc, puncAfter) = pushResult; |
| 1051 | } else if (candidates.size() > 1) { |
| 1052 | updatePuncCandidate(inputContext, utf8::UCS4ToUTF8(chr), |
| 1053 | candidates); |
| 1054 | event.filterAndAccept(); |
| 1055 | return; |
| 1056 | } |
| 1057 | } |
| 1058 | if (event.key().check(*config.quickphrase) && engine_->quickphrase()) { |
| 1059 | auto s = !punc.empty() ? punc + puncAfter : utf8::UCS4ToUTF8(chr); |
| 1060 | auto alt = !punc.empty() ? utf8::UCS4ToUTF8(chr) : ""; |
| 1061 | std::string text; |
| 1062 | if (!s.empty()) { |
| 1063 | text += alt + _(" for ") + s; |
| 1064 | } |
| 1065 | if (!alt.empty()) { |
| 1066 | text += _(" Return for ") + alt; |
| 1067 | } |
| 1068 | engine_->quickphrase()->call<IQuickPhrase::trigger>( |
| 1069 | inputContext, text, "", s, alt, *config.quickphrase); |
| 1070 | event.filterAndAccept(); |
| 1071 | return; |
| 1072 | } |
| 1073 | |
| 1074 | if (!punc.empty()) { |
| 1075 | event.filterAndAccept(); |
| 1076 | auto paired = punc + puncAfter; |
| 1077 | if (inputContext->capabilityFlags().test( |
| 1078 | CapabilityFlag::CommitStringWithCursor)) { |
| 1079 | if (const size_t length = utf8::lengthValidated(punc); |
| 1080 | length != 0 && length != utf8::INVALID_LENGTH) { |
| 1081 | inputContext->commitStringWithCursor(paired, length); |
| 1082 | } else { |
| 1083 | inputContext->commitString(paired); |
| 1084 | } |
| 1085 | } else { |
| 1086 | inputContext->commitString(paired); |
| 1087 | if (const size_t length = utf8::lengthValidated(puncAfter); |
| 1088 | length != 0 && length != utf8::INVALID_LENGTH) { |
| 1089 | for (size_t i = 0; i < length; i++) { |
| 1090 | inputContext->forwardKey(Key(FcitxKey_Left)); |
| 1091 | } |
| 1092 | } |
| 1093 | } |
| 1094 | } |
| 1095 | lastIsPunc_ = true; |
| 1096 | } while (false); |
| 1097 | |
| 1098 | if ((event.filtered() && event.accepted()) || needUpdate) { |
| 1099 | updateUI(/*keepOldCursor=*/false, /*maybePredict=*/maybePredict); |
| 1100 | } |
| 1101 | } |
| 1102 | |
| 1103 | bool TableState::handle2nd3rdCandidate(const TableConfig &config, |
| 1104 | KeyEvent &event) { |
| 1105 | auto *inputContext = event.inputContext(); |
| 1106 | auto candidateList = inputContext->inputPanel().candidateList(); |
| 1107 | if (!candidateList) { |
| 1108 | return false; |
| 1109 | } |
| 1110 | |
| 1111 | struct { |
| 1112 | const KeyList &list; |
| 1113 | int selection; |
| 1114 | } keyHandlers[] = { |
| 1115 | // Index starts with 0 |
| 1116 | {*config.secondCandidate, 1}, |
| 1117 | {*config.thirdCandidate, 2}, |
| 1118 | }; |
| 1119 | |
| 1120 | const int keyReleased = keyReleased_; |
| 1121 | const int keyReleasedIndex = keyReleasedIndex_; |
| 1122 | // Keep these two values, and reset them in the state |
| 1123 | keyReleased_ = -1; |
| 1124 | keyReleasedIndex_ = -2; |
| 1125 | const bool isModifier = event.key().isModifier(); |
| 1126 | if (event.isRelease()) { |
| 1127 | int idx = 0; |
| 1128 | for (auto &keyHandler : keyHandlers) { |
| 1129 | if (keyReleased == idx && |
| 1130 | keyReleasedIndex == event.key().keyListIndex(keyHandler.list)) { |
| 1131 | if (isModifier) { |
| 1132 | if (engine_->instance() |
| 1133 | ->globalConfig() |
| 1134 | .checkModifierOnlyKeyTimeout(lastKeyPressedTime_) && |
| 1135 | keyHandler.selection < candidateList->size()) { |
| 1136 | candidateList->candidate(keyHandler.selection) |
| 1137 | .select(inputContext); |
| 1138 | } |
| 1139 | lastKeyPressedTime_ = 0; |
| 1140 | event.filterAndAccept(); |
| 1141 | return true; |
| 1142 | } |
| 1143 | event.filter(); |
| 1144 | return true; |
| 1145 | } |
| 1146 | idx++; |
| 1147 | } |
| 1148 | } |
| 1149 | |
| 1150 | if (!event.filtered() && !event.isRelease()) { |
| 1151 | int idx = 0; |
| 1152 | for (auto &keyHandler : keyHandlers) { |
| 1153 | auto keyIdx = event.key().keyListIndex(keyHandler.list); |
| 1154 | if (keyIdx >= 0) { |
| 1155 | keyReleased_ = idx; |
| 1156 | keyReleasedIndex_ = keyIdx; |
| 1157 | if (isModifier) { |
| 1158 | lastKeyPressedTime_ = now(CLOCK_MONOTONIC); |
| 1159 | // don't forward to input method, but make it pass |
| 1160 | // through to client. |
| 1161 | event.filter(); |
| 1162 | return true; |
| 1163 | } |
| 1164 | if (keyHandler.selection < candidateList->size()) { |
| 1165 | candidateList->candidate(keyHandler.selection) |
| 1166 | .select(inputContext); |
| 1167 | } |
| 1168 | event.filterAndAccept(); |
| 1169 | return true; |
| 1170 | } |
| 1171 | idx++; |
| 1172 | } |
| 1173 | } |
| 1174 | return false; |
| 1175 | } |
| 1176 | |
| 1177 | bool TableState::handlePuncCandidate(const TableConfig &config, |
| 1178 | KeyEvent &event) { |
| 1179 | auto *inputContext = event.inputContext(); |
| 1180 | if (mode_ != TableMode::Punctuation) { |
| 1181 | return false; |
| 1182 | } |
| 1183 | auto candidateList = inputContext->inputPanel().candidateList(); |
| 1184 | if (!candidateList) { |
| 1185 | reset(); |
| 1186 | return false; |
| 1187 | } |
| 1188 | if (event.key().check(FcitxKey_BackSpace)) { |
| 1189 | event.filterAndAccept(); |
| 1190 | reset(); |
| 1191 | return true; |
| 1192 | } |
| 1193 | |
| 1194 | if (!event.isVirtual()) { |
| 1195 | if (const int idx = event.key().keyListIndex(config.selection.value()); |
| 1196 | idx >= 0) { |
| 1197 | event.filterAndAccept(); |
| 1198 | if (idx < candidateList->size()) { |
| 1199 | candidateList->candidate(idx).select(inputContext); |
| 1200 | } |
| 1201 | return true; |
| 1202 | } |
| 1203 | |
| 1204 | if (auto *movable = candidateList->toCursorMovable()) { |
| 1205 | if (event.key().checkKeyList(*config.nextCandidate)) { |
| 1206 | movable->nextCandidate(); |
| 1207 | updatePuncPreedit(inputContext); |
| 1208 | inputContext->updateUserInterface( |
| 1209 | UserInterfaceComponent::InputPanel); |
| 1210 | event.filterAndAccept(); |
| 1211 | return true; |
| 1212 | } |
| 1213 | if (event.key().checkKeyList(*config.prevCandidate)) { |
| 1214 | movable->prevCandidate(); |
| 1215 | updatePuncPreedit(inputContext); |
| 1216 | inputContext->updateUserInterface( |
| 1217 | UserInterfaceComponent::InputPanel); |
| 1218 | event.filterAndAccept(); |
| 1219 | return true; |
| 1220 | } |
| 1221 | } |
| 1222 | } |
| 1223 | |
| 1224 | auto index = candidateList->cursorIndex(); |
| 1225 | if (index >= 0) { |
| 1226 | candidateList->candidate(index).select(inputContext); |
| 1227 | } |
| 1228 | |
| 1229 | reset(); |
| 1230 | return false; |
| 1231 | } |
| 1232 | |
| 1233 | void TableState::commitBuffer(bool commitCode, bool noRealCommit) { |
| 1234 | auto *context = context_.get(); |
| 1235 | if (!context) { |
| 1236 | return; |
| 1237 | } |
| 1238 | |
| 1239 | if (mode_ == TableMode::Pinyin && !noRealCommit) { |
| 1240 | auto commit = pinyinModePrefix_ + pinyinModeBuffer_.userInput(); |
| 1241 | if (!commit.empty()) { |
| 1242 | ic_->commitString(commit); |
| 1243 | } |
| 1244 | reset(); |
| 1245 | return; |
| 1246 | } |
| 1247 | |
| 1248 | std::string sentence; |
| 1249 | if (!*context->config().commitAfterSelect) { |
| 1250 | sentence = commitSegements(0, context->selectedSize()); |
| 1251 | } |
| 1252 | |
| 1253 | if (commitCode) { |
| 1254 | sentence += context->currentCode(); |
| 1255 | } |
| 1256 | TABLE_DEBUG() << "TableState::commitBuffer " << sentence << " " |
| 1257 | << context->selectedSize(); |
| 1258 | |
| 1259 | if (!noRealCommit && !sentence.empty()) { |
| 1260 | ic_->commitString(sentence); |
| 1261 | } |
| 1262 | // If commitAfterSelect && !useContextBasedOrder, learnLast will be used. |
| 1263 | if (!ic_->capabilityFlags().testAny(CapabilityFlag::PasswordOrSensitive) && |
| 1264 | (!*context->config().commitAfterSelect || |
| 1265 | *context->config().useContextBasedOrder)) { |
| 1266 | context->learn(); |
| 1267 | } |
| 1268 | context->clear(); |
| 1269 | } |
| 1270 | |
| 1271 | void TableState::commitAfterSelect(int commitFrom) { |
| 1272 | auto *context = context_.get(); |
| 1273 | if (!context) { |
| 1274 | return; |
| 1275 | } |
| 1276 | |
| 1277 | const auto &config = context->config(); |
| 1278 | if (!*config.commitAfterSelect) { |
| 1279 | return; |
| 1280 | } |
| 1281 | const std::string sentence = |
| 1282 | commitSegements(commitFrom, context_->selectedSize()); |
| 1283 | if (sentence.empty()) { |
| 1284 | return; |
| 1285 | } |
| 1286 | ic_->commitString(sentence); |
| 1287 | if (!*config.useContextBasedOrder) { |
| 1288 | if (!ic_->capabilityFlags().testAny( |
| 1289 | CapabilityFlag::PasswordOrSensitive)) { |
| 1290 | context->learnLast(); |
| 1291 | } |
| 1292 | } |
| 1293 | } |
| 1294 | |
| 1295 | void TableState::updateUI(bool keepOldCursor, bool maybePredict) { |
| 1296 | int cursor = 0; |
| 1297 | if (keepOldCursor) { |
| 1298 | if (auto candidateList = ic_->inputPanel().candidateList()) { |
| 1299 | if (auto *commonCandidateList = |
| 1300 | dynamic_cast<CommonCandidateList *>(candidateList.get())) { |
| 1301 | cursor = commonCandidateList->globalCursorIndex(); |
| 1302 | } |
| 1303 | } |
| 1304 | } |
| 1305 | cursor = std::max(cursor, 0); |
| 1306 | |
| 1307 | ic_->inputPanel().reset(); |
| 1308 | |
| 1309 | auto *context = context_.get(); |
| 1310 | if (!context) { |
| 1311 | return; |
| 1312 | } |
| 1313 | const auto &config = context->config(); |
| 1314 | auto &inputPanel = ic_->inputPanel(); |
| 1315 | if (!context->userInput().empty()) { |
| 1316 | auto candidates = context->candidates(); |
| 1317 | if (!candidates.empty() && !isComposeTableMode()) { |
| 1318 | auto candidateList = std::make_unique<CommonCandidateList>(); |
| 1319 | size_t idx = 0; |
| 1320 | candidateList->setLayoutHint(*config.candidateLayoutHint); |
| 1321 | candidateList->setCursorPositionAfterPaging( |
| 1322 | CursorPositionAfterPaging::ResetToFirst); |
| 1323 | candidateList->setSelectionKey(*config.selection); |
| 1324 | candidateList->setPageSize(*config.pageSize); |
| 1325 | |
| 1326 | for (const auto &candidate : candidates) { |
| 1327 | Text text; |
| 1328 | Text comment; |
| 1329 | text.append(candidate.toString()); |
| 1330 | std::string hint; |
| 1331 | if (*config.hint) { |
| 1332 | hint = |
| 1333 | context->candidateHint(idx, *config.displayCustomHint); |
| 1334 | } |
| 1335 | if (!hint.empty()) { |
| 1336 | comment.append(*config.hintSeparator); |
| 1337 | comment.append(std::move(hint)); |
| 1338 | } |
| 1339 | if (!config.markerForAutoPhrase->empty() && |
| 1340 | TableContext::isAuto(candidate.sentence())) { |
| 1341 | text.append(*config.markerForAutoPhrase); |
| 1342 | } |
| 1343 | candidateList->append<TableCandidateWord>( |
| 1344 | engine_, std::move(text), std::move(comment), |
| 1345 | *config.spaceBeforeHint, idx); |
| 1346 | idx++; |
| 1347 | } |
| 1348 | if (!candidateList->empty()) { |
| 1349 | auto page = cursor / *config.pageSize; |
| 1350 | if (page >= candidateList->totalPages()) { |
| 1351 | page = candidateList->totalPages() - 1; |
| 1352 | } |
| 1353 | candidateList->setPage(page); |
| 1354 | if (cursor >= candidateList->totalSize()) { |
| 1355 | cursor = candidateList->totalSize() - 1; |
| 1356 | } |
| 1357 | candidateList->setGlobalCursorIndex(cursor); |
| 1358 | } |
| 1359 | candidateList->setActionableImpl( |
| 1360 | std::make_unique<TableActionableCandidateList>(this)); |
| 1361 | inputPanel.setCandidateList(std::move(candidateList)); |
| 1362 | } |
| 1363 | const bool useClientPreedit = |
| 1364 | ic_->capabilityFlags().test(CapabilityFlag::Preedit); |
| 1365 | if (*config.displayCustomHint && context->dict().hasCustomPrompt()) { |
| 1366 | if (useClientPreedit) { |
| 1367 | inputPanel.setClientPreedit(context->preeditText( |
| 1368 | /*hint=*/false, /*clientPreedit=*/true)); |
| 1369 | } |
| 1370 | inputPanel.setPreedit( |
| 1371 | context->preeditText(/*hint=*/true, /*clientPreedit=*/false)); |
| 1372 | } else { |
| 1373 | const Text preeditText = |
| 1374 | context->preeditText(/*hint=*/false, useClientPreedit); |
| 1375 | if (useClientPreedit) { |
| 1376 | inputPanel.setClientPreedit(preeditText); |
| 1377 | } else { |
| 1378 | inputPanel.setPreedit(preeditText); |
| 1379 | } |
| 1380 | } |
| 1381 | if (mode_ == TableMode::ForgetWord) { |
| 1382 | inputPanel.setPreedit(Text()); |
| 1383 | inputPanel.setAuxUp( |
| 1384 | Text(_("Select candidate to be removed from history:"))); |
| 1385 | } |
| 1386 | } |
| 1387 | if (maybePredict && !inputPanel.candidateList() && |
| 1388 | (context->selected() || isContextEmpty())) { |
| 1389 | predict(); |
| 1390 | } |
| 1391 | ic_->updatePreedit(); |
| 1392 | ic_->updateUserInterface(UserInterfaceComponent::InputPanel); |
| 1393 | } |
| 1394 | |
| 1395 | void TableState::updatePuncCandidate( |
| 1396 | InputContext *inputContext, const std::string &original, |
| 1397 | const std::vector<std::string> &candidates) { |
| 1398 | inputContext->inputPanel().reset(); |
| 1399 | auto puncCandidateList = std::make_unique<CommonCandidateList>(); |
| 1400 | puncCandidateList->setSelectionKey(*context_->config().selection); |
| 1401 | puncCandidateList->setPageSize(*context_->config().pageSize); |
| 1402 | puncCandidateList->setCursorPositionAfterPaging( |
| 1403 | CursorPositionAfterPaging::ResetToFirst); |
| 1404 | for (const auto &result : candidates) { |
| 1405 | puncCandidateList->append<TablePunctuationCandidateWord>( |
| 1406 | this, result, original == result); |
| 1407 | } |
| 1408 | puncCandidateList->setCursorIncludeUnselected(false); |
| 1409 | puncCandidateList->setCursorKeepInSamePage(false); |
| 1410 | puncCandidateList->setGlobalCursorIndex(0); |
| 1411 | mode_ = TableMode::Punctuation; |
| 1412 | inputContext->inputPanel().setCandidateList(std::move(puncCandidateList)); |
| 1413 | updatePuncPreedit(inputContext); |
| 1414 | inputContext->updateUserInterface(UserInterfaceComponent::InputPanel); |
| 1415 | } |
| 1416 | |
| 1417 | void TableState::updatePuncPreedit(InputContext *inputContext) { |
| 1418 | auto candidateList = inputContext->inputPanel().candidateList(); |
| 1419 | |
| 1420 | if (inputContext->capabilityFlags().test(CapabilityFlag::Preedit)) { |
| 1421 | if (candidateList->cursorIndex() >= 0) { |
| 1422 | Text preedit; |
| 1423 | |
| 1424 | const auto &candidate = |
| 1425 | candidateList->candidate(candidateList->cursorIndex()); |
| 1426 | if (const auto *puncCandidate = |
| 1427 | dynamic_cast<const TablePunctuationCandidateWord *>( |
| 1428 | &candidate)) { |
| 1429 | preedit.append(puncCandidate->word()); |
| 1430 | } |
| 1431 | |
| 1432 | preedit.setCursor(preedit.textLength()); |
| 1433 | inputContext->inputPanel().setClientPreedit(preedit); |
| 1434 | } |
| 1435 | inputContext->updatePreedit(); |
| 1436 | } |
| 1437 | } |
| 1438 | |
| 1439 | } // namespace fcitx |