Debian Codegraph @

im/table/engine.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 #include "engine.h"
8 #include "config.h"
9 #include "context.h"
10 #include "ime.h"
11 #include "state.h"
12 #include <cstddef>
13 #include <exception>
14 #include <fcitx-config/iniparser.h>
15 #include <fcitx-config/rawconfig.h>
16 #include <fcitx-utils/charutils.h>
17 #include <fcitx-utils/event.h>
18 #include <fcitx-utils/eventloopinterface.h>
19 #include <fcitx-utils/fdstreambuf.h>
20 #include <fcitx-utils/i18n.h>
21 #include <fcitx-utils/log.h>
22 #include <fcitx-utils/macros.h>
23 #include <fcitx-utils/standardpaths.h>
24 #include <fcitx-utils/stringutils.h>
25 #include <fcitx-utils/utf8.h>
26 #include <fcitx/action.h>
27 #include <fcitx/addoninstance.h>
28 #include <fcitx/event.h>
29 #include <fcitx/inputcontext.h>
30 #include <fcitx/inputcontextmanager.h>
31 #include <fcitx/inputcontextproperty.h>
32 #include <fcitx/inputmethodmanager.h>
33 #include <fcitx/inputpanel.h>
34 #include <fcitx/instance.h>
35 #include <fcitx/statusarea.h>
36 #include <fcitx/userinterfacemanager.h>
37 #include <fcntl.h>
38 #include <filesystem>
39 #include <istream>
40 #include <libime/core/historybigram.h>
41 #include <libime/core/languagemodel.h>
42 #include <libime/core/userlanguagemodel.h>
43 #include <libime/pinyin/pinyindictionary.h>
44 #include <libime/pinyin/pinyinencoder.h>
45 #include <libime/pinyin/shuangpinprofile.h>
46 #include <libime/table/tablebaseddictionary.h>
47 #include <map>
48 #include <memory>
49 #include <quickphrase_public.h>
50 #include <string>
51 #include <string_view>
52 #include <unordered_set>
53
54 namespace fcitx {
55
56 TableEngine::TableEngine(Instance *instance)
57 : instance_(instance),
58 factory_([this](InputContext &ic) { return new TableState(&ic, this); }) {
59 ime_ = std::make_unique<TableIME>(
60 &libime::DefaultLanguageModelResolver::instance());
61
62 reloadConfig();
63 instance_->inputContextManager().registerProperty("tableState", &factory_);
64 events_.emplace_back(instance_->watchEvent(
65 EventType::InputMethodGroupChanged, EventWatcherPhase::Default,
66 [this](Event &) {
67 releaseStates();
68 std::unordered_set<std::string> names;
69 for (const auto &im : instance_->inputMethodManager()
70 .currentGroup()
71 .inputMethodList()) {
72 names.insert(im.name());
73 }
74 ime_->releaseUnusedDict(names);
75 preload();
76 }));
77 events_.emplace_back(instance_->watchEvent(
78 EventType::InputContextKeyEvent, EventWatcherPhase::PreInputMethod,
79 [this](Event &event) {
80 auto &keyEvent = static_cast<KeyEvent &>(event);
81 auto *inputContext = keyEvent.inputContext();
82 const auto *entry = instance_->inputMethodEntry(inputContext);
83 if (!entry || entry->addon() != "table") {
84 return;
85 }
86 auto *state = inputContext->propertyFor(&factory_);
87 state->handle2nd3rdCandidate(keyEvent);
88 }));
89
90 predictionAction_.setShortText(*config_.predictionEnabled
91 ? _("Prediction Enabled")
92 : _("Prediction Disabled"));
93 predictionAction_.setLongText(_("Show prediction words"));
94 predictionAction_.connect<SimpleAction::Activated>(
95 [this](InputContext *ic) {
96 config_.predictionEnabled.setValue(!(*config_.predictionEnabled));
97 saveConfig();
98 predictionAction_.setShortText(*config_.predictionEnabled
99 ? _("Prediction Enabled")
100 : _("Prediction Disabled"));
101 predictionAction_.setIcon(*config_.predictionEnabled
102 ? "fcitx-remind-active"
103 : "fcitx-remind-inactive");
104 predictionAction_.update(ic);
105 });
106 instance_->userInterfaceManager().registerAction("table-prediction",
107 &predictionAction_);
108
109 preloadEvent_ = instance_->eventLoop().addDeferEvent([this](EventSource *) {
110 preload();
111 preloadEvent_.reset();
112 return true;
113 });
114 }
115
116 TableEngine::~TableEngine() = default;
117
118 void TableEngine::reloadConfig() {
119 readAsIni(config_, "conf/table.conf");
120 populateConfig();
121 }
122
123 void TableEngine::populateConfig() {
124 reverseShuangPinTable_.reset();
125
126 std::unique_ptr<libime::ShuangpinProfile> shuangpinProfile;
127
128 if (*config_.shuangpinProfile == LookupShuangpinProfileEnum::Custom) {
129 auto file = StandardPaths::global().open(StandardPathsType::PkgConfig,
130 "pinyin/sp.dat");
131 if (file.isValid()) {
132 try {
133 IFDStreamBuf buffer(file.fd());
134 std::istream in(&buffer);
135 shuangpinProfile =
136 std::make_unique<libime::ShuangpinProfile>(in);
137 } catch (const std::exception &e) {
138 TABLE_ERROR() << e.what();
139 }
140 } else {
141 TABLE_ERROR() << "Failed to open shuangpin profile.";
142 }
143 } else if (*config_.shuangpinProfile == LookupShuangpinProfileEnum::No) {
144 reverseShuangPinTable_.reset();
145 } else {
146 libime::ShuangpinBuiltinProfile profile =
147 libime::ShuangpinBuiltinProfile::Ziranma;
148 #define TRANS_SP_PROFILE(PROFILE) \
149 case LookupShuangpinProfileEnum::PROFILE: \
150 profile = libime::ShuangpinBuiltinProfile::PROFILE; \
151 break;
152 switch (*config_.shuangpinProfile) {
153 TRANS_SP_PROFILE(Ziranma)
154 TRANS_SP_PROFILE(MS)
155 TRANS_SP_PROFILE(Ziguang)
156 TRANS_SP_PROFILE(ABC)
157 TRANS_SP_PROFILE(Zhongwenzhixing)
158 TRANS_SP_PROFILE(PinyinJiajia)
159 TRANS_SP_PROFILE(Xiaohe)
160 default:
161 break;
162 }
163 shuangpinProfile = std::make_unique<libime::ShuangpinProfile>(profile);
164 }
165
166 if (!shuangpinProfile) {
167 return;
168 }
169
170 reverseShuangPinTable_ =
171 std::make_unique<std::multimap<std::string, std::string>>();
172 for (const auto &[input, pys] : shuangpinProfile->table()) {
173 for (const auto &[syl, fuzzy] : pys) {
174 if (fuzzy != libime::PinyinFuzzyFlag::None) {
175 continue;
176 }
177 reverseShuangPinTable_->emplace(syl.toString(), input);
178 }
179 }
180 }
181
182 void TableEngine::setSubConfig(const std::string &path,
183 const RawConfig & /*unused*/) {
184 if (path == "reloaddict") {
185 reloadDict();
186 }
187 }
188
189 void TableEngine::activate(const fcitx::InputMethodEntry &entry,
190 fcitx::InputContextEvent &event) {
191 auto *inputContext = event.inputContext();
192 auto *state = inputContext->propertyFor(&factory_);
193 auto *context = state->updateContext(&entry);
194 if (entry.languageCode().starts_with("zh_")) {
195 chttrans();
196 for (const auto *actionName : {"chttrans", "punctuation"}) {
197 if (auto *action = instance_->userInterfaceManager().lookupAction(
198 actionName)) {
199 inputContext->statusArea().addAction(StatusGroup::InputMethod,
200 action);
201 }
202 }
203 }
204 if (context && *context->config().useFullWidth && fullwidth()) {
205 if (auto *action =
206 instance_->userInterfaceManager().lookupAction("fullwidth")) {
207 inputContext->statusArea().addAction(StatusGroup::InputMethod,
208 action);
209 }
210 }
211 if (context && context->prediction()) {
212 predictionAction_.setIcon(*config_.predictionEnabled
213 ? "fcitx-remind-active"
214 : "fcitx-remind-inactive");
215 inputContext->statusArea().addAction(StatusGroup::InputMethod,
216 &predictionAction_);
217 }
218 }
219
220 void TableEngine::deactivate(const fcitx::InputMethodEntry &entry,
221 fcitx::InputContextEvent &event) {
222 reset(entry, event);
223 }
224
225 std::string TableEngine::subMode(const fcitx::InputMethodEntry &entry,
226 fcitx::InputContext &ic) {
227 auto *state = ic.propertyFor(&factory_);
228 if (!state->updateContext(&entry)) {
229 return _("Not available");
230 }
231 return {};
232 }
233
234 void TableEngine::keyEvent(const InputMethodEntry &entry, KeyEvent &event) {
235 FCITX_UNUSED(entry);
236 TABLE_DEBUG() << "Table receive key: " << event.key() << " "
237 << event.isRelease();
238
239 auto *inputContext = event.inputContext();
240 auto *state = inputContext->propertyFor(&factory_);
241 state->keyEvent(entry, event);
242 }
243
244 void TableEngine::reset(const InputMethodEntry &entry,
245 InputContextEvent &event) {
246 TABLE_DEBUG() << "TableEngine::reset";
247 auto *inputContext = event.inputContext();
248
249 auto *state = inputContext->propertyFor(&factory_);
250
251 if (state->mode() == TableMode::Punctuation) {
252 auto candidateList = inputContext->inputPanel().candidateList();
253 if (candidateList && event.type() != EventType::InputContextFocusOut) {
254 auto index = candidateList->cursorIndex();
255 if (index >= 0) {
256 candidateList->candidate(index).select(inputContext);
257 }
258 }
259 } else if (state->context() &&
260 *state->context()->config().commitWhenDeactivate) {
261 // The reason that we do not commit here is we want to force the
262 // behavior. When client get unfocused, the framework will try to commit
263 // the string.
264 state->commitBuffer(true,
265 event.type() == EventType::InputContextFocusOut);
266 }
267 state->reset(&entry);
268 }
269
270 void TableEngine::save() { ime_->saveAll(); }
271
272 const libime::PinyinDictionary &TableEngine::pinyinDict() {
273 if (!pinyinLoaded_) {
274 std::string_view dicts[] = {"sc.dict", "extb.dict"};
275 static_assert(FCITX_ARRAY_SIZE(dicts) <=
276 libime::PinyinDictionary::UserDict + 1);
277 for (size_t i = 0; i < FCITX_ARRAY_SIZE(dicts); i++) {
278 try {
279 const auto &standardPath = StandardPaths::global();
280 auto systemDictFile = standardPath.open(
281 StandardPathsType::Data,
282 std::filesystem::path("libime") / dicts[i]);
283 if (!systemDictFile.isValid()) {
284 systemDictFile = standardPath.open(
285 StandardPathsType::Data,
286 std::filesystem::path(LIBIME_INSTALL_PKGDATADIR) /
287 dicts[i]);
288 }
289
290 IFDStreamBuf buffer(systemDictFile.fd());
291 std::istream in(&buffer);
292 pinyinDict_.load(i, in, libime::PinyinDictFormat::Binary);
293 } catch (const std::exception &e) {
294 TABLE_ERROR() << "Failed to load pinyin dict: " << e.what();
295 }
296 }
297 pinyinLoaded_ = true;
298 }
299 return pinyinDict_;
300 }
301
302 const libime::LanguageModel &TableEngine::pinyinModel() {
303 if (!pinyinLM_) {
304 pinyinLM_ = std::make_unique<libime::LanguageModel>(
305 libime::DefaultLanguageModelResolver::instance()
306 .languageModelFileForLanguage("zh_CN"));
307 }
308 return *pinyinLM_;
309 }
310
311 const Configuration *
312 TableEngine::getConfigForInputMethod(const InputMethodEntry &entry) const {
313 auto dict = ime_->requestDict(entry.uniqueName());
314 return std::get<2>(dict);
315 }
316
317 void TableEngine::setConfigForInputMethod(const InputMethodEntry &entry,
318 const RawConfig &config) {
319 ime_->updateConfig(entry.uniqueName(), config);
320 }
321
322 void TableEngine::releaseStates() {
323 instance_->inputContextManager().foreach([&](InputContext *ic) {
324 auto *state = ic->propertyFor(&factory_);
325 state->release();
326 return true;
327 });
328 }
329
330 void TableEngine::reloadDict() {
331 releaseStates();
332 ime_->reloadAllDict();
333 }
334
335 void TableEngine::preload() {
336 if (!instance_->globalConfig().preloadInputMethod()) {
337 return;
338 }
339
340 auto &imManager = instance_->inputMethodManager();
341 const auto &group = imManager.currentGroup();
342
343 // Preload first input method.
344 if (!group.inputMethodList().empty()) {
345 if (const auto *entry =
346 imManager.entry(group.inputMethodList()[0].name());
347 entry && entry->addon() == "table") {
348 ime_->requestDict(entry->uniqueName());
349 }
350 }
351 // Preload default input method.
352 if (!group.defaultInputMethod().empty()) {
353 if (const auto *entry = imManager.entry(group.defaultInputMethod());
354 entry && entry->addon() == "table") {
355 ime_->requestDict(entry->uniqueName());
356 }
357 }
358 }
359
360 } // namespace fcitx