### LibPinyinBackEnd Initialization and Instance Management Example Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Example demonstrating how to initialize the LibPinyinBackEnd and PinyinConfig, allocate and free a Pinyin instance, and finalize the backend. ```cpp // Example: initialise backend and create a Pinyin instance LibPinyinBackEnd::init(); PinyinConfig::init(); pinyin_instance_t *inst = LibPinyinBackEnd::instance().allocPinyinInstance(); // ... use inst with libpinyin API ... LibPinyinBackEnd::instance().freePinyinInstance(inst); LibPinyinBackEnd::finalize(); ``` -------------------------------- ### Launch Setup Dialog Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Commands to launch the ibus-libpinyin setup dialog for different engines or to resync engine XML files. ```bash # Launch the Pinyin setup dialog ibus-setup-libpinyin libpinyin # Launch the Bopomofo setup dialog ibus-setup-libpinyin libbopomofo # Resync the engine XML file (called automatically on version mismatch) ibus-setup-libpinyin resync-engine ``` -------------------------------- ### Build and Install ibus-libpinyin Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Steps to build and install ibus-libpinyin from source, including dependency installation and configuration for optional features. Ensure to recompile GSettings schemas and restart IBus after installation. ```bash # Install dependencies (Fedora/RHEL example) sudo dnf install ibus-devel libpinyin-devel sqlite-devel lua-devel \ libsoup3-devel json-glib-devel libnotify-devel opencc-devel # Generate configure script ./autogen.sh # Configure with all optional features enabled ./configure \ --prefix=/usr \ --enable-opencc \ --enable-lua-extension \ --enable-cloud-input-mode \ --enable-english-input-mode \ --enable-table-input-mode \ --enable-libnotify # Build and install make -j$(nproc) sudo make install # Recompile GSettings schema sudo glib-compile-schemas /usr/share/glib-2.0/schemas/ # Restart IBus ibus restart ``` -------------------------------- ### EnglishDatabase Usage Example Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Example of using EnglishDatabase to list words starting with a prefix and to train word frequencies. ```cpp std::vector results; EnglishDatabase::instance().listWords("hel", results); // results → ["hello", "help", "held", "helm", ...] // Commit "hello" → reinforce frequency EnglishDatabase::instance().train("hello", 1.0f); ``` -------------------------------- ### Setup Dialog GSettings Configuration Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Demonstrates how to instantiate and use Gio.Settings in Python to read and write configuration values for the ibus-libpinyin engine. ```python # setup/main2.py — PreferencesDialog instantiation from gi.repository import Gio # The dialog binds directly to GSettings schemas config = Gio.Settings.new("com.github.libpinyin.ibus-libpinyin.libpinyin") # Reading a value page_size = config.get_value("lookup-table-page-size").get_int32() # → 5 # Writing a value from gi.repository import GLib config.set_value("fuzzy-pinyin", GLib.Variant.new_boolean(True)) config.set_value("lookup-table-page-size", GLib.Variant.new_int32(9)) config.set_value("double-pinyin", GLib.Variant.new_boolean(True)) config.set_value("double-pinyin-schema", GLib.Variant.new_int32(1)) ``` -------------------------------- ### Connecting Editor Signals in PinyinEngine Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Example demonstrating how to connect signals from an Editor instance to handler methods within the PinyinEngine class. ```APIDOC ## Connecting Editor Signals ### Description This example shows how to connect signals emitted by an `Editor` object to corresponding methods in the `PinyinEngine` class, enabling communication between the input buffer and the engine. ### Example ```cpp void PinyinEngine::connectEditorSignals(EditorPtr editor) { editor->signalCommitText().connect( [this](Text &text) { this->commitText(text); }); editor->signalUpdatePreeditText().connect( [this](Text &text, guint cursor, gboolean visible) { this->updatePreeditText(text, cursor, visible); }); editor->signalUpdateLookupTable().connect( [this](LookupTable &table, gboolean visible) { this->updateLookupTable(table, visible); }); } ``` ### Signals Connected - **`signalCommitText()`**: Connected to `PinyinEngine::commitText`. - **`signalUpdatePreeditText()`**: Connected to `PinyinEngine::updatePreeditText`. - **`signalUpdateLookupTable()`**: Connected to `PinyinEngine::updateLookupTable`. ``` -------------------------------- ### Connecting Editor Signals in PinyinEngine Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Example of how to connect signals from an Editor instance to corresponding methods within the PinyinEngine class. This is typically done during editor initialization. ```cpp // Example: connecting editor signals in PinyinEngine void PinyinEngine::connectEditorSignals(EditorPtr editor) { editor->signalCommitText().connect( [this](Text &text) { this->commitText(text); }); editor->signalUpdatePreeditText().connect( [this](Text &text, guint cursor, gboolean visible) { this->updatePreeditText(text, cursor, visible); }); editor->signalUpdateLookupTable().connect( [this](LookupTable &table, gboolean visible) { this->updateLookupTable(table, visible); }); } ``` -------------------------------- ### Table Input Custom Table Import Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Example of importing a custom phrase table using gsettings. The file format is tab-separated, with phrases and their codes. ```bash $ gsettings set com.github.libpinyin.ibus-libpinyin.libpinyin \ import-custom-table '/home/user/my_table.txt' File format (tab-separated): 你好 3131 中文 2132 ``` -------------------------------- ### ibus-libpinyin Engine Startup and Registration Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Demonstrates the typical IBus component registration flow and command-line options for the ibus-libpinyin engine. This includes running in normal IBus mode, debug mode, and printing the engine's XML descriptor or version. ```c++ // Typical IBus component registration flow (from PYMain.cc) // Invoked automatically by ibus-daemon; can also be run manually for debugging. // Run in normal IBus mode (engine registered via ibus-daemon) // ibus-engine-libpinyin --ibus // Run in debug/standalone mode (engine registers itself with the bus directly) // ibus-engine-libpinyin // Print the active engine XML descriptor (used by ibus-daemon) // ibus-engine-libpinyin --xml // Print version // ibus-engine-libpinyin --version // Output: ibus-libpinyin - Version 1.16.6 // Internal startup sequence (simplified from start_component()): // ibus_init(); // LibPinyinBackEnd::init(); // initialise libpinyin contexts // PinyinConfig::init(); // load GSettings for Pinyin engine // BopomofoConfig::init(); // load GSettings for Bopomofo engine // EnglishDatabase::init(); // open SQLite English word DB // TableDatabase::init(); // open SQLite stroke/radical table DB // factory = ibus_factory_new(connection); // ibus_factory_add_engine(factory, "libpinyin", IBUS_TYPE_PINYIN_ENGINE); // ibus_factory_add_engine(factory, "libbopomofo", IBUS_TYPE_PINYIN_ENGINE); // ibus_main(); // GLib main loop ``` -------------------------------- ### LibPinyinBackEnd Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt A singleton context manager for libpinyin, handling Pinyin and Chewing contexts, user database persistence, and configuration bridging. ```APIDOC ## LibPinyinBackEnd ### Description Manages libpinyin contexts (Pinyin and Chewing), handles user database persistence, and bridges GSettings configuration to libpinyin options. It is a singleton class. ### Singleton Access - `LibPinyinBackEnd &instance()`: Returns the singleton instance. - `init()`: Initializes the backend (call once at startup). - `finalize()`: Finalizes the backend (call at shutdown). ### Configuration - `setPinyinOptions(Config *config)`: Applies GSettings-based options to the Pinyin context. - `setChewingOptions(Config *config)`: Applies GSettings-based options to the Chewing (Bopomofo) context. ### Instance Management - `allocPinyinInstance()`: Allocates a new Pinyin instance. - `freePinyinInstance(pinyin_instance_t *instance)`: Frees a Pinyin instance. - `allocChewingInstance()`: Allocates a new Chewing (Bopomofo) instance. - `freeChewingInstance(pinyin_instance_t *instance)`: Frees a Chewing instance. ### User Data Management - `modified()`: Marks the user database as dirty, triggering a deferred save. - `exportUserPhrase(FILE *dictfile)`: Exports user phrases to a file. - `exportBigramPhrase(FILE *dictfile)`: Exports bigram phrases to a file. - `importPinyinDictionary(const char *filename)`: Imports a Pinyin dictionary from a file. - `exportPinyinDictionary(const char *filename)`: Exports the Pinyin dictionary to a file. - `clearPinyinUserData(const char *target)`: Clears user data (target can be "user" or "all"). ### Learning - `rememberUserInput(pinyin_instance_t *instance, const gchar *phrase)`: Learns a user-committed phrase. - `rememberCloudInput(pinyin_instance_t *instance, const gchar *pinyin, const gchar *phrase)`: Learns from cloud input, associating raw pinyin with a phrase. ``` -------------------------------- ### Available GSettings Keys for libpinyin Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Lists the available GSettings keys for the libpinyin schema, categorized by type (boolean, integer, string). ```text # Available GSettings keys for libpinyin schema: # bool: init-chinese, init-full, init-full-punct, init-simplified-chinese, # double-pinyin, double-pinyin-show-raw, incomplete-pinyin, # correct-pinyin, fuzzy-pinyin, dynamic-adjust, remember-every-input, # shift-select-candidate, minus-equal-page, comma-period-page, # square-bracket-page, auto-commit, lua-extension, english-input-mode, # table-input-mode, use-custom-table, emoji-candidate, # english-candidate, suggestion-candidate, enable-cloud-input, # export-user-phrase, export-bigram-phrase # int: double-pinyin-schema (0..N), lookup-table-orientation (0|1), # lookup-table-page-size (1..10), display-style (0|1|2), # sort-candidate-option, cloud-input-source (0|1), # cloud-candidates-number, cloud-request-delay-time (200..2000) # string: dictionaries, lua-converter, opencc-config, keyboard-layout, # main-switch, letter-switch, punct-switch, both-switch, trad-switch, # import-dictionary, export-dictionary, clear-user-data ``` -------------------------------- ### Cloud Input Configuration Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Configuration settings for enabling and customizing cloud input mode via GSettings. ```bash $ gsettings set com.github.libpinyin.ibus-libpinyin.libpinyin enable-cloud-input true $ gsettings set com.github.libpinyin.ibus-libpinyin.libpinyin cloud-input-source 1 (0 = GOOGLE, 1 = GOOGLE_CN) $ gsettings set com.github.libpinyin.ibus-libpinyin.libpinyin cloud-candidates-number 3 $ gsettings set com.github.libpinyin.ibus-libpinyin.libpinyin cloud-request-delay-time 400 ``` -------------------------------- ### LibPinyinBackEnd Singleton Class Definition Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Defines the LibPinyinBackEnd singleton for managing Pinyin and Chewing contexts, user database persistence, and GSettings configuration. ```cpp class LibPinyinBackEnd { public: // Singleton access static LibPinyinBackEnd &instance(); static void init(); // called once at startup static void finalize(); // called at shutdown / SIGTERM // Apply GSettings-based options to the libpinyin context gboolean setPinyinOptions(Config *config); gboolean setChewingOptions(Config *config); // Allocate / free per-editor libpinyin instances pinyin_instance_t *allocPinyinInstance(); void freePinyinInstance(pinyin_instance_t *instance); pinyin_instance_t *allocChewingInstance(); void freeChewingInstance(pinyin_instance_t *instance); // Mark the user DB as dirty (triggers a deferred save) void modified(); // User phrase management gboolean exportUserPhrase(FILE *dictfile); gboolean exportBigramPhrase(FILE *dictfile); gboolean importPinyinDictionary(const char *filename); gboolean exportPinyinDictionary(const char *filename); gboolean clearPinyinUserData(const char *target); // target: "user" or "all" // Learning — called after a candidate is committed gboolean rememberUserInput(pinyin_instance_t *instance, const gchar *phrase); // Learning from cloud input (pinyin is the raw romanisation) gboolean rememberCloudInput(pinyin_instance_t *instance, const gchar *pinyin, const gchar *phrase); }; ``` -------------------------------- ### Enable Suggestion Candidates Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Command to enable suggestion candidates in GSettings. After committing a phrase, the engine enters suggestion mode showing predicted continuations. ```bash // Enable suggestion candidates: // $ gsettings set com.github.libpinyin.ibus-libpinyin.libpinyin suggestion-candidate true // After committing "你好", the engine enters suggestion mode showing // predicted continuations such as "世界", "朋友", "呀", etc. ``` -------------------------------- ### PinyinEngine Class Definition (PYPPinyinEngine.h) Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Defines the concrete 'PinyinEngine' class, inheriting from 'Engine'. It manages different input modes and dispatches key events to the active editor. This class implements the pure virtual methods from the base 'Engine' class. ```cpp // Input modes managed by PinyinEngine enum { MODE_INIT = 0, // normal Chinese Pinyin mode MODE_PUNCT, // full-width punctuation mode MODE_RAW, // raw Latin pass-through MODE_ENGLISH, // press 'v' → English word input MODE_TABLE, // press 'u' → stroke/radical table input MODE_EXTENSION, // press 'i' → Lua extension commands MODE_SUGGESTION, // post-commit suggestion mode MODE_LAST, }; // PinyinEngine public interface class PinyinEngine : public Engine { public: PinyinEngine(IBusEngine *engine); ~PinyinEngine(); gboolean processKeyEvent(guint keyval, guint keycode, guint modifiers) override; gboolean processAccelKeyEvent(guint keyval, guint keycode, guint modifiers); void focusIn() override; void focusOut() override; void reset() override; void enable() override; void disable() override; void pageUp() override; void pageDown() override; void cursorUp() override; void cursorDown() override; gboolean propertyActivate(const gchar *prop_name, guint prop_state) override; void candidateClicked(guint index, guint button, guint state) override; private: gboolean processPunct(guint keyval, guint keycode, guint modifiers); void showSetupDialog(); void connectEditorSignals(EditorPtr editor); // Lua plugin support (when compiled with --enable-lua-extension) gboolean initLuaPlugin(); gboolean loadLuaScript(const char *filename); }; ``` -------------------------------- ### FullPinyinEditor Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Implements character insertion and preedit rendering for standard full-syllable Pinyin input. ```APIDOC ## FullPinyinEditor ### Description Provides functionality for inserting characters and rendering preedit text for the full Pinyin input scheme. ### Methods - `FullPinyinEditor(PinyinProperties &props, Config &config)`: Constructor. - `insert(gint ch)`: Inserts a character. - `processKeyEvent(guint keyval, guint keycode, guint modifiers)`: Processes key events. - `reset()`: Resets the editor state. - `updateAuxiliaryText()`: Updates auxiliary text. - `updatePinyin()`: Updates Pinyin internal state. - `getLookupCursor()`: Retrieves the cursor position for lookup. ``` -------------------------------- ### Lua API for Registering Commands and Triggers Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt This section shows how to use the `ime` library in Lua scripts to register custom commands and triggers, defining their behavior and associated descriptions. ```APIDOC ## Lua API for Registering Commands and Triggers ### Description Provides functions within Lua scripts to register custom commands and triggers, enabling users to extend the input method engine's functionality. ### Functions #### `ime.register_command(trigger_chars, lua_function, description, leading, help)` Registers a new command that can be triggered by specific characters. - `trigger_chars` (string): The two-character prefix to trigger the command. - `lua_function` (string): The name of the Lua function to execute. - `description` (string): A brief description of the command. - `leading` (string): Specifies input requirements (e.g., "alpha" for alphabetic input, "none" for no input required). - `help` (string): Help text for the command. **Examples:** - `ime.register_command("sj", "get_time", "输入时间", "alpha", "输入可选时间,例如12:34")` - `ime.register_command("rq", "get_date", "输入日期", "alpha", "输入可选日期,例如2013-01-01")` - `ime.register_command("js", "compute", "计算模式", "none", "输入表达式,例如log(2)")` - `ime.register_command("xz", "query_zodiac", "查询星座", "none", "输入您的生日,例如12-3")` #### `ime.register_trigger(lua_function, description, input_triggers, candidate_triggers)` Registers a trigger that can be activated by specific input or candidate strings. - `lua_function` (string): The name of the Lua function to execute when the trigger is activated. - `description` (string): A description of the trigger. - `input_triggers` (table): A list of input strings that activate the trigger. - `candidate_triggers` (table): A list of candidate strings that activate the trigger. **Examples:** - `ime.register_trigger("get_current_time", "显示时间", {}, {'时间'})` - `ime.register_trigger("get_today", "显示日期", {}, {'日期'})` ### Usage Examples **Command Example:** Typing `wh` followed by `Alice` yields the candidate `你好,Alice!` after registering a `greet` function: ```lua function greet(input) return "你好," .. input .. "!" end ime.register_command("wh", "greet", "问候", "alpha", "输入名字") ``` **Trigger Example:** Typing `sj` in the engine shows time candidates. ``` -------------------------------- ### Accessing Pinyin Configuration Keys Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Use these key accessors to read GSettings values for Pinyin configuration. Changes made via gsettings CLI are reflected at runtime without engine restart. ```cpp // Key accessors on Config (all read GSettings values) config.doublePinyin() // bool — double-pinyin mode config.doublePinyinSchema() // DoublePinyinScheme enum config.pageSize() // guint — candidates per page (default 5) config.orientation() // guint — 0=horizontal, 1=vertical config.displayStyle() // DisplayStyle: TRADITIONAL | COMPACT | COMPATIBILITY config.fuzzyPinyin() // bool — fuzzy phoneme matching config.emojiCandidate() // bool — show emoji in candidates config.englishCandidate() // bool — show English words in candidates config.suggestionCandidate() // bool — post-commit suggestions config.enableCloudInput() // bool — cloud input (requires libsoup3) config.cloudInputSource() // CloudInputSource: GOOGLE | GOOGLE_CN config.cloudCandidatesNumber() // guint — how many cloud candidates to fetch config.cloudRequestDelayTime() // guint — milliseconds delay before cloud request config.luaExtension() // bool — Lua scripting enabled config.luaConverter() // string — active Lua converter function name config.mainSwitch() // string — shortcut for Chinese/English toggle (e.g. "") config.punctSwitch() // string — shortcut for full/half punctuation config.tradSwitch() // string — shortcut for Simplified/Traditional toggle config.openccConfig() // string — OpenCC config file (e.g. "s2tw.json") config.rememberEveryInput() // bool — learn every committed phrase config.shiftSelectCandidate() // bool — Shift+1..9 selects candidates ``` -------------------------------- ### C API for Lua Plugin Management Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt This section details the C functions available for managing the Lua plugin object, including creation, script loading, and registration/querying of commands, triggers, and converters. ```APIDOC ## C API for Lua Plugin Management ### Description Functions for creating and managing the Lua plugin object, loading Lua scripts, and registering/querying commands, triggers, and converters. ### Functions #### Plugin Object Management - `IBusEnginePlugin *ibus_engine_plugin_new()`: Creates a new Lua plugin object. - `int ibus_engine_plugin_load_lua_script(IBusEnginePlugin *plugin, const char *filename)`: Loads a Lua script into the plugin. #### Command Management - `gboolean ibus_engine_plugin_add_command(IBusEnginePlugin *plugin, lua_command_t *cmd)`: Adds a custom command. - `const GArray *ibus_engine_plugin_get_available_commands(IBusEnginePlugin *plugin)`: Retrieves a list of available commands. - `const lua_command_t *ibus_engine_plugin_lookup_command(IBusEnginePlugin *plugin, const char *name)`: Looks up a command by its name. #### Trigger Management - `gboolean ibus_engine_plugin_add_trigger(IBusEnginePlugin *plugin, lua_trigger_t *trigger)`: Adds a custom trigger. - `const GArray *ibus_engine_plugin_get_available_triggers(IBusEnginePlugin *plugin)`: Retrieves a list of available triggers. - `gboolean ibus_engine_plugin_match_input(IBusEnginePlugin *plugin, const char *input, const char **func)`: Matches input against registered triggers. - `gboolean ibus_engine_plugin_match_candidate(IBusEnginePlugin *plugin, const char *cand, const char **func)`: Matches a candidate string against registered triggers. #### Converter Management - `gboolean ibus_engine_plugin_add_converter(IBusEnginePlugin *plugin, lua_converter_t *converter)`: Adds a custom converter. - `gboolean ibus_engine_plugin_set_converter(IBusEnginePlugin *plugin, const char *lua_function_name)`: Sets the active converter. - `const char *ibus_engine_plugin_get_converter(IBusEnginePlugin *plugin)`: Retrieves the name of the current converter. #### Lua Function Execution - `int ibus_engine_plugin_call(IBusEnginePlugin *plugin, const char *func, const char *arg /*nullable*/)`: Calls a Lua function with an optional argument. - `gint ibus_engine_plugin_get_n_result(IBusEnginePlugin *plugin)`: Gets the number of results from the last function call. - `gchar *ibus_engine_plugin_get_nth_result(IBusEnginePlugin *plugin, gint index)`: Retrieves the Nth result from the last function call. - `void ibus_engine_plugin_clear_results(IBusEnginePlugin *plugin)`: Clears the results from the last function call. - `const lua_command_candidate_t *ibus_engine_plugin_get_retval(IBusEnginePlugin *plugin)`: Gets the return value of the last function call. - `GArray *ibus_engine_plugin_get_retvals(IBusEnginePlugin *plugin)`: Gets all return values of the last function call. - `void ibus_engine_plugin_free_candidate(lua_command_candidate_t *candidate)`: Frees a candidate object. ``` -------------------------------- ### Modifying Pinyin Configuration via gsettings CLI Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Change settings at runtime using the gsettings command-line tool. No engine restart is necessary for these changes to take effect. ```bash // Change a setting at runtime via gsettings CLI (no engine restart needed) // $ gsettings set com.github.libpinyin.ibus-libpinyin.libpinyin fuzzy-pinyin true // $ gsettings set com.github.libpinyin.ibus-libpinyin.libpinyin double-pinyin true // $ gsettings set com.github.libpinyin.ibus-libpinyin.libpinyin double-pinyin-schema 1 // $ gsettings set com.github.libpinyin.ibus-libpinyin.libpinyin lookup-table-page-size 9 // $ gsettings set com.github.libpinyin.ibus-libpinyin.libpinyin enable-cloud-input true // $ gsettings set com.github.libpinyin.ibus-libpinyin.libpinyin cloud-input-source 1 ``` -------------------------------- ### C API for Lua Plugin Management Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Provides functions for creating, loading scripts, and managing commands, triggers, and converters within the Lua plugin system. Also includes functions for calling Lua functions and retrieving results. ```c // C API for managing the Lua plugin object IBusEnginePlugin *ibus_engine_plugin_new(); int ibus_engine_plugin_load_lua_script(IBusEnginePlugin *plugin, const char *filename); // Register / query commands gboolean ibus_engine_plugin_add_command(IBusEnginePlugin *plugin, lua_command_t *cmd); const GArray *ibus_engine_plugin_get_available_commands(IBusEnginePlugin *plugin); const lua_command_t *ibus_engine_plugin_lookup_command(IBusEnginePlugin *plugin, const char *name); // Register / query triggers gboolean ibus_engine_plugin_add_trigger(IBusEnginePlugin *plugin, lua_trigger_t *trigger); const GArray *ibus_engine_plugin_get_available_triggers(IBusEnginePlugin *plugin); gboolean ibus_engine_plugin_match_input(IBusEnginePlugin *plugin, const char *input, const char **func); gboolean ibus_engine_plugin_match_candidate(IBusEnginePlugin *plugin, const char *cand, const char **func); // Register / select converters gboolean ibus_engine_plugin_add_converter(IBusEnginePlugin *plugin, lua_converter_t *converter); gboolean ibus_engine_plugin_set_converter(IBusEnginePlugin *plugin, const char *lua_function_name); const char *ibus_engine_plugin_get_converter(IBusEnginePlugin *plugin); // Call a Lua function and retrieve results int ibus_engine_plugin_call(IBusEnginePlugin *plugin, const char *func, const char *arg /*nullable*/); gint ibus_engine_plugin_get_n_result(IBusEnginePlugin *plugin); gchar *ibus_engine_plugin_get_nth_result(IBusEnginePlugin *plugin, gint index); void ibus_engine_plugin_clear_results(IBusEnginePlugin *plugin); const lua_command_candidate_t *ibus_engine_plugin_get_retval(IBusEnginePlugin *plugin); GArray *ibus_engine_plugin_get_retvals(IBusEnginePlugin *plugin); void ibus_engine_plugin_free_candidate(lua_command_candidate_t *candidate); ``` -------------------------------- ### Abstract Engine Class Definition (PYEngine.h) Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Defines the abstract C++ base class 'Engine' that wraps an IBusEngine*. It declares pure virtual methods that must be implemented by subclasses and protected helper methods for interacting with the IBus C API. ```cpp // PYEngine.h — key virtual interface namespace PY { class Engine { public: Engine(IBusEngine *engine); virtual ~Engine(); // Returns true when the current input field is a password field gboolean contentIsPassword(); // --- Pure virtual interface (must be implemented by PinyinEngine) --- virtual gboolean processKeyEvent(guint keyval, guint keycode, guint modifiers) = 0; virtual void focusIn() = 0; virtual void reset() = 0; virtual void enable() = 0; virtual void disable() = 0; virtual void pageUp() = 0; virtual void pageDown() = 0; virtual void cursorUp() = 0; virtual void cursorDown() = 0; virtual gboolean propertyActivate(const gchar *prop_name, guint prop_state) = 0; virtual void candidateClicked(guint index, guint button, guint state) = 0; protected: // Helpers that forward to ibus_engine_* C API void commitText(Text &text); void updatePreeditText(Text &text, guint cursor, gboolean visible); void updateLookupTable(LookupTable &table, gboolean visible); void updateAuxiliaryText(Text &text, gboolean visible); void registerProperties(PropList &props); void updateProperty(Property &prop); protected: Pointer m_engine; IBusInputPurpose m_input_purpose; // IBUS_CHECK_VERSION >= 1.5.4 }; // Helper: convert a keyval+modifier pair to a human-readable accelerator name // e.g. keyval=GDK_KEY_f, modifiers=IBUS_CONTROL_MASK | IBUS_SHIFT_MASK // → name = "f" gputBoolean pinyin_accelerator_name(guint keyval, guint modifiers, std::string &name); } // namespace PY ``` -------------------------------- ### BopomofoEditor Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Manages character insertion and preedit rendering for Zhuyin (Bopomofo) phonetic notation, primarily for zh_TW locale. ```APIDOC ## BopomofoEditor ### Description Handles input and preedit rendering for the Zhuyin (Bopomofo) phonetic system, used mainly with the "libbopomofo" engine for the zh_TW locale. ### Methods - `BopomofoEditor(PinyinProperties &props, Config &config)`: Constructor. - `processBopomofo(guint keyval, guint keycode, guint modifiers)`: Processes Bopomofo input. - `processGuideKey(guint keyval, guint keycode, guint modifiers)`: Processes guide key events. - `processSelectKey(guint keyval, guint keycode, guint modifiers)`: Processes select key events. - `updateLookupTableLabel()`: Updates the lookup table label. - `updateLookupTable()`: Updates the lookup table. - `updatePreeditText()`: Updates the preedit text. - `updateAuxiliaryText()`: Updates auxiliary text. - `updatePinyin()`: Updates Pinyin internal state. - `commit(const gchar *str)`: Commits a string. - `insert(gint ch)`: Inserts a character. - `reset()`: Resets the editor state. ``` -------------------------------- ### Lua API for Registering Commands and Triggers Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Defines how to register custom commands and triggers using the `ime` library in Lua scripts. Commands can be triggered by specific character sequences and have optional input requirements. ```lua -- lua/base.lua — built-in Lua commands (excerpt) -- Custom commands are added to ~/.config/ibus/libpinyin/user.lua --ime.register_command(trigger_chars, lua_function, description, leading, help) -- leading: "alpha" = input must be alpha chars, "none" = no input required ime.register_command("sj", "get_time", "输入时间", "alpha", "输入可选时间,例如12:34") ime.register_command("rq", "get_date", "输入日期", "alpha", "输入可选日期,例如2013-01-01") ime.register_command("js", "compute", "计算模式", "none", "输入表达式,例如log(2)") ime.register_command("xz", "query_zodiac","查询星座", "none", "输入您的生日,例如12-3") --ime.register_trigger(lua_function, description, input_triggers, candidate_triggers) ime.register_trigger("get_current_time", "显示时间", {}, {'时间'}) ime.register_trigger("get_today", "显示日期", {}, {'日期'}) -- Example: typing "sj" in the engine shows time candidates -- get_time("14:30") → {"14:30", "14时30分", "十四时三十分"} -- Example: typing "js" followed by an expression -- compute("sin(pi/2)") → 1.0 -- compute("log(2)") → 0.69314718055995 -- Add a custom command in user.lua: function greet(input) return "你好," .. input .. "!" end ime.register_command("wh", "greet", "问候", "alpha", "输入名字") -- Typing "wh" then "Alice" yields candidate "你好,Alice!" ``` -------------------------------- ### DoublePinyinEditor Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Handles character insertion and preedit rendering for two-keystroke-per-syllable Pinyin input, supporting various schemas. ```APIDOC ## DoublePinyinEditor ### Description Enables two-keystroke-per-syllable Pinyin input, supporting schemas like Shuangpin, ZiRanMa, and Microsoft. Activated by setting "double-pinyin" = true in GSettings. ### Methods - `DoublePinyinEditor(PinyinProperties &props, Config &config)`: Constructor. - `insert(gint ch)`: Inserts a character. - `processKeyEvent(guint keyval, guint keycode, guint modifiers)`: Processes key events. - `reset()`: Resets the editor state. - `updateAuxiliaryText()`: Updates auxiliary text. - `updatePinyin()`: Updates Pinyin internal state. ``` -------------------------------- ### FullPinyinEditor Class Definition Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Defines the FullPinyinEditor class for standard full-syllable Pinyin input. Inherits from PinyinEditor. ```cpp class FullPinyinEditor : public PinyinEditor { public: FullPinyinEditor(PinyinProperties &props, Config &config); gboolean insert(gint ch) override; gboolean processKeyEvent(guint keyval, guint keycode, guint modifiers) override; void reset() override; void updateAuxiliaryText() override; protected: void updatePinyin() override; guint getLookupCursor(); }; ``` -------------------------------- ### PhoneticEditor Class Definition Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Defines the PhoneticEditor class, inheriting from Editor and managing libpinyin instances and candidate providers. Use this for Pinyin and Bopomofo input methods. ```cpp class PhoneticEditor : public Editor { public: PhoneticEditor(PinyinProperties &props, Config &config); virtual ~PhoneticEditor(); // Overridden navigation and update void pageUp() override; void pageDown() override; void cursorUp() override; void cursorDown() override; void reset() override; void update() override; void updateAll() override; gboolean processKeyEvent(guint keyval, guint keycode, guint modifiers) override; gboolean processSpace(guint keyval, guint keycode, guint modifiers); gboolean processFunctionKey(guint keyval, guint keycode, guint modifiers); // Candidate management void updateLookupTable(); void updateLookupTableFast(); gboolean updateCandidates(); // rebuilds m_candidates from all providers gboolean fillLookupTable(); // populates IBus LookupTable from m_candidates // Pure virtuals for concrete editors (FullPinyinEditor, DoublePinyinEditor, etc.) virtual gboolean insert(gint ch) = 0; virtual void updatePreeditText() = 0; virtual void updateAuxiliaryText() = 0; virtual void updatePinyin() = 0; virtual void commit(const gchar *str) = 0; // Lua plugin (when --enable-lua-extension) gboolean setLuaPlugin(IBusEnginePlugin *plugin); protected: // Candidate selection gboolean selectCandidate(guint i); gboolean selectCandidateInPage(guint i); void directCommit(const gchar *str); // Cursor helpers guint getPinyinCursor(); guint getLookupCursor(); gboolean removeCharBefore(); gboolean removeCharAfter(); gboolean removeWordBefore(); gboolean moveCursorLeft(); gboolean moveCursorRight(); gboolean moveCursorToBegin(); gboolean moveCursorToEnd(); protected: guint m_pinyin_len; LookupTable m_lookup_table; guint m_lookup_cursor; String m_buffer; pinyin_instance_t *m_instance; // libpinyin handle std::vector m_candidates; // merged candidate list // Candidate providers (compiled in conditionally) LibPinyinCandidates m_libpinyin_candidates; // always present TraditionalCandidates m_traditional_candidates; // always present EmojiCandidates m_emoji_candidates; // always present EnglishCandidates m_english_candidates; // IBUS_BUILD_ENGLISH_INPUT_MODE LuaTriggerCandidates m_lua_trigger_candidates; // IBUS_BUILD_LUA_EXTENSION LuaConverterCandidates m_lua_converter_candidates; CloudCandidates m_cloud_candidates; // ENABLE_CLOUD_INPUT_MODE }; ``` -------------------------------- ### CloudCandidates Class Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Manages asynchronous HTTP requests to cloud input APIs for enhanced candidate suggestions. It handles input mode settings, request processing, and candidate selection. ```APIDOC ## CloudCandidates Class Performs asynchronous HTTP requests to Google Pinyin or Google-CN cloud input APIs via libsoup3, and injects results into the candidate list. Enabled only when compiled with `--enable-cloud-input-mode`. ### Methods - `void setInputMode(InputMode mode)`: Set input romanisation mode for correct API query encoding. Supported modes: `FullPinyin`, `DoublePinyin`, `Bopomofo`. - `gboolean processCandidates(std::vector &candidates)`: Called during `updateCandidates()`. Launches async request and returns cached results. - `int selectCandidate(EnhancedCandidate &enhanced)`: Selects an enhanced candidate. - `void delayedCloudAsyncRequest(const gchar *pinyin)`: Initiates an asynchronous request, deferred by `cloudRequestDelayTime` milliseconds, and cancels any previous pending requests. - `void cloudAsyncRequest(gpointer user_data)`: Executes the asynchronous cloud request. - `void cloudSyncRequest(const gchar *pinyin, std::vector &candidates)`: Performs a synchronous request, suitable for testing or blocking scenarios. - `void updateLookupTable()`: Updates the lookup table. ### Public State - `guint m_source_event_id`: Source event ID. - `SoupMessage *m_message`: Soup message object for the HTTP request. - `GCancellable*m_cancel_message`: GCancellable object for cancelling the message. - `std::string m_last_requested_pinyin`: Stores the last requested pinyin string. ``` -------------------------------- ### EnhancedCandidates Provider Interface Template Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt A template interface for candidate providers. It includes methods for processing candidates, selecting a candidate, and removing a candidate. ```cpp // Template provider interface template class EnhancedCandidates { public: gboolean processCandidates(std::vector &candidates); int selectCandidate(EnhancedCandidate &enhanced); gboolean removeCandidate(EnhancedCandidate &enhanced); protected: IEditor *m_editor; }; ``` -------------------------------- ### BopomofoEditor Class Definition Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Defines the BopomofoEditor class for Zhuyin (Bopomofo) phonetic notation, primarily for zh_TW locale. Inherits from PhoneticEditor. ```cpp class BopomofoEditor : public PhoneticEditor { public: BopomofoEditor(PinyinProperties &props, Config &config); protected: String bopomofo; // accumulates BoPoMoFo keystrokes gboolean m_select_mode; gboolean processBopomofo(guint keyval, guint keycode, guint modifiers); gboolean processGuideKey(guint keyval, guint keycode, guint modifiers); gboolean processSelectKey(guint keyval, guint keycode, guint modifiers); void updateLookupTableLabel(); void updateLookupTable() override; void updatePreeditText() override; void updateAuxiliaryText() override; void updatePinyin() override; void commit(const gchar *str) override; gboolean insert(gint ch) override; void reset() override; }; ``` -------------------------------- ### EnglishDatabase Class Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt A singleton class managing a SQLite database of English words with frequency scores, powering the English candidate mode. ```APIDOC ## EnglishDatabase Class A singleton that manages a SQLite3 database of English words with frequency scores. It powers the English candidate mode (activated by pressing `v` while the engine is active). ### Methods - `static void init()`: Initializes the EnglishDatabase. - `static EnglishDatabase &instance()`: Returns the singleton instance of `EnglishDatabase`. #### Database Lifecycle - `gboolean isDatabaseExisted(const char *filename)`: Checks if the database file exists. - `gboolean createDatabase(const char *filename)`: Creates a new database file. - `gboolean openDatabase(const char *system_db, const char *user_db)`: Opens the system and user database files. #### Lookup - `gboolean hasWord(const char *word)`: Checks if a word exists in the database. - `gboolean listWords(const char *prefix, std::vector &words)`: Returns up to N words whose spelling begins with the given prefix, sorted by frequency. #### User Word Management - `gboolean getUserWordInfo(const char *word, float &freq)`: Retrieves the frequency of a user-defined word. - `gboolean insertUserWord(const char *word, float freq)`: Inserts a new user word into the database. - `gboolean updateUserWord(const char *word, float freq)`: Updates the frequency of an existing user word. - `gboolean deleteUserWord(const char *word)`: Deletes a user word from the database. #### Training - `gboolean train(const char *word, float delta)`: Reinforces a word's frequency by a given delta (called on commit). ``` -------------------------------- ### PinyinProperties Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Manages the toolbar properties visible in the IBus language bar, including Chinese/English mode, character width, punctuation width, Simplified/Traditional Chinese mode, and Lua converter selection. ```APIDOC ## `PinyinProperties` — IBus Property Panel (`src/PYPinyinProperties.h`) ### Description Manages the toolbar properties visible in the IBus language bar: Chinese/English mode, full/half-width character mode, full/half-width punctuation mode, Simplified/Traditional Chinese mode, and the Lua converter selector. ### Methods - `PinyinProperties(Config &config)`: Constructor. - `toggleModeChinese()`: Toggles between Chinese and English input modes. - `toggleModeFull()`: Toggles between full-width and half-width letter modes. - `toggleModeFullPunct()`: Toggles between full-width and half-width punctuation modes. - `toggleModeSimp()`: Toggles between Simplified and Traditional Chinese modes. - `reset()`: Restores default settings from Config. - `modeChinese() const`: Returns true if Chinese input is active. - `modeFull() const`: Returns true if full-width letters are active. - `modeFullPunct() const`: Returns true if full-width punctuation is active. - `modeSimp() const`: Returns true if Simplified Chinese mode is active. - `properties()`: Returns a reference to the PropList for registering with ibus_engine_register_properties(). - `propertyActivate(const gchar *prop_name, guint prop_state)`: Handles clicks on property panel buttons. - `signalUpdateProperty()`: Returns a signal that fires when a property's icon/label needs updating. - `setLuaPlugin(IBusEnginePlugin *plugin)`: Sets the Lua plugin for the converter. - `toggleLuaConverter(int prefix_len, const gchar *prop_name, guint prop_state)`: Toggles the Lua converter. - `appendLuaConverter()`: Appends a Lua converter. ### Default Keyboard Shortcuts - `main-switch`: "" → toggle Chinese/English - `punct-switch`: "period" → toggle full/half punctuation - `trad-switch`: "f" → toggle Simplified/Traditional - `letter-switch`: "" → toggle full/half letters (unbound by default) ``` -------------------------------- ### EnglishDatabase Class Definition Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Defines the EnglishDatabase singleton for managing an SQLite database of English words and their frequencies. It supports word lookup, user word management, and frequency training. ```cpp class EnglishDatabase { public: static void init(); static EnglishDatabase &instance(); // Database lifecycle gboolean isDatabaseExisted(const char *filename); gboolean createDatabase(const char *filename); gboolean openDatabase(const char *system_db, const char *user_db); // Lookup gboolean hasWord(const char *word); // Returns up to N words whose spelling begins with prefix, sorted by frequency gboolean listWords(const char *prefix, std::vector &words); // User word management gboolean getUserWordInfo(const char *word, float &freq); gboolean insertUserWord(const char *word, float freq); gboolean updateUserWord(const char *word, float freq); gboolean deleteUserWord(const char *word); // Reinforce a word's frequency by delta (called on commit) gboolean train(const char *word, float delta); }; ``` -------------------------------- ### DoublePinyinEditor Class Definition Source: https://context7.com/libpinyin/ibus-libpinyin/llms.txt Defines the DoublePinyinEditor class for two-keystroke-per-syllable Pinyin input. Activated by 'double-pinyin' GSettings. Supports various schemas. ```cpp class DoublePinyinEditor : public PinyinEditor { public: DoublePinyinEditor(PinyinProperties &props, Config &config); gboolean insert(gint ch) override; gboolean processKeyEvent(guint keyval, guint keycode, guint modifiers) override; void reset() override; protected: void updateAuxiliaryText() override; void updatePinyin() override; }; ```