Debian Codegraph @

modules/chttrans/chttrans-native.cpp

raw
1 /*
2 * SPDX-FileCopyrightText: 2017-2017 CSSlayer <[email protected]>
3 *
4 * SPDX-License-Identifier: LGPL-2.1-or-later
5 *
6 */
7 #include "chttrans-native.h"
8 #include "chttrans.h"
9 #include <cstdint>
10 #include <fcitx-utils/fdstreambuf.h>
11 #include <fcitx-utils/standardpaths.h>
12 #include <fcitx-utils/utf8.h>
13 #include <fcntl.h>
14 #include <istream>
15 #include <string>
16 #include <string_view>
17
18 #define TABLE_GBKS2T "chttrans/gbks2t.tab"
19
20 using namespace fcitx;
21
22 bool NativeBackend::loadOnce(const ChttransConfig & /*unused*/) {
23 auto file =
24 StandardPaths::global().open(StandardPathsType::PkgData, TABLE_GBKS2T);
25 if (!file.isValid()) {
26 return false;
27 }
28
29 IFDStreamBuf buffer(file.fd());
30 std::istream in(&buffer);
31
32 std::string strBuf;
33 while (std::getline(in, strBuf)) {
34 // Get two char.
35 auto simpStart = strBuf.begin();
36 uint32_t simp;
37 uint32_t trad;
38
39 auto tradStart = utf8::getNextChar(simpStart, strBuf.end(), &simp);
40 auto end = utf8::getNextChar(tradStart, strBuf.end(), &trad);
41 if (!utf8::isValidChar(simp) || !utf8::isValidChar(trad)) {
42 continue;
43 }
44 std::string_view simpView(simpStart, tradStart);
45 std::string_view tradView(tradStart, end);
46 s2tMap_.try_emplace(std::string(simpView), tradView);
47 t2sMap_.try_emplace(std::string(tradView), simpView);
48 }
49 return true;
50 }
51
52 std::string convert(const NativeBackend::MapType &transMap,
53 const std::string &strHZ) {
54 auto len = utf8::lengthValidated(strHZ);
55 if (len == utf8::INVALID_LENGTH) {
56 return strHZ;
57 }
58 auto range = fcitx::utf8::MakeUTF8StringViewRange(strHZ);
59 std::string result;
60 for (const auto &value : range) {
61 auto iter = transMap.find(value);
62 if (iter != transMap.end()) {
63 result.append(iter->second);
64 } else {
65 result.append(value);
66 }
67 }
68
69 return result;
70 }
71
72 std::string NativeBackend::convertSimpToTrad(const std::string &strHZ) {
73 return convert(s2tMap_, strHZ);
74 }
75
76 std::string NativeBackend::convertTradToSimp(const std::string &strHZ) {
77 return convert(t2sMap_, strHZ);
78 }