Debian Codegraph @

modules/chttrans/chttrans.cpp

raw
1 /*
2 * SPDX-FileCopyrightText: 2016-2016 CSSlayer <[email protected]>
3 *
4 * SPDX-License-Identifier: LGPL-2.1-or-later
5 *
6 */
7
8 #include "chttrans.h"
9 #include "chttrans-native.h"
10 #include "config.h"
11 #include "notifications_public.h"
12 #include <algorithm>
13 #include <cassert>
14 #include <cstddef>
15 #include <exception>
16 #include <fcitx-config/iniparser.h>
17 #include <fcitx-utils/i18n.h>
18 #include <fcitx-utils/log.h>
19 #include <fcitx-utils/standardpaths.h>
20 #include <fcitx-utils/stringutils.h>
21 #include <fcitx-utils/utf8.h>
22 #include <fcitx/addonfactory.h>
23 #include <fcitx/addoninstance.h>
24 #include <fcitx/addonmanager.h>
25 #include <fcitx/event.h>
26 #include <fcitx/inputcontext.h>
27 #include <fcitx/inputmethodentry.h>
28 #include <fcitx/instance.h>
29 #include <fcitx/text.h>
30 #include <fcitx/userinterface.h>
31 #include <fcitx/userinterfacemanager.h>
32 #include <fcntl.h>
33 #include <filesystem>
34 #include <format>
35 #include <fstream>
36 #include <ios>
37 #include <iterator>
38 #include <memory>
39 #include <string>
40 #include <string_view>
41 #include <unordered_map>
42 #include <utility>
43 #include <vector>
44
45 #ifdef ENABLE_OPENCC
46 #include "chttrans-opencc.h"
47 #ifdef HAS_BOOST_JSON
48 #include <boost/json/parse.hpp>
49 #include <boost/json/src.hpp>
50 #include <boost/json/value_to.hpp>
51 #endif
52 #endif
53
54 using namespace fcitx;
55
56 std::unordered_map<std::string, std::vector<std::filesystem::path>>
57 openCCBuiltInPath() {
58 std::unordered_map<std::string, std::vector<std::filesystem::path>> result;
59 std::filesystem::path prefix;
60 #ifdef OPENCC_PREFIX
61 prefix = OPENCC_PREFIX;
62 #endif
63 if (!prefix.empty()) {
64 result["datadir"] = {prefix / "share"};
65 result["pkgdatadir"] = {prefix / "share/opencc"};
66 }
67 return result;
68 }
69
70 const StandardPaths &openCCStandardPath() {
71 static const StandardPaths standardPath("opencc", openCCBuiltInPath(),
72 StandardPaths::global().options());
73 return standardPath;
74 }
75
76 static ChttransIMType inputMethodEntryType(const InputMethodEntry &entry) {
77 if (entry.languageCode() == "zh_CN") {
78 return ChttransIMType::Simp;
79 }
80 if (entry.languageCode() == "zh_HK" || entry.languageCode() == "zh_TW") {
81 return ChttransIMType::Trad;
82 }
83 return ChttransIMType::Other;
84 }
85
86 Chttrans::Chttrans(fcitx::Instance *instance) : instance_(instance) {
87 instance_->userInterfaceManager().registerAction("chttrans",
88 &toggleAction_);
89 #ifdef ENABLE_OPENCC
90 backends_.emplace(ChttransEngine::OpenCC,
91 std::make_unique<OpenCCBackend>());
92 #endif
93 backends_.emplace(ChttransEngine::Native,
94 std::make_unique<NativeBackend>());
95 reloadConfig();
96
97 eventHandler_ = instance_->watchEvent(
98 EventType::InputContextKeyEvent, EventWatcherPhase::Default,
99 [this](Event &event) {
100 auto &keyEvent = static_cast<KeyEvent &>(event);
101 if (keyEvent.isRelease()) {
102 return;
103 }
104 auto *ic = keyEvent.inputContext();
105 if (!toggleAction_.isParent(&ic->statusArea())) {
106 return;
107 }
108 auto type = currentType(ic);
109 if (type == ChttransIMType::Other) {
110 return;
111 }
112 if (keyEvent.key().checkKeyList(config_.hotkey.value())) {
113 toggle(ic);
114 // Note that type is old value before toggle, we simply try to
115 // avoid recalculation.
116 bool isTraditional = (type != ChttransIMType::Trad);
117 if (notifications()) {
118 notifications()->call<INotifications::showTip>(
119 "fcitx-chttrans-toggle",
120 _("Simplified and Traditional Chinese Translation"),
121 isTraditional ? "fcitx-chttrans-active"
122 : "fcitx-chttrans-inactive",
123 isTraditional ? _("Switch to Traditional Chinese")
124 : _("Switch to Simplified Chinese"),
125 isTraditional ? _("Traditional Chinese is enabled.")
126 : _("Simplified Chinese is enabled."),
127 1000);
128 }
129 keyEvent.filterAndAccept();
130 ic->updateUserInterface(UserInterfaceComponent::InputPanel);
131 }
132 });
133 outputFilterConn_ = instance_->connect<Instance::OutputFilter>(
134 [this](InputContext *inputContext, Text &text) {
135 // Short cut for empty string.
136 if (text.empty()) {
137 return;
138 }
139 if (!toggleAction_.isParent(&inputContext->statusArea())) {
140 return;
141 }
142 auto type = convertType(inputContext);
143 if (type == ChttransIMType::Other) {
144 return;
145 }
146 auto oldString = text.toString();
147 auto oldLength = utf8::lengthValidated(oldString);
148 if (oldLength == utf8::INVALID_LENGTH) {
149 return;
150 }
151 auto newString = convert(type, oldString);
152 auto newLength = utf8::lengthValidated(newString);
153 if (newLength == utf8::INVALID_LENGTH) {
154 return;
155 }
156 Text newText;
157 // Short cut for most common case, the text contains only one
158 // string.
159 if (text.size() == 1) {
160 newText.append(std::move(newString), text.formatAt(0));
161 } else {
162 size_t off = 0;
163 size_t remainLength = newLength;
164 for (size_t i = 0; i < text.size(); i++) {
165 auto segmentLength = utf8::length(text.stringAt(i));
166 segmentLength = std::min(remainLength, segmentLength);
167 remainLength -= segmentLength;
168 size_t segmentByteLength = utf8::ncharByteLength(
169 newString.begin() + off, segmentLength);
170 newText.append(newString.substr(off, segmentByteLength),
171 text.formatAt(i));
172 off = off + segmentByteLength;
173 }
174 }
175 if (text.cursor() > 0) {
176 auto length = utf8::length(oldString, 0, text.cursor());
177 length = std::min(length, newLength);
178 newText.setCursor(
179 utf8::ncharByteLength(newText.toString().begin(), length));
180 } else {
181 newText.setCursor(text.cursor());
182 }
183 text = std::move(newText);
184 });
185 commitFilterConn_ = instance_->connect<Instance::CommitFilter>(
186 [this](InputContext *inputContext, std::string &str) {
187 if (!toggleAction_.isParent(&inputContext->statusArea())) {
188 return;
189 }
190 auto type = convertType(inputContext);
191 if (type == ChttransIMType::Other) {
192 return;
193 }
194 str = convert(type, str);
195 });
196 }
197
198 void Chttrans::toggle(InputContext *ic) {
199 if (!toggleAction_.isParent(&ic->statusArea())) {
200 return;
201 }
202 auto type = inputMethodType(ic);
203 if (type == ChttransIMType::Other) {
204 return;
205 }
206 const auto *entry = instance_->inputMethodEntry(ic);
207 if (enabledIM_.contains(entry->uniqueName())) {
208 enabledIM_.erase(entry->uniqueName());
209 } else {
210 enabledIM_.insert(entry->uniqueName());
211 }
212 syncToConfig();
213 toggleAction_.update(ic);
214 ic->updateUserInterface(fcitx::UserInterfaceComponent::InputPanel);
215 ic->updatePreedit();
216 }
217
218 void Chttrans::reloadConfig() {
219 readAsIni(config_, "conf/chttrans.conf");
220 populateConfig();
221 }
222
223 void Chttrans::populateConfig() {
224 enabledIM_.clear();
225 enabledIM_.insert(config_.enabledIM.value().begin(),
226 config_.enabledIM.value().end());
227 for (const auto &backend : backends_) {
228 if (backend.second->loaded()) {
229 backend.second->updateConfig(config_);
230 }
231 }
232 #ifdef ENABLE_OPENCC
233 auto engine = config_.engine.value();
234 #else
235 auto engine = ChttransEngine::Native;
236 #endif
237
238 auto iter = backends_.find(engine);
239 if (iter == backends_.end() && engine != ChttransEngine::Native) {
240 iter = backends_.find(ChttransEngine::Native);
241 }
242 if (iter == backends_.end()) {
243 currentBackend_ = nullptr;
244 } else {
245 currentBackend_ = iter->second.get();
246 }
247 toggleAction_.setHotkey(config_.hotkey.value());
248 }
249
250 void Chttrans::syncToConfig() {
251 std::vector<std::string> values_;
252 values_.reserve(enabledIM_.size());
253 for (const auto &id : enabledIM_) {
254 values_.push_back(id);
255 }
256 config_.enabledIM.setValue(std::move(values_));
257 }
258
259 void Chttrans::save() {
260 syncToConfig();
261 safeSaveAsIni(config_, "conf/chttrans.conf");
262 }
263
264 const Configuration *Chttrans::getConfig() const {
265 #ifdef ENABLE_OPENCC
266 std::vector<std::pair<std::string, std::string>> profiles{
267 {"default", _("Default")}};
268 constexpr std::string_view JsonSuffix = ".json";
269 auto files = openCCStandardPath().locate(
270 StandardPathsType::PkgData, ".",
271 pathfilter::extension(std::string(JsonSuffix)));
272 profiles.reserve(files.size() + 1);
273 // files is std::map, so file name is already sorted.
274 for (const auto &file : files) {
275 #ifdef HAS_BOOST_JSON
276 try {
277 std::ifstream in(file.second, std::ios::in | std::ios::binary);
278 std::string strBuf(std::istreambuf_iterator<char>(in), {});
279 auto jv = boost::json::parse(strBuf);
280 const auto &obj = jv.as_object();
281 auto name = boost::json::value_to<std::string>(obj.at("name"));
282 std::string description = file.first.stem();
283 if (!name.empty()) {
284 description = std::format("{0}: {1}", description,
285 C_("OpenCC Profile", name));
286 }
287 profiles.emplace_back(file.first, std::move(description));
288 } catch (const std::exception &e) {
289 FCITX_WARN() << "Failed to parse " << file.first;
290 profiles.emplace_back(file.first, file.first);
291 }
292 #else
293 profiles.emplace_back(file.first, file.first);
294 #endif
295 }
296 config_.openCCS2TProfile.annotation().setProfiles(profiles);
297 config_.openCCT2SProfile.annotation().setProfiles(std::move(profiles));
298 #endif
299 return &config_;
300 }
301
302 std::string Chttrans::convert(ChttransIMType type, const std::string &str) {
303 if (!currentBackend_ || !currentBackend_->load(config_)) {
304 return str;
305 }
306
307 if (type == ChttransIMType::Trad) {
308 return currentBackend_->convertSimpToTrad(str);
309 }
310 return currentBackend_->convertTradToSimp(str);
311 }
312
313 ChttransIMType
314 Chttrans::inputMethodType(fcitx::InputContext *inputContext) const {
315 auto *engine = instance_->inputMethodEngine(inputContext);
316 const auto *entry = instance_->inputMethodEntry(inputContext);
317 if (!engine || !entry) {
318 return ChttransIMType::Other;
319 }
320 return inputMethodEntryType(*entry);
321 }
322
323 ChttransIMType Chttrans::convertType(fcitx::InputContext *inputContext) const {
324 auto type = inputMethodType(inputContext);
325 if (type == ChttransIMType::Other) {
326 return ChttransIMType::Other;
327 }
328
329 const auto *entry = instance_->inputMethodEntry(inputContext);
330 assert(entry);
331 if (!enabledIM_.contains(entry->uniqueName())) {
332 return ChttransIMType::Other;
333 }
334
335 return type == ChttransIMType::Simp ? ChttransIMType::Trad
336 : ChttransIMType::Simp;
337 }
338
339 ChttransIMType Chttrans::currentType(fcitx::InputContext *inputContext) const {
340 auto type = inputMethodType(inputContext);
341 if (type == ChttransIMType::Other) {
342 return ChttransIMType::Other;
343 }
344
345 const auto *entry = instance_->inputMethodEntry(inputContext);
346 assert(entry);
347 if (!enabledIM_.contains(entry->uniqueName())) {
348 return type;
349 }
350
351 return type == ChttransIMType::Simp ? ChttransIMType::Trad
352 : ChttransIMType::Simp;
353 }
354
355 class ChttransModuleFactory : public AddonFactory {
356 AddonInstance *create(AddonManager *manager) override {
357 registerDomain("fcitx5-chinese-addons", FCITX_INSTALL_LOCALEDIR);
358 return new Chttrans(manager->instance());
359 }
360 };
361
362 FCITX_ADDON_FACTORY_V2(chttrans, ChttransModuleFactory)