Fcitx
instance.cpp
1 /*
2  * SPDX-FileCopyrightText: 2016-2016 CSSlayer <wengxt@gmail.com>
3  *
4  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  */
7 #include "config.h"
8 
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <algorithm>
12 #include <array>
13 #include <cassert>
14 #include <csignal>
15 #include <cstdint>
16 #include <cstdlib>
17 #include <filesystem>
18 #include <functional>
19 #include <iostream>
20 #include <iterator>
21 #include <memory>
22 #include <optional>
23 #include <stdexcept>
24 #include <string>
25 #include <string_view>
26 #include <tuple>
27 #include <unordered_map>
28 #include <unordered_set>
29 #include <utility>
30 #include <vector>
31 #include <getopt.h>
32 #include "fcitx-config/configuration.h"
33 #include "fcitx-config/iniparser.h"
34 #include "fcitx-config/option.h"
36 #include "fcitx-utils/cutf8.h"
37 #include "fcitx-utils/environ.h"
38 #include "fcitx-utils/event.h"
39 #include "fcitx-utils/eventdispatcher.h"
40 #include "fcitx-utils/eventloopinterface.h"
41 #include "fcitx-utils/fs.h"
42 #include "fcitx-utils/handlertable.h"
43 #include "fcitx-utils/i18n.h"
44 #include "fcitx-utils/key.h"
45 #include "fcitx-utils/keysym.h"
46 #include "fcitx-utils/log.h"
47 #include "fcitx-utils/macros.h"
48 #include "fcitx-utils/misc.h"
49 #include "fcitx-utils/misc_p.h"
53 #include "fcitx-utils/utf8.h"
54 #include "../../modules/notifications/notifications_public.h"
55 #include "addonmanager.h"
56 #include "event.h"
57 #include "focusgroup.h"
58 #include "globalconfig.h"
59 #include "inputcontextmanager.h"
60 #include "inputcontextproperty.h"
61 #include "inputmethodengine.h"
62 #include "inputmethodentry.h"
63 #include "inputmethodgroup.h"
64 #include "inputmethodmanager.h"
65 #include "instance.h"
66 #include "instance_p.h"
67 #include "misc_p.h"
68 #include "statusarea.h"
69 #include "text.h"
70 #include "userinterface.h"
71 #include "userinterfacemanager.h"
72 
73 #ifdef HAVE_SYS_WAIT_H
74 #include <sys/wait.h>
75 #endif
76 
77 #ifdef ENABLE_X11
78 #define FCITX_NO_XCB
79 #include <../modules/xcb/xcb_public.h>
80 #endif
81 
82 #ifdef ENABLE_KEYBOARD
83 #include <xkbcommon/xkbcommon-compose.h>
84 #include <xkbcommon/xkbcommon.h>
85 #endif
86 
87 FCITX_DEFINE_LOG_CATEGORY(keyTrace, "key_trace");
88 
89 namespace fcitx {
90 
91 namespace {
92 
93 constexpr uint64_t AutoSaveMinInUsecs = 60ULL * 1000000ULL; // 30 minutes
94 constexpr uint64_t AutoSaveIdleTime = 60ULL * 1000000ULL; // 1 minutes
95 
96 FCITX_CONFIGURATION(DefaultInputMethod,
97  Option<std::vector<std::string>> defaultInputMethods{
98  this, "DefaultInputMethod", "DefaultInputMethod"};
99  Option<std::vector<std::string>> extraLayouts{
100  this, "ExtraLayout", "ExtraLayout"};);
101 
102 void initAsDaemon() {
103 #ifndef _WIN32
104  pid_t pid = fork();
105  if (pid > 0) {
106  waitpid(pid, nullptr, 0);
107  exit(0);
108  }
109  setsid();
110  auto oldint = signal(SIGINT, SIG_IGN);
111  auto oldhup = signal(SIGHUP, SIG_IGN);
112  auto oldquit = signal(SIGQUIT, SIG_IGN);
113  auto oldpipe = signal(SIGPIPE, SIG_IGN);
114  auto oldttou = signal(SIGTTOU, SIG_IGN);
115  auto oldttin = signal(SIGTTIN, SIG_IGN);
116  auto oldchld = signal(SIGCHLD, SIG_IGN);
117  if (fork() > 0) {
118  exit(0);
119  }
120  (void)chdir("/");
121 
122  signal(SIGINT, oldint);
123  signal(SIGHUP, oldhup);
124  signal(SIGQUIT, oldquit);
125  signal(SIGPIPE, oldpipe);
126  signal(SIGTTOU, oldttou);
127  signal(SIGTTIN, oldttin);
128  signal(SIGCHLD, oldchld);
129 #endif
130 }
131 
132 // Whether the input context is forced to the fallback keyboard input
133 // method. Password fields only count when input method is not allowed for
134 // password fields, since otherwise they use the regular input method. This
135 // must mirror the condition in Instance::inputMethod().
136 bool isInputMethodDisabled(const CapabilityFlags &flags,
137  bool allowInputMethodForPassword) {
138  return flags.test(CapabilityFlag::Disable) ||
139  (flags.test(CapabilityFlag::Password) &&
140  !allowInputMethodForPassword);
141 }
142 
143 // Switch IM when these capabilities change.
144 bool shouldSwitchIM(const CapabilityFlags &oldFlags,
145  const CapabilityFlags &newFlags,
146  bool allowInputMethodForPassword) {
147  return isInputMethodDisabled(oldFlags, allowInputMethodForPassword) !=
148  isInputMethodDisabled(newFlags, allowInputMethodForPassword);
149 }
150 
151 } // namespace
152 
153 void InstanceArgument::printUsage() const {
154  std::cout
155  << "Usage: " << argv0 << " [Option]\n"
156  << " --disable <addon names>\tA comma separated list of addons to "
157  "be disabled.\n"
158  << "\t\t\t\t\"all\" can be used to disable all addons.\n"
159  << " --enable <addon names>\tA comma separated list of addons to "
160  "be enabled.\n"
161  << "\t\t\t\t\"all\" can be used to enable all addons.\n"
162  << "\t\t\t\tThis value will override the value in the flag "
163  "--disable.\n"
164  << " --verbose <logging rule>\tSet the logging rule for "
165  "displaying message.\n"
166  << "\t\t\t\tSyntax: category1=level1,category2=level2, ...\n"
167  << "\t\t\t\tE.g. default=4,key_trace=5\n"
168  << "\t\t\t\tLevels are numbers ranging from 0 to 5.\n"
169  << "\t\t\t\t\t0 - NoLog\n"
170  << "\t\t\t\t\t1 - Fatal\n"
171  << "\t\t\t\t\t2 - Error\n"
172  << "\t\t\t\t\t3 - Warn\n"
173  << "\t\t\t\t\t4 - Info (default)\n"
174  << "\t\t\t\t\t5 - Debug\n"
175  << "\t\t\t\tSome built-in categories are:\n"
176  << "\t\t\t\t\tdefault - miscellaneous category used by fcitx own "
177  "library.\n"
178  << "\t\t\t\t\tkey_trace - print the key event received by fcitx.\n"
179  << "\t\t\t\t\t\"*\" may be used to represent all logging "
180  "category.\n"
181  << " -u, --ui <addon name>\t\tSet the UI addon to be used.\n"
182  << " -d\t\t\t\tRun as a daemon.\n"
183  << " -D\t\t\t\tDo not run as a daemon (default).\n"
184  << " -s <seconds>\t\t\tNumber of seconds to wait before start.\n"
185  << " -k, --keep\t\t\tKeep running even the main display is "
186  "disconnected.\n"
187  << " -r, --replace\t\t\tReplace the existing instance.\n"
188  << " -o --option <option>\t\tPass the option to addons\n"
189  << "\t\t\t\t<option> is in format like:\n"
190  << "\t\t\t\tname1=opt1a:opt1b,name2=opt2a:opt2b... .\n"
191  << " -v, --version\t\t\tShow version and quit.\n"
192  << " -h, --help\t\t\tShow this help message and quit.\n";
193 }
194 
195 InstancePrivate::InstancePrivate(Instance *q) : QPtrHolder<Instance>(q) {
196 #ifdef ENABLE_KEYBOARD
197  const auto &locale = getCurrentLocale();
198  assert(!locale.empty());
199  xkbContext_.reset(xkb_context_new(XKB_CONTEXT_NO_FLAGS));
200  if (xkbContext_) {
201  xkb_context_set_log_level(xkbContext_.get(), XKB_LOG_LEVEL_CRITICAL);
202  xkbComposeTable_.reset(xkb_compose_table_new_from_locale(
203  xkbContext_.get(), locale.data(), XKB_COMPOSE_COMPILE_NO_FLAGS));
204  if (!xkbComposeTable_) {
205  FCITX_INFO()
206  << "Trying to fallback to compose table for en_US.UTF-8";
207  xkbComposeTable_.reset(xkb_compose_table_new_from_locale(
208  xkbContext_.get(), "en_US.UTF-8",
209  XKB_COMPOSE_COMPILE_NO_FLAGS));
210  }
211  if (!xkbComposeTable_) {
212  FCITX_WARN()
213  << "No compose table is loaded, you may want to check your "
214  "locale settings.";
215  }
216  }
217 #endif
218 }
219 
220 std::unique_ptr<HandlerTableEntry<EventHandler>>
221 InstancePrivate::watchEvent(EventType type, EventWatcherPhase phase,
222  EventHandler callback) {
223  return eventHandlers_[type][phase].add(std::move(callback));
224 }
225 
226 #ifdef ENABLE_KEYBOARD
227 xkb_keymap *InstancePrivate::keymap(const std::string &display,
228  const std::string &layout,
229  const std::string &variant) {
230  auto layoutAndVariant = stringutils::concat(layout, "-", variant);
231  if (auto *keymapPtr = findValue(keymapCache_[display], layoutAndVariant)) {
232  return (*keymapPtr).get();
233  }
234  struct xkb_rule_names names;
235  names.layout = layout.c_str();
236  names.variant = variant.c_str();
237  std::tuple<std::string, std::string, std::string> xkbParam;
238  if (auto *param = findValue(xkbParams_, display)) {
239  xkbParam = *param;
240  } else {
241  if (!xkbParams_.empty()) {
242  xkbParam = xkbParams_.begin()->second;
243  } else {
244  xkbParam = std::make_tuple(DEFAULT_XKB_RULES, "pc101", "");
245  }
246  }
247  if (globalConfig_.overrideXkbOption()) {
248  std::get<2>(xkbParam) = globalConfig_.customXkbOption();
249  }
250  names.rules = std::get<0>(xkbParam).c_str();
251  names.model = std::get<1>(xkbParam).c_str();
252  names.options = std::get<2>(xkbParam).c_str();
253  UniqueCPtr<xkb_keymap, xkb_keymap_unref> keymap(xkb_keymap_new_from_names(
254  xkbContext_.get(), &names, XKB_KEYMAP_COMPILE_NO_FLAGS));
255  auto result =
256  keymapCache_[display].emplace(layoutAndVariant, std::move(keymap));
257  assert(result.second);
258  return result.first->second.get();
259 }
260 #endif
261 
262 std::pair<std::unordered_set<std::string>, std::unordered_set<std::string>>
263 InstancePrivate::overrideAddons() {
264  std::unordered_set<std::string> enabled;
265  std::unordered_set<std::string> disabled;
266  for (const auto &addon : globalConfig_.enabledAddons()) {
267  enabled.insert(addon);
268  }
269  for (const auto &addon : globalConfig_.disabledAddons()) {
270  enabled.erase(addon);
271  disabled.insert(addon);
272  }
273  for (const auto &addon : arg_.enableList) {
274  disabled.erase(addon);
275  enabled.insert(addon);
276  }
277  for (const auto &addon : arg_.disableList) {
278  enabled.erase(addon);
279  disabled.insert(addon);
280  }
281  return {enabled, disabled};
282 }
283 
284 void InstancePrivate::buildDefaultGroup() {
285  /// Figure out XKB layout information from system.
286  auto *defaultGroup = q_func()->defaultFocusGroup();
287  bool infoFound = false;
288  std::string layouts;
289  std::string variants;
290  auto guessLayout = [this, &layouts, &variants,
291  &infoFound](FocusGroup *focusGroup) {
292  // For now we can only do this on X11.
293  if (!focusGroup->display().starts_with("x11:")) {
294  return true;
295  }
296 #ifdef ENABLE_X11
297  auto *xcb = addonManager_.addon("xcb");
298  auto x11Name = focusGroup->display().substr(4);
299  if (xcb) {
300  auto rules = xcb->call<IXCBModule::xkbRulesNames>(x11Name);
301  if (!rules[2].empty()) {
302  layouts = rules[2];
303  variants = rules[3];
304  infoFound = true;
305  return false;
306  }
307  }
308 #else
309  FCITX_UNUSED(this);
310  FCITX_UNUSED(layouts);
311  FCITX_UNUSED(variants);
312  FCITX_UNUSED(infoFound);
313 #endif
314  return true;
315  };
316  if (!defaultGroup || guessLayout(defaultGroup)) {
317  icManager_.foreachGroup(
318  [defaultGroup, &guessLayout](FocusGroup *focusGroup) {
319  if (defaultGroup == focusGroup) {
320  return true;
321  }
322  return guessLayout(focusGroup);
323  });
324  }
325  if (!infoFound) {
326  layouts = "us";
327  variants = "";
328  }
329 
330  // layouts and variants are comma separated list for layout information.
331  constexpr char imNamePrefix[] = "keyboard-";
332  auto layoutTokens =
333  stringutils::split(layouts, ",", stringutils::SplitBehavior::KeepEmpty);
334  auto variantTokens = stringutils::split(
335  variants, ",", stringutils::SplitBehavior::KeepEmpty);
336  auto size = std::max(layoutTokens.size(), variantTokens.size());
337  // Make sure we have token to be the same size.
338  layoutTokens.resize(size);
339  variantTokens.resize(size);
340 
341  OrderedSet<std::string> imLayouts;
342  for (decltype(size) i = 0; i < size; i++) {
343  if (layoutTokens[i].empty()) {
344  continue;
345  }
346  std::string layoutName = layoutTokens[i];
347  if (!variantTokens[i].empty()) {
348  layoutName = stringutils::concat(layoutName, "-", variantTokens[i]);
349  }
350 
351  // Skip the layout if we don't have it.
352  if (!imManager_.entry(stringutils::concat(imNamePrefix, layoutName))) {
353  continue;
354  }
355  // Avoid add duplicate entry. layout might have weird duplicate.
356  imLayouts.pushBack(layoutName);
357  }
358 
359  // Load the default profile.
360  auto lang = stripLanguage(getCurrentLanguage());
361  DefaultInputMethod defaultIMConfig;
362  readAsIni(defaultIMConfig, StandardPathsType::PkgData,
363  std::filesystem::path("default") / lang);
364 
365  // Add extra layout from profile.
366  for (const auto &extraLayout : defaultIMConfig.extraLayouts.value()) {
367  if (!imManager_.entry(stringutils::concat(imNamePrefix, extraLayout))) {
368  continue;
369  }
370  imLayouts.pushBack(extraLayout);
371  }
372 
373  // Make sure imLayouts is not empty.
374  if (imLayouts.empty()) {
375  imLayouts.pushBack("us");
376  }
377 
378  // Figure out the first available default input method.
379  std::string defaultIM;
380  for (const auto &im : defaultIMConfig.defaultInputMethods.value()) {
381  if (imManager_.entry(im)) {
382  defaultIM = im;
383  break;
384  }
385  }
386 
387  // Create a group for each layout.
388  std::vector<std::string> groupOrders;
389  for (const auto &imLayout : imLayouts) {
390  std::string groupName;
391  if (imLayouts.size() == 1) {
392  groupName = _("Default");
393  } else {
394  groupName = _("Group {}", imManager_.groupCount() + 1);
395  }
396  imManager_.addEmptyGroup(groupName);
397  groupOrders.push_back(groupName);
398  InputMethodGroup group(groupName);
399  group.inputMethodList().emplace_back(
400  InputMethodGroupItem(stringutils::concat(imNamePrefix, imLayout)));
401  if (!defaultIM.empty()) {
402  group.inputMethodList().emplace_back(
403  InputMethodGroupItem(defaultIM));
404  }
405  FCITX_INFO() << "Items in " << groupName << ": "
406  << group.inputMethodList();
407  group.setDefaultLayout(imLayout);
408  imManager_.setGroup(std::move(group));
409  }
410  FCITX_INFO() << "Generated groups: " << groupOrders;
411  imManager_.setGroupOrder(groupOrders);
412 }
413 
414 void InstancePrivate::showInputMethodInformation(InputContext *ic) {
415  FCITX_Q();
416  auto *inputState = ic->propertyFor(&inputStateFactory_);
417  auto *engine = q->inputMethodEngine(ic);
418  const auto *entry = q->inputMethodEntry(ic);
419  auto &imManager = q->inputMethodManager();
420 
421  if (!inputState->isActive() &&
422  !globalConfig_.showFirstInputMethodInformation()) {
423  return;
424  }
425 
426  std::string display;
427  if (engine) {
428  auto subMode = engine->subMode(*entry, *ic);
429  auto subModeLabel = engine->subModeLabel(*entry, *ic);
430  auto name = globalConfig_.compactInputMethodInformation() &&
431  !entry->label().empty()
432  ? entry->label()
433  : entry->name();
434  if (globalConfig_.compactInputMethodInformation() &&
435  !subModeLabel.empty()) {
436  display = std::move(subModeLabel);
437  } else if (subMode.empty()) {
438  display = std::move(name);
439  } else {
440  display = _("{0} ({1})", name, subMode);
441  }
442  } else if (entry) {
443  display = _("{0} (Not available)", entry->name());
444  } else {
445  display = _("(Not available)");
446  }
447  if (!globalConfig_.compactInputMethodInformation() &&
448  imManager.groupCount() > 1) {
449  display = _("Group {0}: {1}", imManager.currentGroup().name(), display);
450  }
451  inputState->showInputMethodInformation(display);
452 }
453 
454 bool InstancePrivate::canActivate(InputContext *ic) {
455  FCITX_Q();
456  if (!q->canTrigger()) {
457  return false;
458  }
459  auto *inputState = ic->propertyFor(&inputStateFactory_);
460  return !inputState->isActive();
461 }
462 
463 bool InstancePrivate::canDeactivate(InputContext *ic) {
464  FCITX_Q();
465  if (!q->canTrigger()) {
466  return false;
467  }
468  auto *inputState = ic->propertyFor(&inputStateFactory_);
469  return inputState->isActive();
470 }
471 
472 void InstancePrivate::navigateGroup(InputContext *ic, const Key &key,
473  bool forward) {
474  auto *inputState = ic->propertyFor(&inputStateFactory_);
475  inputState->pendingGroupIndex_ =
476  (inputState->pendingGroupIndex_ +
477  (forward ? 1 : imManager_.groupCount() - 1)) %
478  imManager_.groupCount();
479  FCITX_DEBUG() << "Switch to group " << inputState->pendingGroupIndex_;
480 
481  if (notifications_ && !isSingleKey(key)) {
482  notifications_->call<INotifications::showTip>(
483  "enumerate-group", _("Input Method"), "input-keyboard",
484  _("Switch group"),
485  _("Switch group to {0}",
486  imManager_.groups()[inputState->pendingGroupIndex_]),
487  3000);
488  }
489 }
490 
491 void InstancePrivate::acceptGroupChange(const Key &key, InputContext *ic) {
492  FCITX_DEBUG() << "Accept group change, isSingleKey: " << key;
493 
494  auto *inputState = ic->propertyFor(&inputStateFactory_);
495  auto groups = imManager_.groups();
496  if (groups.size() > inputState->pendingGroupIndex_) {
497  if (isSingleKey(key)) {
498  FCITX_DEBUG() << "EnumerateGroupTo: "
499  << inputState->pendingGroupIndex_ << " " << key;
500  imManager_.enumerateGroupTo(groups[inputState->pendingGroupIndex_]);
501  } else {
502  FCITX_DEBUG() << "SetCurrentGroup: "
503  << inputState->pendingGroupIndex_ << " " << key;
504  imManager_.setCurrentGroup(groups[inputState->pendingGroupIndex_]);
505  }
506  }
507  inputState->pendingGroupIndex_ = 0;
508 }
509 
510 InputState::InputState(InstancePrivate *d, InputContext *ic)
511  : d_ptr(d), ic_(ic) {
512  active_ = d->globalConfig_.activeByDefault();
513 #ifdef ENABLE_KEYBOARD
514  if (d->xkbComposeTable_) {
515  xkbComposeState_.reset(xkb_compose_state_new(
516  d->xkbComposeTable_.get(), XKB_COMPOSE_STATE_NO_FLAGS));
517  }
518 #endif
519 }
520 
521 void InputState::showInputMethodInformation(const std::string &name) {
522  ic_->inputPanel().setAuxUp(Text(name));
523  ic_->updateUserInterface(UserInterfaceComponent::InputPanel);
524  lastInfo_ = name;
525  imInfoTimer_ = d_ptr->eventLoop_.addTimeEvent(
526  CLOCK_MONOTONIC, now(CLOCK_MONOTONIC) + 1000000, 0,
527  [this](EventSourceTime *, uint64_t) {
528  hideInputMethodInfo();
529  return true;
530  });
531 }
532 
533 #ifdef ENABLE_KEYBOARD
534 xkb_state *InputState::customXkbState(bool refresh) {
535  auto *instance = d_ptr->q_func();
536  const InputMethodGroup &group = d_ptr->imManager_.currentGroup();
537  const auto im = instance->inputMethod(ic_);
538  auto layout = group.layoutFor(im);
539  if (layout.empty() && im.starts_with("keyboard-")) {
540  layout = im.substr(9);
541  }
542  if (layout.empty() || layout == group.defaultLayout()) {
543  // Use system one.
544  xkbState_.reset();
545  modsAllReleased_ = false;
546  lastXkbLayout_.clear();
547  return nullptr;
548  }
549 
550  if (layout == lastXkbLayout_ && !refresh) {
551  return xkbState_.get();
552  }
553 
554  lastXkbLayout_ = layout;
555  const auto layoutAndVariant = parseLayout(layout);
556  if (auto *keymap = d_ptr->keymap(ic_->display(), layoutAndVariant.first,
557  layoutAndVariant.second)) {
558  xkbState_.reset(xkb_state_new(keymap));
559  } else {
560  xkbState_.reset();
561  }
562  modsAllReleased_ = false;
563  return xkbState_.get();
564 }
565 #endif
566 
567 void InputState::setActive(bool active) {
568  if (active_ != active) {
569  active_ = active;
570  ic_->updateProperty(&d_ptr->inputStateFactory_);
571  }
572 }
573 
574 void InputState::setLocalIM(const std::string &localIM) {
575  if (localIM_ != localIM) {
576  localIM_ = localIM;
577  ic_->updateProperty(&d_ptr->inputStateFactory_);
578  }
579 }
580 
581 void InputState::copyTo(InputContextProperty *other) {
582  auto *otherState = static_cast<InputState *>(other);
583  if (otherState->active_ == active_ && otherState->localIM_ == localIM_) {
584  return;
585  }
586 
587  if (otherState->ic_->hasFocus()) {
588  FCITX_DEBUG() << "Sync state to focused ic: "
589  << otherState->ic_->program();
590  CheckInputMethodChanged imChangedRAII(otherState->ic_, d_ptr);
591  otherState->active_ = active_;
592  otherState->localIM_ = localIM_;
593  } else {
594  otherState->active_ = active_;
595  otherState->localIM_ = localIM_;
596  }
597 }
598 
599 void InputState::reset() {
600 #ifdef ENABLE_KEYBOARD
601  if (xkbComposeState_) {
602  xkb_compose_state_reset(xkbComposeState_.get());
603  }
604 #endif
605  pendingGroupIndex_ = 0;
606  keyReleased_ = -1;
607  lastKeyPressed_ = Key();
608  lastKeyPressedTime_ = 0;
609  totallyReleased_ = true;
610 }
611 
612 void InputState::hideInputMethodInfo() {
613  if (!imInfoTimer_) {
614  return;
615  }
616  imInfoTimer_.reset();
617  auto &panel = ic_->inputPanel();
618  if (panel.auxDown().empty() && panel.preedit().empty() &&
619  panel.clientPreedit().empty() &&
620  (!panel.candidateList() || panel.candidateList()->empty()) &&
621  panel.auxUp().size() == 1 && panel.auxUp().stringAt(0) == lastInfo_) {
622  panel.reset();
623  ic_->updateUserInterface(UserInterfaceComponent::InputPanel);
624  }
625 }
626 
627 #ifdef ENABLE_KEYBOARD
628 void InputState::resetXkbState() {
629  lastXkbLayout_.clear();
630  xkbState_.reset();
631 }
632 #endif
633 
634 CheckInputMethodChanged::CheckInputMethodChanged(InputContext *ic,
635  InstancePrivate *instance)
636  : instance_(instance->q_func()), instancePrivate_(instance),
637  ic_(ic->watch()), inputMethod_(instance_->inputMethod(ic)),
638  reason_(InputMethodSwitchedReason::Other) {
639  auto *inputState = ic->propertyFor(&instance->inputStateFactory_);
640  if (!inputState->imChanged_) {
641  inputState->imChanged_ = this;
642  } else {
643  ic_.unwatch();
644  }
645 }
646 
647 CheckInputMethodChanged::~CheckInputMethodChanged() {
648  if (!ic_.isValid()) {
649  return;
650  }
651  auto *ic = ic_.get();
652  auto *inputState = ic->propertyFor(&instancePrivate_->inputStateFactory_);
653  inputState->imChanged_ = nullptr;
654  if (inputMethod_ != instance_->inputMethod(ic) && !ignore_) {
655  instance_->postEvent(
656  InputContextSwitchInputMethodEvent(reason_, inputMethod_, ic));
657  }
658 }
659 
660 Instance::Instance(int argc, char **argv) {
661  InstanceArgument arg;
662  arg.parseOption(argc, argv);
663  if (arg.quietQuit) {
664  throw InstanceQuietQuit();
665  }
666 
667  if (arg.runAsDaemon) {
668  initAsDaemon();
669  }
670 
671  if (arg.overrideDelay > 0) {
672  sleep(arg.overrideDelay);
673  }
674 
675  // we need fork before this
676  d_ptr = std::make_unique<InstancePrivate>(this);
677  FCITX_D();
678  d->arg_ = arg;
679  d->eventDispatcher_.attach(&d->eventLoop_);
680  d->addonManager_.setInstance(this);
681  d->addonManager_.setAddonOptions(arg.addonOptions_);
682  d->icManager_.setInstance(this);
683  d->tempModeManager_ = std::make_unique<TempModeManager>(this);
684  d->connections_.emplace_back(
685  d->imManager_.connect<InputMethodManager::CurrentGroupAboutToChange>(
686  [this, d](const std::string &lastGroup) {
687  d->icManager_.foreachFocused([this](InputContext *ic) {
688  assert(ic->hasFocus());
689  InputContextSwitchInputMethodEvent event(
690  InputMethodSwitchedReason::GroupChange, inputMethod(ic),
691  ic);
692  deactivateInputMethod(event);
693  return true;
694  });
695  d->lastGroup_ = lastGroup;
697  }));
698  d->connections_.emplace_back(
699  d->imManager_.connect<InputMethodManager::CurrentGroupChanged>(
700  [this, d](const std::string &newGroup) {
701  d->icManager_.foreachFocused([this](InputContext *ic) {
702  assert(ic->hasFocus());
703  InputContextSwitchInputMethodEvent event(
704  InputMethodSwitchedReason::GroupChange, "", ic);
705  activateInputMethod(event);
706  return true;
707  });
708  postEvent(InputMethodGroupChangedEvent());
709  if (!d->lastGroup_.empty() && !newGroup.empty() &&
710  d->lastGroup_ != newGroup && d->notifications_ &&
711  d->imManager_.groupCount() > 1) {
712  d->notifications_->call<INotifications::showTip>(
713  "enumerate-group", _("Input Method"), "input-keyboard",
714  _("Switch group"),
715  _("Switched group to {0}",
716  d->imManager_.currentGroup().name()),
717  3000);
718  }
719  d->lastGroup_ = newGroup;
720  }));
721 
722  d->eventWatchers_.emplace_back(d->watchEvent(
723  EventType::InputContextCapabilityAboutToChange,
724  EventWatcherPhase::ReservedFirst, [this, d](Event &event) {
725  auto &capChanged =
726  static_cast<CapabilityAboutToChangeEvent &>(event);
727  if (!capChanged.inputContext()->hasFocus()) {
728  return;
729  }
730 
731  if (!shouldSwitchIM(
732  capChanged.oldFlags(), capChanged.newFlags(),
733  d->globalConfig_.allowInputMethodForPassword())) {
734  return;
735  }
736 
739  inputMethod(capChanged.inputContext()),
740  capChanged.inputContext());
741  deactivateInputMethod(switchIM);
742  }));
743  d->eventWatchers_.emplace_back(d->watchEvent(
744  EventType::InputContextCapabilityChanged,
745  EventWatcherPhase::ReservedFirst, [this, d](Event &event) {
746  auto &capChanged = static_cast<CapabilityChangedEvent &>(event);
747  if (!capChanged.inputContext()->hasFocus()) {
748  return;
749  }
750 
751  if (!shouldSwitchIM(
752  capChanged.oldFlags(), capChanged.newFlags(),
753  d->globalConfig_.allowInputMethodForPassword())) {
754  return;
755  }
756 
759  capChanged.inputContext());
760  activateInputMethod(switchIM);
761  }));
762 
763  d->eventWatchers_.emplace_back(watchEvent(
764  EventType::InputContextKeyEvent, EventWatcherPhase::InputMethod,
765  [this, d](Event &event) {
766  auto &keyEvent = static_cast<KeyEvent &>(event);
767  auto *ic = keyEvent.inputContext();
768  CheckInputMethodChanged imChangedRAII(ic, d);
769  auto origKey = keyEvent.origKey().normalize();
770 
771  struct {
772  const KeyList &list;
773  std::function<bool()> check;
774  std::function<void(bool)> trigger;
775  } keyHandlers[] = {
776  {.list = d->globalConfig_.triggerKeys(),
777  .check = [this]() { return canTrigger(); },
778  .trigger =
779  [this, ic](bool totallyReleased) {
780  return trigger(ic, totallyReleased);
781  }},
782  {.list = d->globalConfig_.altTriggerKeys(),
783  .check = [this, ic]() { return canAltTrigger(ic); },
784  .trigger = [this, ic](bool) { return altTrigger(ic); }},
785  {.list = d->globalConfig_.activateKeys(),
786  .check = [ic, d]() { return d->canActivate(ic); },
787  .trigger = [this, ic](bool) { return activate(ic); }},
788  {.list = d->globalConfig_.deactivateKeys(),
789  .check = [ic, d]() { return d->canDeactivate(ic); },
790  .trigger = [this, ic](bool) { return deactivate(ic); }},
791  {.list = d->globalConfig_.enumerateForwardKeys(),
792  .check = [this, ic]() { return canEnumerate(ic); },
793  .trigger = [this, ic](bool) { return enumerate(ic, true); }},
794  {.list = d->globalConfig_.enumerateBackwardKeys(),
795  .check = [this, ic]() { return canEnumerate(ic); },
796  .trigger = [this, ic](bool) { return enumerate(ic, false); }},
797  {.list = d->globalConfig_.enumerateGroupForwardKeys(),
798  .check = [this]() { return canChangeGroup(); },
799  .trigger = [ic, d, origKey](
800  bool) { d->navigateGroup(ic, origKey, true); }},
801  {.list = d->globalConfig_.enumerateGroupBackwardKeys(),
802  .check = [this]() { return canChangeGroup(); },
803  .trigger =
804  [ic, d, origKey](bool) {
805  d->navigateGroup(ic, origKey, false);
806  }},
807  };
808 
809  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
810  int keyReleased = inputState->keyReleased_;
811  Key lastKeyPressed = inputState->lastKeyPressed_;
812  // Keep this value, and reset them in the state
813  inputState->keyReleased_ = -1;
814  const bool isModifier = origKey.isModifier();
815  if (keyEvent.isRelease()) {
816  int idx = 0;
817  for (auto &keyHandler : keyHandlers) {
818  if (keyReleased == idx &&
819  origKey.isReleaseOfModifier(lastKeyPressed) &&
820  keyHandler.check()) {
821  if (isModifier) {
822  if (d->globalConfig_.checkModifierOnlyKeyTimeout(
823  inputState->lastKeyPressedTime_)) {
824  keyHandler.trigger(
825  inputState->totallyReleased_);
826  }
827  inputState->lastKeyPressedTime_ = 0;
828  if (origKey.hasModifier()) {
829  inputState->totallyReleased_ = false;
830  }
831  }
832  keyEvent.filter();
833  break;
834  }
835  idx++;
836  }
837  if (isSingleModifier(origKey)) {
838  inputState->totallyReleased_ = true;
839  }
840  }
841 
842  if (inputState->pendingGroupIndex_ &&
843  inputState->totallyReleased_) {
844  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
845  if (inputState->imChanged_) {
846  inputState->imChanged_->ignore();
847  }
848  d->acceptGroupChange(lastKeyPressed, ic);
849  inputState->lastKeyPressed_ = Key();
850  }
851 
852  if (!keyEvent.filtered() && !keyEvent.isRelease()) {
853  int idx = 0;
854  for (auto &keyHandler : keyHandlers) {
855  auto keyIdx = origKey.keyListIndex(keyHandler.list);
856  if (keyIdx >= 0 && keyHandler.check()) {
857  inputState->keyReleased_ = idx;
858  inputState->lastKeyPressed_ = origKey;
859  if (isModifier) {
860  inputState->lastKeyPressedTime_ =
861  now(CLOCK_MONOTONIC);
862  // don't forward to input method, but make it pass
863  // through to client.
864  keyEvent.filter();
865  return;
866  }
867  keyHandler.trigger(inputState->totallyReleased_);
868  if (origKey.hasModifier()) {
869  inputState->totallyReleased_ = false;
870  }
871  keyEvent.filterAndAccept();
872  return;
873  }
874  idx++;
875  }
876  }
877  }));
878  d->eventWatchers_.emplace_back(watchEvent(
879  EventType::InputContextKeyEvent, EventWatcherPhase::PreInputMethod,
880  [d](Event &event) {
881  auto &keyEvent = static_cast<KeyEvent &>(event);
882  auto *ic = keyEvent.inputContext();
883  if (!keyEvent.isRelease() &&
884  keyEvent.key().checkKeyList(
885  d->globalConfig_.togglePreeditKeys())) {
886  // Clear client preedit on disable.
887  ic->reset();
888  ic->setEnablePreedit(!ic->isPreeditEnabled());
889  if (d->notifications_) {
890  d->notifications_->call<INotifications::showTip>(
891  "toggle-preedit", _("Input Method"), "", _("Preedit"),
892  ic->isPreeditEnabled() ? _("Preedit enabled")
893  : _("Preedit disabled"),
894  3000);
895  }
896  keyEvent.filterAndAccept();
897  }
898  }));
899  d->eventWatchers_.emplace_back(d->watchEvent(
900  EventType::InputContextKeyEvent, EventWatcherPhase::ReservedFirst,
901  [d](Event &event) {
902  // Update auto save.
903  d->idleStartTimestamp_ = now(CLOCK_MONOTONIC);
904  auto &keyEvent = static_cast<KeyEvent &>(event);
905  auto *ic = keyEvent.inputContext();
906  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
907 #ifdef ENABLE_KEYBOARD
908  auto *xkbState = inputState->customXkbState();
909  if (xkbState) {
910  if (auto *mods = findValue(d->stateMask_, ic->display())) {
911  FCITX_KEYTRACE() << "Update mask to customXkbState";
912  // Keep latched, but propagate depressed optionally and
913  // locked.
914  uint32_t depressed;
915  if (inputState->isModsAllReleased()) {
916  depressed = xkb_state_serialize_mods(
917  xkbState, XKB_STATE_MODS_DEPRESSED);
918  } else {
919  depressed = std::get<0>(*mods);
920  }
921  if (std::get<0>(*mods) == 0) {
922  inputState->setModsAllReleased();
923  }
924  auto latched = xkb_state_serialize_mods(
925  xkbState, XKB_STATE_MODS_LATCHED);
926  auto locked = std::get<2>(*mods);
927 
928  // set modifiers in depressed if they don't appear in any of
929  // the final masks
930  // depressed |= ~(depressed | latched | locked);
931  FCITX_DEBUG()
932  << depressed << " " << latched << " " << locked;
933  xkb_state_update_mask(xkbState, depressed, latched, locked,
934  0, 0, 0);
935  }
936  const uint32_t effective = xkb_state_serialize_mods(
937  xkbState, XKB_STATE_MODS_EFFECTIVE);
938  auto newSym = xkb_state_key_get_one_sym(
939  xkbState, keyEvent.rawKey().code());
940  auto newModifier = KeyStates(effective);
941  auto *keymap = xkb_state_get_keymap(xkbState);
942  if (keyEvent.rawKey().states().test(KeyState::Repeat) &&
943  xkb_keymap_key_repeats(keymap, keyEvent.rawKey().code())) {
944  newModifier |= KeyState::Repeat;
945  }
946 
947  const uint32_t modsDepressed = xkb_state_serialize_mods(
948  xkbState, XKB_STATE_MODS_DEPRESSED);
949  const uint32_t modsLatched =
950  xkb_state_serialize_mods(xkbState, XKB_STATE_MODS_LATCHED);
951  const uint32_t modsLocked =
952  xkb_state_serialize_mods(xkbState, XKB_STATE_MODS_LOCKED);
953  FCITX_KEYTRACE() << "Current mods: " << modsDepressed << " "
954  << modsLatched << " " << modsLocked;
955  auto newCode = keyEvent.rawKey().code();
956  Key key(static_cast<KeySym>(newSym), newModifier, newCode);
957  FCITX_KEYTRACE()
958  << "Custom Xkb translated Key: " << key.toString();
959  keyEvent.setRawKey(key);
960  }
961 #endif
962  FCITX_KEYTRACE() << "KeyEvent: " << keyEvent.key()
963  << " rawKey: " << keyEvent.rawKey()
964  << " origKey: " << keyEvent.origKey()
965  << " Release:" << keyEvent.isRelease()
966  << " keycode: " << keyEvent.origKey().code()
967  << " program: " << ic->program();
968 
969  if (keyEvent.isRelease()) {
970  return;
971  }
972  inputState->hideInputMethodInfo();
973  }));
974  d->eventWatchers_.emplace_back(
976  EventWatcherPhase::InputMethod, [this](Event &event) {
977  auto &keyEvent = static_cast<KeyEvent &>(event);
978  auto *ic = keyEvent.inputContext();
979  auto *engine = inputMethodEngine(ic);
980  const auto *entry = inputMethodEntry(ic);
981  if (!engine || !entry) {
982  return;
983  }
984  engine->keyEvent(*entry, keyEvent);
985  }));
986  d->eventWatchers_.emplace_back(watchEvent(
987  EventType::InputContextVirtualKeyboardEvent,
988  EventWatcherPhase::InputMethod, [this](Event &event) {
989  auto &keyEvent = static_cast<VirtualKeyboardEvent &>(event);
990  auto *ic = keyEvent.inputContext();
991  auto *engine = inputMethodEngine(ic);
992  const auto *entry = inputMethodEntry(ic);
993  if (!engine || !entry) {
994  return;
995  }
996  engine->virtualKeyboardEvent(*entry, keyEvent);
997  }));
998  d->eventWatchers_.emplace_back(watchEvent(
999  EventType::InputContextInvokeAction, EventWatcherPhase::InputMethod,
1000  [this](Event &event) {
1001  auto &invokeActionEvent = static_cast<InvokeActionEvent &>(event);
1002  auto *ic = invokeActionEvent.inputContext();
1003  auto *engine = inputMethodEngine(ic);
1004  const auto *entry = inputMethodEntry(ic);
1005  if (!engine || !entry) {
1006  return;
1007  }
1008  engine->invokeAction(*entry, invokeActionEvent);
1009  }));
1010  d->eventWatchers_.emplace_back(d->watchEvent(
1011  EventType::InputContextKeyEvent, EventWatcherPhase::ReservedLast,
1012  [this](Event &event) {
1013  auto &keyEvent = static_cast<KeyEvent &>(event);
1014  auto *ic = keyEvent.inputContext();
1015  auto *engine = inputMethodEngine(ic);
1016  const auto *entry = inputMethodEntry(ic);
1017  if (!engine || !entry) {
1018  return;
1019  }
1020  engine->filterKey(*entry, keyEvent);
1021  emit<Instance::KeyEventResult>(keyEvent);
1022 #ifdef ENABLE_KEYBOARD
1023  if (keyEvent.forward()) {
1024  FCITX_D();
1025  // Always let the release key go through, since it shouldn't
1026  // produce character. Otherwise it may wrongly trigger wayland
1027  // client side repetition.
1028  if (keyEvent.isRelease()) {
1029  keyEvent.filter();
1030  return;
1031  }
1032  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
1033  if (auto *xkbState = inputState->customXkbState()) {
1034  if (auto utf32 = xkb_state_key_get_utf32(
1035  xkbState, keyEvent.key().code())) {
1036  // Ignore newline, return, backspace, tab, and delete.
1037  if (utf32 == '\n' || utf32 == '\b' || utf32 == '\r' ||
1038  utf32 == '\t' || utf32 == '\033' ||
1039  utf32 == '\x7f') {
1040  return;
1041  }
1042  if (keyEvent.key().states().testAny(
1043  KeyStates{KeyState::Ctrl, KeyState::Alt}) ||
1044  keyEvent.rawKey().sym() ==
1045  keyEvent.origKey().sym()) {
1046  return;
1047  }
1048  FCITX_KEYTRACE() << "Will commit char: " << utf32;
1049  ic->commitString(utf8::UCS4ToUTF8(utf32));
1050  keyEvent.filterAndAccept();
1051  } else if (!keyEvent.key().states().testAny(
1052  KeyStates{KeyState::Ctrl, KeyState::Alt}) &&
1053  keyEvent.rawKey().sym() !=
1054  keyEvent.origKey().sym() &&
1055  Key::keySymToUnicode(keyEvent.origKey().sym()) !=
1056  0) {
1057  // filter key for the case that: origKey will produce
1058  // character, while the translated will not.
1059  keyEvent.filterAndAccept();
1060  }
1061  }
1062  }
1063 #endif
1064  }));
1065  d->eventWatchers_.emplace_back(d->watchEvent(
1066  EventType::InputContextFocusIn, EventWatcherPhase::ReservedFirst,
1067  [this, d](Event &event) {
1068  auto &icEvent = static_cast<InputContextEvent &>(event);
1069  auto isSameProgram = [&icEvent, d]() {
1070  // Check if they are same IC, or they are same program.
1071  return (icEvent.inputContext() == d->lastUnFocusedIc_.get()) ||
1072  (!icEvent.inputContext()->program().empty() &&
1073  (icEvent.inputContext()->program() ==
1074  d->lastUnFocusedProgram_));
1075  };
1076 
1077  if (d->globalConfig_.resetStateWhenFocusIn() ==
1078  PropertyPropagatePolicy::All ||
1079  (d->globalConfig_.resetStateWhenFocusIn() ==
1080  PropertyPropagatePolicy::Program &&
1081  !isSameProgram())) {
1082  if (d->globalConfig_.activeByDefault()) {
1083  activate(icEvent.inputContext());
1084  } else {
1085  deactivate(icEvent.inputContext());
1086  }
1087  }
1088 
1089  activateInputMethod(icEvent);
1090 
1091  auto *inputContext = icEvent.inputContext();
1092  if (!inputContext->clientControlVirtualkeyboardShow()) {
1093  inputContext->showVirtualKeyboard();
1094  }
1095 
1096  if (!d->globalConfig_.showInputMethodInformationWhenFocusIn()) {
1097  return;
1098  }
1099  // Give some time because the cursor location may need some time
1100  // to be updated. Do not check the Disable capability here:
1101  // clients may update the capability for the newly focused
1102  // widget shortly after the focus in, so check it when the
1103  // timer fires instead. This avoids showing the information
1104  // of the fallback keyboard layout for input contexts that
1105  // are about to be disabled, and keeps showing it for input
1106  // contexts that are about to be enabled.
1107  d->focusInImInfoTimer_ = d->eventLoop_.addTimeEvent(
1108  CLOCK_MONOTONIC, now(CLOCK_MONOTONIC) + 30000, 0,
1109  [d, icRef = icEvent.inputContext()->watch()](EventSourceTime *,
1110  uint64_t) {
1111  // Check if ic is still valid, has focus and is not
1112  // disabled.
1113  if (auto *ic = icRef.get();
1114  ic && ic->hasFocus() &&
1115  !ic->capabilityFlags().test(CapabilityFlag::Disable)) {
1116  d->showInputMethodInformation(ic);
1117  }
1118  return true;
1119  });
1120  }));
1121  d->eventWatchers_.emplace_back(d->watchEvent(
1122  EventType::InputContextFocusOut, EventWatcherPhase::ReservedFirst,
1123  [d](Event &event) {
1124  auto &icEvent = static_cast<InputContextEvent &>(event);
1125  auto *ic = icEvent.inputContext();
1126  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
1127  inputState->reset();
1128  if (!ic->capabilityFlags().test(
1129  CapabilityFlag::ClientUnfocusCommit)) {
1130  // do server side commit
1131  auto commit =
1132  ic->inputPanel().clientPreedit().toStringForCommit();
1133  if (!commit.empty()) {
1134  ic->commitString(commit);
1135  }
1136  }
1137  }));
1138  d->eventWatchers_.emplace_back(d->watchEvent(
1139  EventType::InputContextFocusOut, EventWatcherPhase::InputMethod,
1140  [this, d](Event &event) {
1141  auto &icEvent = static_cast<InputContextEvent &>(event);
1142  d->lastUnFocusedProgram_ = icEvent.inputContext()->program();
1143  d->lastUnFocusedIc_ = icEvent.inputContext()->watch();
1144  deactivateInputMethod(icEvent);
1145 
1146  auto *inputContext = icEvent.inputContext();
1147  if (!inputContext->clientControlVirtualkeyboardHide()) {
1148  inputContext->hideVirtualKeyboard();
1149  }
1150  }));
1151  d->eventWatchers_.emplace_back(d->watchEvent(
1152  EventType::InputContextReset, EventWatcherPhase::ReservedFirst,
1153  [d](Event &event) {
1154  auto &icEvent = static_cast<InputContextEvent &>(event);
1155  auto *ic = icEvent.inputContext();
1156  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
1157  inputState->reset();
1158  }));
1159  d->eventWatchers_.emplace_back(
1160  watchEvent(EventType::InputContextReset, EventWatcherPhase::InputMethod,
1161  [this](Event &event) {
1162  auto &icEvent = static_cast<InputContextEvent &>(event);
1163  auto *ic = icEvent.inputContext();
1164  if (!ic->hasFocus()) {
1165  return;
1166  }
1167  auto *engine = inputMethodEngine(ic);
1168  const auto *entry = inputMethodEntry(ic);
1169  if (!engine || !entry) {
1170  return;
1171  }
1172  engine->reset(*entry, icEvent);
1173  }));
1174  d->eventWatchers_.emplace_back(d->watchEvent(
1176  EventWatcherPhase::ReservedFirst, [this](Event &event) {
1177  auto &icEvent =
1178  static_cast<InputContextSwitchInputMethodEvent &>(event);
1179  auto *ic = icEvent.inputContext();
1180  if (!ic->hasFocus()) {
1181  return;
1182  }
1183  deactivateInputMethod(icEvent);
1184  activateInputMethod(icEvent);
1185  }));
1186  d->eventWatchers_.emplace_back(d->watchEvent(
1188  EventWatcherPhase::ReservedLast, [this, d](Event &event) {
1189  auto &icEvent =
1190  static_cast<InputContextSwitchInputMethodEvent &>(event);
1191  auto *ic = icEvent.inputContext();
1192  if (!ic->hasFocus()) {
1193  return;
1194  }
1195 
1196  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
1197  inputState->lastIMChangeIsAltTrigger_ =
1198  icEvent.reason() == InputMethodSwitchedReason::AltTrigger;
1199 
1200  if ((icEvent.reason() != InputMethodSwitchedReason::Trigger &&
1201  icEvent.reason() != InputMethodSwitchedReason::AltTrigger &&
1202  icEvent.reason() != InputMethodSwitchedReason::Enumerate &&
1203  icEvent.reason() != InputMethodSwitchedReason::Activate &&
1204  icEvent.reason() != InputMethodSwitchedReason::Other &&
1205  icEvent.reason() != InputMethodSwitchedReason::GroupChange &&
1206  icEvent.reason() != InputMethodSwitchedReason::Deactivate)) {
1207  return;
1208  }
1209  showInputMethodInformation(ic);
1210  }));
1211  d->eventWatchers_.emplace_back(
1212  d->watchEvent(EventType::InputMethodGroupChanged,
1213  EventWatcherPhase::ReservedLast, [this, d](Event &) {
1214  // Use a timer here. so we can get focus back to real
1215  // window.
1216  d->imGroupInfoTimer_ = d->eventLoop_.addTimeEvent(
1217  CLOCK_MONOTONIC, now(CLOCK_MONOTONIC) + 30000, 0,
1218  [this](EventSourceTime *, uint64_t) {
1219  inputContextManager().foreachFocused(
1220  [this](InputContext *ic) {
1221  showInputMethodInformation(ic);
1222  return true;
1223  });
1224  return true;
1225  });
1226  }));
1227 
1228  d->eventWatchers_.emplace_back(d->watchEvent(
1229  EventType::InputContextUpdateUI, EventWatcherPhase::ReservedFirst,
1230  [d](Event &event) {
1231  auto &icEvent = static_cast<InputContextUpdateUIEvent &>(event);
1232  if (icEvent.immediate()) {
1233  d->uiManager_.update(icEvent.component(),
1234  icEvent.inputContext());
1235  d->uiManager_.flush();
1236  } else {
1237  d->uiManager_.update(icEvent.component(),
1238  icEvent.inputContext());
1239  d->uiUpdateEvent_->setOneShot();
1240  }
1241  }));
1242  d->eventWatchers_.emplace_back(d->watchEvent(
1243  EventType::InputContextDestroyed, EventWatcherPhase::ReservedFirst,
1244  [d](Event &event) {
1245  auto &icEvent = static_cast<InputContextEvent &>(event);
1246  d->uiManager_.expire(icEvent.inputContext());
1247  }));
1248  d->eventWatchers_.emplace_back(d->watchEvent(
1249  EventType::InputMethodModeChanged, EventWatcherPhase::ReservedFirst,
1250  [d](Event &) { d->uiManager_.updateAvailability(); }));
1251  d->uiUpdateEvent_ = d->eventLoop_.addDeferEvent([d](EventSource *) {
1252  d->uiManager_.flush();
1253  return true;
1254  });
1255  d->uiUpdateEvent_->setEnabled(false);
1256  d->periodicalSave_ = d->eventLoop_.addTimeEvent(
1257  CLOCK_MONOTONIC, now(CLOCK_MONOTONIC) + 1000000, AutoSaveIdleTime,
1258  [this, d](EventSourceTime *time, uint64_t) {
1259  if (exiting()) {
1260  return true;
1261  }
1262 
1263  // Check if the idle time is long enough.
1264  auto currentTime = now(CLOCK_MONOTONIC);
1265  if (currentTime <= d->idleStartTimestamp_ ||
1266  currentTime - d->idleStartTimestamp_ < AutoSaveIdleTime) {
1267  // IF not idle, shorten the next checking period.
1268  time->setNextInterval(2 * AutoSaveIdleTime);
1269  time->setOneShot();
1270  return true;
1271  }
1272 
1273  FCITX_INFO() << "Running autosave...";
1274  save();
1275  FCITX_INFO() << "End autosave";
1276  if (d->globalConfig_.autoSavePeriod() > 0) {
1277  time->setNextInterval(d->globalConfig_.autoSavePeriod() *
1278  AutoSaveMinInUsecs);
1279  time->setOneShot();
1280  }
1281  return true;
1282  });
1283  d->periodicalSave_->setEnabled(false);
1284 }
1285 
1286 Instance::~Instance() {
1287  FCITX_D();
1288  d->tempModeManager_.reset();
1289  d->icManager_.finalize();
1290  d->addonManager_.unload();
1291  d->notifications_ = nullptr;
1292  d->icManager_.setInstance(nullptr);
1293 }
1294 
1295 void InstanceArgument::parseOption(int argc, char **argv) {
1296  if (argc >= 1) {
1297  argv0 = argv[0];
1298  } else {
1299  argv0 = "fcitx5";
1300  }
1301  struct option longOptions[] = {{"enable", required_argument, nullptr, 0},
1302  {"disable", required_argument, nullptr, 0},
1303  {"verbose", required_argument, nullptr, 0},
1304  {"keep", no_argument, nullptr, 'k'},
1305  {"ui", required_argument, nullptr, 'u'},
1306  {"replace", no_argument, nullptr, 'r'},
1307  {"version", no_argument, nullptr, 'v'},
1308  {"help", no_argument, nullptr, 'h'},
1309  {"option", required_argument, nullptr, 'o'},
1310  {nullptr, 0, 0, 0}};
1311 
1312  int optionIndex = 0;
1313  int c;
1314  std::string addonOptionString;
1315  while ((c = getopt_long(argc, argv, "ru:dDs:hvo:k", longOptions,
1316  &optionIndex)) != EOF) {
1317  switch (c) {
1318  case 0: {
1319  switch (optionIndex) {
1320  case 0:
1321  enableList = stringutils::split(optarg, ",");
1322  break;
1323  case 1:
1324  disableList = stringutils::split(optarg, ",");
1325  break;
1326  case 2:
1327  Log::setLogRule(optarg);
1328  break;
1329  default:
1330  quietQuit = true;
1331  printUsage();
1332  break;
1333  }
1334  } break;
1335  case 'r':
1336  tryReplace = true;
1337  break;
1338  case 'u':
1339  uiName = optarg;
1340  break;
1341  case 'd':
1342  runAsDaemon = true;
1343  break;
1344  case 'D':
1345  runAsDaemon = false;
1346  break;
1347  case 'k':
1348  exitWhenMainDisplayDisconnected = false;
1349  break;
1350  case 's':
1351  overrideDelay = std::atoi(optarg);
1352  break;
1353  case 'h':
1354  quietQuit = true;
1355  printUsage();
1356  break;
1357  case 'v':
1358  quietQuit = true;
1359  printVersion();
1360  break;
1361  case 'o':
1362  addonOptionString = optarg;
1363  break;
1364  default:
1365  quietQuit = true;
1366  printUsage();
1367  }
1368  if (quietQuit) {
1369  break;
1370  }
1371  }
1372 
1373  std::unordered_map<std::string, std::vector<std::string>> addonOptions;
1374  for (const std::string_view item :
1375  stringutils::split(addonOptionString, ",")) {
1376  auto tokens = stringutils::split(item, "=");
1377  if (tokens.size() != 2) {
1378  continue;
1379  }
1380  addonOptions[tokens[0]] = stringutils::split(tokens[1], ":");
1381  }
1382  addonOptions_ = std::move(addonOptions);
1383 }
1384 
1386 #ifdef _WIN32
1387  FCITX_UNUSED(fd);
1388 #else
1389  FCITX_D();
1390  d->signalPipe_ = fd;
1391  d->signalPipeEvent_ = d->eventLoop_.addIOEvent(
1392  fd, IOEventFlag::In, [this](EventSource *, int, IOEventFlags) {
1393  handleSignal();
1394  return true;
1395  });
1396 #endif
1397 }
1398 
1400  FCITX_D();
1401  return d->arg_.tryReplace;
1402 }
1403 
1405  FCITX_D();
1406  return d->arg_.exitWhenMainDisplayDisconnected;
1407 }
1408 
1409 bool Instance::exiting() const {
1410  FCITX_D();
1411  return d->exit_;
1412 }
1413 
1414 void Instance::handleSignal() {
1415 #ifndef _WIN32
1416  FCITX_D();
1417  uint8_t signo = 0;
1418  while (fs::safeRead(d->signalPipe_, &signo, sizeof(signo)) > 0) {
1419  if (signo == SIGINT || signo == SIGTERM || signo == SIGQUIT ||
1420  signo == SIGXCPU) {
1421  exit();
1422  } else if (signo == SIGUSR1) {
1423  reloadConfig();
1424  } else if (signo == SIGCHLD) {
1425  d->zombieReaper_->setNextInterval(2000000);
1426  d->zombieReaper_->setOneShot();
1427  }
1428  }
1429 #endif
1430 }
1431 
1433  FCITX_D();
1434  if (!d->arg_.uiName.empty()) {
1435  d->arg_.enableList.push_back(d->arg_.uiName);
1436  }
1437  reloadConfig();
1438  d->icManager_.registerProperty("inputState", &d->inputStateFactory_);
1439  std::unordered_set<std::string> enabled;
1440  std::unordered_set<std::string> disabled;
1441  std::tie(enabled, disabled) = d->overrideAddons();
1442  FCITX_INFO() << "Override Enabled Addons: " << enabled;
1443  FCITX_INFO() << "Override Disabled Addons: " << disabled;
1444  d->addonManager_.load(enabled, disabled);
1445  if (d->exit_) {
1446  return;
1447  }
1448  d->imManager_.load([d](InputMethodManager &) { d->buildDefaultGroup(); });
1449  d->uiManager_.load(d->arg_.uiName);
1450 
1451  const auto *entry = d->imManager_.entry("keyboard-us");
1452  FCITX_LOG_IF(Error, !entry) << "Couldn't find keyboard-us";
1453  d->preloadInputMethodEvent_ = d->eventLoop_.addTimeEvent(
1454  CLOCK_MONOTONIC, now(CLOCK_MONOTONIC) + 1000000, 0,
1455  [this](EventSourceTime *, uint64_t) {
1456  FCITX_D();
1457  if (d->exit_ || !d->globalConfig_.preloadInputMethod()) {
1458  return false;
1459  }
1460  // Preload first input method.
1461  if (!d->imManager_.currentGroup().inputMethodList().empty()) {
1462  if (const auto *entry =
1463  d->imManager_.entry(d->imManager_.currentGroup()
1464  .inputMethodList()[0]
1465  .name())) {
1466  d->addonManager_.addon(entry->addon(), true);
1467  }
1468  }
1469  // Preload default input method.
1470  if (!d->imManager_.currentGroup().defaultInputMethod().empty()) {
1471  if (const auto *entry = d->imManager_.entry(
1472  d->imManager_.currentGroup().defaultInputMethod())) {
1473  d->addonManager_.addon(entry->addon(), true);
1474  }
1475  }
1476  return false;
1477  });
1478 #ifndef _WIN32
1479  d->zombieReaper_ = d->eventLoop_.addTimeEvent(
1480  CLOCK_MONOTONIC, now(CLOCK_MONOTONIC), 0,
1481  [](EventSourceTime *, uint64_t) {
1482  pid_t res;
1483  while ((res = waitpid(-1, nullptr, WNOHANG)) > 0) {
1484  }
1485  return false;
1486  });
1487  d->zombieReaper_->setEnabled(false);
1488 #endif
1489 
1490  d->exitEvent_ = d->eventLoop_.addExitEvent([this](EventSource *) {
1491  FCITX_DEBUG() << "Running save...";
1492  save();
1493  return false;
1494  });
1495  d->notifications_ = d->addonManager_.addon("notifications", true);
1496 }
1497 
1499  FCITX_D();
1500  if (d->arg_.quietQuit) {
1501  return 0;
1502  }
1503  d->exit_ = false;
1504  d->exitCode_ = 0;
1505  initialize();
1506  if (d->exit_) {
1507  return d->exitCode_;
1508  }
1509  d->running_ = true;
1510  auto r = eventLoop().exec();
1511  d->running_ = false;
1512 
1513  return r ? d->exitCode_ : 1;
1514 }
1515 
1516 void Instance::setRunning(bool running) {
1517  FCITX_D();
1518  d->running_ = running;
1519 }
1520 
1521 bool Instance::isRunning() const {
1522  FCITX_D();
1523  return d->running_;
1524 }
1525 
1526 InputMethodMode Instance::inputMethodMode() const {
1527  FCITX_D();
1528  return d->inputMethodMode_;
1529 }
1530 
1531 void Instance::setInputMethodMode(InputMethodMode mode) {
1532  FCITX_D();
1533  if (d->inputMethodMode_ == mode) {
1534  return;
1535  }
1536  d->inputMethodMode_ = mode;
1537  postEvent(InputMethodModeChangedEvent());
1538 }
1539 
1541  FCITX_D();
1542  return d->restart_;
1543 }
1544 
1545 bool Instance::virtualKeyboardAutoShow() const {
1546  FCITX_D();
1547  return d->virtualKeyboardAutoShow_;
1548 }
1549 
1550 void Instance::setVirtualKeyboardAutoShow(bool autoShow) {
1551  FCITX_D();
1552  d->virtualKeyboardAutoShow_ = autoShow;
1553 }
1554 
1555 bool Instance::virtualKeyboardAutoHide() const {
1556  FCITX_D();
1557  return d->virtualKeyboardAutoHide_;
1558 }
1559 
1560 void Instance::setVirtualKeyboardAutoHide(bool autoHide) {
1561  FCITX_D();
1562  d->virtualKeyboardAutoHide_ = autoHide;
1563 }
1564 
1565 VirtualKeyboardFunctionMode Instance::virtualKeyboardFunctionMode() const {
1566  FCITX_D();
1567  return d->virtualKeyboardFunctionMode_;
1568 }
1569 
1570 void Instance::setVirtualKeyboardFunctionMode(
1571  VirtualKeyboardFunctionMode mode) {
1572  FCITX_D();
1573  d->virtualKeyboardFunctionMode_ = mode;
1574 }
1575 
1577  FCITX_D();
1578  d->binaryMode_ = true;
1579 }
1580 
1581 bool Instance::canRestart() const {
1582  FCITX_D();
1583  const auto &addonNames = d->addonManager_.loadedAddonNames();
1584  return d->binaryMode_ &&
1585  std::all_of(addonNames.begin(), addonNames.end(),
1586  [d](const std::string &name) {
1587  auto *addon = d->addonManager_.lookupAddon(name);
1588  if (!addon) {
1589  return true;
1590  }
1591  return addon->canRestart();
1592  });
1593 }
1594 
1595 InstancePrivate *Instance::privateData() {
1596  FCITX_D();
1597  return d;
1598 }
1599 
1601  FCITX_D();
1602  return d->eventLoop_;
1603 }
1604 
1606  FCITX_D();
1607  return d->eventDispatcher_;
1608 }
1609 
1611  FCITX_D();
1612  return d->icManager_;
1613 }
1614 
1616  FCITX_D();
1617  return d->addonManager_;
1618 }
1619 
1621  FCITX_D();
1622  return d->imManager_;
1623 }
1624 
1626  FCITX_D();
1627  return d->imManager_;
1628 }
1629 
1631  FCITX_D();
1632  return *d->tempModeManager_;
1633 }
1634 
1636  FCITX_D();
1637  return d->uiManager_;
1638 }
1639 
1641  FCITX_D();
1642  return d->globalConfig_;
1643 }
1644 
1645 bool Instance::postEvent(Event &event) {
1646  return std::as_const(*this).postEvent(event);
1647 }
1648 
1649 bool Instance::postEvent(Event &event) const {
1650  FCITX_D();
1651  if (d->exit_) {
1652  return false;
1653  }
1654  auto iter = d->eventHandlers_.find(event.type());
1655  if (iter != d->eventHandlers_.end()) {
1656  const auto &handlers = iter->second;
1657  EventWatcherPhase phaseOrder[] = {
1658  EventWatcherPhase::ReservedFirst, EventWatcherPhase::PreInputMethod,
1659  EventWatcherPhase::InputMethod, EventWatcherPhase::PostInputMethod,
1660  EventWatcherPhase::ReservedLast};
1661 
1662  for (auto phase : phaseOrder) {
1663  if (auto iter2 = handlers.find(phase); iter2 != handlers.end()) {
1664  for (auto &handler : iter2->second.view()) {
1665  handler(event);
1666  if (event.filtered()) {
1667  break;
1668  }
1669  }
1670  }
1671  if (event.filtered()) {
1672  break;
1673  }
1674  }
1675 
1676  // Make sure this part of fix is always executed regardless of the
1677  // filter.
1678  if (event.type() == EventType::InputContextKeyEvent) {
1679  auto &keyEvent = static_cast<KeyEvent &>(event);
1680  auto *ic = keyEvent.inputContext();
1681 #ifdef ENABLE_KEYBOARD
1682  do {
1683  if (!keyEvent.forward() && !keyEvent.origKey().code()) {
1684  break;
1685  }
1686  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
1687  auto *xkbState = inputState->customXkbState();
1688  if (!xkbState) {
1689  break;
1690  }
1691  // This need to be called after xkb_state_key_get_*, and should
1692  // be called against all Key regardless whether they are
1693  // filtered or not.
1694  xkb_state_update_key(xkbState, keyEvent.origKey().code(),
1695  keyEvent.isRelease() ? XKB_KEY_UP
1696  : XKB_KEY_DOWN);
1697  } while (0);
1698 #endif
1699  if (ic->capabilityFlags().test(CapabilityFlag::KeyEventOrderFix) &&
1700  !keyEvent.accepted() && ic->hasPendingEventsStrictOrder()) {
1701  // Re-forward the event to ensure we got delivered later than
1702  // commit.
1703  keyEvent.filterAndAccept();
1704  ic->forwardKey(keyEvent.origKey(), keyEvent.isRelease(),
1705  keyEvent.time());
1706  }
1707  d_ptr->uiManager_.flush();
1708  }
1709  }
1710  return event.accepted();
1711 }
1712 
1713 std::unique_ptr<HandlerTableEntry<EventHandler>>
1714 Instance::watchEvent(EventType type, EventWatcherPhase phase,
1715  EventHandler callback) {
1716  FCITX_D();
1717  if (phase == EventWatcherPhase::ReservedFirst ||
1718  phase == EventWatcherPhase::ReservedLast) {
1719  throw std::invalid_argument("Reserved Phase is only for internal use");
1720  }
1721  return d->watchEvent(type, phase, std::move(callback));
1722 }
1723 
1724 bool groupContains(const InputMethodGroup &group, const std::string &name) {
1725  const auto &list = group.inputMethodList();
1726  auto iter = std::find_if(list.begin(), list.end(),
1727  [&name](const InputMethodGroupItem &item) {
1728  return item.name() == name;
1729  });
1730  return iter != list.end();
1731 }
1732 
1734  FCITX_D();
1735  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
1736  // Small hack to make sure when InputMethodEngine::deactivate is called,
1737  // current im is the right one.
1738  if (!inputState->overrideDeactivateIM_.empty()) {
1739  return inputState->overrideDeactivateIM_;
1740  }
1741 
1742  const auto &group = d->imManager_.currentGroup();
1743  if (ic->capabilityFlags().test(CapabilityFlag::Disable) ||
1744  (ic->capabilityFlags().test(CapabilityFlag::Password) &&
1745  !d->globalConfig_.allowInputMethodForPassword())) {
1746  auto defaultLayoutIM =
1747  stringutils::concat("keyboard-", group.defaultLayout());
1748  const auto *entry = d->imManager_.entry(defaultLayoutIM);
1749  if (!entry) {
1750  entry = d->imManager_.entry("keyboard-us");
1751  }
1752  return entry ? entry->uniqueName() : "";
1753  }
1754 
1755  if (group.inputMethodList().empty()) {
1756  return "";
1757  }
1758  if (inputState->isActive()) {
1759  if (!inputState->localIM_.empty() &&
1760  groupContains(group, inputState->localIM_)) {
1761  return inputState->localIM_;
1762  }
1763  return group.defaultInputMethod();
1764  }
1765 
1766  return group.inputMethodList()[0].name();
1767 }
1768 
1770  FCITX_D();
1771  auto imName = inputMethod(ic);
1772  if (imName.empty()) {
1773  return nullptr;
1774  }
1775  return d->imManager_.entry(imName);
1776 }
1777 
1779  FCITX_D();
1780  const auto *entry = inputMethodEntry(ic);
1781  if (!entry) {
1782  return nullptr;
1783  }
1784  return static_cast<InputMethodEngine *>(
1785  d->addonManager_.addon(entry->addon(), true));
1786 }
1787 
1789  FCITX_D();
1790  const auto *entry = d->imManager_.entry(name);
1791  if (!entry) {
1792  return nullptr;
1793  }
1794  return static_cast<InputMethodEngine *>(
1795  d->addonManager_.addon(entry->addon(), true));
1796 }
1797 
1799  std::string icon;
1800  const auto *entry = inputMethodEntry(ic);
1801  if (entry) {
1802  auto *engine = inputMethodEngine(ic);
1803  if (engine) {
1804  icon = engine->subModeIcon(*entry, *ic);
1805  }
1806  if (icon.empty()) {
1807  icon = entry->icon();
1808  }
1809  } else {
1810  icon = "input-keyboard";
1811  }
1812  return icon;
1813 }
1814 
1816  std::string label;
1817 
1818  const auto *entry = inputMethodEntry(ic);
1819  auto *engine = inputMethodEngine(ic);
1820 
1821  if (engine && entry) {
1822  label = engine->subModeLabel(*entry, *ic);
1823  }
1824  if (label.empty() && entry) {
1825  label = entry->label();
1826  }
1827  return label;
1828 }
1829 
1830 uint32_t Instance::processCompose(InputContext *ic, KeySym keysym) {
1831 #ifdef ENABLE_KEYBOARD
1832  FCITX_D();
1833  auto *state = ic->propertyFor(&d->inputStateFactory_);
1834 
1835  auto *xkbComposeState = state->xkbComposeState();
1836  if (!xkbComposeState) {
1837  return 0;
1838  }
1839 
1840  auto keyval = static_cast<xkb_keysym_t>(keysym);
1841 
1842  enum xkb_compose_feed_result result =
1843  xkb_compose_state_feed(xkbComposeState, keyval);
1844  if (result == XKB_COMPOSE_FEED_IGNORED) {
1845  return 0;
1846  }
1847 
1848  enum xkb_compose_status status =
1849  xkb_compose_state_get_status(xkbComposeState);
1850  if (status == XKB_COMPOSE_NOTHING) {
1851  return 0;
1852  }
1853  if (status == XKB_COMPOSE_COMPOSED) {
1854  char buffer[FCITX_UTF8_MAX_LENGTH + 1] = {'\0', '\0', '\0', '\0',
1855  '\0', '\0', '\0'};
1856  int length =
1857  xkb_compose_state_get_utf8(xkbComposeState, buffer, sizeof(buffer));
1858  xkb_compose_state_reset(xkbComposeState);
1859  if (length == 0) {
1860  return FCITX_INVALID_COMPOSE_RESULT;
1861  }
1862 
1863  uint32_t c = utf8::getChar(buffer);
1864  return utf8::isValidChar(c) ? c : 0;
1865  }
1866  if (status == XKB_COMPOSE_CANCELLED) {
1867  xkb_compose_state_reset(xkbComposeState);
1868  }
1869 
1870  return FCITX_INVALID_COMPOSE_RESULT;
1871 #else
1872  FCITX_UNUSED(ic);
1873  FCITX_UNUSED(keysym);
1874  return 0;
1875 #endif
1876 }
1877 
1878 std::optional<std::string> Instance::processComposeString(InputContext *ic,
1879  KeySym keysym) {
1880 #ifdef ENABLE_KEYBOARD
1881  FCITX_D();
1882  auto *state = ic->propertyFor(&d->inputStateFactory_);
1883 
1884  auto *xkbComposeState = state->xkbComposeState();
1885  if (!xkbComposeState) {
1886  return std::string();
1887  }
1888 
1889  auto keyval = static_cast<xkb_keysym_t>(keysym);
1890  enum xkb_compose_feed_result result =
1891  xkb_compose_state_feed(xkbComposeState, keyval);
1892 
1893  if (result == XKB_COMPOSE_FEED_IGNORED) {
1894  return std::string();
1895  }
1896 
1897  enum xkb_compose_status status =
1898  xkb_compose_state_get_status(xkbComposeState);
1899  if (status == XKB_COMPOSE_NOTHING) {
1900  return std::string();
1901  }
1902  if (status == XKB_COMPOSE_COMPOSED) {
1903  // This may not be NUL-terminiated.
1904  std::array<char, 256> buffer;
1905  auto length = xkb_compose_state_get_utf8(xkbComposeState, buffer.data(),
1906  buffer.size());
1907  xkb_compose_state_reset(xkbComposeState);
1908  if (length == 0) {
1909  return std::nullopt;
1910  }
1911 
1912  auto bufferBegin = buffer.begin();
1913  auto bufferEnd = std::next(bufferBegin, length);
1914  if (utf8::validate(bufferBegin, bufferEnd)) {
1915  return std::string(bufferBegin, bufferEnd);
1916  }
1917  return std::nullopt;
1918  }
1919  if (status == XKB_COMPOSE_CANCELLED) {
1920  xkb_compose_state_reset(xkbComposeState);
1921  }
1922  return std::nullopt;
1923 #else
1924  FCITX_UNUSED(ic);
1925  FCITX_UNUSED(keysym);
1926  return std::string();
1927 #endif
1928 }
1929 
1931 #ifdef ENABLE_KEYBOARD
1932  FCITX_D();
1933  auto *state = inputContext->propertyFor(&d->inputStateFactory_);
1934 
1935  auto *xkbComposeState = state->xkbComposeState();
1936  if (!xkbComposeState) {
1937  return false;
1938  }
1939 
1940  return xkb_compose_state_get_status(xkbComposeState) ==
1941  XKB_COMPOSE_COMPOSING;
1942 #else
1943  FCITX_UNUSED(inputContext);
1944  return false;
1945 #endif
1946 }
1947 
1949 #ifdef ENABLE_KEYBOARD
1950  FCITX_D();
1951  auto *state = inputContext->propertyFor(&d->inputStateFactory_);
1952  auto *xkbComposeState = state->xkbComposeState();
1953  if (!xkbComposeState) {
1954  return;
1955  }
1956  xkb_compose_state_reset(xkbComposeState);
1957 #else
1958  FCITX_UNUSED(inputContext);
1959 #endif
1960 }
1961 
1963  FCITX_D();
1964  // Refresh timestamp for next auto save.
1965  d->idleStartTimestamp_ = now(CLOCK_MONOTONIC);
1966  d->imManager_.save();
1967  d->addonManager_.saveAll();
1968 }
1969 
1971  FCITX_D();
1972  if (auto *ic = mostRecentInputContext()) {
1973  CheckInputMethodChanged imChangedRAII(ic, d);
1974  activate(ic);
1975  }
1976 }
1977 
1978 std::string Instance::addonForInputMethod(const std::string &imName) {
1979 
1980  if (const auto *entry = inputMethodManager().entry(imName)) {
1981  return entry->uniqueName();
1982  }
1983  return {};
1984 }
1985 
1987  startProcess(
1988  {StandardPaths::fcitxPath("bindir", "fcitx5-configtool").string()});
1989 }
1990 
1991 void Instance::configureAddon(const std::string & /*unused*/) {}
1992 
1993 void Instance::configureInputMethod(const std::string & /*unused*/) {}
1994 
1996  if (auto *ic = mostRecentInputContext()) {
1997  if (const auto *entry = inputMethodEntry(ic)) {
1998  return entry->uniqueName();
1999  }
2000  }
2001  return {};
2002 }
2003 
2004 std::string Instance::currentUI() {
2005  FCITX_D();
2006  return d->uiManager_.currentUI();
2007 }
2008 
2010  FCITX_D();
2011  if (auto *ic = mostRecentInputContext()) {
2012  CheckInputMethodChanged imChangedRAII(ic, d);
2013  deactivate(ic);
2014  }
2015 }
2016 
2017 void Instance::exit() { exit(0); }
2018 
2019 void Instance::exit(int exitCode) {
2020  FCITX_D();
2021  d->exit_ = true;
2022  d->exitCode_ = exitCode;
2023  if (d->running_) {
2024  d->eventLoop_.exit();
2025  }
2026 }
2027 
2028 void Instance::reloadAddonConfig(const std::string &addonName) {
2029  auto *addon = addonManager().addon(addonName);
2030  if (addon) {
2031  addon->reloadConfig();
2032  }
2033 }
2034 
2036  FCITX_D();
2037  auto [enabled, disabled] = d->overrideAddons();
2038  d->addonManager_.load(enabled, disabled);
2039  d->imManager_.refresh();
2040 }
2041 
2043  FCITX_D();
2044  readAsIni(d->globalConfig_.config(), StandardPathsType::PkgConfig,
2045  "config");
2046  FCITX_DEBUG() << "Trigger Key: "
2047  << Key::keyListToString(d->globalConfig_.triggerKeys());
2048  d->icManager_.setPropertyPropagatePolicy(
2049  d->globalConfig_.shareInputState());
2050  if (d->globalConfig_.preeditEnabledByDefault() !=
2051  d->icManager_.isPreeditEnabledByDefault()) {
2052  d->icManager_.setPreeditEnabledByDefault(
2053  d->globalConfig_.preeditEnabledByDefault());
2054  d->icManager_.foreach([d](InputContext *ic) {
2055  ic->setEnablePreedit(d->globalConfig_.preeditEnabledByDefault());
2056  return true;
2057  });
2058  }
2059 #ifdef ENABLE_KEYBOARD
2060  d->keymapCache_.clear();
2061  if (d->inputStateFactory_.registered()) {
2062  d->icManager_.foreach([d](InputContext *ic) {
2063  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
2064  inputState->resetXkbState();
2065  return true;
2066  });
2067  }
2068 #endif
2069  if (d->running_) {
2070  postEvent(GlobalConfigReloadedEvent());
2071  }
2072 
2073  if (d->globalConfig_.autoSavePeriod() <= 0) {
2074  d->periodicalSave_->setEnabled(false);
2075  } else {
2076  d->periodicalSave_->setNextInterval(AutoSaveMinInUsecs *
2077  d->globalConfig_.autoSavePeriod());
2078  d->periodicalSave_->setOneShot();
2079  }
2080 }
2081 
2083  FCITX_D();
2084  d->imManager_.reset([d](InputMethodManager &) { d->buildDefaultGroup(); });
2085 }
2086 
2088  FCITX_D();
2089  if (!canRestart()) {
2090  return;
2091  }
2092  d->restart_ = true;
2093  exit();
2094 }
2095 
2096 void Instance::setCurrentInputMethod(const std::string &name) {
2097  setCurrentInputMethod(mostRecentInputContext(), name, false);
2098 }
2099 
2100 void Instance::setCurrentInputMethod(InputContext *ic, const std::string &name,
2101  bool local) {
2102  FCITX_D();
2103  if (!canTrigger()) {
2104  return;
2105  }
2106 
2107  auto &imManager = inputMethodManager();
2108  const auto &imList = imManager.currentGroup().inputMethodList();
2109  auto iter = std::find_if(imList.begin(), imList.end(),
2110  [&name](const InputMethodGroupItem &item) {
2111  return item.name() == name;
2112  });
2113  if (iter == imList.end()) {
2114  return;
2115  }
2116 
2117  auto setGlobalDefaultInputMethod = [d](const std::string &name) {
2118  std::vector<std::unique_ptr<CheckInputMethodChanged>> groupRAIICheck;
2119  d->icManager_.foreachFocused([d, &groupRAIICheck](InputContext *ic) {
2120  assert(ic->hasFocus());
2121  groupRAIICheck.push_back(
2122  std::make_unique<CheckInputMethodChanged>(ic, d));
2123  return true;
2124  });
2125  d->imManager_.setDefaultInputMethod(name);
2126  };
2127 
2128  auto idx = std::distance(imList.begin(), iter);
2129  if (ic) {
2130  CheckInputMethodChanged imChangedRAII(ic, d);
2131  auto currentIM = inputMethod(ic);
2132  if (currentIM == name) {
2133  return;
2134  }
2135  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
2136 
2137  if (idx != 0) {
2138  if (local) {
2139  inputState->setLocalIM(name);
2140  } else {
2141  inputState->setLocalIM({});
2142 
2143  setGlobalDefaultInputMethod(name);
2144  }
2145  inputState->setActive(true);
2146  } else {
2147  inputState->setActive(false);
2148  }
2149  if (inputState->imChanged_) {
2150  inputState->imChanged_->setReason(InputMethodSwitchedReason::Other);
2151  }
2152  } else {
2153  // We can't set local input method if we don't have a IC, but we should
2154  // still to change the global default.
2155  if (local) {
2156  return;
2157  }
2158  if (idx != 0) {
2159  setGlobalDefaultInputMethod(name);
2160  }
2161  return;
2162  }
2163 }
2164 
2166  FCITX_D();
2167  if (auto *ic = mostRecentInputContext()) {
2168  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
2169  return inputState->isActive() ? 2 : 1;
2170  }
2171  return 0;
2172 }
2173 
2175  FCITX_D();
2176  if (auto *ic = mostRecentInputContext()) {
2177  CheckInputMethodChanged imChangedRAII(ic, d);
2178  trigger(ic, true);
2179  }
2180 }
2181 
2182 void Instance::enumerate(bool forward) {
2183  FCITX_D();
2184  if (auto *ic = mostRecentInputContext()) {
2185  CheckInputMethodChanged imChangedRAII(ic, d);
2186  enumerate(ic, forward);
2187  }
2188 }
2189 
2190 bool Instance::canTrigger() const {
2191  const auto &imManager = inputMethodManager();
2192  return (imManager.currentGroup().inputMethodList().size() > 1);
2193 }
2194 
2195 bool Instance::canAltTrigger(InputContext *ic) const {
2196  if (!canTrigger()) {
2197  return false;
2198  }
2199  FCITX_D();
2200  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
2201  if (inputState->isActive()) {
2202  return true;
2203  }
2204  return inputState->lastIMChangeIsAltTrigger_;
2205 }
2206 
2207 bool Instance::canEnumerate(InputContext *ic) const {
2208  FCITX_D();
2209  if (!canTrigger()) {
2210  return false;
2211  }
2212 
2213  if (d->globalConfig_.enumerateSkipFirst()) {
2214  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
2215  if (!inputState->isActive()) {
2216  return false;
2217  }
2218  return d->imManager_.currentGroup().inputMethodList().size() > 2;
2219  }
2220 
2221  return true;
2222 }
2223 
2224 bool Instance::canChangeGroup() const {
2225  const auto &imManager = inputMethodManager();
2226  return (imManager.groupCount() > 1);
2227 }
2228 
2230  FCITX_D();
2231  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
2232  if (!canTrigger()) {
2233  return false;
2234  }
2235  inputState->setActive(!inputState->isActive());
2236  if (inputState->imChanged_) {
2237  inputState->imChanged_->setReason(reason);
2238  }
2239  return true;
2240 }
2241 
2242 bool Instance::trigger(InputContext *ic, bool totallyReleased) {
2243  FCITX_D();
2244  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
2245  if (!canTrigger()) {
2246  return false;
2247  }
2248  // Active -> inactive -> enumerate.
2249  // Inactive -> active -> inactive -> enumerate.
2250  if (totallyReleased) {
2251  toggle(ic);
2252  inputState->firstTrigger_ = true;
2253  } else {
2254  if (!d->globalConfig_.enumerateWithTriggerKeys() ||
2255  (inputState->firstTrigger_ && inputState->isActive()) ||
2256  (d->globalConfig_.enumerateSkipFirst() &&
2257  d->imManager_.currentGroup().inputMethodList().size() <= 2)) {
2258  toggle(ic);
2259  } else {
2260  enumerate(ic, true);
2261  }
2262  inputState->firstTrigger_ = false;
2263  }
2264  return true;
2265 }
2266 
2267 bool Instance::altTrigger(InputContext *ic) {
2268  if (!canAltTrigger(ic)) {
2269  return false;
2270  }
2271 
2273  return true;
2274 }
2275 
2276 bool Instance::activate(InputContext *ic) {
2277  FCITX_D();
2278  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
2279  if (!canTrigger()) {
2280  return false;
2281  }
2282  if (inputState->isActive()) {
2283  return true;
2284  }
2285  inputState->setActive(true);
2286  if (inputState->imChanged_) {
2287  inputState->imChanged_->setReason(InputMethodSwitchedReason::Activate);
2288  }
2289  return true;
2290 }
2291 
2293  FCITX_D();
2294  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
2295  if (!canTrigger()) {
2296  return false;
2297  }
2298  if (!inputState->isActive()) {
2299  return true;
2300  }
2301  inputState->setActive(false);
2302  if (inputState->imChanged_) {
2303  inputState->imChanged_->setReason(
2305  }
2306  return true;
2307 }
2308 
2309 bool Instance::enumerate(InputContext *ic, bool forward) {
2310  FCITX_D();
2311  auto &imManager = inputMethodManager();
2312  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
2313  const auto &imList = imManager.currentGroup().inputMethodList();
2314  if (!canTrigger()) {
2315  return false;
2316  }
2317 
2318  if (d->globalConfig_.enumerateSkipFirst() && imList.size() <= 2) {
2319  return false;
2320  }
2321 
2322  auto currentIM = inputMethod(ic);
2323 
2324  auto iter = std::ranges::find_if(
2325  imList, [&currentIM](const InputMethodGroupItem &item) {
2326  return item.name() == currentIM;
2327  });
2328  if (iter == imList.end()) {
2329  return false;
2330  }
2331  int idx = std::distance(imList.begin(), iter);
2332  auto nextIdx = [forward, &imList](int idx) {
2333  // be careful not to use negative to avoid overflow.
2334  return (idx + (forward ? 1 : (imList.size() - 1))) % imList.size();
2335  };
2336 
2337  idx = nextIdx(idx);
2338  if (d->globalConfig_.enumerateSkipFirst() && idx == 0) {
2339  idx = nextIdx(idx);
2340  }
2341  if (idx != 0) {
2342  std::vector<std::unique_ptr<CheckInputMethodChanged>> groupRAIICheck;
2343  d->icManager_.foreachFocused([d, &groupRAIICheck](InputContext *ic) {
2344  assert(ic->hasFocus());
2345  groupRAIICheck.push_back(
2346  std::make_unique<CheckInputMethodChanged>(ic, d));
2347  return true;
2348  });
2349  imManager.setDefaultInputMethod(imList[idx].name());
2350  inputState->setActive(true);
2351  inputState->setLocalIM({});
2352  } else {
2353  inputState->setActive(false);
2354  }
2355  if (inputState->imChanged_) {
2356  inputState->imChanged_->setReason(InputMethodSwitchedReason::Enumerate);
2357  }
2358 
2359  return true;
2360 }
2361 
2362 std::string Instance::commitFilter(InputContext *inputContext,
2363  const std::string &orig) {
2364  std::string result = orig;
2365  emit<Instance::CommitFilter>(inputContext, result);
2366  return result;
2367 }
2368 
2369 Text Instance::outputFilter(InputContext *inputContext, const Text &orig) {
2370  Text result = orig;
2371  emit<Instance::OutputFilter>(inputContext, result);
2372  if ((&orig == &inputContext->inputPanel().clientPreedit() ||
2373  &orig == &inputContext->inputPanel().preedit()) &&
2374  !globalConfig().showPreeditForPassword() &&
2375  inputContext->capabilityFlags().test(CapabilityFlag::Password)) {
2376  Text newText;
2377  for (int i = 0, e = result.size(); i < e; i++) {
2378  auto length = utf8::length(result.stringAt(i));
2379  std::string dot;
2380  dot.reserve(length * 3);
2381  while (length != 0) {
2382  dot += "\xe2\x80\xa2";
2383  length -= 1;
2384  }
2385  newText.append(std::move(dot),
2386  result.formatAt(i) | TextFormatFlag::DontCommit);
2387  }
2388  result = std::move(newText);
2389  }
2390  return result;
2391 }
2392 
2394  FCITX_D();
2395  return d->icManager_.lastFocusedInputContext();
2396 }
2397 
2399  FCITX_D();
2400  return d->icManager_.mostRecentInputContext();
2401 }
2402 
2404  FCITX_D();
2405  d->uiManager_.flush();
2406 }
2407 
2408 int scoreForGroup(FocusGroup *group, const std::string &displayHint) {
2409  // Hardcode wayland over X11.
2410  if (displayHint.empty()) {
2411  if (group->display() == "x11:") {
2412  return 2;
2413  }
2414  if (group->display().starts_with("x11:")) {
2415  return 1;
2416  }
2417  if (group->display() == "wayland:") {
2418  return 4;
2419  }
2420  if (group->display().starts_with("wayland:")) {
2421  return 3;
2422  }
2423  } else {
2424  if (group->display() == displayHint) {
2425  return 2;
2426  }
2427  if (group->display().starts_with(displayHint)) {
2428  return 1;
2429  }
2430  }
2431  return -1;
2432 }
2433 
2434 FocusGroup *Instance::defaultFocusGroup(const std::string &displayHint) {
2435  FCITX_D();
2436  FocusGroup *defaultFocusGroup = nullptr;
2437 
2438  int score = 0;
2439  d->icManager_.foreachGroup(
2440  [&score, &displayHint, &defaultFocusGroup](FocusGroup *group) {
2441  auto newScore = scoreForGroup(group, displayHint);
2442  if (newScore > score) {
2443  defaultFocusGroup = group;
2444  score = newScore;
2445  }
2446 
2447  return true;
2448  });
2449  return defaultFocusGroup;
2450 }
2451 
2452 void Instance::activateInputMethod(InputContextEvent &event) {
2453  FCITX_D();
2454  FCITX_DEBUG() << "Instance::activateInputMethod";
2455  InputContext *ic = event.inputContext();
2456  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
2457  const auto *entry = inputMethodEntry(ic);
2458  if (entry) {
2459  FCITX_DEBUG() << "Activate: "
2460  << "[Last]:" << inputState->lastIM_
2461  << " [Activating]:" << entry->uniqueName();
2462  assert(inputState->lastIM_.empty());
2463  inputState->lastIM_ = entry->uniqueName();
2464  }
2465  auto *engine = inputMethodEngine(ic);
2466  if (!engine || !entry) {
2467  return;
2468  }
2469 #ifdef ENABLE_KEYBOARD
2470  if (auto *xkbState = inputState->customXkbState(true)) {
2471  if (auto *mods = findValue(d->stateMask_, ic->display())) {
2472  FCITX_KEYTRACE() << "Update mask to customXkbState";
2473  auto depressed = std::get<0>(*mods);
2474  auto latched = std::get<1>(*mods);
2475  auto locked = std::get<2>(*mods);
2476 
2477  // set modifiers in depressed if they don't appear in any of the
2478  // final masks
2479  // depressed |= ~(depressed | latched | locked);
2480  FCITX_KEYTRACE() << depressed << " " << latched << " " << locked;
2481  if (depressed == 0) {
2482  inputState->setModsAllReleased();
2483  }
2484  xkb_state_update_mask(xkbState, depressed, latched, locked, 0, 0,
2485  0);
2486  }
2487  }
2488 #endif
2489  ic->statusArea().clearGroup(StatusGroup::InputMethod);
2490  engine->activate(*entry, event);
2491  postEvent(InputMethodActivatedEvent(entry->uniqueName(), ic));
2492 }
2493 
2494 void Instance::deactivateInputMethod(InputContextEvent &event) {
2495  FCITX_D();
2496  FCITX_DEBUG() << "Instance::deactivateInputMethod event_type="
2497  << static_cast<uint32_t>(event.type());
2498  InputContext *ic = event.inputContext();
2499  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
2500  const InputMethodEntry *entry = nullptr;
2501  InputMethodEngine *engine = nullptr;
2502 
2504  auto &icEvent =
2505  static_cast<InputContextSwitchInputMethodEvent &>(event);
2506  FCITX_DEBUG() << "Switch reason: "
2507  << static_cast<int>(icEvent.reason());
2508  FCITX_DEBUG() << "Old Input method: " << icEvent.oldInputMethod();
2509  entry = d->imManager_.entry(icEvent.oldInputMethod());
2510  } else {
2511  entry = inputMethodEntry(ic);
2512  }
2513  if (entry) {
2514  FCITX_DEBUG() << "Deactivate: "
2515  << "[Last]:" << inputState->lastIM_
2516  << " [Deactivating]:" << entry->uniqueName();
2517  assert(entry->uniqueName() == inputState->lastIM_);
2518  engine = static_cast<InputMethodEngine *>(
2519  d->addonManager_.addon(entry->addon()));
2520  }
2521  inputState->lastIM_.clear();
2522  if (!engine || !entry) {
2523  return;
2524  }
2525  inputState->overrideDeactivateIM_ = entry->uniqueName();
2526  engine->deactivate(*entry, event);
2527  inputState->overrideDeactivateIM_.clear();
2528  postEvent(InputMethodDeactivatedEvent(entry->uniqueName(), ic));
2529 }
2530 
2531 bool Instance::enumerateGroup(bool forward) {
2532  auto &imManager = inputMethodManager();
2533  auto groups = imManager.groups();
2534  if (groups.size() <= 1) {
2535  return false;
2536  }
2537  if (forward) {
2538  imManager.setCurrentGroup(groups[1]);
2539  } else {
2540  imManager.setCurrentGroup(groups.back());
2541  }
2542  return true;
2543 }
2544 
2546  FCITX_DEBUG() << "Input method switched";
2547  FCITX_D();
2548  if (!d->globalConfig_.showInputMethodInformation()) {
2549  return;
2550  }
2551  d->showInputMethodInformation(ic);
2552 }
2553 
2555  const std::string &message) {
2556  FCITX_DEBUG() << "Input method switched";
2557  FCITX_D();
2558  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
2559  inputState->showInputMethodInformation(message);
2560 }
2561 
2563  FCITX_D();
2564  return (isInFlatpak() &&
2565  std::filesystem::is_regular_file("/app/.updated")) ||
2566  d->addonManager_.checkUpdate() || d->imManager_.checkUpdate() ||
2567  postEvent(CheckUpdateEvent());
2568 }
2569 
2570 void Instance::setXkbParameters(const std::string &display,
2571  const std::string &rule,
2572  const std::string &model,
2573  const std::string &options) {
2574 #ifdef ENABLE_KEYBOARD
2575  FCITX_D();
2576  bool resetState = false;
2577  if (auto *param = findValue(d->xkbParams_, display)) {
2578  if (std::get<0>(*param) != rule || std::get<1>(*param) != model ||
2579  std::get<2>(*param) != options) {
2580  std::get<0>(*param) = rule;
2581  std::get<1>(*param) = model;
2582  std::get<2>(*param) = options;
2583  resetState = true;
2584  }
2585  } else {
2586  d->xkbParams_.emplace(display, std::make_tuple(rule, model, options));
2587  }
2588 
2589  if (resetState) {
2590  d->keymapCache_[display].clear();
2591  d->icManager_.foreach([d, &display](InputContext *ic) {
2592  if (ic->display() == display ||
2593  !d->xkbParams_.contains(ic->display())) {
2594  auto *inputState = ic->propertyFor(&d->inputStateFactory_);
2595  inputState->resetXkbState();
2596  }
2597  return true;
2598  });
2599  }
2600 #else
2601  FCITX_UNUSED(display);
2602  FCITX_UNUSED(rule);
2603  FCITX_UNUSED(model);
2604  FCITX_UNUSED(options);
2605 #endif
2606 }
2607 
2608 void Instance::updateXkbStateMask(const std::string &display,
2609  uint32_t depressed_mods,
2610  uint32_t latched_mods, uint32_t locked_mods) {
2611  FCITX_D();
2612  d->stateMask_[display] =
2613  std::make_tuple(depressed_mods, latched_mods, locked_mods);
2614 }
2615 
2616 void Instance::clearXkbStateMask(const std::string &display) {
2617  FCITX_D();
2618  d->stateMask_.erase(display);
2619 }
2620 
2621 const char *Instance::version() { return FCITX_VERSION_STRING; }
2622 
2623 } // namespace fcitx
void updateXkbStateMask(const std::string &display, uint32_t depressed_mods, uint32_t latched_mods, uint32_t locked_mods)
Update xkb state mask for given display.
Definition: instance.cpp:2608
Describe a Key in fcitx.
Definition: key.h:41
void restart()
Restart fcitx instance, this should only be used within a regular Fcitx server, not within embedded m...
Definition: instance.cpp:2087
void reloadAddonConfig(const std::string &addonName)
Reload certain addon config.
Definition: instance.cpp:2028
CapabilityFlags capabilityFlags() const
Returns the current capability flags.
FCITXCORE_DEPRECATED uint32_t processCompose(InputContext *ic, KeySym keysym)
Handle current XCompose state.
Definition: instance.cpp:1830
std::string inputMethodIcon(InputContext *ic)
Return the input method icon for input context.
Definition: instance.cpp:1798
void setXkbParameters(const std::string &display, const std::string &rule, const std::string &model, const std::string &options)
Set xkb RLVMO tuple for given display.
Definition: instance.cpp:2570
void activate()
Activate last focused input context. (Switch to the active input method)
Definition: instance.cpp:1970
EventType
Type of input method events.
Definition: event.h:66
Switched by alternative trigger key.
ResetEvent is generated.
void resetCompose(InputContext *inputContext)
Reset the compose state.
Definition: instance.cpp:1948
T::PropertyType * propertyFor(const T *factory)
Helper function to return the input context property in specific type by given factory.
Definition: inputcontext.h:288
std::string UCS4ToUTF8(uint32_t code)
Convert UCS4 to UTF8 string.
Definition: utf8.cpp:21
FocusInEvent is generated when client gets focused.
Formatted string commonly used in user interface.
Whether client request input method to be disabled.
FocusGroup * defaultFocusGroup(const std::string &displayHint={})
Get the default focus group with given display hint.
Definition: instance.cpp:2434
static uint32_t keySymToUnicode(KeySym sym)
Convert keysym to a unicode.
Definition: key.cpp:738
void flushUI()
All user interface update is batched internally.
Definition: instance.cpp:2403
This is generated when input method group changed.
std::string commitFilter(InputContext *inputContext, const std::string &orig)
Update the commit string to frontend.
Definition: instance.cpp:2362
AddonManager & addonManager()
Get the addon manager.
Definition: instance.cpp:1615
std::string currentInputMethod()
Return the current input method of last focused input context.
Definition: instance.cpp:1995
Manage registered TempMode objects for an Instance.
Simple file system related API for checking file status.
size_t length(Iter start, Iter end)
Return the number UTF-8 characters in the string iterator range.
Definition: utf8.h:33
bool validate(Iter start, Iter end)
Check if the string iterator range is valid utf8 string.
Definition: utf8.h:74
when user switch to a different input method by hand such as ctrl+shift by default, or by ui, default behavior is reset IM.
InputMethodSwitchedReason
The reason why input method is switched to another.
Definition: event.h:42
void deactivate()
Deactivate last focused input context.
Definition: instance.cpp:2009
int state()
Return a fcitx5-remote compatible value for the state.
Definition: instance.cpp:2165
Definition: action.cpp:17
InputMethodEngine * inputMethodEngine(InputContext *ic)
Return the input method engine object for given input context.
Definition: instance.cpp:1778
void setSignalPipe(int fd)
Set the pipe forwarding unix signal information.
Definition: instance.cpp:1385
InputMethodMode inputMethodMode() const
The current global input method mode.
Definition: instance.cpp:1526
void initialize()
Initialize fcitx.
Definition: instance.cpp:1432
EventLoop & eventLoop()
Get the fcitx event loop.
Definition: instance.cpp:1600
std::string currentUI()
Return the name of current user interface addon.
Definition: instance.cpp:2004
bool exitWhenMainDisplayDisconnected() const
Check whether command line specify whether to keep fcitx running.
Definition: instance.cpp:1404
C++ Utility functions for handling utf8 strings.
InputContext * mostRecentInputContext()
Return the most recent focused input context.
Definition: instance.cpp:2398
FCITX_NODISCARD std::unique_ptr< HandlerTableEntry< EventHandler > > watchEvent(EventType type, EventWatcherPhase phase, EventHandler callback)
Add a callback to for certain event type.
Definition: instance.cpp:1714
InputContextManager & inputContextManager()
Get the input context manager.
Definition: instance.cpp:1610
void setEnablePreedit(bool enable)
Override the preedit hint from client.
std::vector< std::string > split(std::string_view str, std::string_view delim, SplitBehavior behavior)
Split the string by delim.
virtual bool filtered() const
Whether a event is filtered by handler.
Definition: event.h:254
void clearGroup(StatusGroup group)
Clear only given status group.
Definition: statusarea.cpp:80
bool hasFocus() const
Returns whether the input context holds the input focus.
bool isRunning() const
Whether event loop is started and still running.
Definition: instance.cpp:1521
A class represents a formatted string.
Definition: text.h:27
bool willTryReplace() const
Check whether command line specify if it will replace an existing fcitx server.
Definition: instance.cpp:1399
Class to manage all the input method relation information.
bool isRestartRequested() const
Whether restart is requested.
Definition: instance.cpp:1540
Manager class for user interface.
Instance(int argc, char *argv[])
A main function like construct to be used to create Fcitx Instance.
Definition: instance.cpp:660
Base class for fcitx event.
Definition: event.h:225
virtual void deactivate(const InputMethodEntry &entry, InputContextEvent &event)
Called when input context switch its input method.
bool isValidChar(uint32_t c)
Check the chr value is not two invalid value above.
Definition: utf8.h:97
std::string inputMethodLabel(InputContext *ic)
Return the input method label for input context.
Definition: instance.cpp:1815
void save()
Save everything including input method profile and addon data.
Definition: instance.cpp:1962
Enum type for input context capability.
Class for status area in UI.
void resetInputMethodList()
Reset the input method configuration and recreate based on system language.
Definition: instance.cpp:2082
Switched by capability change (e.g. password field)
Base class for User Interface addon.
A thread safe class to post event to a certain EventLoop.
void clearXkbStateMask(const std::string &display)
Clear xkb state mask for given display.
Definition: instance.cpp:2616
Enum flag for text formatting.
void configure()
Launch configtool.
Definition: instance.cpp:1986
bool checkUpdate() const
Check if need to invoke Instance::refresh.
Definition: instance.cpp:2562
New Utility classes to handle application specific path.
uint32_t getChar(Iter iter, Iter end)
Get next UCS4 char from iter, do not cross end.
Definition: utf8.h:104
InvokeAction event is generated when client click on the preedit.
InputMethodManager & inputMethodManager()
Get the input method manager.
Definition: instance.cpp:1620
void reloadConfig()
Reload global config.
Definition: instance.cpp:2042
int exec()
Start the event loop of Fcitx.
Definition: instance.cpp:1498
C-style utf8 utility functions.
TempModeManager & tempModeManager()
Get the temporary mode manager.
Definition: instance.cpp:1630
void setBinaryMode()
Set if this instance is running as fcitx5 binary.
Definition: instance.cpp:1576
bool isModifier() const
Check if the key is a modifier press.
Definition: key.cpp:460
InputContext * lastFocusedInputContext()
Return a focused input context.
Definition: instance.cpp:2393
std::string display() const
Returns the display server of the client.
void toggle()
Toggle between the first input method and active input method.
Definition: instance.cpp:2174
Notify the input method mode is changed.
Definition: event.h:659
void setCurrentInputMethod(const std::string &imName)
Set the input method of last focused input context.
Definition: instance.cpp:2096
void setRunning(bool running)
Let other know that event loop is already running.
Definition: instance.cpp:1516
bool canRestart() const
Check if fcitx 5 can safely restart by itself.
Definition: instance.cpp:1581
void showCustomInputMethodInformation(InputContext *ic, const std::string &message)
Show a small popup with input popup window with current input method information. ...
Definition: instance.cpp:2554
std::optional< std::string > processComposeString(InputContext *ic, KeySym keysym)
Handle current XCompose state.
Definition: instance.cpp:1878
void refresh()
Load newly installed input methods and addons.
Definition: instance.cpp:2035
Input method mode changed.
std::string inputMethod(InputContext *ic)
Return the unique name of input method for given input context.
Definition: instance.cpp:1733
UserInterfaceManager & userInterfaceManager()
Get the user interface manager.
Definition: instance.cpp:1635
void enumerate(bool forward)
Enumerate input method with in current group.
Definition: instance.cpp:2182
bool exiting() const
Check whether fcitx is in exiting process.
Definition: instance.cpp:1409
Key sym related types.
void showInputMethodInformation(InputContext *ic)
Show a small popup with input popup window with current input method information. ...
Definition: instance.cpp:2545
StatusArea & statusArea()
Returns the associated StatusArea.
String handle utilities.
Input Method Manager For fcitx.
EventType type() const
Type of event, can be used to decide event class.
Definition: event.h:235
bool empty() const
Whether input panel is totally empty.
Definition: inputpanel.cpp:122
void setInputMethodMode(InputMethodMode mode)
Set the current global input method mode.
Definition: instance.cpp:1531
FCITXCORE_DEPRECATED void reset(ResetReason reason)
Called when input context state need to be reset.
ssize_t safeRead(int fd, void *data, size_t maxlen)
a simple wrapper around read(), ignore EINTR.
Definition: fs.cpp:230
std::string addonForInputMethod(const std::string &imName)
Return the addon name of given input method.
Definition: instance.cpp:1978
Input Context Property for Fcitx.
static std::filesystem::path fcitxPath(const char *path, const std::filesystem::path &subPath={})
Return fcitx specific path defined at compile time.
An input context represents a client of Fcitx.
Definition: inputcontext.h:50
GlobalConfig & globalConfig()
Get the global config.
Definition: instance.cpp:1640
void exit()
Exit the fcitx event loop.
Definition: instance.cpp:2017
EventDispatcher & eventDispatcher()
Return a shared event dispatcher that is already attached to instance&#39;s event loop.
Definition: instance.cpp:1605
Key event is generated when client press or release a key.
const InputMethodEntry * inputMethodEntry(InputContext *ic)
Return the input method entry for given input context.
Definition: instance.cpp:1769
Class to represent a key.
Log utilities.
bool isComposing(InputContext *inputContext)
Check whether input context is composing or not.
Definition: instance.cpp:1930
static std::string keyListToString(const Container &container, KeyStringFormat format=KeyStringFormat::Portable)
Convert a key list to string.
Definition: key.h:204
Notify the global config is reloaded.
Definition: event.h:670
when using lost focus this might be variance case to case.
Addon Manager class.
static const char * version()
Return the version string of Fcitx.
Definition: instance.cpp:2621
Text outputFilter(InputContext *inputContext, const Text &orig)
Update the string that will be displayed in user interface.
Definition: instance.cpp:2369