-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDictypeFcitx.cpp
More file actions
374 lines (332 loc) · 13.3 KB
/
DictypeFcitx.cpp
File metadata and controls
374 lines (332 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#include <iomanip>
#include <sstream>
#include <fcitx-config/iniparser.h>
#include <fcitx/addonfactory.h>
#include <fcitx/addonmanager.h>
#include <fcitx/event.h>
#include <fcitx/inputpanel.h>
#include <fcitx/instance.h>
#include <grpcpp/client_context.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/security/credentials.h>
#include <grpcpp/support/client_callback.h>
#include "dictype.grpc.pb.h"
#include "DictypeFcitx.h"
#include "DictypeLog.h"
#include "DictypeState.h"
#include "GrpcClient.h"
static std::string toHex(const std::array<uint8_t, 16>& data) {
std::ostringstream oss;
oss << std::hex << std::setfill('0');
for (uint8_t b : data) {
oss << std::setw(2) << static_cast<int>(b);
}
return oss.str();
}
DictypeFcitx::DictypeFcitx(fcitx::AddonManager* addonManager)
: eventLoop_(addonManager->eventLoop()),
dispatcher_(addonManager->instance()->eventDispatcher()),
instance_(addonManager->instance()) {
DICTYPE_INFO() << "created";
eventHandlers_.emplace_back(instance_->watchEvent(
fcitx::EventType::InputContextKeyEvent,
fcitx::EventWatcherPhase::Default, [this](fcitx::Event& event) {
auto& keyEvent = dynamic_cast<fcitx::KeyEvent&>(event);
if (keyEvent.isRelease()) {
return;
}
if (keyEvent.key().checkKeyList(*config_.triggerKey1)) {
if (running_.load(std::memory_order_acquire)) {
stop_();
} else {
trigger_(keyEvent, "Profile1");
}
keyEvent.filterAndAccept();
} else if (keyEvent.key().checkKeyList(*config_.triggerKey2)) {
if (running_.load(std::memory_order_acquire)) {
stop_();
} else {
trigger_(keyEvent, "Profile2");
}
keyEvent.filterAndAccept();
} else if (keyEvent.key().checkKeyList(*config_.triggerKey3)) {
if (running_.load(std::memory_order_acquire)) {
stop_();
} else {
trigger_(keyEvent, "Profile3");
}
keyEvent.filterAndAccept();
} else if (keyEvent.key().checkKeyList(*config_.triggerKey4)) {
if (running_.load(std::memory_order_acquire)) {
stop_();
} else {
trigger_(keyEvent, "Profile4");
}
keyEvent.filterAndAccept();
} else if (keyEvent.key().checkKeyList(*config_.triggerKey5)) {
if (running_.load(std::memory_order_acquire)) {
stop_();
} else {
trigger_(keyEvent, "Profile5");
}
keyEvent.filterAndAccept();
}
}));
const auto cred = grpc::experimental::LocalCredentials(UDS);
auto channelArgs = grpc::ChannelArguments();
channelArgs.SetString(GRPC_ARG_DEFAULT_AUTHORITY, "localhost");
const auto channel =
grpc::CreateCustomChannel(getServerEndpoint_(), cred, channelArgs);
auto stubTemp = Dictype::Dictype::NewStub(channel);
this->stub.swap(stubTemp);
}
DictypeFcitx::~DictypeFcitx() = default;
fcitx::Instance* DictypeFcitx::instance() const { return instance_; }
void DictypeFcitx::closeUI_() const {
if (state_.getStage() == DictypeStage::Errored) {
return;
}
const auto inputContextOpt = state_.inputContext();
if (!inputContextOpt.has_value()) {
DICTYPE_WARN() << "input context is gone.";
return;
}
auto* inputContext = *inputContextOpt;
inputContext->inputPanel().reset();
inputContext->updateUserInterface(
fcitx::UserInterfaceComponent::InputPanel);
}
void DictypeFcitx::updateUI_() const {
const auto inputContextOpt = state_.inputContext();
if (!inputContextOpt.has_value()) {
DICTYPE_WARN() << "input context is gone.";
return;
}
auto* inputContext = *inputContextOpt;
inputContext->inputPanel().reset();
const std::string uuid = toHex(inputContext->uuid());
DICTYPE_INFO() << "InputContext: " << uuid << " Update UI "
<< state_.getUncommittedText();
fcitx::TextFormatFlags format = fcitx::TextFormatFlag::DontCommit;
const bool clientPreedit =
inputContext->capabilityFlags().test(fcitx::CapabilityFlag::Preedit);
if (clientPreedit) {
format = {fcitx::TextFormatFlag::Underline,
fcitx::TextFormatFlag::DontCommit};
}
if (const std::string uncommitted = state_.getUncommittedText();
!uncommitted.empty()) {
fcitx::Text preedit;
preedit.append(state_.getUncommittedText(), format);
preedit.setCursor(static_cast<int>(preedit.textLength()));
if (clientPreedit) {
inputContext->inputPanel().setClientPreedit(preedit);
} else {
inputContext->inputPanel().setPreedit(preedit);
}
inputContext->updatePreedit();
DICTYPE_INFO() << "PreEdit: " << preedit.toString();
}
{
fcitx::Text auxUp;
switch (state_.getStage()) {
case DictypeStage::Closed: {
break;
}
case DictypeStage::Connecting: {
auxUp = fcitx::Text(std::string{"🟡 "} + _("Connecting"));
break;
}
case DictypeStage::Errored: {
auxUp = fcitx::Text(std::string{"🔴 "} + _("Error: ") +
state_.getErrorMsg());
break;
}
case DictypeStage::Transcribing: {
auxUp = fcitx::Text(std::string{"🟢 "} + _("Transcribing"));
break;
}
case DictypeStage::Stopping: {
auxUp = fcitx::Text(std::string{"🟠 "} + _("Stopping"));
break;
}
default: {
}
}
if (!auxUp.empty()) {
inputContext->inputPanel().setAuxUp(auxUp);
}
}
inputContext->updateUserInterface(
fcitx::UserInterfaceComponent::InputPanel);
}
void DictypeFcitx::reloadConfig() { readAsIni(config_, configFile); }
const fcitx::Configuration* DictypeFcitx::getConfig() const { return &config_; }
void DictypeFcitx::setConfig(const fcitx::RawConfig& raw_config) {
config_.load(raw_config, true);
safeSaveAsIni(config_, configFile);
}
std::string DictypeFcitx::getServerEndpoint_() {
const uid_t uid = getuid();
std::ostringstream oss;
oss << "unix:///var/run/user/" << uid << "/dictype/dictyped.socket";
return oss.str();
}
void DictypeFcitx::trigger_(const fcitx::KeyEvent& keyEvent,
const std::string& profileName) const {
auto* inputContext = keyEvent.inputContext();
{
DICTYPE_INFO() << "Triggered " << profileName;
if (!state_.newSession(inputContext)) {
DICTYPE_ERROR() << "Previous session is not cleared.";
return;
}
}
const auto syncState = [](const DictypeFcitx* that) {
const auto inputContextOpt = that->state_.inputContext();
if (!inputContextOpt.has_value()) {
DICTYPE_WARN() << "input context is gone.";
if (that->running_.load(std::memory_order_acquire)) {
that->stop_();
}
return;
}
const auto lastFocusedInputContext =
that->instance()->lastFocusedInputContext();
auto* inputContext = *inputContextOpt;
if (lastFocusedInputContext != inputContext) {
// WORKAROUND: I suspect with some backends, InputContext
// commitString() always commits to the currently focused text
// widget, not the text widget associated with InputContext.
if (lastFocusedInputContext == nullptr) {
DICTYPE_INFO() << "No focused InputContext. Delaying commit...";
} else {
const std::string uuid = toHex(lastFocusedInputContext->uuid());
DICTYPE_INFO()
<< "last focused input uuid: " << uuid
<< ". Different InputContexts detected. Delaying "
"commit...";
}
// TODO: watch for the re-focus, and run syncState() again.
return;
}
if (const auto committable = that->state_.takeCommittableText();
committable.has_value()) {
const std::string uuid = toHex(inputContext->uuid());
DICTYPE_INFO() << uuid << " committing: " << committable.value();
inputContext->commitString(committable.value());
}
that->updateUI_();
};
// Start a non-blocking gRPC streaming call to dictyped.
try {
// Capture the necessary pointers for updating state and UI.
const auto onResponse = [ref = this->watch(), syncState](
const Dictype::TranscribeResponse& resp) {
const auto that = ref.get();
if (that == nullptr) {
DICTYPE_WARN() << "instance is gone.";
return;
}
Dictype::TranscribeResponse responseCopy = resp;
that->dispatcher_.scheduleWithContext(
ref, [ref, syncState, resp = std::move(responseCopy)]() {
const auto that2 = ref.get();
if (that2 == nullptr) {
DICTYPE_WARN() << "instance is gone.";
return;
}
// Update state text from response and refresh UI.
that2->state_.setText(resp);
syncState(that2);
});
};
// When the stream completes (OK or error), clear running_.
const auto onDone = [ref = this->watch(),
syncState](const grpc::Status& s) {
const auto that = ref.get();
if (that == nullptr) {
DICTYPE_WARN() << "instance is gone.";
return;
}
const auto statusCopy = grpc::Status{s};
that->dispatcher_.scheduleWithContext(
ref, [ref, syncState, status = statusCopy]() {
const auto that2 = ref.get();
if (that2 == nullptr) {
DICTYPE_WARN() << "instance is gone.";
return;
}
if (!status.ok()) {
that2->state_.setError(status.error_message());
DICTYPE_ERROR() << "stream ended with error: "
<< status.error_message();
} else {
DICTYPE_INFO() << "stream completed.";
}
syncState(that2);
that2->updateUI_();
that2->closeUI_();
that2->state_.clear();
that2->running_.store(false, std::memory_order_release);
});
};
// Reactor deletes itself upon completion; do not hold the pointer.
(void)new GrpcClient(stub.get(), std::move(onResponse),
std::move(onDone), profileName);
// Mark running only after we've successfully dispatched the stream.
if (state_.getStage() == DictypeStage::Closed) {
state_.setConnecting();
running_.store(true, std::memory_order_release);
DICTYPE_INFO() << "Started transcribe stream.";
}
} catch (...) {
DICTYPE_ERROR() << "Failed to start transcribe stream.";
state_.setError("Unexpected error: failed to start stream.");
}
updateUI_();
}
void DictypeFcitx::stop_() const {
if (state_.getStage() == DictypeStage::Stopping) {
DICTYPE_INFO() << "Stop RPC skipped: already stopping.";
return;
}
try {
auto* ctx = new grpc::ClientContext();
auto* req = new Dictype::StopRequest();
auto* resp = new Dictype::StopResponse();
stub->async()->Stop(
ctx, req, resp,
[ref = this->watch(), ctx, req, resp](const grpc::Status& s) {
const auto that = ref.get();
if (that == nullptr) {
DICTYPE_WARN() << "instance is gone.";
} else {
if (!s.ok()) {
DICTYPE_ERROR()
<< "Stop RPC failed (async): " << s.error_message();
that->state_.setError(s.error_message());
} else {
DICTYPE_INFO() << "Stop RPC ok (async), stopped="
<< resp->stopped();
that->state_.stop();
}
that->updateUI_();
}
delete ctx;
delete req;
delete resp;
});
DICTYPE_INFO() << "Stop RPC dispatched asynchronously.";
} catch (...) {
DICTYPE_ERROR() << "Failed to dispatch Stop RPC (async).";
state_.setError("Failed to stop.");
updateUI_();
}
}
class DictypeFcitxFactory final : public fcitx::AddonFactory {
fcitx::AddonInstance* create(fcitx::AddonManager* manager) override {
return new DictypeFcitx(manager);
}
};
FCITX_ADDON_FACTORY_V2(dictype, DictypeFcitxFactory);