Debian Codegraph @

im/pinyin/customphrase.cpp

raw symbols SCIP
1 /*
2 * SPDX-FileCopyrightText: 2023-2023 CSSlayer <[email protected]>
3 *
4 * SPDX-License-Identifier: LGPL-2.1-or-later
5 *
6 */
7 #include "customphrase.h"
8 #include <algorithm>
9 #include <cassert>
10 #include <charconv>
11 #include <chrono>
12 #include <cstdint>
13 #include <ctime>
14 #include <fcitx-utils/charutils.h>
15 #include <fcitx-utils/log.h>
16 #include <fcitx-utils/stringutils.h>
17 #include <format>
18 #include <functional>
19 #include <istream>
20 #include <iterator>
21 #include <libime/core/datrie.h>
22 #include <limits>
23 #include <map>
24 #include <optional>
25 #include <ostream>
26 #include <string>
27 #include <string_view>
28 #include <system_error>
29 #include <tuple>
30 #include <utility>
31 #include <vector>
32
33 namespace fcitx {
34
35 namespace {
36
37 // localtime_s is relatively evil and we simply want to avoid it.
38 namespace localtime_helper {
39
40 struct not_available_tag {};
41
42 [[maybe_unused]] not_available_tag localtime_r(...) { return {}; }
43
44 } // namespace localtime_helper
45
46 struct localtime_impl {
47 std::tm tm_{};
48 std::time_t time_{};
49
50 bool get() {
51 using namespace localtime_helper;
52 return localtime_fallback(localtime_r(&time_, &tm_));
53 }
54
55 bool localtime_fallback(std::tm *t) { return t != nullptr; }
56
57 bool localtime_fallback(localtime_helper::not_available_tag) {
58 // This is a least worse option since win has thread-local for it.
59 auto *t = std::localtime(&time_);
60 if (t) {
61 tm_ = *t;
62 return true;
63 }
64 return false;
65 }
66 };
67
68 void normalizeData(std::vector<CustomPhrase> &data) {
69 std::ranges::stable_sort(
70 data, [](const CustomPhrase &lhs, const CustomPhrase &rhs) {
71 return lhs.order() < rhs.order();
72 });
73 }
74
75 std::optional<int> parseInt(std::string_view input) {
76 int out;
77 const std::from_chars_result result =
78 std::from_chars(input.data(), input.data() + input.size(), out);
79 if (result.ec == std::errc::invalid_argument ||
80 result.ec == std::errc::result_out_of_range) {
81 return std::nullopt;
82 }
83 return out;
84 }
85
86 using ParseResult = std::tuple<std::string_view, int, std::string_view>;
87
88 std::optional<ParseResult> parseCustomPhraseLine(std::string_view line) {
89 size_t i = 0;
90
91 // Consume all letters.
92 for (; i < line.size() &&
93 (charutils::islower(line[i]) || charutils::isupper(line[i]));
94 i += 1) {
95 }
96 if (i == 0) {
97 return std::nullopt;
98 }
99
100 const std::string_view alpha = line.substr(0, i);
101 if (i >= line.size() || line[i] != ',') {
102 return std::nullopt;
103 }
104 i += 1;
105 int sign = 1;
106 if (i < line.size() && line[i] == '-') {
107 sign = -1;
108 i += 1;
109 }
110 const size_t orderStart = i;
111 for (; i < line.size() && charutils::isdigit(line[i]); i += 1) {
112 }
113 if (i == orderStart || i >= line.size() || line[i] != '=') {
114 return std::nullopt;
115 }
116
117 int order = 0;
118 if (auto result = parseInt(line.substr(orderStart, i - orderStart))) {
119 order = *result;
120 }
121 // Zero is invalid value.
122 if (order == 0) {
123 return std::nullopt;
124 }
125 order *= sign;
126
127 return std::make_tuple(alpha, order, line.substr(i + 1));
128 }
129
130 bool isComment(std::string_view line) {
131 return line.starts_with(';') || line.starts_with('#');
132 }
133
134 inline std::tm currentTm() {
135 #if defined(FCITX_CUSTOM_PHRASE_TEST)
136 std::tm timePoint;
137 timePoint.tm_year = 2023 - 1900;
138 timePoint.tm_mon = 6;
139 timePoint.tm_mday = 11;
140 timePoint.tm_wday = 2;
141 timePoint.tm_hour = 23;
142 timePoint.tm_min = 16;
143 timePoint.tm_sec = 6;
144 return timePoint;
145 #else
146 const std::chrono::system_clock::time_point now =
147 std::chrono::system_clock::now();
148 localtime_impl impl{.time_ = std::chrono::system_clock::to_time_t(now)};
149 impl.get();
150 return impl.tm_;
151 #endif
152 }
153
154 int currentYear() { return currentTm().tm_year + 1900; }
155 int currentMonth() { return currentTm().tm_mon + 1; }
156 int currentDay() { return currentTm().tm_mday; }
157 int currentWeekday() { return currentTm().tm_wday; }
158 int currentHour() { return currentTm().tm_hour; }
159 int currentMinute() { return currentTm().tm_min; }
160 int currentSecond() { return currentTm().tm_sec; }
161 int currentHalfHour() {
162 const int hour = currentHour() % 12;
163 return (hour == 0) ? 12 : hour;
164 }
165
166 std::string toChineseYear(std::string_view num) {
167 constexpr std::string_view chineseDigit[] = {
168 "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九",
169 };
170 std::string result;
171 result.reserve(num.size() * 3);
172 for (const char c : num) {
173 assert(charutils::isdigit(c));
174 result += chineseDigit[c - '0'];
175 }
176 return result;
177 }
178
179 std::string toChineseWeekDay(int num) {
180 assert(num >= 0 && num < 7);
181 constexpr std::string_view chineseWeekday[] = {
182 "日", "一", "二", "三", "四", "五", "六",
183 };
184 return std::string(chineseWeekday[num]);
185 }
186
187 std::string toChineseTwoDigitNumber(int num, bool leadingZero) {
188 assert(num >= 0 && num < 100);
189 constexpr std::string_view chineseDigit[] = {
190 "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十",
191 };
192 if (num == 0) {
193 return std::string(chineseDigit[0]);
194 }
195 const int tens = num / 10;
196 const int ones = num % 10;
197 std::string prefix;
198 if (tens == 0) {
199 if (leadingZero) {
200 prefix = chineseDigit[0];
201 }
202 } else if (tens == 1) {
203 prefix = chineseDigit[10];
204 } else {
205 prefix = stringutils::concat(chineseDigit[tens], chineseDigit[10]);
206 }
207 std::string suffix;
208 if (ones != 0) {
209 suffix = chineseDigit[ones];
210 }
211 return prefix + suffix;
212 }
213
214 } // namespace
215
216 bool CustomPhrase::isDynamic() const { return value().starts_with("#"); }
217
218 std::string CustomPhrase::evaluate(
219 const std::function<std::string(std::string_view key)> &evaluator) const {
220 assert(evaluator);
221
222 if (!isDynamic()) {
223 return value_;
224 }
225 std::string_view content = value_;
226 content = content.substr(1);
227 std::string output;
228 output.reserve(content.size());
229 size_t variableNameStart = 0;
230 size_t variableNameLength = 0;
231
232 enum class State {
233 Normal,
234 VariableStart,
235 BracedVariable,
236 Variable,
237 };
238
239 auto state = State::Normal;
240
241 for (size_t i = 0; i < content.size();) {
242 const char c = content[i];
243
244 switch (state) {
245 case State::Normal:
246 if (c == '$') {
247 state = State::VariableStart;
248 } else {
249 output += c;
250 }
251 i += 1;
252 break;
253
254 case State::VariableStart:
255 if (c == '{') {
256 variableNameStart = i + 1;
257 variableNameLength = 0;
258 state = State::BracedVariable;
259 } else if (c == '$') {
260 output += '$';
261 state = State::Normal;
262 } else if (charutils::islower(c) || charutils::isupper(c) ||
263 c == '_') {
264 variableNameStart = i;
265 variableNameLength = 1;
266 state = State::Variable;
267 } else {
268 output += '$';
269 output += c;
270 state = State::Normal;
271 }
272 i += 1;
273 break;
274
275 case State::BracedVariable:
276 if (c == '}') {
277 output += evaluator(
278 content.substr(variableNameStart, variableNameLength));
279 state = State::Normal;
280 } else {
281 variableNameLength += 1;
282 state = State::BracedVariable;
283 }
284 i += 1;
285 break;
286
287 case State::Variable:
288 if (charutils::islower(c) || charutils::isupper(c) ||
289 charutils::isdigit(c) || c == '_') {
290 variableNameLength += 1;
291 state = State::Variable;
292 i += 1;
293 } else {
294 output += evaluator(
295 content.substr(variableNameStart, variableNameLength));
296 state = State::Normal;
297 }
298 break;
299 }
300 }
301
302 switch (state) {
303 case State::Normal:
304 break;
305 case State::VariableStart:
306 output += '$';
307 break;
308 case State::BracedVariable:
309 output += "${";
310 output += content.substr(variableNameStart, variableNameLength);
311 break;
312 case State::Variable:
313 output +=
314 evaluator(content.substr(variableNameStart, variableNameLength));
315 break;
316 }
317
318 return output;
319 }
320
321 std::string CustomPhrase::builtinEvaluator(std::string_view key) {
322 static const std::map<std::string, std::function<std::string()>,
323 std::less<>>
324 table = {
325 {"year", []() { return std::to_string(currentYear()); }},
326 {"year_yy",
327 []() { return std::format("{:02d}", currentYear() % 100); }},
328 {"month", []() { return std::to_string(currentMonth()); }},
329 {"month_mm",
330 []() { return std::format("{:02d}", currentMonth()); }},
331 {"day", []() { return std::to_string(currentDay()); }},
332 {"day_dd", []() { return std::format("{:02d}", currentDay()); }},
333 {"weekday", []() { return std::to_string(currentWeekday()); }},
334 {"fullhour", []() { return std::format("{:02d}", currentHour()); }},
335 {"halfhour",
336 []() { return std::format("{:02d}", currentHalfHour()); }},
337 {"ampm", []() { return currentHour() < 12 ? "AM" : "PM"; }},
338 {"minute", []() { return std::format("{:02d}", currentMinute()); }},
339 {"second", []() { return std::format("{:02d}", currentSecond()); }},
340 {"year_cn",
341 []() { return toChineseYear(std::to_string(currentYear())); }},
342 {"year_yy_cn",
343 []() {
344 return toChineseYear(
345 std::format("{:02d}", currentYear() % 100));
346 }},
347 {"month_cn",
348 []() {
349 return toChineseTwoDigitNumber(currentMonth(),
350 /*leadingZero=*/false);
351 }},
352 {"day_cn",
353 []() {
354 return toChineseTwoDigitNumber(currentDay(),
355 /*leadingZero=*/false);
356 }},
357 {"weekday_cn", []() { return toChineseWeekDay(currentWeekday()); }},
358 {"fullhour_cn",
359 []() {
360 return toChineseTwoDigitNumber(currentHour(),
361 /*leadingZero=*/false);
362 }},
363 {"halfhour_cn",
364 []() {
365 return toChineseTwoDigitNumber(currentHalfHour(),
366 /*leadingZero=*/false);
367 }},
368 {"ampm_cn", []() { return currentHour() < 12 ? "上午" : "下午"; }},
369 {"minute_cn",
370 []() {
371 return toChineseTwoDigitNumber(currentMinute(),
372 /*leadingZero=*/true);
373 }},
374 {"second_cn",
375 []() {
376 return toChineseTwoDigitNumber(currentSecond(),
377 /*leadingZero=*/true);
378 }},
379 };
380
381 auto iter = table.find(key);
382 if (iter != table.end()) {
383 return iter->second();
384 }
385 return "";
386 }
387
388 CustomPhraseDict::CustomPhraseDict() = default;
389
390 void CustomPhraseDict::load(std::istream &in, bool loadDisabled) {
391 clear();
392 std::string line;
393 // Line looks like
394 // [a-z]+,[-][0-9]+=phrase
395 CustomPhrase *multiline = nullptr;
396 // If loadDisabled is true
397 CustomPhrase dummyPhrase(-1, {});
398 auto cleanUpMultiline = [&multiline]() {
399 if (!multiline) {
400 return;
401 }
402
403 if (!multiline->value().empty()) {
404 multiline->mutableValue().pop_back();
405 }
406
407 multiline = nullptr;
408 };
409
410 while (std::getline(in, line)) {
411 if (!multiline) {
412 if (isComment(line)) {
413 continue;
414 }
415 }
416
417 auto parseResult = parseCustomPhraseLine(line);
418 if (parseResult) {
419 cleanUpMultiline();
420 auto [key, order, data] = *parseResult;
421 std::string value{data};
422 if (value.size() >= 2 && value.starts_with('"') &&
423 value.ends_with('"')) {
424 if (auto unescape = stringutils::unescapeForValue(value)) {
425 value = *unescape;
426 }
427 }
428
429 if (!loadDisabled && order < 0) {
430 if (data.empty()) {
431 multiline = &dummyPhrase;
432 }
433 continue;
434 }
435 auto index = index_.exactMatchSearch(key);
436 if (TrieType::isNoValue(index)) {
437 if (data_.size() >= std::numeric_limits<int32_t>::max()) {
438 break;
439 }
440 index = data_.size();
441 index_.set(key, index);
442 data_.push_back({});
443 }
444 data_[index].push_back(CustomPhrase(order, std::move(value)));
445 if (data.empty()) {
446 multiline = &data_[index].back();
447 }
448 } else if (multiline && multiline != &dummyPhrase) {
449 multiline->mutableValue().append(line);
450 // Always append new line, and we will pop the last new line in
451 // cleanUpMultiline.
452 multiline->mutableValue().append("\n");
453 }
454 }
455 cleanUpMultiline();
456 for (auto &data : data_) {
457 normalizeData(data);
458 }
459 }
460
461 const std::vector<CustomPhrase> *
462 CustomPhraseDict::lookup(std::string_view key) const {
463 auto index = index_.exactMatchSearch(key);
464 if (TrieType::isNoValue(index)) {
465 return nullptr;
466 }
467
468 return &data_[index];
469 }
470
471 std::vector<CustomPhrase> *
472 CustomPhraseDict::getOrCreateEntry(std::string_view key) {
473
474 auto index = index_.exactMatchSearch(key);
475 if (TrieType::isNoValue(index)) {
476 if (data_.size() >= std::numeric_limits<int32_t>::max()) {
477 return nullptr;
478 }
479 index = data_.size();
480 index_.set(key, index);
481 data_.push_back({});
482 }
483 return &data_[index];
484 }
485
486 void CustomPhraseDict::addPhrase(std::string_view key, std::string_view value,
487 int order) {
488 if (order == 0) {
489 return;
490 }
491 if (auto *entry = getOrCreateEntry(key)) {
492 entry->push_back(CustomPhrase(order, std::string(value)));
493 }
494 }
495
496 void CustomPhraseDict::pinPhrase(std::string_view key, std::string_view value) {
497 removePhrase(key, value);
498 if (auto *entry = getOrCreateEntry(key)) {
499 // enabled item is 1 based.
500 entry->insert(entry->begin(), CustomPhrase(1, std::string(value)));
501 normalizeData(*entry);
502 }
503 }
504
505 void CustomPhraseDict::removePhrase(std::string_view key,
506 std::string_view value) {
507
508 auto index = index_.exactMatchSearch(key);
509 if (TrieType::isNoValue(index)) {
510 return;
511 }
512
513 data_[index].erase(std::remove_if(data_[index].begin(), data_[index].end(),
514 [&value](const CustomPhrase &item) {
515 return value == item.value();
516 }),
517 data_[index].end());
518 }
519
520 void CustomPhraseDict::save(std::ostream &out) const {
521 std::string buf;
522 index_.foreach([&out, &buf,
523 this](uint32_t value, size_t _len,
524 libime::DATrie<uint32_t>::position_type pos) {
525 index_.suffix(buf, _len, pos);
526 for (const auto &phrase : data_[value]) {
527 auto escaped = fcitx::stringutils::escapeForValue(phrase.value());
528 out << buf << "," << phrase.order() << "=";
529 if (escaped.size() != phrase.value().size()) {
530 // Always quote escaped value.
531 if (escaped.front() != '"') {
532 out << '"';
533 }
534 out << escaped;
535 if (escaped.back() != '"') {
536 out << '"';
537 }
538 } else {
539 out << phrase.value();
540 }
541 out << '\n';
542 }
543 return true;
544 });
545 }
546
547 void CustomPhraseDict::clear() {
548 index_.clear();
549 data_.clear();
550 }
551 } // namespace fcitx