| 1 | /* |
| 2 | * SPDX-FileCopyrightText: 2017-2017 CSSlayer <[email protected]> |
| 3 | * |
| 4 | * SPDX-License-Identifier: LGPL-2.1-or-later |
| 5 | * |
| 6 | */ |
| 7 | #include "ime.h" |
| 8 | #include <cstdint> |
| 9 | #include <exception> |
| 10 | #include <fcitx-config/iniparser.h> |
| 11 | #include <fcitx-config/rawconfig.h> |
| 12 | #include <fcitx-utils/fdstreambuf.h> |
| 13 | #include <fcitx-utils/key.h> |
| 14 | #include <fcitx-utils/log.h> |
| 15 | #include <fcitx-utils/macros.h> |
| 16 | #include <fcitx-utils/standardpaths.h> |
| 17 | #include <fcitx-utils/stringutils.h> |
| 18 | #include <fcntl.h> |
| 19 | #include <filesystem> |
| 20 | #include <fstream> |
| 21 | #include <ios> |
| 22 | #include <istream> |
| 23 | #include <libime/core/languagemodel.h> |
| 24 | #include <libime/core/userlanguagemodel.h> |
| 25 | #include <libime/core/utils.h> |
| 26 | #include <libime/table/tablebaseddictionary.h> |
| 27 | #include <libime/table/tableoptions.h> |
| 28 | #include <memory> |
| 29 | #include <ostream> |
| 30 | #include <ranges> |
| 31 | #include <set> |
| 32 | #include <stdexcept> |
| 33 | #include <string> |
| 34 | #include <tuple> |
| 35 | #include <unordered_set> |
| 36 | #include <utility> |
| 37 | |
| 38 | namespace fcitx { |
| 39 | |
| 40 | FCITX_DEFINE_LOG_CATEGORY(table_logcategory, "table") |
| 41 | |
| 42 | namespace { |
| 43 | |
| 44 | struct BinaryOrTextDict { |
| 45 | bool operator()(const std::filesystem::path &path) const { |
| 46 | return path.extension() == ".txt" || path.extension() == ".dict"; |
| 47 | } |
| 48 | }; |
| 49 | |
| 50 | libime::OrderPolicy converOrderPolicy(fcitx::OrderPolicy policy) { |
| 51 | switch (policy) { |
| 52 | #define POLICY_CONVERT(NAME) \ |
| 53 | case fcitx::OrderPolicy::NAME: \ |
| 54 | return libime::OrderPolicy::NAME; |
| 55 | POLICY_CONVERT(No) |
| 56 | POLICY_CONVERT(Freq) |
| 57 | POLICY_CONVERT(Fast) |
| 58 | } |
| 59 | return libime::OrderPolicy::Freq; |
| 60 | } |
| 61 | |
| 62 | void populateOptions(libime::TableBasedDictionary *dict, |
| 63 | const TableConfigRoot &root) { |
| 64 | libime::TableOptions options; |
| 65 | |
| 66 | options.setOrderPolicy(converOrderPolicy(*root.config->orderPolicy)); |
| 67 | options.setNoSortInputLength(*root.config->noSortInputLength); |
| 68 | options.setAutoSelect(*root.config->autoSelect); |
| 69 | options.setAutoSelectLength(*root.config->autoSelectLength); |
| 70 | options.setAutoSelectRegex(*root.config->autoSelectRegex); |
| 71 | options.setNoMatchAutoSelectLength(*root.config->noMatchAutoSelectLength); |
| 72 | options.setNoMatchAutoSelectRegex(*root.config->noMatchAutoSelectRegex); |
| 73 | options.setMatchingKey( |
| 74 | Key::keySymToUnicode(root.config->matchingKey->sym())); |
| 75 | std::set<uint32_t> endKeys; |
| 76 | TABLE_DEBUG() << "End key" << *root.config->endKey; |
| 77 | for (const auto &key : *root.config->endKey) { |
| 78 | auto chr = Key::keySymToUnicode(key.sym()); |
| 79 | if (chr) { |
| 80 | endKeys.insert(chr); |
| 81 | } |
| 82 | } |
| 83 | options.setEndKey(std::move(endKeys)); |
| 84 | options.setExactMatch(*root.config->exactMatch); |
| 85 | options.setLearning(*root.config->learning); |
| 86 | options.setAutoPhraseLength(*root.config->autoPhraseLength); |
| 87 | options.setSaveAutoPhraseAfter(*root.config->saveAutoPhraseAfter); |
| 88 | options.setAutoRuleSet(std::unordered_set<std::string>( |
| 89 | root.config->autoRuleSet->begin(), root.config->autoRuleSet->end())); |
| 90 | options.setLanguageCode(*root.im->languageCode); |
| 91 | options.setSortByCodeLength(*root.config->sortByCodeLength); |
| 92 | |
| 93 | dict->setTableOptions(std::move(options)); |
| 94 | } |
| 95 | } // namespace |
| 96 | |
| 97 | TableIME::TableIME(libime::LanguageModelResolver *lm) : lm_(lm) {} |
| 98 | |
| 99 | std::tuple<libime::TableBasedDictionary *, libime::UserLanguageModel *, |
| 100 | const TableConfig *> |
| 101 | TableIME::requestDict(const std::string &name) { |
| 102 | auto iter = tables_.find(name); |
| 103 | if (iter == tables_.end()) { |
| 104 | TABLE_DEBUG() << "Load table config for: " << name; |
| 105 | iter = tables_ |
| 106 | .emplace(std::piecewise_construct, std::make_tuple(name), |
| 107 | std::make_tuple()) |
| 108 | .first; |
| 109 | auto &root = iter->second.root; |
| 110 | |
| 111 | const auto filename = std::filesystem::path("inputmethod") / |
| 112 | stringutils::concat(name, ".conf"); |
| 113 | |
| 114 | for (auto mode : {StandardPathsMode::System, StandardPathsMode::User}) { |
| 115 | auto file = StandardPaths::global().open(StandardPathsType::PkgData, |
| 116 | filename, mode); |
| 117 | if (file.isValid()) { |
| 118 | RawConfig rawConfig; |
| 119 | readFromIni(rawConfig, file.fd()); |
| 120 | root.load(rawConfig, true); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | // So "Default" can be reset to current value. |
| 125 | root.syncDefaultValueToCurrent(); |
| 126 | |
| 127 | const std::string customization = |
| 128 | stringutils::joinPath("table", stringutils::concat(name, ".conf")); |
| 129 | for (auto mode : {StandardPathsMode::System, StandardPathsMode::User}) { |
| 130 | auto file = StandardPaths::global().open( |
| 131 | StandardPathsType::PkgConfig, customization, mode); |
| 132 | // reverse the order, so we end up parse user file at last. |
| 133 | if (file.isValid()) { |
| 134 | RawConfig rawConfig; |
| 135 | readFromIni(rawConfig, file.fd()); |
| 136 | root.load(rawConfig, true); |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | try { |
| 141 | auto dict = std::make_unique<libime::TableBasedDictionary>(); |
| 142 | auto dictFile = StandardPaths::global().open( |
| 143 | StandardPathsType::PkgData, *root.config->file); |
| 144 | TABLE_DEBUG() << "Load table at: " << *root.config->file; |
| 145 | if (!dictFile.isValid()) { |
| 146 | throw std::runtime_error("Couldn't open file"); |
| 147 | } |
| 148 | IFDStreamBuf buffer(dictFile.fd()); |
| 149 | std::istream in(&buffer); |
| 150 | dict->load(in); |
| 151 | iter->second.dict = std::move(dict); |
| 152 | } catch (const std::exception &e) { |
| 153 | TABLE_ERROR() << "Failed to load table: " << *root.config->file |
| 154 | << ", error: " << e.what(); |
| 155 | } |
| 156 | |
| 157 | if (auto *dict = iter->second.dict.get()) { |
| 158 | try { |
| 159 | auto dictFile = StandardPaths::global().open( |
| 160 | StandardPathsType::PkgData, |
| 161 | stringutils::concat("table/", name, ".user.dict"), |
| 162 | StandardPathsMode::User); |
| 163 | IFDStreamBuf buffer(dictFile.fd()); |
| 164 | std::istream in(&buffer); |
| 165 | dict->loadUser(in); |
| 166 | } catch (const std::exception &e) { |
| 167 | TABLE_DEBUG() << e.what(); |
| 168 | } |
| 169 | |
| 170 | dict->removeAllExtra(); |
| 171 | auto extraDicts = StandardPaths::global().locate( |
| 172 | StandardPathsType::PkgData, |
| 173 | stringutils::concat("table/", name, ".dict.d"), |
| 174 | BinaryOrTextDict()); |
| 175 | for (const auto &[name, file] : extraDicts) { |
| 176 | try { |
| 177 | std::ifstream in(file, std::ios::in | std::ios::binary); |
| 178 | const auto fileFormat = name.extension() == ".txt" |
| 179 | ? libime::TableFormat::Text |
| 180 | : libime::TableFormat::Binary; |
| 181 | dict->loadExtra(in, fileFormat); |
| 182 | } catch (const std::exception &e) { |
| 183 | TABLE_DEBUG() << e.what(); |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | populateOptions(dict, iter->second.root); |
| 188 | std::shared_ptr<const libime::StaticLanguageModelFile> lmFile; |
| 189 | try { |
| 190 | if (*iter->second.root.config->useSystemLanguageModel) { |
| 191 | lmFile = lm_->languageModelFileForLanguage( |
| 192 | dict->tableOptions().languageCode()); |
| 193 | } |
| 194 | } catch (...) { |
| 195 | TABLE_DEBUG() |
| 196 | << "Load language model for " |
| 197 | << dict->tableOptions().languageCode() << " failed."; |
| 198 | } |
| 199 | iter->second.model = |
| 200 | std::make_unique<libime::UserLanguageModel>(lmFile); |
| 201 | iter->second.model->setUseOnlyUnigram( |
| 202 | !*iter->second.root.config->useContextBasedOrder); |
| 203 | |
| 204 | try { |
| 205 | auto dictFile = StandardPaths::global().open( |
| 206 | StandardPathsType::PkgData, |
| 207 | stringutils::concat("table/", name, ".history"), |
| 208 | StandardPathsMode::User); |
| 209 | IFDStreamBuf buffer(dictFile.fd()); |
| 210 | std::istream in(&buffer); |
| 211 | iter->second.model->load(in); |
| 212 | } catch (const std::exception &e) { |
| 213 | TABLE_DEBUG() << e.what(); |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | return {iter->second.dict.get(), iter->second.model.get(), |
| 219 | &(*iter->second.root.config)}; |
| 220 | } |
| 221 | |
| 222 | void TableIME::saveAll() { |
| 223 | for (const auto &p : tables_) { |
| 224 | saveDict(p.first); |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | void TableIME::updateConfig(const std::string &name, const RawConfig &config) { |
| 229 | auto iter = tables_.find(name); |
| 230 | if (iter == tables_.end()) { |
| 231 | return; |
| 232 | } |
| 233 | iter->second.root.config.mutableValue()->load(config, true); |
| 234 | |
| 235 | if (iter->second.dict) { |
| 236 | populateOptions(iter->second.dict.get(), iter->second.root); |
| 237 | } |
| 238 | |
| 239 | safeSaveAsIni(iter->second.root, StandardPathsType::PkgConfig, |
| 240 | stringutils::concat("table/", name, ".conf")); |
| 241 | } |
| 242 | |
| 243 | void TableIME::releaseUnusedDict(const std::unordered_set<std::string> &names) { |
| 244 | for (auto iter = tables_.begin(); iter != tables_.end();) { |
| 245 | if (!names.contains(iter->first)) { |
| 246 | TABLE_DEBUG() << "Release unused table: " << iter->first; |
| 247 | saveDict(iter->first); |
| 248 | iter = tables_.erase(iter); |
| 249 | } else { |
| 250 | ++iter; |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | void TableIME::saveDict(const std::string &name) { |
| 256 | auto iter = tables_.find(name); |
| 257 | if (iter == tables_.end()) { |
| 258 | return; |
| 259 | } |
| 260 | libime::TableBasedDictionary *dict = iter->second.dict.get(); |
| 261 | libime::UserLanguageModel *lm = iter->second.model.get(); |
| 262 | if (!dict || !lm || !*iter->second.root.config->learning) { |
| 263 | return; |
| 264 | } |
| 265 | auto fileName = stringutils::joinPath("table", name); |
| 266 | |
| 267 | StandardPaths::global().safeSave(StandardPathsType::PkgData, |
| 268 | fileName + ".user.dict", [dict](int fd) { |
| 269 | OFDStreamBuf buffer(fd); |
| 270 | std::ostream out(&buffer); |
| 271 | try { |
| 272 | dict->saveUser(out); |
| 273 | return static_cast<bool>(out); |
| 274 | } catch (const std::exception &) { |
| 275 | return false; |
| 276 | } |
| 277 | }); |
| 278 | |
| 279 | StandardPaths::global().safeSave(StandardPathsType::PkgData, |
| 280 | fileName + ".history", [lm](int fd) { |
| 281 | OFDStreamBuf buffer(fd); |
| 282 | std::ostream out(&buffer); |
| 283 | try { |
| 284 | lm->save(out); |
| 285 | return static_cast<bool>(out); |
| 286 | } catch (const std::exception &) { |
| 287 | return false; |
| 288 | } |
| 289 | }); |
| 290 | } |
| 291 | |
| 292 | void TableIME::reloadAllDict() { |
| 293 | std::unordered_set<std::string> names; |
| 294 | for (const auto &pair : tables_) { |
| 295 | names.insert(pair.first); |
| 296 | } |
| 297 | tables_.clear(); |
| 298 | for (const auto &name : names) { |
| 299 | requestDict(name); |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | } // namespace fcitx |