Debian Codegraph @

src/quwei.cpp

raw symbols SCIP
1 /*
2 * SPDX-FileCopyrightText: 2021~2021 CSSlayer <[email protected]>
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 *
6 */
7 #include "quwei.h"
8 #include <fcitx-utils/i18n.h>
9 #include <fcitx-utils/utf8.h>
10 #include <fcitx/candidatelist.h>
11 #include <fcitx/inputpanel.h>
12 #include <fcitx/instance.h>
13 #include <fcitx/userinterfacemanager.h>
14 #include <punctuation_public.h>
15 #include <quickphrase_public.h>
16 #include <utility>
17
18 namespace {
19
20 // Template to help resolve iconv parameter issue on BSD.
21 template <class T>
22 struct function_traits;
23
24 // partial specialization for function pointer
25 template <class R, class... Args>
26 struct function_traits<R (*)(Args...)> {
27 using result_type = R;
28 using argument_types = std::tuple<Args...>;
29 };
30
31 template <class T>
32 using second_argument_type = typename std::tuple_element<
33 1, typename function_traits<T>::argument_types>::type;
34
35 static const std::array<fcitx::Key, 10> selectionKeys = {
36 fcitx::Key{FcitxKey_1}, fcitx::Key{FcitxKey_2}, fcitx::Key{FcitxKey_3},
37 fcitx::Key{FcitxKey_4}, fcitx::Key{FcitxKey_5}, fcitx::Key{FcitxKey_6},
38 fcitx::Key{FcitxKey_7}, fcitx::Key{FcitxKey_8}, fcitx::Key{FcitxKey_9},
39 fcitx::Key{FcitxKey_0},
40 };
41
42 class QuweiCandidateWord : public fcitx::CandidateWord {
43 public:
44 QuweiCandidateWord(QuweiEngine *engine, std::string text)
45 : engine_(engine) {
46 setText(fcitx::Text(std::move(text)));
47 }
48
49 void select(fcitx::InputContext *inputContext) const override {
50 inputContext->commitString(text().toString());
51 auto state = inputContext->propertyFor(engine_->factory());
52 state->reset();
53 }
54
55 private:
56 QuweiEngine *engine_;
57 };
58
59 class QuweiCandidateList : public fcitx::CandidateList,
60 public fcitx::PageableCandidateList,
61 public fcitx::CursorMovableCandidateList {
62 public:
63 QuweiCandidateList(QuweiEngine *engine, fcitx::InputContext *ic,
64 const std::string &code)
65 : engine_(engine), ic_(ic), code_(std::stoi(code)) {
66 setPageable(this);
67 setCursorMovable(this);
68 for (int i = 0; i < 10; i++) {
69 const char label[2] = {static_cast<char>('0' + (i + 1) % 10), '\0'};
70 labels_[i].append(label);
71 labels_[i].append(". ");
72 }
73 generate();
74 }
75
76 const fcitx::Text &label(int idx) const override { return labels_[idx]; }
77
78 const fcitx::CandidateWord &candidate(int idx) const override {
79 return *candidates_[idx];
80 }
81 int size() const override { return 10; }
82 fcitx::CandidateLayoutHint layoutHint() const override {
83 return fcitx::CandidateLayoutHint::NotSet;
84 }
85 bool usedNextBefore() const override { return false; }
86 void prev() override {
87 if (!hasPrev()) {
88 return;
89 }
90 --code_;
91 auto state = ic_->propertyFor(engine_->factory());
92 state->setCode(code_);
93 }
94 void next() override {
95 if (!hasNext()) {
96 return;
97 }
98 code_++;
99 auto state = ic_->propertyFor(engine_->factory());
100 state->setCode(code_);
101 }
102
103 bool hasPrev() const override { return code_ > 0; }
104
105 bool hasNext() const override { return code_ < 999; }
106
107 void prevCandidate() override { cursor_ = (cursor_ + 9) % 10; }
108
109 void nextCandidate() override { cursor_ = (cursor_ + 1) % 10; }
110
111 int cursorIndex() const override { return cursor_; }
112
113 private:
114 void generate() {
115 for (int i = 0; i < 10; i++) {
116 auto code = code_ * 10 + (i + 1);
117 auto qu = code / 100;
118 auto wei = code % 100;
119
120 // Quwei to GB2312 (0xA0 + qu, 0xA0 + wei)
121 char in[3];
122 if (qu >= 95) { /* Process extend Qu 95 and 96 */
123 in[0] = qu - 95 + 0xA8;
124 in[1] = wei + 0x40;
125
126 /* skip 0xa87f and 0xa97f */
127 if (in[1] >= 0x7f) {
128 in[1]++;
129 }
130 } else {
131 in[0] = qu + 0xa0;
132 in[1] = wei + 0xa0;
133 }
134
135 size_t insize = 2, avail = FCITX_UTF8_MAX_LENGTH + 1;
136 std::remove_pointer_t<second_argument_type<decltype(&::iconv)>>
137 inbuf = in;
138
139 char out[FCITX_UTF8_MAX_LENGTH + 1];
140 char *outbuf = out;
141 iconv(engine_->conv(), &inbuf, &insize, &outbuf, &avail);
142 *outbuf = '\0';
143 candidates_[i] = std::make_unique<QuweiCandidateWord>(engine_, out);
144 }
145 }
146
147 QuweiEngine *engine_;
148 fcitx::InputContext *ic_;
149 fcitx::Text labels_[10];
150 std::unique_ptr<QuweiCandidateWord> candidates_[10];
151 int code_;
152 int cursor_ = 0;
153 };
154
155 } // namespace
156
157 void QuweiState::keyEvent(fcitx::KeyEvent &event) {
158 if (auto candidateList = ic_->inputPanel().candidateList()) {
159 int idx = event.key().keyListIndex(selectionKeys);
160 if (idx >= 0 && idx < candidateList->size()) {
161 event.accept();
162 candidateList->candidate(idx).select(ic_);
163 return;
164 }
165 if (event.key().checkKeyList(
166 engine_->instance()->globalConfig().defaultPrevPage())) {
167 if (auto *pageable = candidateList->toPageable();
168 pageable && pageable->hasPrev()) {
169 event.accept();
170 pageable->prev();
171 ic_->updateUserInterface(
172 fcitx::UserInterfaceComponent::InputPanel);
173 }
174 return event.filterAndAccept();
175 }
176
177 if (event.key().checkKeyList(
178 engine_->instance()->globalConfig().defaultNextPage())) {
179 if (auto *pageable = candidateList->toPageable();
180 pageable && pageable->hasNext()) {
181 pageable->next();
182 ic_->updateUserInterface(
183 fcitx::UserInterfaceComponent::InputPanel);
184 }
185 return event.filterAndAccept();
186 }
187 }
188
189 if (buffer_.empty()) {
190 if (!event.key().isDigit()) {
191 // if it gonna commit something
192 auto c = fcitx::Key::keySymToUnicode(event.key().sym());
193 if (!c) {
194 return;
195 }
196 std::string punc, puncAfter;
197 // skip key pad
198 if (c && !event.key().isKeyPad()) {
199 std::tie(punc, puncAfter) =
200 engine_->punctuation()
201 ->call<fcitx::IPunctuation::pushPunctuationV2>("zh_CN",
202 ic_, c);
203 }
204 if (event.key().check(FcitxKey_semicolon) &&
205 engine_->quickphrase()) {
206 auto keyString = fcitx::utf8::UCS4ToUTF8(c);
207 // s is punc or key
208 auto output = !punc.empty() ? (punc + puncAfter) : keyString;
209 // alt is key or empty
210 auto altOutput = !punc.empty() ? keyString : "";
211 // if no punc: key -> key (s = key, alt = empty)
212 // if there's punc: key -> punc, return -> key (s = punc, alt =
213 // key)
214 std::string text;
215 engine_->quickphrase()->call<fcitx::IQuickPhrase::trigger>(
216 ic_, text, "", output, altOutput,
217 fcitx::Key(FcitxKey_semicolon));
218 event.filterAndAccept();
219 return;
220 }
221 if (!punc.empty()) {
222 event.filterAndAccept();
223 ic_->commitString(punc + puncAfter);
224 if (size_t length = fcitx::utf8::lengthValidated(puncAfter);
225 length != 0 && length != fcitx::utf8::INVALID_LENGTH) {
226 for (size_t i = 0; i < length; i++) {
227 ic_->forwardKey(fcitx::Key(FcitxKey_Left));
228 }
229 }
230 }
231 return;
232 }
233 } else {
234 if (event.key().check(FcitxKey_BackSpace)) {
235 buffer_.backspace();
236 updateUI();
237 return event.filterAndAccept();
238 }
239 if (event.key().check(FcitxKey_Return)) {
240 ic_->commitString(buffer_.userInput());
241 reset();
242 return event.filterAndAccept();
243 }
244 if (event.key().check(FcitxKey_Escape)) {
245 reset();
246 return event.filterAndAccept();
247 }
248 if (!event.key().isDigit()) {
249 return event.filterAndAccept();
250 }
251 }
252
253 if (event.key().isDigit()) {
254 buffer_.type('0' + event.key().digit());
255 }
256 updateUI();
257 return event.filterAndAccept();
258 }
259
260 void QuweiState::setCode(int code) {
261 if (code < 0 || code > 999) {
262 return;
263 }
264 buffer_.clear();
265 auto codeStr = std::to_string(code);
266 while (codeStr.size() < 3) {
267 codeStr = "0" + codeStr;
268 }
269 buffer_.type(std::to_string(code));
270 updateUI();
271 }
272
273 void QuweiState::updateUI() {
274 auto &inputPanel = ic_->inputPanel();
275 inputPanel.reset();
276 if (buffer_.size() == 3) {
277 inputPanel.setCandidateList(std::make_unique<QuweiCandidateList>(
278 engine_, ic_, buffer_.userInput()));
279 }
280 if (ic_->capabilityFlags().test(fcitx::CapabilityFlag::Preedit)) {
281 fcitx::Text preedit(buffer_.userInput(),
282 fcitx::TextFormatFlag::HighLight);
283 inputPanel.setClientPreedit(preedit);
284 } else {
285 fcitx::Text preedit(buffer_.userInput());
286 inputPanel.setPreedit(preedit);
287 }
288 ic_->updateUserInterface(fcitx::UserInterfaceComponent::InputPanel);
289 ic_->updatePreedit();
290 }
291
292 QuweiEngine::QuweiEngine(fcitx::Instance *instance)
293 : instance_(instance), factory_([this](fcitx::InputContext &ic) {
294 return new QuweiState(this, &ic);
295 }) {
296 conv_ = iconv_open("UTF-8", "GB18030");
297 if (conv_ == reinterpret_cast<iconv_t>(-1)) {
298 throw std::runtime_error("Failed to create converter");
299 }
300 instance->inputContextManager().registerProperty("quweiState", &factory_);
301 }
302
303 void QuweiEngine::activate(const fcitx::InputMethodEntry &entry,
304 fcitx::InputContextEvent &event) {
305 FCITX_UNUSED(entry);
306 auto *inputContext = event.inputContext();
307 // Request full width.
308 fullwidth();
309 chttrans();
310 for (const auto *actionName : {"chttrans", "punctuation", "fullwidth"}) {
311 if (auto *action =
312 instance_->userInterfaceManager().lookupAction(actionName)) {
313 inputContext->statusArea().addAction(
314 fcitx::StatusGroup::InputMethod, action);
315 }
316 }
317 }
318
319 void QuweiEngine::keyEvent(const fcitx::InputMethodEntry &entry,
320 fcitx::KeyEvent &keyEvent) {
321 FCITX_UNUSED(entry);
322 if (keyEvent.isRelease() || keyEvent.key().states()) {
323 return;
324 }
325 // FCITX_INFO() << keyEvent.key() << " isRelease=" << keyEvent.isRelease();
326 auto ic = keyEvent.inputContext();
327 auto *state = ic->propertyFor(&factory_);
328 state->keyEvent(keyEvent);
329 }
330
331 void QuweiEngine::reset(const fcitx::InputMethodEntry &,
332 fcitx::InputContextEvent &event) {
333 auto *state = event.inputContext()->propertyFor(&factory_);
334 state->reset();
335 }
336
337 FCITX_ADDON_FACTORY(QuweiEngineFactory);