Fcitx
instance.h
1 /*
2  * SPDX-FileCopyrightText: 2016-2016 CSSlayer <wengxt@gmail.com>
3  *
4  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  */
7 #ifndef _FCITX_INSTANCE_H_
8 #define _FCITX_INSTANCE_H_
9 
10 #include <memory>
11 #include <string>
13 #include <fcitx-utils/eventdispatcher.h>
14 #include <fcitx-utils/macros.h>
15 #include <fcitx/event.h>
16 #include <fcitx/fcitxcore_export.h>
17 #include <fcitx/globalconfig.h>
18 #include <fcitx/text.h>
19 
20 #define FCITX_INVALID_COMPOSE_RESULT 0xffffffff
21 
22 namespace fcitx {
23 
24 class InputContext;
25 class InstancePrivate;
26 class EventLoop;
27 class AddonManager;
28 class InputContextManager;
29 class InputMethodManager;
30 class InputMethodEngine;
31 class InputMethodEntry;
32 class UserInterfaceManager;
33 class GlobalConfig;
34 class FocusGroup;
35 
36 using EventHandler = std::function<void(Event &event)>;
37 
38 /**
39  * The function mode of virtual keyboard.
40  */
41 enum class VirtualKeyboardFunctionMode : uint32_t { Full = 1, Limited = 2 };
42 
43 /**
44  * The event handling phase of event pipeline.
45  */
46 enum class EventWatcherPhase {
47  /**
48  * Handler executed before input method.
49  *
50  * Useful for addons that want to implement an independent mode.
51  *
52  * A common workflow of such addon is:
53  * 1. Check a hotkey in PostInputMethod phase to trigger the mode
54  * 2. Handle all the key event in PreInputMethod phase just like regular
55  * input method.
56  */
57  PreInputMethod,
58  /**
59  * Handlers to be executed right after input method.
60  *
61  * The input method keyEvent is registered with an internal handler. So all
62  * the new handler in this phase will still executed after input method.
63  */
64  InputMethod,
65  /**
66  * Handlers to be executed after input method.
67  *
68  * common use case is when you want to implement a key that triggers a
69  * standalone action.
70  */
71  PostInputMethod,
72  /// Internal phase to be executed first
73  ReservedFirst,
74  /// Internal phase to be executed last
75  ReservedLast,
76  Default = PostInputMethod
77 };
78 
79 struct FCITXCORE_EXPORT InstanceQuietQuit : public std::exception {};
80 
81 /**
82  * An instance represents a standalone Fcitx instance. Usually there is only one
83  * of such object.
84  *
85  * Fcitx Instance provides the access to all the addons and sub components. It
86  * also provides a event pipeline for handling input method related event.
87  */
88 class FCITXCORE_EXPORT Instance : public ConnectableObject {
89 public:
90  /**
91  * A main function like construct to be used to create Fcitx Instance.
92  *
93  * For more details, see --help of fcitx5 command.
94  *
95  * @param argc number of argument
96  * @param argv command line arguments
97  */
98  Instance(int argc, char *argv[]);
99 
100  ~Instance();
101 
102  bool initialized() const { return !!d_ptr; }
103 
104  /**
105  * Set the pipe forwarding unix signal information.
106  *
107  * Fcitx Instance is running within its own thread, usually main thread. In
108  * order to make it handle signal correctly in a thread-safe way, it is
109  * possible to set a file descriptor that write the signal number received
110  * by the signal handler. Usually this is done through a self-pipe. This is
111  * already handled by Fcitx default server implementation, normal addon user
112  * should not touch this. The common usecase is when you want to embed Fcitx
113  * into your own program.
114  *
115  * @param fd file descriptor
116  */
117  void setSignalPipe(int fd);
118 
119  /**
120  * Start the event loop of Fcitx.
121  *
122  * @return return value that can be used as main function return code.
123  */
124  int exec();
125 
126  /**
127  * Check whether command line specify if it will replace an existing fcitx
128  * server.
129  *
130  * This function is only useful if your addon provides a way to replace
131  * existing fcitx server. Basically it is checking whether -r is passed to
132  * fcitx command line.
133  *
134  * @return whether to replace existing fcitx server. Default value is false.
135  */
136  bool willTryReplace() const;
137 
138  /**
139  * Check whether command line specify whether to keep fcitx running.
140  *
141  * There could be multiple display server, such as X/Wayland/etc. Fcitx
142  * usually will exit when the connection is closed. Command line -k can
143  * override this behavior and keep Fcitx running.
144  *
145  * @return whether to exit after main display is disconnected.
146  */
147  bool exitWhenMainDisplayDisconnected() const;
148 
149  /**
150  * Check whether fcitx is in exiting process.
151  *
152  * @return
153  */
154  bool exiting() const;
155 
156  /// Get the fcitx event loop.
157  EventLoop &eventLoop();
158 
159  /**
160  * Return a shared event dispatcher that is already attached to instance's
161  * event loop.
162  *
163  * @return shared event dispatcher.
164  * @since 5.1.9
165  */
166  EventDispatcher &eventDispatcher();
167 
168  /// Get the addon manager.
169  AddonManager &addonManager();
170 
171  /// Get the input context manager
172  InputContextManager &inputContextManager();
173 
174  /// Get the user interface manager
175  UserInterfaceManager &userInterfaceManager();
176 
177  /// Get the input method manager
178  InputMethodManager &inputMethodManager();
179 
180  /// Get the input method manager
181  const InputMethodManager &inputMethodManager() const;
182 
183  /// Get the global config.
184  GlobalConfig &globalConfig();
185 
186  // TODO: Merge this when we can break API.
187  bool postEvent(Event &event);
188  bool postEvent(Event &&event) { return postEvent(event); }
189 
190  /**
191  * Put a event to the event pipe line.
192  *
193  * @param event Input method event
194  * @return return the value of event.accepted()
195  */
196  bool postEvent(Event &event) const;
197  bool postEvent(Event &&event) const { return postEvent(event); }
198 
199  /**
200  * Add a callback to for certain event type.
201  *
202  * @param type event type
203  * @param phase the stage that callback will be executed.
204  * @param callback callback function.
205  * @return Handle to the callback, the callback will be removed when it is
206  * deleted.
207  */
208  FCITX_NODISCARD std::unique_ptr<HandlerTableEntry<EventHandler>>
209  watchEvent(EventType type, EventWatcherPhase phase, EventHandler callback);
210 
211  /// Return the unique name of input method for given input context.
212  std::string inputMethod(InputContext *ic);
213 
214  /// Return the input method entry for given input context.
215  const InputMethodEntry *inputMethodEntry(InputContext *ic);
216 
217  /// Return the input method engine object for given input context.
218  InputMethodEngine *inputMethodEngine(InputContext *ic);
219 
220  /// Return the input method engine object for given unique input method
221  /// name.
222  InputMethodEngine *inputMethodEngine(const std::string &name);
223 
224  /**
225  * Return the input method icon for input context.
226  *
227  * It will fallback to input-keyboard by default if no input method is
228  * available.
229  *
230  * @param ic input context
231  * @return icon name.
232  *
233  * @see InputMethodEngine::subModeIcon
234  */
235  std::string inputMethodIcon(InputContext *ic);
236 
237  /**
238  * Return the input method label for input context.
239  *
240  * @param ic input context
241  * @return label.
242  *
243  * @see InputMethodEngine::subModeLabel
244  * @since 5.0.11
245  */
246  std::string inputMethodLabel(InputContext *ic);
247 
248  /**
249  * Handle current XCompose state.
250  *
251  * @param ic input context.
252  * @param keysym key symbol.
253  *
254  * @return unicode
255  *
256  * @see processComposeString
257  */
258  FCITXCORE_DEPRECATED uint32_t processCompose(InputContext *ic,
259  KeySym keysym);
260 
261  /**
262  * Handle current XCompose state.
263  *
264  * @param ic input context.
265  * @param keysym key symbol.
266  *
267  * @return the composed string, if it returns nullopt, it means compose is
268  * invalid.
269  *
270  * @see processComposeString
271  * @since 5.0.4
272  */
273  std::optional<std::string> processComposeString(InputContext *ic,
274  KeySym keysym);
275 
276  /// Reset the compose state.
277  void resetCompose(InputContext *inputContext);
278 
279  /// Check whether input context is composing or not.
280  bool isComposing(InputContext *inputContext);
281 
282  /**
283  * Update the commit string to frontend
284  *
285  * This function should be not be used directly since it is already used
286  * internally by InputContext::commitString.
287  *
288  * @param inputContext input context
289  * @param orig original string
290  * @return the updated string.
291  * @see InputContext::commitString
292  */
293  std::string commitFilter(InputContext *inputContext,
294  const std::string &orig);
295  /**
296  * Update the string that will be displayed in user interface.
297  *
298  * This function should only be used by frontend for client preedit, or user
299  * interface, for the other field in input panel.
300  *
301  * @see InputPanel
302  *
303  * @param inputContext input context
304  * @param orig orig text
305  * @return fcitx::Text
306  */
307  Text outputFilter(InputContext *inputContext, const Text &orig);
308 
309  FCITX_DECLARE_SIGNAL(Instance, CommitFilter,
310  void(InputContext *inputContext, std::string &orig));
311  FCITX_DECLARE_SIGNAL(Instance, OutputFilter,
312  void(InputContext *inputContext, Text &orig));
313  FCITX_DECLARE_SIGNAL(Instance, KeyEventResult,
314  void(const KeyEvent &keyEvent));
315  /**
316  * \deprecated
317  */
319 
320  /// Return a focused input context.
321  InputContext *lastFocusedInputContext();
322  /// Return the most recent focused input context. If there isn't such ic,
323  /// return the last unfocused input context.
324  InputContext *mostRecentInputContext();
325 
326  /// All user interface update is batched internally. This function will
327  /// flush all the batched UI update immediately.
328  void flushUI();
329 
330  // controller functions.
331 
332  /// Exit the fcitx event loop
333  void exit();
334 
335  /// Exit the fcitx event loop with an exit code.
336  void exit(int exitCode);
337 
338  /// Restart fcitx instance, this should only be used within a regular Fcitx
339  /// server, not within embedded mode.
340  void restart();
341 
342  /// Launch configtool
343  void configure();
344 
345  FCITXCORE_DEPRECATED void configureAddon(const std::string &addon);
346  FCITXCORE_DEPRECATED void configureInputMethod(const std::string &imName);
347 
348  /// Return the name of current user interface addon.
349  std::string currentUI();
350 
351  /// Return the addon name of given input method.
352  std::string addonForInputMethod(const std::string &imName);
353 
354  // Following functions are operations against lastFocusedInputContext
355 
356  /// Activate last focused input context. (Switch to the active input method)
357  void activate();
358 
359  /// Deactivate last focused input context. (Switch to the first input
360  /// method)
361  void deactivate();
362 
363  /// Toggle between the first input method and active input method.
364  void toggle();
365 
366  /// Reset the input method configuration and recreate based on system
367  /// language.
368  void resetInputMethodList();
369 
370  /// Return a fcitx5-remote compatible value for the state.
371  int state();
372 
373  /// Reload global config.
374  void reloadConfig();
375  /// Reload certain addon config.
376  void reloadAddonConfig(const std::string &addonName);
377  /// Load newly installed input methods and addons.
378  void refresh();
379 
380  /// Return the current input method of last focused input context.
381  std::string currentInputMethod();
382 
383  /// Set the input method of last focused input context.
384  void setCurrentInputMethod(const std::string &imName);
385 
386  /**
387  * Set the input method of given input context.
388  *
389  * The input method need to be within the current group. Local parameter can
390  * be used to set the input method only for this input context.
391  *
392  * @param ic input context
393  * @param imName unique name of a input method
394  * @param local
395  */
396  void setCurrentInputMethod(InputContext *ic, const std::string &imName,
397  bool local);
398 
399  /*
400  * Enumerate input method group
401  *
402  * This function has different behavior comparing to
403  * InputMethodManager::enumerateGroup Do not use this..
404  */
405  FCITXCORE_DEPRECATED
406  bool enumerateGroup(bool forward);
407 
408  /// Enumerate input method with in current group
409  void enumerate(bool forward);
410 
411  /**
412  * Get the default focus group with given display hint.
413  *
414  * This function is used by frontend to assign a focus group from an unknown
415  * display server.
416  *
417  * @param displayHint Display server hint, it can something like be x11: /
418  * wayland:
419  * @return focus group
420  */
421  FocusGroup *defaultFocusGroup(const std::string &displayHint = {});
422 
423  /**
424  * Set xkb RLVMO tuple for given display
425  *
426  * @param display display name
427  * @param rule xkb rule name
428  * @param model xkb model name
429  * @param options xkb option
430  */
431  void setXkbParameters(const std::string &display, const std::string &rule,
432  const std::string &model, const std::string &options);
433 
434  /// Update xkb state mask for given display
435  void updateXkbStateMask(const std::string &display, uint32_t depressed_mods,
436  uint32_t latched_mods, uint32_t locked_mods);
437 
438  /// Clear xkb state mask for given display
439  void clearXkbStateMask(const std::string &display);
440 
441  /**
442  * Show a small popup with input popup window with current input method
443  * information.
444  *
445  * The popup will be hidden after certain amount of time.
446  *
447  * This is useful for input method that has multiple sub modes. It can be
448  * called with switching sub modes within the input method.
449  *
450  * The behavior is controlled by global config.
451  *
452  * @param ic input context.
453  */
454  void showInputMethodInformation(InputContext *ic);
455 
456  /**
457  * Show a small popup with input popup window with current input method
458  * information.
459  *
460  * The popup will be hidden after certain amount of time. The popup will
461  * always be displayed, regardless of the showInputMethodInformation in
462  * global config.
463  *
464  * This is useful for input method that has internal switches.
465  *
466  * @param ic input context.
467  * @param message message string to be displayed
468  * @since 5.1.11
469  */
470  void showCustomInputMethodInformation(InputContext *ic,
471  const std::string &message);
472 
473  /**
474  * Check if need to invoke Instance::refresh.
475  *
476  * @return need update
477  * @see Instance::refresh
478  */
479  bool checkUpdate() const;
480 
481  /// Return the version string of Fcitx.
482  static const char *version();
483 
484  /**
485  * Save everything including input method profile and addon data.
486  *
487  * It also reset the idle save timer.
488  *
489  * @since 5.0.14
490  */
491  void save();
492 
493  /**
494  * Initialize fcitx.
495  *
496  * This is only intended to be used if you want to handle event loop on your
497  * own. Otherwise you should use Instance::exec().
498  *
499  * @since 5.0.14
500  */
501  void initialize();
502 
503  /**
504  * Let other know that event loop is already running.
505  *
506  * This should only be used if you run event loop on your own.
507  * @since 5.0.14
508  */
509  void setRunning(bool running);
510 
511  /**
512  * Whether event loop is started and still running.
513  * @since 5.0.14
514  */
515  bool isRunning() const;
516 
517  /**
518  * The current global input method mode.
519  *
520  * It may affect the user interface and behavior of certain key binding.
521  * @since 5.1.0
522  */
523  InputMethodMode inputMethodMode() const;
524 
525  /**
526  * Set the current global input method mode.
527  *
528  * @see InputMethodMode
529  * @see InputMethodModeChanged
530  * @since 5.1.0
531  */
532  void setInputMethodMode(InputMethodMode mode);
533 
534  /**
535  * Whether restart is requested.
536  * @since 5.0.18
537  */
538  bool isRestartRequested() const;
539 
540  bool virtualKeyboardAutoShow() const;
541 
542  void setVirtualKeyboardAutoShow(bool autoShow);
543 
544  bool virtualKeyboardAutoHide() const;
545 
546  void setVirtualKeyboardAutoHide(bool autoHide);
547 
548  VirtualKeyboardFunctionMode virtualKeyboardFunctionMode() const;
549 
550  void setVirtualKeyboardFunctionMode(VirtualKeyboardFunctionMode mode);
551 
552  /**
553  * Set if this instance is running as fcitx5 binary.
554  *
555  * This will affect return value of Instance::canRestart.
556  *
557  * @see Instance::canRestart
558  * @since 5.1.6
559  */
560  void setBinaryMode();
561 
562  /**
563  * Check if fcitx 5 can safely restart by itself.
564  *
565  * When the existing fcitx 5 instance returns false, fcitx5 -r, or
566  * Instance::restart will just be no-op.
567  *
568  * @return whether it is safe for fcitx to restart on its own.
569  * @see AddonInstance::setCanRestart
570  * @since 5.1.6
571  */
572  bool canRestart() const;
573 
574 protected:
575  // For testing purpose
576  InstancePrivate *privateData();
577 
578 private:
579  void handleSignal();
580 
581  bool canTrigger() const;
582  bool canAltTrigger(InputContext *ic) const;
583  bool canEnumerate(InputContext *ic) const;
584  bool canChangeGroup() const;
585  bool trigger(InputContext *ic, bool totallyReleased);
586  bool altTrigger(InputContext *ic);
587  bool activate(InputContext *ic);
588  bool deactivate(InputContext *ic);
589  bool enumerate(InputContext *ic, bool forward);
590  bool toggle(InputContext *ic, InputMethodSwitchedReason reason =
592 
593  void activateInputMethod(InputContextEvent &event);
594  void deactivateInputMethod(InputContextEvent &event);
595 
596  std::unique_ptr<InstancePrivate> d_ptr;
597  FCITX_DECLARE_PRIVATE(Instance);
598 };
599 }; // namespace fcitx
600 
601 #endif // _FCITX_INSTANCE_H_
Base class for all object supports connection.
EventType
Type of input method events.
Definition: event.h:65
An instance represents a standalone Fcitx instance.
Definition: instance.h:88
Formatted string commonly used in user interface.
#define FCITX_DECLARE_SIGNAL(CLASS_NAME, NAME,...)
Declare signal by type.
InputMethodSwitchedReason
The reason why input method is switched to another.
Definition: event.h:41
Definition: action.cpp:17
Utilities to enable use object with signal.
A class represents a formatted string.
Definition: text.h:27
Class to manage all the input method relation information.
Base class for fcitx event.
Definition: event.h:212
A thread safe class to post event to a certain EventLoop.
CheckUpdateEvent is posted when the Instance is requested to check for newly installed addons and inp...
Input Method event for Fcitx.
An input context represents a client of Fcitx.
Definition: inputcontext.h:47