/
instance.cpp
2538 lines (2323 loc) · 86.5 KB
/
instance.cpp
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SPDX-FileCopyrightText: 2016-2016 CSSlayer <wengxt@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*
*/
#include "config.h"
#include <fcntl.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include <memory>
#include <stdexcept>
#include <unordered_map>
#include <utility>
#include <fmt/format.h>
#include <getopt.h>
#include "fcitx-config/iniparser.h"
#include "fcitx-utils/capabilityflags.h"
#include "fcitx-utils/event.h"
#include "fcitx-utils/eventdispatcher.h"
#include "fcitx-utils/i18n.h"
#include "fcitx-utils/log.h"
#include "fcitx-utils/misc.h"
#include "fcitx-utils/standardpath.h"
#include "fcitx-utils/stringutils.h"
#include "fcitx-utils/utf8.h"
#include "fcitx/event.h"
#include "fcitx/inputmethodgroup.h"
#include "../../modules/notifications/notifications_public.h"
#include "addonmanager.h"
#include "focusgroup.h"
#include "globalconfig.h"
#include "inputcontextmanager.h"
#include "inputcontextproperty.h"
#include "inputmethodengine.h"
#include "inputmethodentry.h"
#include "inputmethodmanager.h"
#include "instance.h"
#include "instance_p.h"
#include "misc_p.h"
#include "userinterfacemanager.h"
#ifdef ENABLE_X11
#define FCITX_NO_XCB
#include <../modules/xcb/xcb_public.h>
#endif
#ifdef ENABLE_KEYBOARD
#include <xkbcommon/xkbcommon-compose.h>
#include <xkbcommon/xkbcommon.h>
#endif
FCITX_DEFINE_LOG_CATEGORY(keyTrace, "key_trace");
namespace fcitx {
namespace {
constexpr uint64_t AutoSaveMinInUsecs = 60ull * 1000000ull; // 30 minutes
constexpr uint64_t AutoSaveIdleTime = 60ull * 1000000ull; // 1 minutes
FCITX_CONFIGURATION(DefaultInputMethod,
Option<std::vector<std::string>> defaultInputMethods{
this, "DefaultInputMethod", "DefaultInputMethod"};
Option<std::vector<std::string>> extraLayouts{
this, "ExtraLayout", "ExtraLayout"};);
void initAsDaemon() {
pid_t pid;
if ((pid = fork()) > 0) {
waitpid(pid, nullptr, 0);
exit(0);
}
setsid();
auto oldint = signal(SIGINT, SIG_IGN);
auto oldhup = signal(SIGHUP, SIG_IGN);
auto oldquit = signal(SIGQUIT, SIG_IGN);
auto oldpipe = signal(SIGPIPE, SIG_IGN);
auto oldttou = signal(SIGTTOU, SIG_IGN);
auto oldttin = signal(SIGTTIN, SIG_IGN);
auto oldchld = signal(SIGCHLD, SIG_IGN);
if (fork() > 0) {
exit(0);
}
(void)chdir("/");
signal(SIGINT, oldint);
signal(SIGHUP, oldhup);
signal(SIGQUIT, oldquit);
signal(SIGPIPE, oldpipe);
signal(SIGTTOU, oldttou);
signal(SIGTTIN, oldttin);
signal(SIGCHLD, oldchld);
}
// Switch IM when these capabilities change.
bool shouldSwitchIM(const CapabilityFlags &oldFlags,
const CapabilityFlags &newFlags) {
const bool oldDisable = oldFlags.testAny(
CapabilityFlags{CapabilityFlag::Password, CapabilityFlag::Disable});
const bool newDisable = newFlags.testAny(
CapabilityFlags{CapabilityFlag::Password, CapabilityFlag::Disable});
return oldDisable != newDisable;
}
} // namespace
void InstanceArgument::printUsage() const {
std::cout
<< "Usage: " << argv0 << " [Option]\n"
<< " --disable <addon names>\tA comma separated list of addons to "
"be disabled.\n"
<< "\t\t\t\t\"all\" can be used to disable all addons.\n"
<< " --enable <addon names>\tA comma separated list of addons to "
"be enabled.\n"
<< "\t\t\t\t\"all\" can be used to enable all addons.\n"
<< "\t\t\t\tThis value will override the value in the flag "
"--disable.\n"
<< " --verbose <logging rule>\tSet the logging rule for "
"displaying message.\n"
<< "\t\t\t\tSyntax: category1=level1,category2=level2, ...\n"
<< "\t\t\t\tE.g. default=4,key_trace=5\n"
<< "\t\t\t\tLevels are numbers ranging from 0 to 5.\n"
<< "\t\t\t\t\t0 - NoLog\n"
<< "\t\t\t\t\t1 - Fatal\n"
<< "\t\t\t\t\t2 - Error\n"
<< "\t\t\t\t\t3 - Warn\n"
<< "\t\t\t\t\t4 - Info (default)\n"
<< "\t\t\t\t\t5 - Debug\n"
<< "\t\t\t\tSome built-in categories are:\n"
<< "\t\t\t\t\tdefault - miscellaneous category used by fcitx own "
"library.\n"
<< "\t\t\t\t\tkey_trace - print the key event received by fcitx.\n"
<< "\t\t\t\t\t\"*\" may be used to represent all logging "
"category.\n"
<< " -u, --ui <addon name>\t\tSet the UI addon to be used.\n"
<< " -d\t\t\t\tRun as a daemon.\n"
<< " -D\t\t\t\tDo not run as a daemon (default).\n"
<< " -s <seconds>\t\t\tNumber of seconds to wait before start.\n"
<< " -k, --keep\t\t\tKeep running even the main display is "
"disconnected.\n"
<< " -r, --replace\t\t\tReplace the existing instance.\n"
<< " -o --option <option>\t\tPass the option to addons\n"
<< "\t\t\t\t<option> is in format like:\n"
<< "\t\t\t\tname1=opt1a:opt1b,name2=opt2a:opt2b... .\n"
<< " -v, --version\t\t\tShow version and quit.\n"
<< " -h, --help\t\t\tShow this help message and quit.\n";
}
InstancePrivate::InstancePrivate(Instance *q) : QPtrHolder<Instance>(q) {
const char *locale = getenv("LC_ALL");
if (!locale) {
locale = getenv("LC_CTYPE");
}
if (!locale) {
locale = getenv("LANG");
}
if (!locale) {
locale = "C";
}
#ifdef ENABLE_KEYBOARD
xkbContext_.reset(xkb_context_new(XKB_CONTEXT_NO_FLAGS));
if (xkbContext_) {
xkb_context_set_log_level(xkbContext_.get(), XKB_LOG_LEVEL_CRITICAL);
xkbComposeTable_.reset(xkb_compose_table_new_from_locale(
xkbContext_.get(), locale, XKB_COMPOSE_COMPILE_NO_FLAGS));
if (!xkbComposeTable_) {
FCITX_INFO()
<< "Trying to fallback to compose table for en_US.UTF-8";
xkbComposeTable_.reset(xkb_compose_table_new_from_locale(
xkbContext_.get(), "en_US.UTF-8",
XKB_COMPOSE_COMPILE_NO_FLAGS));
}
if (!xkbComposeTable_) {
FCITX_WARN()
<< "No compose table is loaded, you may want to check your "
"locale settings.";
}
}
#endif
}
std::unique_ptr<HandlerTableEntry<EventHandler>>
InstancePrivate::watchEvent(EventType type, EventWatcherPhase phase,
EventHandler callback) {
return eventHandlers_[type][phase].add(std::move(callback));
}
#ifdef ENABLE_KEYBOARD
xkb_keymap *InstancePrivate::keymap(const std::string &display,
const std::string &layout,
const std::string &variant) {
auto layoutAndVariant = stringutils::concat(layout, "-", variant);
if (auto *keymapPtr = findValue(keymapCache_[display], layoutAndVariant)) {
return (*keymapPtr).get();
}
struct xkb_rule_names names;
names.layout = layout.c_str();
names.variant = variant.c_str();
std::tuple<std::string, std::string, std::string> xkbParam;
if (auto *param = findValue(xkbParams_, display)) {
xkbParam = *param;
} else {
if (!xkbParams_.empty()) {
xkbParam = xkbParams_.begin()->second;
} else {
xkbParam = std::make_tuple(DEFAULT_XKB_RULES, "pc101", "");
}
}
if (globalConfig_.overrideXkbOption()) {
std::get<2>(xkbParam) = globalConfig_.customXkbOption();
}
names.rules = std::get<0>(xkbParam).c_str();
names.model = std::get<1>(xkbParam).c_str();
names.options = std::get<2>(xkbParam).c_str();
UniqueCPtr<xkb_keymap, xkb_keymap_unref> keymap(xkb_keymap_new_from_names(
xkbContext_.get(), &names, XKB_KEYMAP_COMPILE_NO_FLAGS));
auto result =
keymapCache_[display].emplace(layoutAndVariant, std::move(keymap));
assert(result.second);
return result.first->second.get();
}
#endif
std::pair<std::unordered_set<std::string>, std::unordered_set<std::string>>
InstancePrivate::overrideAddons() {
std::unordered_set<std::string> enabled;
std::unordered_set<std::string> disabled;
for (const auto &addon : globalConfig_.enabledAddons()) {
enabled.insert(addon);
}
for (const auto &addon : globalConfig_.disabledAddons()) {
enabled.erase(addon);
disabled.insert(addon);
}
for (auto &addon : arg_.enableList) {
disabled.erase(addon);
enabled.insert(addon);
}
for (auto &addon : arg_.disableList) {
enabled.erase(addon);
disabled.insert(addon);
}
return {enabled, disabled};
}
void InstancePrivate::buildDefaultGroup() {
/// Figure out XKB layout information from system.
auto *defaultGroup = q_func()->defaultFocusGroup();
bool infoFound = false;
std::string layouts, variants;
auto guessLayout = [this, &layouts, &variants,
&infoFound](FocusGroup *focusGroup) {
// For now we can only do this on X11.
if (!stringutils::startsWith(focusGroup->display(), "x11:")) {
return true;
}
#ifdef ENABLE_X11
auto *xcb = addonManager_.addon("xcb");
auto x11Name = focusGroup->display().substr(4);
if (xcb) {
auto rules = xcb->call<IXCBModule::xkbRulesNames>(x11Name);
if (!rules[2].empty()) {
layouts = rules[2];
variants = rules[3];
infoFound = true;
return false;
}
}
#else
FCITX_UNUSED(this);
FCITX_UNUSED(layouts);
FCITX_UNUSED(variants);
FCITX_UNUSED(infoFound);
#endif
return true;
};
if (!defaultGroup || guessLayout(defaultGroup)) {
icManager_.foreachGroup(
[defaultGroup, &guessLayout](FocusGroup *focusGroup) {
if (defaultGroup == focusGroup) {
return true;
}
return guessLayout(focusGroup);
});
}
if (!infoFound) {
layouts = "us";
variants = "";
}
// layouts and variants are comma separated list for layout information.
constexpr char imNamePrefix[] = "keyboard-";
auto layoutTokens =
stringutils::split(layouts, ",", stringutils::SplitBehavior::KeepEmpty);
auto variantTokens = stringutils::split(
variants, ",", stringutils::SplitBehavior::KeepEmpty);
auto size = std::max(layoutTokens.size(), variantTokens.size());
// Make sure we have token to be the same size.
layoutTokens.resize(size);
variantTokens.resize(size);
OrderedSet<std::string> imLayouts;
for (decltype(size) i = 0; i < size; i++) {
if (layoutTokens[i].empty()) {
continue;
}
std::string layoutName = layoutTokens[i];
if (!variantTokens[i].empty()) {
layoutName = stringutils::concat(layoutName, "-", variantTokens[i]);
}
// Skip the layout if we don't have it.
if (!imManager_.entry(stringutils::concat(imNamePrefix, layoutName))) {
continue;
}
// Avoid add duplicate entry. layout might have weird duplicate.
imLayouts.pushBack(layoutName);
}
// Load the default profile.
auto lang = stripLanguage(getCurrentLanguage());
auto defaultProfile = StandardPath::global().open(
StandardPath::Type::PkgData, stringutils::joinPath("default", lang),
O_RDONLY);
RawConfig config;
DefaultInputMethod defaultIMConfig;
readFromIni(config, defaultProfile.fd());
defaultIMConfig.load(config);
// Add extra layout from profile.
for (const auto &extraLayout : defaultIMConfig.extraLayouts.value()) {
if (!imManager_.entry(stringutils::concat(imNamePrefix, extraLayout))) {
continue;
}
imLayouts.pushBack(extraLayout);
}
// Make sure imLayouts is not empty.
if (imLayouts.empty()) {
imLayouts.pushBack("us");
}
// Figure out the first available default input method.
std::string defaultIM;
for (const auto &im : defaultIMConfig.defaultInputMethods.value()) {
if (imManager_.entry(im)) {
defaultIM = im;
break;
}
}
// Create a group for each layout.
std::vector<std::string> groupOrders;
for (const auto &imLayout : imLayouts) {
std::string groupName;
if (imLayouts.size() == 1) {
groupName = _("Default");
} else {
groupName = fmt::format(_("Group {}"), imManager_.groupCount() + 1);
}
imManager_.addEmptyGroup(groupName);
groupOrders.push_back(groupName);
InputMethodGroup group(groupName);
group.inputMethodList().emplace_back(
InputMethodGroupItem(stringutils::concat(imNamePrefix, imLayout)));
if (!defaultIM.empty()) {
group.inputMethodList().emplace_back(
InputMethodGroupItem(defaultIM));
}
FCITX_INFO() << "Items in " << groupName << ": "
<< group.inputMethodList();
group.setDefaultLayout(imLayout);
imManager_.setGroup(std::move(group));
}
FCITX_INFO() << "Generated groups: " << groupOrders;
imManager_.setGroupOrder(groupOrders);
}
void InstancePrivate::showInputMethodInformation(InputContext *ic) {
FCITX_Q();
auto *inputState = ic->propertyFor(&inputStateFactory_);
auto *engine = q->inputMethodEngine(ic);
const auto *entry = q->inputMethodEntry(ic);
auto &imManager = q->inputMethodManager();
if (!inputState->isActive() &&
!globalConfig_.showFirstInputMethodInformation()) {
return;
}
std::string display;
if (engine) {
auto subMode = engine->subMode(*entry, *ic);
auto subModeLabel = engine->subModeLabel(*entry, *ic);
auto name = globalConfig_.compactInputMethodInformation() &&
!entry->label().empty()
? entry->label()
: entry->name();
if (globalConfig_.compactInputMethodInformation() &&
!subModeLabel.empty()) {
display = std::move(subModeLabel);
} else if (subMode.empty()) {
display = std::move(name);
} else {
display = fmt::format(_("{0} ({1})"), name, subMode);
}
} else if (entry) {
display = fmt::format(_("{0} (Not available)"), entry->name());
} else {
display = _("(Not available)");
}
if (!globalConfig_.compactInputMethodInformation() &&
imManager.groupCount() > 1) {
display = fmt::format(_("Group {0}: {1}"),
imManager.currentGroup().name(), display);
}
inputState->showInputMethodInformation(display);
}
bool InstancePrivate::canActivate(InputContext *ic) {
FCITX_Q();
if (!q->canTrigger()) {
return false;
}
auto *inputState = ic->propertyFor(&inputStateFactory_);
return !inputState->isActive();
}
bool InstancePrivate::canDeactivate(InputContext *ic) {
FCITX_Q();
if (!q->canTrigger()) {
return false;
}
auto *inputState = ic->propertyFor(&inputStateFactory_);
return inputState->isActive();
}
void InstancePrivate::navigateGroup(InputContext *ic, const Key &key,
bool forward) {
auto *inputState = ic->propertyFor(&inputStateFactory_);
inputState->pendingGroupIndex_ =
(inputState->pendingGroupIndex_ +
(forward ? 1 : imManager_.groupCount() - 1)) %
imManager_.groupCount();
FCITX_DEBUG() << "Switch to group " << inputState->pendingGroupIndex_;
if (notifications_ && !isSingleKey(key)) {
notifications_->call<INotifications::showTip>(
"enumerate-group", _("Input Method"), "input-keyboard",
_("Switch group"),
fmt::format(_("Switch group to {0}"),
imManager_.groups()[inputState->pendingGroupIndex_]),
3000);
}
}
void InstancePrivate::acceptGroupChange(const Key &key, InputContext *ic) {
FCITX_DEBUG() << "Accept group change, isSingleKey: " << key;
auto *inputState = ic->propertyFor(&inputStateFactory_);
auto groups = imManager_.groups();
if (groups.size() > inputState->pendingGroupIndex_) {
if (isSingleKey(key)) {
FCITX_DEBUG() << "EnumerateGroupTo: "
<< inputState->pendingGroupIndex_ << " " << key;
imManager_.enumerateGroupTo(groups[inputState->pendingGroupIndex_]);
} else {
FCITX_DEBUG() << "SetCurrentGroup: "
<< inputState->pendingGroupIndex_ << " " << key;
imManager_.setCurrentGroup(groups[inputState->pendingGroupIndex_]);
}
}
inputState->pendingGroupIndex_ = 0;
}
InputState::InputState(InstancePrivate *d, InputContext *ic)
: d_ptr(d), ic_(ic) {
active_ = d->globalConfig_.activeByDefault();
#ifdef ENABLE_KEYBOARD
if (d->xkbComposeTable_) {
xkbComposeState_.reset(xkb_compose_state_new(
d->xkbComposeTable_.get(), XKB_COMPOSE_STATE_NO_FLAGS));
}
#endif
}
void InputState::showInputMethodInformation(const std::string &name) {
ic_->inputPanel().setAuxUp(Text(name));
ic_->updateUserInterface(UserInterfaceComponent::InputPanel);
lastInfo_ = name;
imInfoTimer_ = d_ptr->eventLoop_.addTimeEvent(
CLOCK_MONOTONIC, now(CLOCK_MONOTONIC) + 1000000, 0,
[this](EventSourceTime *, uint64_t) {
hideInputMethodInfo();
return true;
});
}
#ifdef ENABLE_KEYBOARD
xkb_state *InputState::customXkbState(bool refresh) {
auto *instance = d_ptr->q_func();
const InputMethodGroup &group = d_ptr->imManager_.currentGroup();
const auto im = instance->inputMethod(ic_);
auto layout = group.layoutFor(im);
if (layout.empty() && stringutils::startsWith(im, "keyboard-")) {
layout = im.substr(9);
}
if (layout.empty() || layout == group.defaultLayout()) {
// Use system one.
xkbState_.reset();
modsAllReleased_ = false;
lastXkbLayout_.clear();
return nullptr;
}
if (layout == lastXkbLayout_ && !refresh) {
return xkbState_.get();
}
lastXkbLayout_ = layout;
const auto layoutAndVariant = parseLayout(layout);
if (auto *keymap = d_ptr->keymap(ic_->display(), layoutAndVariant.first,
layoutAndVariant.second)) {
xkbState_.reset(xkb_state_new(keymap));
} else {
xkbState_.reset();
}
modsAllReleased_ = false;
return xkbState_.get();
}
#endif
void InputState::setActive(bool active) {
if (active_ != active) {
active_ = active;
ic_->updateProperty(&d_ptr->inputStateFactory_);
}
}
void InputState::setLocalIM(const std::string &localIM) {
if (localIM_ != localIM) {
localIM_ = localIM;
ic_->updateProperty(&d_ptr->inputStateFactory_);
}
}
void InputState::copyTo(InputContextProperty *other) {
auto *otherState = static_cast<InputState *>(other);
if (otherState->active_ == active_ && otherState->localIM_ == localIM_) {
return;
}
if (otherState->ic_->hasFocus()) {
FCITX_DEBUG() << "Sync state to focused ic: "
<< otherState->ic_->program();
CheckInputMethodChanged imChangedRAII(otherState->ic_, d_ptr);
otherState->active_ = active_;
otherState->localIM_ = localIM_;
} else {
otherState->active_ = active_;
otherState->localIM_ = localIM_;
}
}
void InputState::reset() {
#ifdef ENABLE_KEYBOARD
if (xkbComposeState_) {
xkb_compose_state_reset(xkbComposeState_.get());
}
#endif
pendingGroupIndex_ = 0;
keyReleased_ = -1;
lastKeyPressed_ = Key();
totallyReleased_ = true;
}
void InputState::hideInputMethodInfo() {
if (!imInfoTimer_) {
return;
}
imInfoTimer_.reset();
auto &panel = ic_->inputPanel();
if (panel.auxDown().empty() && panel.preedit().empty() &&
panel.clientPreedit().empty() &&
(!panel.candidateList() || panel.candidateList()->empty()) &&
panel.auxUp().size() == 1 && panel.auxUp().stringAt(0) == lastInfo_) {
panel.reset();
ic_->updateUserInterface(UserInterfaceComponent::InputPanel);
}
}
#ifdef ENABLE_KEYBOARD
void InputState::resetXkbState() {
lastXkbLayout_.clear();
xkbState_.reset();
}
#endif
CheckInputMethodChanged::CheckInputMethodChanged(InputContext *ic,
InstancePrivate *instance)
: instance_(instance->q_func()), instancePrivate_(instance),
ic_(ic->watch()), inputMethod_(instance_->inputMethod(ic)),
reason_(InputMethodSwitchedReason::Other) {
auto *inputState = ic->propertyFor(&instance->inputStateFactory_);
if (!inputState->imChanged_) {
inputState->imChanged_ = this;
} else {
ic_.unwatch();
}
}
CheckInputMethodChanged::~CheckInputMethodChanged() {
if (!ic_.isValid()) {
return;
}
auto *ic = ic_.get();
auto *inputState = ic->propertyFor(&instancePrivate_->inputStateFactory_);
inputState->imChanged_ = nullptr;
if (inputMethod_ != instance_->inputMethod(ic) && !ignore_) {
instance_->postEvent(
InputContextSwitchInputMethodEvent(reason_, inputMethod_, ic));
}
}
Instance::Instance(int argc, char **argv) {
InstanceArgument arg;
arg.parseOption(argc, argv);
if (arg.quietQuit) {
throw InstanceQuietQuit();
}
if (arg.runAsDaemon) {
initAsDaemon();
}
if (arg.overrideDelay > 0) {
sleep(arg.overrideDelay);
}
// we need fork before this
d_ptr = std::make_unique<InstancePrivate>(this);
FCITX_D();
d->arg_ = arg;
d->eventDispatcher_.attach(&d->eventLoop_);
d->addonManager_.setInstance(this);
d->addonManager_.setAddonOptions(arg.addonOptions_);
d->icManager_.setInstance(this);
d->connections_.emplace_back(
d->imManager_.connect<InputMethodManager::CurrentGroupAboutToChange>(
[this, d](const std::string &lastGroup) {
d->icManager_.foreachFocused([this](InputContext *ic) {
assert(ic->hasFocus());
InputContextSwitchInputMethodEvent event(
InputMethodSwitchedReason::GroupChange, inputMethod(ic),
ic);
deactivateInputMethod(event);
return true;
});
d->lastGroup_ = lastGroup;
postEvent(InputMethodGroupAboutToChangeEvent());
}));
d->connections_.emplace_back(
d->imManager_.connect<InputMethodManager::CurrentGroupChanged>(
[this, d](const std::string &newGroup) {
d->icManager_.foreachFocused([this](InputContext *ic) {
assert(ic->hasFocus());
InputContextSwitchInputMethodEvent event(
InputMethodSwitchedReason::GroupChange, "", ic);
activateInputMethod(event);
return true;
});
postEvent(InputMethodGroupChangedEvent());
if (!d->lastGroup_.empty() && !newGroup.empty() &&
d->lastGroup_ != newGroup && d->notifications_ &&
d->imManager_.groupCount() > 1) {
d->notifications_->call<INotifications::showTip>(
"enumerate-group", _("Input Method"), "input-keyboard",
_("Switch group"),
fmt::format(_("Switched group to {0}"),
d->imManager_.currentGroup().name()),
3000);
}
d->lastGroup_ = newGroup;
}));
d->eventWatchers_.emplace_back(d->watchEvent(
EventType::InputContextCapabilityAboutToChange,
EventWatcherPhase::ReservedFirst, [this](Event &event) {
auto &capChanged =
static_cast<CapabilityAboutToChangeEvent &>(event);
if (!capChanged.inputContext()->hasFocus()) {
return;
}
if (!shouldSwitchIM(capChanged.oldFlags(), capChanged.newFlags())) {
return;
}
InputContextSwitchInputMethodEvent switchIM(
InputMethodSwitchedReason::CapabilityChanged,
inputMethod(capChanged.inputContext()),
capChanged.inputContext());
deactivateInputMethod(switchIM);
}));
d->eventWatchers_.emplace_back(d->watchEvent(
EventType::InputContextCapabilityChanged,
EventWatcherPhase::ReservedFirst, [this](Event &event) {
auto &capChanged = static_cast<CapabilityChangedEvent &>(event);
if (!capChanged.inputContext()->hasFocus()) {
return;
}
if (!shouldSwitchIM(capChanged.oldFlags(), capChanged.newFlags())) {
return;
}
InputContextSwitchInputMethodEvent switchIM(
InputMethodSwitchedReason::CapabilityChanged, "",
capChanged.inputContext());
activateInputMethod(switchIM);
}));
d->eventWatchers_.emplace_back(watchEvent(
EventType::InputContextKeyEvent, EventWatcherPhase::InputMethod,
[this, d](Event &event) {
auto &keyEvent = static_cast<KeyEvent &>(event);
auto *ic = keyEvent.inputContext();
CheckInputMethodChanged imChangedRAII(ic, d);
auto origKey = keyEvent.origKey().normalize();
struct {
const KeyList &list;
std::function<bool()> check;
std::function<void(bool)> trigger;
} keyHandlers[] = {
{d->globalConfig_.triggerKeys(),
[this]() { return canTrigger(); },
[this, ic](bool totallyReleased) {
return trigger(ic, totallyReleased);
}},
{d->globalConfig_.altTriggerKeys(),
[this, ic]() { return canAltTrigger(ic); },
[this, ic](bool) { return altTrigger(ic); }},
{d->globalConfig_.activateKeys(),
[ic, d]() { return d->canActivate(ic); },
[this, ic](bool) { return activate(ic); }},
{d->globalConfig_.deactivateKeys(),
[ic, d]() { return d->canDeactivate(ic); },
[this, ic](bool) { return deactivate(ic); }},
{d->globalConfig_.enumerateForwardKeys(),
[this, ic]() { return canEnumerate(ic); },
[this, ic](bool) { return enumerate(ic, true); }},
{d->globalConfig_.enumerateBackwardKeys(),
[this, ic]() { return canEnumerate(ic); },
[this, ic](bool) { return enumerate(ic, false); }},
{d->globalConfig_.enumerateGroupForwardKeys(),
[this]() { return canChangeGroup(); },
[ic, d, origKey](bool) {
return d->navigateGroup(ic, origKey, true);
}},
{d->globalConfig_.enumerateGroupBackwardKeys(),
[this]() { return canChangeGroup(); },
[ic, d, origKey](bool) {
return d->navigateGroup(ic, origKey, false);
}},
};
auto *inputState = ic->propertyFor(&d->inputStateFactory_);
int keyReleased = inputState->keyReleased_;
Key lastKeyPressed = inputState->lastKeyPressed_;
// Keep this value, and reset them in the state
inputState->keyReleased_ = -1;
const bool isModifier = origKey.isModifier();
if (keyEvent.isRelease()) {
int idx = 0;
for (auto &keyHandler : keyHandlers) {
if (keyReleased == idx &&
origKey.isReleaseOfModifier(lastKeyPressed) &&
keyHandler.check()) {
if (isModifier) {
keyHandler.trigger(inputState->totallyReleased_);
if (origKey.hasModifier()) {
inputState->totallyReleased_ = false;
}
}
keyEvent.filter();
break;
}
idx++;
}
if (isSingleModifier(origKey)) {
inputState->totallyReleased_ = true;
}
}
if (inputState->pendingGroupIndex_ &&
inputState->totallyReleased_) {
auto *inputState = ic->propertyFor(&d->inputStateFactory_);
if (inputState->imChanged_) {
inputState->imChanged_->ignore();
}
d->acceptGroupChange(lastKeyPressed, ic);
inputState->lastKeyPressed_ = Key();
}
if (!keyEvent.filtered() && !keyEvent.isRelease()) {
int idx = 0;
for (auto &keyHandler : keyHandlers) {
auto keyIdx = origKey.keyListIndex(keyHandler.list);
if (keyIdx >= 0 && keyHandler.check()) {
inputState->keyReleased_ = idx;
inputState->lastKeyPressed_ = origKey;
if (isModifier) {
// don't forward to input method, but make it pass
// through to client.
return keyEvent.filter();
}
keyHandler.trigger(inputState->totallyReleased_);
if (origKey.hasModifier()) {
inputState->totallyReleased_ = false;
}
return keyEvent.filterAndAccept();
}
idx++;
}
}
}));
d->eventWatchers_.emplace_back(watchEvent(
EventType::InputContextKeyEvent, EventWatcherPhase::PreInputMethod,
[d](Event &event) {
auto &keyEvent = static_cast<KeyEvent &>(event);
auto *ic = keyEvent.inputContext();
if (!keyEvent.isRelease() &&
keyEvent.key().checkKeyList(
d->globalConfig_.togglePreeditKeys())) {
ic->setEnablePreedit(!ic->isPreeditEnabled());
if (d->notifications_) {
d->notifications_->call<INotifications::showTip>(
"toggle-preedit", _("Input Method"), "", _("Preedit"),
ic->isPreeditEnabled() ? _("Preedit enabled")
: _("Preedit disabled"),
3000);
}
keyEvent.filterAndAccept();
}
}));
d->eventWatchers_.emplace_back(d->watchEvent(
EventType::InputContextKeyEvent, EventWatcherPhase::ReservedFirst,
[d](Event &event) {
// Update auto save.
d->idleStartTimestamp_ = now(CLOCK_MONOTONIC);
auto &keyEvent = static_cast<KeyEvent &>(event);
auto *ic = keyEvent.inputContext();
auto *inputState = ic->propertyFor(&d->inputStateFactory_);
#ifdef ENABLE_KEYBOARD
auto *xkbState = inputState->customXkbState();
if (xkbState) {
if (auto *mods = findValue(d->stateMask_, ic->display())) {
FCITX_KEYTRACE() << "Update mask to customXkbState";
// Keep latched, but propagate depressed optionally and
// locked.
uint32_t depressed;
if (inputState->isModsAllReleased()) {
depressed = xkb_state_serialize_mods(
xkbState, XKB_STATE_MODS_DEPRESSED);
} else {
depressed = std::get<0>(*mods);
}
if (std::get<0>(*mods) == 0) {
inputState->setModsAllReleased();
}
auto latched = xkb_state_serialize_mods(
xkbState, XKB_STATE_MODS_LATCHED);
auto locked = std::get<2>(*mods);
// set modifiers in depressed if they don't appear in any of
// the final masks
// depressed |= ~(depressed | latched | locked);
FCITX_DEBUG()
<< depressed << " " << latched << " " << locked;
xkb_state_update_mask(xkbState, depressed, latched, locked,
0, 0, 0);
}
const uint32_t effective = xkb_state_serialize_mods(
xkbState, XKB_STATE_MODS_EFFECTIVE);
auto newSym = xkb_state_key_get_one_sym(
xkbState, keyEvent.rawKey().code());
auto newModifier = KeyStates(effective);
auto keymap = xkb_state_get_keymap(xkbState);
if (keyEvent.rawKey().states().test(KeyState::Repeat) &&
xkb_keymap_key_repeats(keymap, keyEvent.rawKey().code())) {
newModifier |= KeyState::Repeat;
}
const uint32_t modsDepressed = xkb_state_serialize_mods(
xkbState, XKB_STATE_MODS_DEPRESSED);
const uint32_t modsLatched =
xkb_state_serialize_mods(xkbState, XKB_STATE_MODS_LATCHED);
const uint32_t modsLocked =
xkb_state_serialize_mods(xkbState, XKB_STATE_MODS_LOCKED);
FCITX_KEYTRACE() << "Current mods: " << modsDepressed << " "
<< modsLatched << " " << modsLocked;
auto newCode = keyEvent.rawKey().code();
Key key(static_cast<KeySym>(newSym), newModifier, newCode);
FCITX_KEYTRACE()
<< "Custom Xkb translated Key: " << key.toString();
keyEvent.setRawKey(key);
}
#endif
FCITX_KEYTRACE() << "KeyEvent: " << keyEvent.key()
<< " rawKey: " << keyEvent.rawKey()
<< " origKey: " << keyEvent.origKey()
<< " Release:" << keyEvent.isRelease()
<< " keycode: " << keyEvent.origKey().code();
if (keyEvent.isRelease()) {
return;
}
inputState->hideInputMethodInfo();
}));
d->eventWatchers_.emplace_back(
watchEvent(EventType::InputContextKeyEvent,
EventWatcherPhase::InputMethod, [this](Event &event) {
auto &keyEvent = static_cast<KeyEvent &>(event);
auto *ic = keyEvent.inputContext();
auto *engine = inputMethodEngine(ic);
const auto *entry = inputMethodEntry(ic);
if (!engine || !entry) {
return;
}
engine->keyEvent(*entry, keyEvent);
}));
d->eventWatchers_.emplace_back(watchEvent(
EventType::InputContextVirtualKeyboardEvent,
EventWatcherPhase::InputMethod, [this](Event &event) {
auto &keyEvent = static_cast<VirtualKeyboardEvent &>(event);
auto *ic = keyEvent.inputContext();
auto *engine = inputMethodEngine(ic);
const auto *entry = inputMethodEntry(ic);
if (!engine || !entry) {
return;
}
engine->virtualKeyboardEvent(*entry, keyEvent);
}));
d->eventWatchers_.emplace_back(watchEvent(
EventType::InputContextInvokeAction, EventWatcherPhase::InputMethod,
[this](Event &event) {
auto &invokeActionEvent = static_cast<InvokeActionEvent &>(event);
auto *ic = invokeActionEvent.inputContext();
auto *engine = inputMethodEngine(ic);
const auto *entry = inputMethodEntry(ic);
if (!engine || !entry) {
return;
}
engine->invokeAction(*entry, invokeActionEvent);
}));
d->eventWatchers_.emplace_back(d->watchEvent(
EventType::InputContextKeyEvent, EventWatcherPhase::ReservedLast,
[this](Event &event) {
auto &keyEvent = static_cast<KeyEvent &>(event);
auto *ic = keyEvent.inputContext();
auto *engine = inputMethodEngine(ic);
const auto *entry = inputMethodEntry(ic);
if (!engine || !entry) {
return;
}
engine->filterKey(*entry, keyEvent);
emit<Instance::KeyEventResult>(keyEvent);
#ifdef ENABLE_KEYBOARD
if (keyEvent.forward()) {
FCITX_D();
// Always let the release key go through, since it shouldn't
// produce character. Otherwise it may wrongly trigger wayland
// client side repetition.
if (keyEvent.isRelease()) {
keyEvent.filter();
return;
}
auto *inputState = ic->propertyFor(&d->inputStateFactory_);
if (auto *xkbState = inputState->customXkbState()) {
if (auto utf32 = xkb_state_key_get_utf32(
xkbState, keyEvent.key().code())) {
// Ignore newline, return, backspace, tab, and delete.
if (utf32 == '\n' || utf32 == '\b' || utf32 == '\r' ||
utf32 == '\t' || utf32 == '\033' ||
utf32 == '\x7f') {
return;
}
if (keyEvent.key().states().test(KeyState::Ctrl) ||
keyEvent.rawKey().sym() ==
keyEvent.origKey().sym()) {
return;
}
FCITX_KEYTRACE() << "Will commit char: " << utf32;
ic->commitString(utf8::UCS4ToUTF8(utf32));