From 4f021ea04085cc9ce0d8ed676b650edb98dd3d69 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 17:11:01 +0000 Subject: [PATCH] stoa-predict: become a Wayland input method The suggestions now sit in a popup next to the text cursor, and the arrow keys work: Down/Up enter the popup, Left/Right move, Enter or Tab accepts, Esc dismisses. Neither is possible from a shell panel, which cannot see another app's caret nor take keys without stealing focus, so the daemon is now an input method (input-method-v2, as fcitx): - the compositor places its popup surface at the caret (cairo + Pango into shm buffers, Stoa palette); - a keyboard grab sees each key; keys it does not use are forwarded through its virtual keyboard, which niri and sway route past the grab; - the word before the cursor comes from text-input surrounding text, or from the keys themselves in terminals, which send none; - the choice is committed with commit_string (+ delete_surrounding_text, or BackSpaces looked up in the current keymap for terminals). That also fixes emoji, which never went in: wtype refused non-ASCII without a UTF-8 locale and dropped a lone keystroke 9 times in 15. evdev and the input group are no longer needed for prediction. The Noctalia plugin keeps only its service (start/stop/notify); the panel is gone. Brave and Obsidian get --enable-wayland-ime --wayland-text-input-version=3 so Chromium talks to the input method. SIGTERM keeps its default action: a Python handler never runs while libwayland sits in poll(), which left the daemon alive on toggle-off. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CrdbH4MCHhLKimzdRSzXZp --- README.md | 2 +- config/hypr/hyprland.lua | 2 +- config/niri/config.kdl | 2 +- install.sh | 16 +- .../input-method-unstable-v2.xml | 494 ++++++++++ .../virtual-keyboard-unstable-v1.xml | 112 +++ scripts/stoa-predict.py | 895 +++++++++++++----- scripts/stoa-predict.sh | 112 +-- setup/post-install.sh | 6 +- .../noctalia-plugins/stoa-predict/panel.luau | 89 -- .../noctalia-plugins/stoa-predict/plugin.toml | 48 +- .../stoa-predict/service.luau | 79 +- 12 files changed, 1347 insertions(+), 510 deletions(-) create mode 100644 scripts/stoa-predict-protocols/input-method-unstable-v2.xml create mode 100644 scripts/stoa-predict-protocols/virtual-keyboard-unstable-v1.xml delete mode 100644 theme/noctalia-plugins/stoa-predict/panel.luau diff --git a/README.md b/README.md index 316da26..0fecb69 100644 --- a/README.md +++ b/README.md @@ -168,7 +168,7 @@ A family of small, single-purpose `stoa-*` tools — each one exists because rea stoa-fetchSystem fetchstoa-resizeBatch resize images stoa-wallsWallpaper generatorstoa-renameRegex rename + preview stoa-memento-dataMemento Mori data (desktop widget)stoa-locksmithFind + end what's locking a file/folder - stoa-doctorSystem health checkstoa-predictText prediction + emoji suggestions (Noctalia panel) + stoa-doctorSystem health checkstoa-predictWord + emoji suggestions at the text cursor (input method) stoa-screensaverLiving marble screensaverstoa-archiveCompress selection / extract archives stoa-clipboardClipboard + pins stoa-driveCloud drive (rclone) diff --git a/config/hypr/hyprland.lua b/config/hypr/hyprland.lua index 7c8b7d8..4e6372f 100644 --- a/config/hypr/hyprland.lua +++ b/config/hypr/hyprland.lua @@ -153,7 +153,7 @@ hl.bind("ALT + SHIFT + Tab", hl.dsp.exec_cmd( -- ── Apps ── hl.bind(mod .. " + A", hl.dsp.exec_cmd("~/.local/bin/stoa-store")) hl.bind(mod .. " + B", hl.dsp.exec_cmd( - "brave --password-store=basic --enable-features=UseOzonePlatform --ozone-platform=wayland")) + "brave --password-store=basic --enable-features=UseOzonePlatform --ozone-platform=wayland --enable-wayland-ime --wayland-text-input-version=3")) hl.bind(mod .. " + C", hl.dsp.exec_cmd("qalculate-gtk")) hl.bind(mod .. " + SHIFT + E", hl.dsp.exec_cmd("kitty -e lf")) hl.bind(mod .. " + E", hl.dsp.exec_cmd("thunar")) diff --git a/config/niri/config.kdl b/config/niri/config.kdl index 715f0a8..a8cb8c6 100644 --- a/config/niri/config.kdl +++ b/config/niri/config.kdl @@ -204,7 +204,7 @@ binds { // ── Apps ── Mod+A { spawn-sh "~/.local/bin/stoa-store"; } - Mod+B { spawn-sh "brave --password-store=basic --enable-features=UseOzonePlatform --ozone-platform=wayland"; } + Mod+B { spawn-sh "brave --password-store=basic --enable-features=UseOzonePlatform --ozone-platform=wayland --enable-wayland-ime --wayland-text-input-version=3"; } Mod+C { spawn "qalculate-gtk"; } Mod+Shift+E { spawn "kitty" "-e" "lf"; } Mod+E { spawn "thunar"; } diff --git a/install.sh b/install.sh index 575ce32..b321b93 100755 --- a/install.sh +++ b/install.sh @@ -629,7 +629,7 @@ Version=1.0 Name=Brave Web Browser GenericName=Web Browser Comment=Access the Internet -Exec=brave --password-store=basic --enable-features=UseOzonePlatform --ozone-platform=wayland %U +Exec=brave --password-store=basic --enable-features=UseOzonePlatform --ozone-platform=wayland --enable-wayland-ime --wayland-text-input-version=3 %U StartupNotify=true Terminal=false Icon=brave-desktop @@ -640,13 +640,23 @@ Actions=new-window;new-private-window; [Desktop Action new-window] Name=New Window -Exec=brave --password-store=basic --enable-features=UseOzonePlatform --ozone-platform=wayland +Exec=brave --password-store=basic --enable-features=UseOzonePlatform --ozone-platform=wayland --enable-wayland-ime --wayland-text-input-version=3 [Desktop Action new-private-window] Name=New Incognito Window -Exec=brave --password-store=basic --enable-features=UseOzonePlatform --ozone-platform=wayland --incognito +Exec=brave --password-store=basic --enable-features=UseOzonePlatform --ozone-platform=wayland --enable-wayland-ime --wayland-text-input-version=3 --incognito BRAVE echo -e " ${O}[+] brave-browser.desktop (--password-store=basic)${R}" +# --enable-wayland-ime --wayland-text-input-version=3 (above, and in the +# Super+B binds): Chromium only talks to a Wayland input method through +# text-input-v3 with these, and stoa-predict is one. Obsidian is Electron; +# Arch's launcher appends ~/.config/obsidian/user-flags.conf to its argv. +OBSIDIAN_FLAGS="${CONFIG_DIR}/obsidian/user-flags.conf" +if ! grep -qs -- "--enable-wayland-ime" "$OBSIDIAN_FLAGS"; then + mkdir -p "$(dirname "$OBSIDIAN_FLAGS")" + printf '%s\n' "--enable-wayland-ime" "--wayland-text-input-version=3" >> "$OBSIDIAN_FLAGS" + echo -e " ${O}[+] obsidian user-flags.conf (Wayland input method)${R}" +fi echo "" echo -e "${F}Shell configuration:${R}" diff --git a/scripts/stoa-predict-protocols/input-method-unstable-v2.xml b/scripts/stoa-predict-protocols/input-method-unstable-v2.xml new file mode 100644 index 0000000..84d0470 --- /dev/null +++ b/scripts/stoa-predict-protocols/input-method-unstable-v2.xml @@ -0,0 +1,494 @@ + + + + + Copyright © 2008-2011 Kristian Høgsberg + Copyright © 2010-2011 Intel Corporation + Copyright © 2012-2013 Collabora, Ltd. + Copyright © 2012, 2013 Intel Corporation + Copyright © 2015, 2016 Jan Arne Petersen + Copyright © 2017, 2018 Red Hat, Inc. + Copyright © 2018 Purism SPC + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + This protocol allows applications to act as input methods for compositors. + + An input method context is used to manage the state of the input method. + + Text strings are UTF-8 encoded, their indices and lengths are in bytes. + + This document adheres to the RFC 2119 when using words like "must", + "should", "may", etc. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + An input method object allows for clients to compose text. + + The objects connects the client to a text input in an application, and + lets the client to serve as an input method for a seat. + + The zwp_input_method_v2 object can occupy two distinct states: active and + inactive. In the active state, the object is associated to and + communicates with a text input. In the inactive state, there is no + associated text input, and the only communication is with the compositor. + Initially, the input method is in the inactive state. + + Requests issued in the inactive state must be accepted by the compositor. + Because of the serial mechanism, and the state reset on activate event, + they will not have any effect on the state of the next text input. + + There must be no more than one input method object per seat. + + + + + + + + + Notification that a text input focused on this seat requested the input + method to be activated. + + This event serves the purpose of providing the compositor with an + active input method. + + This event resets all state associated with previous + surrounding_text, text_change_cause, and content_type events, as well + as the state associated with set_preedit_string, commit_string, and + delete_surrounding_text requests. In addition, it marks the + zwp_input_method_v2 object as active, and makes any existing + zwp_input_popup_surface_v2 objects visible. + + The surrounding_text, and content_type events must follow before the + next done event if the text input supports the respective + functionality. + + State set with this event is double-buffered. It will get applied on + the next zwp_input_method_v2.done event, and stay valid until changed. + + + + + + Notification that no focused text input currently needs an active + input method on this seat. + + This event marks the zwp_input_method_v2 object as inactive. The + compositor must make all existing zwp_input_popup_surface_v2 objects + invisible until the next activate event. + + State set with this event is double-buffered. It will get applied on + the next zwp_input_method_v2.done event, and stay valid until changed. + + + + + + Updates the surrounding plain text around the cursor, excluding the + preedit text. + + If any preedit text is present, it is replaced with the cursor for the + purpose of this event. + + The argument text is a buffer containing the surrounding text, and must + include the cursor position, and the complete selection. It should + contain additional characters before and after these. There is a + maximum length of wayland messages, so text can not be longer than 4000 + bytes. + + cursor is the byte offset of the cursor within the text buffer. + + anchor is the byte offset of the selection anchor within the text + buffer. If there is no selected text, anchor must be the same as + cursor. + + If this event does not arrive before the first done event, the input + method may assume that the text input does not support this + functionality and ignore following surrounding_text events. + + Values set with this event are double-buffered. They will get applied + and set to initial values on the next zwp_input_method_v2.done + event. + + The initial state for affected fields is empty, meaning that the text + input does not support sending surrounding text. If the empty values + get applied, subsequent attempts to change them may have no effect. + + + + + + + + + Tells the input method why the text surrounding the cursor changed. + + Whenever the client detects an external change in text, cursor, or + anchor position, it must issue this request to the compositor. This + request is intended to give the input method a chance to update the + preedit text in an appropriate way, e.g. by removing it when the user + starts typing with a keyboard. + + cause describes the source of the change. + + The value set with this event is double-buffered. It will get applied + and set to its initial value on the next zwp_input_method_v2.done + event. + + The initial value of cause is input_method. + + + + + + + Indicates the content type and hint for the current + zwp_input_method_v2 instance. + + Values set with this event are double-buffered. They will get applied + on the next zwp_input_method_v2.done event. + + The initial value for hint is none, and the initial value for purpose + is normal. + + + + + + + + Atomically applies state changes recently sent to the client. + + The done event establishes and updates the state of the client, and + must be issued after any changes to apply them. + + Text input state (content purpose, content hint, surrounding text, and + change cause) is conceptually double-buffered within an input method + context. + + Events modify the pending state, as opposed to the current state in use + by the input method. A done event atomically applies all pending state, + replacing the current state. After done, the new pending state is as + documented for each related request. + + Events must be applied in the order of arrival. + + Neither current nor pending state are modified unless noted otherwise. + + + + + + Send the commit string text for insertion to the application. + + Inserts a string at current cursor position (see commit event + sequence). The string to commit could be either just a single character + after a key press or the result of some composing. + + The argument text is a buffer containing the string to insert. There is + a maximum length of wayland messages, so text can not be longer than + 4000 bytes. + + Values set with this event are double-buffered. They must be applied + and reset to initial on the next zwp_text_input_v3.commit request. + + The initial value of text is an empty string. + + + + + + + Send the pre-edit string text to the application text input. + + Place a new composing text (pre-edit) at the current cursor position. + Any previously set composing text must be removed. Any previously + existing selected text must be removed. The cursor is moved to a new + position within the preedit string. + + The argument text is a buffer containing the preedit string. There is + a maximum length of wayland messages, so text can not be longer than + 4000 bytes. + + The arguments cursor_begin and cursor_end are counted in bytes relative + to the beginning of the submitted string buffer. Cursor should be + hidden by the text input when both are equal to -1. + + cursor_begin indicates the beginning of the cursor. cursor_end + indicates the end of the cursor. It may be equal or different than + cursor_begin. + + Values set with this event are double-buffered. They must be applied on + the next zwp_input_method_v2.commit event. + + The initial value of text is an empty string. The initial value of + cursor_begin, and cursor_end are both 0. + + + + + + + + + Remove the surrounding text. + + before_length and after_length are the number of bytes before and after + the current cursor index (excluding the preedit text) to delete. + + If any preedit text is present, it is replaced with the cursor for the + purpose of this event. In effect before_length is counted from the + beginning of preedit text, and after_length from its end (see commit + event sequence). + + Values set with this event are double-buffered. They must be applied + and reset to initial on the next zwp_input_method_v2.commit request. + + The initial values of both before_length and after_length are 0. + + + + + + + + Apply state changes from commit_string, set_preedit_string and + delete_surrounding_text requests. + + The state relating to these events is double-buffered, and each one + modifies the pending state. This request replaces the current state + with the pending state. + + The connected text input is expected to proceed by evaluating the + changes in the following order: + + 1. Replace existing preedit string with the cursor. + 2. Delete requested surrounding text. + 3. Insert commit string with the cursor at its end. + 4. Calculate surrounding text to send. + 5. Insert new preedit text in cursor position. + 6. Place cursor inside preedit text. + + The serial number reflects the last state of the zwp_input_method_v2 + object known to the client. The value of the serial argument must be + equal to the number of done events already issued by that object. When + the compositor receives a commit request with a serial different than + the number of past done events, it must proceed as normal, except it + should not change the current state of the zwp_input_method_v2 object. + + + + + + + Creates a new zwp_input_popup_surface_v2 object wrapping a given + surface. + + The surface gets assigned the "input_popup" role. If the surface + already has an assigned role, the compositor must issue a protocol + error. + + + + + + + + Allow an input method to receive hardware keyboard input and process + key events to generate text events (with pre-edit) over the wire. This + allows input methods which compose multiple key events for inputting + text like it is done for CJK languages. + + The compositor should send all keyboard events on the seat to the grab + holder via the returned wl_keyboard object. Nevertheless, the + compositor may decide not to forward any particular event. The + compositor must not further process any event after it has been + forwarded to the grab holder. + + Releasing the resulting wl_keyboard object releases the grab. + + + + + + + The input method ceased to be available. + + The compositor must issue this event as the only event on the object if + there was another input_method object associated with the same seat at + the time of its creation. + + The compositor must issue this request when the object is no longer + usable, e.g. due to seat removal. + + The input method context becomes inert and should be destroyed after + deactivation is handled. Any further requests and events except for the + destroy request must be ignored. + + + + + + Destroys the zwp_text_input_v2 object and any associated child + objects, i.e. zwp_input_popup_surface_v2 and + zwp_input_method_keyboard_grab_v2. + + + + + + + This interface marks a surface as a popup for interacting with an input + method. + + The compositor should place it near the active text input area. It must + be visible if and only if the input method is in the active state. + + The client must not destroy the underlying wl_surface while the + zwp_input_popup_surface_v2 object exists. + + + + + Notify about the position of the area of the text input expressed as a + rectangle in surface local coordinates. + + This is a hint to the input method telling it the relative position of + the text being entered. + + + + + + + + + + + + + + The zwp_input_method_keyboard_grab_v2 interface represents an exclusive + grab of the wl_keyboard interface associated with the seat. + + + + + This event provides a file descriptor to the client which can be + memory-mapped to provide a keyboard mapping description. + + + + + + + + + A key was pressed or released. + The time argument is a timestamp with millisecond granularity, with an + undefined base. + + + + + + + + + + Notifies clients that the modifier and/or group state has changed, and + it should update its local state. + + + + + + + + + + + + + + + Informs the client about the keyboard's repeat rate and delay. + + This event is sent as soon as the zwp_input_method_keyboard_grab_v2 + object has been created, and is guaranteed to be received by the + client before any key press event. + + Negative values for either rate or delay are illegal. A rate of zero + will disable any repeating (regardless of the value of delay). + + This event can be sent later on as well with a new value if necessary, + so clients should continue listening for the event past the creation + of zwp_input_method_keyboard_grab_v2. + + + + + + + + + The input method manager allows the client to become the input method on + a chosen seat. + + No more than one input method must be associated with any seat at any + given time. + + + + + Request a new input zwp_input_method_v2 object associated with a given + seat. + + + + + + + + Destroys the zwp_input_method_manager_v2 object. + + The zwp_input_method_v2 objects originating from it remain valid. + + + + diff --git a/scripts/stoa-predict-protocols/virtual-keyboard-unstable-v1.xml b/scripts/stoa-predict-protocols/virtual-keyboard-unstable-v1.xml new file mode 100644 index 0000000..a888e5f --- /dev/null +++ b/scripts/stoa-predict-protocols/virtual-keyboard-unstable-v1.xml @@ -0,0 +1,112 @@ + + + + Copyright © 2008-2011 Kristian Høgsberg + Copyright © 2010-2013 Intel Corporation + Copyright © 2012-2013 Collabora, Ltd. + Copyright © 2018 Purism SPC + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + + The virtual keyboard provides an application with requests which emulate + the behaviour of a physical keyboard. + + This interface can be used by clients on its own to provide raw input + events, or it can accompany the input method protocol. + + + + + Provide a file descriptor to the compositor which can be + memory-mapped to provide a keyboard mapping description. + + + + + + + + + + + + + + A key was pressed or released. + The time argument is a timestamp with millisecond granularity, with an + undefined base. All requests regarding a single object must share the + same clock. + + Keymap must be set before issuing this request. + + State carries a value from the key_state enumeration. + + + + + + + + + Notifies the compositor that the modifier and/or group state has + changed, and it should update state. + + The client should use wl_keyboard.modifiers event to synchronize its + internal state with seat state. + + Keymap must be set before issuing this request. + + + + + + + + + + + + + + + A virtual keyboard manager allows an application to provide keyboard + input events as if they came from a physical keyboard. + + + + + + + + + Creates a new virtual keyboard associated to a seat. + + If the compositor enables a keyboard to perform arbitrary actions, it + should present an error when an untrusted client requests a new + keyboard. + + + + + + diff --git a/scripts/stoa-predict.py b/scripts/stoa-predict.py index 8e4a0c3..f647d95 100755 --- a/scripts/stoa-predict.py +++ b/scripts/stoa-predict.py @@ -1,28 +1,41 @@ #!/usr/bin/env python3 # ╔══════════════════════════════════════════════════════════════╗ -# ║ STOA LINUX — Text Prediction Daemon ║ +# ║ STOA LINUX — Text Prediction (Wayland input method) ║ # ║ "Choose your words with care." — Epictetus ║ # ║ ║ -# ║ System-wide word suggestions via evdev, shown by the ║ -# ║ Noctalia stoa/predict plugin. ║ -# ║ Requires: python-evdev, wtype ║ -# ║ User must be in the 'input' group. ║ +# ║ Word and emoji suggestions in a popup next to the text ║ +# ║ cursor. Runs as a Wayland input method (input-method-v2, ║ +# ║ the protocol fcitx uses), started and stopped by the ║ +# ║ Noctalia stoa/predict plugin (Super+Shift+S). ║ +# ║ ║ +# ║ ↓ / ↑ enter the popup (and leave it again) ║ +# ║ ← / → move between suggestions ║ +# ║ Enter/Tab accept Esc dismiss click accept ║ +# ║ ║ +# ║ Requires: python-pywayland, python-cairo, python-gobject ║ +# ║ (Pango). Apps need text-input-v3: GTK, Qt, kitty, foot, ║ +# ║ Zed, Firefox; Chromium/Electron with --enable-wayland-ime. ║ # ╚══════════════════════════════════════════════════════════════╝ +# +# stdout is read by theme/noctalia-plugins/stoa-predict/service.luau: one +# JSON object per line, {"ready": true} once the input method is +# registered, or {"error": "..."} before exiting. Logs go to stderr. -import asyncio +import ctypes import json +import mmap import os +import re import signal import subprocess import sys +import time from bisect import bisect_left from pathlib import Path -import evdev -from evdev import ecodes - # ── Configuration ── MAX_SUGGESTIONS = 5 +MAX_EMOJIS = 3 MIN_PREFIX = 2 DICT_PATHS = [ Path.home() / ".config/stoa/predict-words.txt", @@ -31,41 +44,51 @@ ] _RUNTIME_DIR = os.environ.get("XDG_RUNTIME_DIR") or "/tmp" PIDFILE = f"{_RUNTIME_DIR}/stoa-predict.pid" -SUGGEST_FILE = f"{_RUNTIME_DIR}/stoa-predict.json" - -# ── Keycode to character mapping (US/BR base — lowercase) ── -KEY_MAP = { - ecodes.KEY_A: "a", ecodes.KEY_B: "b", ecodes.KEY_C: "c", - ecodes.KEY_D: "d", ecodes.KEY_E: "e", ecodes.KEY_F: "f", - ecodes.KEY_G: "g", ecodes.KEY_H: "h", ecodes.KEY_I: "i", - ecodes.KEY_J: "j", ecodes.KEY_K: "k", ecodes.KEY_L: "l", - ecodes.KEY_M: "m", ecodes.KEY_N: "n", ecodes.KEY_O: "o", - ecodes.KEY_P: "p", ecodes.KEY_Q: "q", ecodes.KEY_R: "r", - ecodes.KEY_S: "s", ecodes.KEY_T: "t", ecodes.KEY_U: "u", - ecodes.KEY_V: "v", ecodes.KEY_W: "w", ecodes.KEY_X: "x", - ecodes.KEY_Y: "y", ecodes.KEY_Z: "z", -} - -# Keys that reset the word buffer -RESET_KEYS = { - ecodes.KEY_SPACE, ecodes.KEY_ENTER, ecodes.KEY_TAB, - ecodes.KEY_ESC, ecodes.KEY_DOT, ecodes.KEY_COMMA, - ecodes.KEY_SEMICOLON, ecodes.KEY_APOSTROPHE, - ecodes.KEY_SLASH, ecodes.KEY_MINUS, ecodes.KEY_EQUAL, - ecodes.KEY_LEFTBRACE, ecodes.KEY_RIGHTBRACE, - ecodes.KEY_GRAVE, ecodes.KEY_BACKSLASH, - ecodes.KEY_HOME, ecodes.KEY_END, - ecodes.KEY_LEFT, ecodes.KEY_RIGHT, ecodes.KEY_UP, ecodes.KEY_DOWN, -} - -# Modifier keys to ignore -MODIFIER_KEYS = { - ecodes.KEY_LEFTSHIFT, ecodes.KEY_RIGHTSHIFT, - ecodes.KEY_LEFTCTRL, ecodes.KEY_RIGHTCTRL, - ecodes.KEY_LEFTALT, ecodes.KEY_RIGHTALT, - ecodes.KEY_LEFTMETA, ecodes.KEY_RIGHTMETA, - ecodes.KEY_CAPSLOCK, ecodes.KEY_NUMLOCK, -} +PROTOCOL_DIR = Path(__file__).resolve().parent / "stoa-predict-protocols" +WAYLAND_XML = Path("/usr/share/wayland/wayland.xml") + +# The last word before the cursor: a run of letters (any script, so +# "ação" and "über" count; digits and "_" end it). +WORD_BEFORE_CURSOR = re.compile(r"[^\W\d_]+$") + + +def say(**payload): + """One protocol line for the Noctalia service.""" + print(json.dumps(payload), flush=True) + + +def log(message: str): + print(f"[predict] {message}", file=sys.stderr, flush=True) + + +DEBUG = bool(os.environ.get("STOA_PREDICT_DEBUG")) + + +def debug(message: str): + if DEBUG: + log(message) + + +def remove_pidfile(): + """Only ours: a second instance that lost the input-method slot must not + delete the file pointing at the one that holds it.""" + try: + if Path(PIDFILE).read_text().strip() == str(os.getpid()): + os.remove(PIDFILE) + except OSError: + pass + + +def quit_now(code: int = 0): + """Exit from anywhere, including a Wayland callback. pywayland runs + callbacks through cffi, which swallows SystemExit ("Exception ignored + from cffi callback"), so sys.exit() there would leave the daemon + running. Closing the connection is all the cleanup the compositor needs: + it drops the keyboard grab and the popup with it.""" + remove_pidfile() + sys.stdout.flush() + sys.stderr.flush() + os._exit(code) class EmojiIndex: @@ -315,204 +338,628 @@ def search(self, prefix: str, limit: int = MAX_SUGGESTIONS) -> list[str]: return results -class PredictDaemon: - """Main daemon: reads evdev input, emits suggestions on stdout. - Protocol (read by theme/noctalia-plugins/stoa-predict/service.luau): - one JSON object per line, {"prefix", "words", "emojis", "visible"}, - written whenever the suggestions change. Diagnostics go to stderr. - """ +# ── Wayland protocol bindings ── +# pywayland ships the core protocol only. input-method-v2 and +# virtual-keyboard-v1 are wlroots protocols that no Arch package installs, +# so their XML lives next to this script and the bindings are generated +# once into ~/.cache (keyed by the XML and pywayland version). The core +# protocol is generated into the same package because the generated code +# imports it relatively (`from .wayland import WlSeat`). +def load_protocols(): + import hashlib + import importlib + import shutil + + import pywayland + from pywayland.scanner.protocol import Protocol + + xmls = [ + WAYLAND_XML, + PROTOCOL_DIR / "input-method-unstable-v2.xml", + PROTOCOL_DIR / "virtual-keyboard-unstable-v1.xml", + ] + digest = hashlib.sha256( + b"".join(p.read_bytes() for p in xmls) + pywayland.__version__.encode() + ).hexdigest()[:16] + cache = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") + root = cache / "stoa" / "predict-protocols" / digest + package = root / "stoa_wl" + if not (package / "__init__.py").exists(): + staging = root.with_name(f"{digest}.tmp{os.getpid()}") + shutil.rmtree(staging, ignore_errors=True) + (staging / "stoa_wl").mkdir(parents=True) # Protocol.output uses a plain os.mkdir + protocols = [Protocol.parse_file(str(p)) for p in xmls] + imports = {i.name: p.name for p in protocols for i in p.interface} + for protocol in protocols: + protocol.output(str(staging / "stoa_wl"), imports) + (staging / "stoa_wl" / "__init__.py").touch() + shutil.rmtree(root, ignore_errors=True) + os.replace(staging, root) + sys.path.insert(0, str(root)) + return ( + importlib.import_module("stoa_wl.wayland"), + importlib.import_module("stoa_wl.input_method_unstable_v2"), + importlib.import_module("stoa_wl.virtual_keyboard_unstable_v1"), + ) + + +# ── xkbcommon (ctypes; libxkbcommon is already on every Wayland system) ── +class Xkb: + """Turns the grab's keycodes into keysyms and text, for the arrow keys + and for following the typed word in apps that send no surrounding text + (terminals).""" def __init__(self): - self.dictionary = WordDictionary() - self.emoji_index = EmojiIndex() - self.buffer = "" - self.last_suggestions: list[str] = [] - self.ctrl_held = False - self.alt_held = False - self.meta_held = False - - def find_keyboards(self) -> list[evdev.InputDevice]: - """Find all keyboard input devices.""" - keyboards = [] - for path in evdev.list_devices(): - try: - dev = evdev.InputDevice(path) - caps = dev.capabilities(verbose=False) - if ecodes.EV_KEY in caps: - key_caps = caps[ecodes.EV_KEY] - # Must have letter keys to be a keyboard - if ecodes.KEY_A in key_caps and ecodes.KEY_Z in key_caps: - keyboards.append(dev) - print(f"[predict] Found keyboard: {dev.name} ({dev.path})", file=sys.stderr) - except Exception: - continue - - if not keyboards: - print("[predict] ERROR: No keyboard devices found.", file=sys.stderr) - print("[predict] Make sure you are in the 'input' group:", file=sys.stderr) - print("[predict] sudo usermod -aG input $USER", file=sys.stderr) - print("[predict] (then log out and back in)", file=sys.stderr) - return keyboards - - def emit(self, suggestions: list[str], force: bool = False): - """Publish suggestion data to the plugin (stdout) and SUGGEST_FILE.""" - if suggestions == self.last_suggestions and not force: + lib = ctypes.CDLL("libxkbcommon.so.0") + lib.xkb_context_new.restype = ctypes.c_void_p + lib.xkb_context_new.argtypes = [ctypes.c_int] + lib.xkb_keymap_new_from_string.restype = ctypes.c_void_p + lib.xkb_keymap_new_from_string.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_int] + lib.xkb_keymap_unref.argtypes = [ctypes.c_void_p] + lib.xkb_state_new.restype = ctypes.c_void_p + lib.xkb_state_new.argtypes = [ctypes.c_void_p] + lib.xkb_state_unref.argtypes = [ctypes.c_void_p] + lib.xkb_state_update_mask.argtypes = [ctypes.c_void_p] + [ctypes.c_uint32] * 6 + lib.xkb_state_key_get_one_sym.restype = ctypes.c_uint32 + lib.xkb_state_key_get_one_sym.argtypes = [ctypes.c_void_p, ctypes.c_uint32] + lib.xkb_keymap_min_keycode.restype = ctypes.c_uint32 + lib.xkb_keymap_min_keycode.argtypes = [ctypes.c_void_p] + lib.xkb_keymap_max_keycode.restype = ctypes.c_uint32 + lib.xkb_keymap_max_keycode.argtypes = [ctypes.c_void_p] + lib.xkb_state_key_get_utf8.restype = ctypes.c_int + lib.xkb_state_key_get_utf8.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_char_p, ctypes.c_size_t] + self.lib = lib + self.context = lib.xkb_context_new(0) + self.keymap = None + self.state = None + + def set_keymap(self, text: bytes): + keymap = self.lib.xkb_keymap_new_from_string(self.context, text, 1, 0) + if not keymap: + log("could not compile the grab keymap") return - self.last_suggestions = suggestions - - # Get related emojis for the current buffer - emojis = self.emoji_index.search(self.buffer) if self.buffer else [] - - data = json.dumps({ - "prefix": self.buffer, - "words": suggestions, - "emojis": emojis, - "visible": len(suggestions) > 0 or len(emojis) > 0, - }) - - # `stoa-predict select N` reads the prefix and words back from here. + if self.state: + self.lib.xkb_state_unref(self.state) + self.lib.xkb_keymap_unref(self.keymap) + self.keymap = keymap + self.state = self.lib.xkb_state_new(keymap) + + def update(self, depressed, latched, locked, group): + if self.state: + self.lib.xkb_state_update_mask(self.state, depressed, latched, locked, 0, 0, group) + + def keysym(self, key: int) -> int: + return self.lib.xkb_state_key_get_one_sym(self.state, key + 8) if self.state else 0 + + def key_for(self, sym: int, fallback: int) -> int: + """The evdev code that produces `sym` in the current keymap. The + grab's keymap is whatever the keyboard sends, so do not assume the + US/evdev code for BackSpace.""" + if self.state: + first = self.lib.xkb_keymap_min_keycode(self.keymap) + last = self.lib.xkb_keymap_max_keycode(self.keymap) + for code in range(first, last + 1): + if self.lib.xkb_state_key_get_one_sym(self.state, code) == sym: + return code - 8 + return fallback + + def text(self, key: int) -> str: + if not self.state: + return "" + buf = ctypes.create_string_buffer(16) + n = self.lib.xkb_state_key_get_utf8(self.state, key + 8, buf, 16) + return buf.raw[:n].decode("utf-8", "replace") if n > 0 else "" + + +XK_BACKSPACE, XK_TAB, XK_RETURN, XK_ESCAPE = 0xFF08, 0xFF09, 0xFF0D, 0xFF1B +XK_LEFT, XK_UP, XK_RIGHT, XK_DOWN = 0xFF51, 0xFF52, 0xFF53, 0xFF54 +XK_KP_ENTER = 0xFF8D +# Keys that move the caret or end the word without typing text. +XK_WORD_BREAKERS = {XK_TAB, XK_RETURN, XK_ESCAPE, XK_LEFT, XK_UP, XK_RIGHT, XK_DOWN, XK_KP_ENTER, + 0xFF50, 0xFF57, 0xFF55, 0xFF56, 0xFFFF} # Home End PgUp PgDn Delete +KEY_BACKSPACE = 14 # evdev BackSpace; the fallback when the keymap has none +KEY_PRESSED, KEY_RELEASED = 1, 0 + + +def match_case(word: str, typed: str) -> str: + """Suggestions come from a lowercase list; follow the case of what was typed.""" + if len(typed) > 1 and typed.isupper(): + return word.upper() + if typed[:1].isupper(): + return word[:1].upper() + word[1:] + return word + + +def load_palette() -> dict: + """Colours of the active Stoa palette (Super+S → Theme writes StoaCustom).""" + colours = { + "mSurface": "#211e19", "mOnSurface": "#d4cfc4", "mOnSurfaceVariant": "#a89f91", + "mPrimary": "#c49a5c", "mOnPrimary": "#211e19", "mOutline": "#6e6a62", + "mSurfaceVariant": "#2d2921", + } + palettes = Path.home() / ".config/noctalia/palettes" + for name in ("StoaCustom.json", "Stoa.json"): try: - with open(SUGGEST_FILE, "w") as f: - f.write(data) - except Exception: - pass - - print(data, flush=True) - - def reset(self): - """Forget the typed word. `stoa-predict select` sends SIGUSR1 after - typing a suggestion with wtype — virtual-keyboard input never reaches - evdev, so the daemon would otherwise keep the old prefix.""" - self.buffer = "" - self.emit([], force=True) - - def process_key(self, keycode: int, key_state: int): - """Process a single key event.""" - # Only handle key-down events - if key_state != 1: - # Track modifier releases - if key_state == 0: - if keycode in (ecodes.KEY_LEFTCTRL, ecodes.KEY_RIGHTCTRL): - self.ctrl_held = False - elif keycode in (ecodes.KEY_LEFTALT, ecodes.KEY_RIGHTALT): - self.alt_held = False - elif keycode in (ecodes.KEY_LEFTMETA, ecodes.KEY_RIGHTMETA): - self.meta_held = False - return - - # Track modifiers - if keycode in (ecodes.KEY_LEFTCTRL, ecodes.KEY_RIGHTCTRL): - self.ctrl_held = True - return - if keycode in (ecodes.KEY_LEFTALT, ecodes.KEY_RIGHTALT): - self.alt_held = True - return - if keycode in (ecodes.KEY_LEFTMETA, ecodes.KEY_RIGHTMETA): - self.meta_held = True - return + data = json.loads((palettes / name).read_text(encoding="utf-8")) + colours.update({k: v for k, v in data.get("dark", {}).items() if isinstance(v, str)}) + break + except (OSError, ValueError): + continue + return colours + + +def rgb(hex_colour: str, alpha: float = 1.0): + h = hex_colour.lstrip("#") + return (int(h[0:2], 16) / 255, int(h[2:4], 16) / 255, int(h[4:6], 16) / 255, alpha) + + +class Popup: + """The suggestion strip: an input-method popup surface, which the + compositor places next to the text cursor (below it, or above when + there is no room), drawn with cairo + Pango into shm buffers.""" + + PAD, GAP, CHIP_PAD_X, CHIP_PAD_Y, RADIUS = 5, 3, 9, 4, 7 + FONT = "Sans 10.5" + + def __init__(self, app): + import cairo + import gi + gi.require_version("Pango", "1.0") + gi.require_version("PangoCairo", "1.0") + from gi.repository import Pango, PangoCairo + self.cairo, self.Pango, self.PangoCairo = cairo, Pango, PangoCairo + self.app = app + self.surface = app.compositor.create_surface() + self.popup = app.im.get_input_popup_surface(self.surface) + self.visible = False + self.chips = [] # (x0, x1) in surface coordinates, per item + self.buffers = [] # live (buffer, pool, mmap, fd) + self.palette = load_palette() + + def _buffer(self, width, height): + stride = width * 4 + size = stride * height + fd = os.memfd_create("stoa-predict", os.MFD_CLOEXEC) + os.ftruncate(fd, size) + data = mmap.mmap(fd, size) + pool = self.app.shm.create_pool(fd, size) + buffer = pool.create_buffer(0, width, height, stride, self.app.wl.WlShm.format.argb8888.value) + entry = (buffer, pool, data, fd) + self.buffers.append(entry) + + def released(_buffer): + buffer.destroy() + pool.destroy() + data.close() + os.close(fd) + if entry in self.buffers: + self.buffers.remove(entry) + + buffer.dispatcher["release"] = released + return buffer, data, stride + + def show(self, items, selected): + cairo, Pango, PangoCairo = self.cairo, self.Pango, self.PangoCairo + scale = self.app.scale + font = Pango.FontDescription.from_string(self.FONT) + + # Measure on a scratch surface first. + scratch = cairo.Context(cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1)) + layouts = [] + for _kind, text in items: + layout = PangoCairo.create_layout(scratch) + layout.set_font_description(font) + layout.set_text(text, -1) + layouts.append((layout, *layout.get_pixel_size())) + hint = PangoCairo.create_layout(scratch) + hint.set_font_description(font) + hint.set_text("↓", -1) + hint_w, hint_h = hint.get_pixel_size() + + text_h = max([h for _l, _w, h in layouts] + [hint_h]) + chip_h = text_h + 2 * self.CHIP_PAD_Y + width = self.PAD + self.chips = [] + for _layout, w, _h in layouts: + self.chips.append((width, width + w + 2 * self.CHIP_PAD_X)) + width += w + 2 * self.CHIP_PAD_X + self.GAP + if selected is None: + width += hint_w + self.CHIP_PAD_X + width += self.PAD - self.GAP + height = chip_h + 2 * self.PAD + + buffer, data, stride = self._buffer(width * scale, height * scale) + image = cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32, width * scale, height * scale, stride) + cr = cairo.Context(image) + cr.scale(scale, scale) + p = self.palette + + def rounded(cr, x, y, w, h, r): + cr.new_sub_path() + cr.arc(x + w - r, y + r, r, -1.5708, 0) + cr.arc(x + w - r, y + h - r, r, 0, 1.5708) + cr.arc(x + r, y + h - r, r, 1.5708, 3.1416) + cr.arc(x + r, y + r, r, 3.1416, 4.7124) + cr.close_path() + + cr.set_operator(cairo.OPERATOR_SOURCE) + cr.set_source_rgba(0, 0, 0, 0) + cr.paint() + cr.set_operator(cairo.OPERATOR_OVER) + rounded(cr, 0.5, 0.5, width - 1, height - 1, self.RADIUS + 2) + cr.set_source_rgba(*rgb(p["mSurface"], 0.97)) + cr.fill_preserve() + cr.set_source_rgba(*rgb(p["mOutline"], 0.8)) + cr.set_line_width(1) + cr.stroke() + + for i, ((layout, w, h), (x0, x1)) in enumerate(zip(layouts, self.chips)): + kind = items[i][0] + if i == selected: + rounded(cr, x0, self.PAD, x1 - x0, chip_h, self.RADIUS) + cr.set_source_rgba(*rgb(p["mPrimary"])) + cr.fill() + colour = p["mOnPrimary"] + elif kind == "emoji": + colour = p["mOnSurface"] + else: + colour = p["mPrimary"] if (selected is None and i == 0) else p["mOnSurface"] + cr.set_source_rgba(*rgb(colour)) + cr.move_to(x0 + self.CHIP_PAD_X, self.PAD + (chip_h - h) / 2) + PangoCairo.show_layout(cr, layout) + if selected is None: + cr.set_source_rgba(*rgb(p["mOnSurfaceVariant"], 0.8)) + cr.move_to(width - self.PAD - hint_w - self.CHIP_PAD_X / 2, self.PAD + (chip_h - hint_h) / 2) + PangoCairo.show_layout(cr, hint) + image.flush() + + self.surface.set_buffer_scale(scale) + self.surface.attach(buffer, 0, 0) + self.surface.damage_buffer(0, 0, width * scale, height * scale) + self.surface.commit() + self.visible = True + + def hide(self): + if self.visible: + self.surface.attach(None, 0, 0) + self.surface.commit() + self.visible = False + self.chips = [] + + def hit(self, x: float) -> int | None: + for i, (x0, x1) in enumerate(self.chips): + if x0 <= x < x1: + return i + return None + + +class InputMethod: + def __init__(self, words, emojis): + from pywayland.client import Display + + self.wl, self.imp, self.vkp = load_protocols() + self.words, self.emojis = words, emojis + self.display = Display() + self.display.connect() + self.compositor = self.shm = self.seat = self.im_manager = self.vk_manager = None + self.output_scales = {} + registry = self.display.get_registry() + registry.dispatcher["global"] = self._global + self.display.roundtrip() + self.display.roundtrip() # wl_output scale / seat capabilities + + missing = [n for n, v in (("wl_compositor", self.compositor), ("wl_shm", self.shm), ("wl_seat", self.seat), + ("zwp_input_method_manager_v2", self.im_manager), + ("zwp_virtual_keyboard_manager_v1", self.vk_manager)) if v is None] + if missing: + say(error="This compositor does not offer " + ", ".join(missing) + " — text prediction needs a Wayland input method.") + sys.exit(1) - # Ignore keystrokes with modifiers (shortcuts, not typing) - if self.ctrl_held or self.alt_held or self.meta_held: - # Ctrl+A, Ctrl+C, etc. — reset buffer - self.buffer = "" - self.emit([]) + self.im = self.im_manager.get_input_method(self.seat) + self.vk = self.vk_manager.create_virtual_keyboard(self.seat) + self.xkb = Xkb() + self.keymap_sent = False + self.grab = None + self.serial = 0 + + # Pending state (applied on `done`) and current state. + self.pending_active = False + self.pending_surrounding = None + self.active = False + self.surrounding_known = False + self.before_cursor = "" + self.typed = "" # fallback for apps without surrounding text + self.items = [] + self.selected = None # None = popup shown but not entered + self.dismissed_prefix = None # Esc hides the popup until the word changes + self.consumed = set() # keys whose press we kept from the app + + for event in ("activate", "deactivate", "surrounding_text", "done", "unavailable"): + self.im.dispatcher[event] = getattr(self, f"_im_{event}") + self.im.dispatcher["text_change_cause"] = lambda *_: None + self.im.dispatcher["content_type"] = lambda *_: None + + self.popup = Popup(self) + self.popup.popup.dispatcher["text_input_rectangle"] = lambda *_: None + + self.pointer = None + self.pointer_x = None + self.display.roundtrip() + + @property + def scale(self) -> int: + return max(self.output_scales.values(), default=1) + + # ── registry ── + def _global(self, registry, name, interface, version): + wl = self.wl + if interface == "wl_compositor": + self.compositor = registry.bind(name, wl.WlCompositor, min(version, 4)) + elif interface == "wl_shm": + self.shm = registry.bind(name, wl.WlShm, 1) + elif interface == "wl_seat" and self.seat is None: + self.seat = registry.bind(name, wl.WlSeat, min(version, 5)) + self.seat.dispatcher["capabilities"] = self._seat_capabilities + self.seat.dispatcher["name"] = lambda *_: None + elif interface == "wl_output": + output = registry.bind(name, wl.WlOutput, min(version, 2)) + self.output_scales[name] = 1 + + def scale(_output, factor, key=name): + self.output_scales[key] = factor + + output.dispatcher["scale"] = scale + for event in ("geometry", "mode", "done"): + output.dispatcher[event] = lambda *_: None + elif interface == "zwp_input_method_manager_v2": + self.im_manager = registry.bind(name, self.imp.ZwpInputMethodManagerV2, 1) + elif interface == "zwp_virtual_keyboard_manager_v1": + self.vk_manager = registry.bind(name, self.vkp.ZwpVirtualKeyboardManagerV1, 1) + + def _seat_capabilities(self, seat, caps): + has_pointer = bool(caps & self.wl.WlSeat.capability.pointer.value) + if has_pointer and self.pointer is None: + self.pointer = seat.get_pointer() + self.pointer.dispatcher["enter"] = self._pointer_enter + self.pointer.dispatcher["leave"] = lambda *_: setattr(self, "pointer_x", None) + self.pointer.dispatcher["motion"] = lambda _p, _t, x, _y: setattr(self, "pointer_x", x) if self.pointer_x is not None else None + self.pointer.dispatcher["button"] = self._pointer_button + for event in ("axis", "frame", "axis_source", "axis_stop", "axis_discrete"): + self.pointer.dispatcher[event] = lambda *_: None + + # ── pointer: click a suggestion ── + def _pointer_enter(self, _pointer, _serial, surface, x, _y): + self.pointer_x = x if surface == self.popup.surface else None + + def _pointer_button(self, _pointer, _serial, _time, _button, state): + if state == 1 and self.pointer_x is not None and self.popup.visible: + index = self.popup.hit(self.pointer_x) + if index is not None: + self.accept(index) + + # ── input method state ── + def _im_activate(self, _im): + self.pending_active = True + self.pending_surrounding = None + + def _im_deactivate(self, _im): + self.pending_active = False + + def _im_surrounding_text(self, _im, text, cursor, _anchor): + self.pending_surrounding = (text, cursor) + + def _im_unavailable(self, _im): + say(error="Another input method (fcitx, ibus…) is already running; stop it to use Stoa text prediction.") + quit_now(1) + + def _im_done(self, _im): + self.serial += 1 + debug(f"done #{self.serial}: active={self.pending_active} surrounding={self.pending_surrounding!r}") + was_active = self.active + self.active = self.pending_active + if self.active and not was_active: + self.surrounding_known = False + self.before_cursor = "" + self.typed = "" + self.dismissed_prefix = None + self._grab_keyboard() + elif was_active and not self.active: + self._release_keyboard() + self.selected = None + self.popup.hide() return - - # Skip other modifier keys - if keycode in MODIFIER_KEYS: + if self.pending_surrounding is not None: + text, cursor = self.pending_surrounding + self.pending_surrounding = None + self.surrounding_known = True + self.before_cursor = text.encode("utf-8")[:cursor].decode("utf-8", "ignore") + self.refresh() + + # ── keyboard grab ── + def _grab_keyboard(self): + if self.grab is not None: return - - # Backspace: remove last char - if keycode == ecodes.KEY_BACKSPACE: - if self.buffer: - self.buffer = self.buffer[:-1] - if len(self.buffer) >= MIN_PREFIX: - suggestions = self.dictionary.search(self.buffer) - self.emit(suggestions) - else: - self.emit([]) + self.grab = self.im.grab_keyboard() + self.grab.dispatcher["keymap"] = self._grab_keymap + self.grab.dispatcher["key"] = self._grab_key + self.grab.dispatcher["modifiers"] = self._grab_modifiers + self.grab.dispatcher["repeat_info"] = lambda *_: None + + def _release_keyboard(self): + if self.grab is not None: + self.grab.release() + self.grab = None + self.consumed.clear() + + def _grab_keymap(self, _grab, fmt, fd, size): + try: + with mmap.mmap(fd, size, prot=mmap.PROT_READ) as data: + self.xkb.set_keymap(data[:].rstrip(b"\0")) + self.vk.keymap(fmt, fd, size) + self.keymap_sent = True + finally: + os.close(fd) + + def _grab_modifiers(self, _grab, _serial, depressed, latched, locked, group): + self.xkb.update(depressed, latched, locked, group) + if self.keymap_sent: + self.vk.modifiers(depressed, latched, locked, group) + + def _forward(self, time_ms, key, state): + if self.keymap_sent: + self.vk.key(time_ms, key, state) + + def _grab_key(self, _grab, _serial, time_ms, key, state): + debug(f"key {key} {'down' if state else 'up'} sym={self.xkb.keysym(key):#x}") + if state == KEY_RELEASED: + if key in self.consumed: + self.consumed.discard(key) + else: + self._forward(time_ms, key, state) return - # Reset keys (space, enter, punctuation, arrows) - if keycode in RESET_KEYS: - self.buffer = "" - self.emit([]) + sym = self.xkb.keysym(key) + if self.popup.visible and self.navigate(sym): + self.consumed.add(key) return - - # Letter keys - char = KEY_MAP.get(keycode) - if char: - self.buffer += char - if len(self.buffer) >= MIN_PREFIX: - suggestions = self.dictionary.search(self.buffer) - self.emit(suggestions) + self._forward(time_ms, key, state) + + # Follow the word ourselves for apps that send no surrounding text. + if sym == XK_BACKSPACE: + self.typed = self.typed[:-1] + else: + text = self.xkb.text(key) + if text and WORD_BEFORE_CURSOR.fullmatch(text): + self.typed += text + elif text or sym in XK_WORD_BREAKERS: + self.typed = "" + if not self.surrounding_known: + self.refresh() + + # ── suggestions ── + def prefix(self) -> str: + if self.surrounding_known: + match = WORD_BEFORE_CURSOR.search(self.before_cursor) + return match.group(0) if match else "" + return self.typed + + def refresh(self): + prefix = self.prefix() + debug(f"prefix={prefix!r}") + if self.dismissed_prefix is not None and prefix != self.dismissed_prefix: + self.dismissed_prefix = None + items = [] + if len(prefix) >= MIN_PREFIX and self.dismissed_prefix is None: + items = [("word", match_case(w, prefix)) for w in self.words.search(prefix)] + items += [("emoji", e["emoji"]) for e in self.emojis.search(prefix, MAX_EMOJIS)] + if items != self.items: + self.items = items + self.selected = None + if self.items: + self.popup.show(self.items, self.selected) + else: + self.popup.hide() + + def navigate(self, sym) -> bool: + """Arrow-key handling while the popup is up. True = key consumed.""" + if self.selected is None: + if sym in (XK_DOWN, XK_UP): + self.selected = 0 + self.popup.show(self.items, self.selected) + return True + if sym == XK_ESCAPE: # let the app see Esc too (vim…) + self.dismiss() + return False + if sym in (XK_LEFT, XK_RIGHT): + step = -1 if sym == XK_LEFT else 1 + self.selected = (self.selected + step) % len(self.items) + self.popup.show(self.items, self.selected) + return True + if sym in (XK_DOWN, XK_UP): + self.selected = None + self.popup.show(self.items, self.selected) + return True + if sym in (XK_RETURN, XK_KP_ENTER, XK_TAB): + self.accept(self.selected) + return True + if sym == XK_ESCAPE: + self.dismiss() + return True + # Any other key leaves the popup and reaches the app. + self.selected = None + self.popup.show(self.items, self.selected) + return False + + def dismiss(self): + self.dismissed_prefix = self.prefix() + self.selected = None + self.items = [] + self.popup.hide() + + def accept(self, index: int): + kind, text = self.items[index] + prefix = self.prefix() + if kind == "word": + if self.surrounding_known: + self.im.delete_surrounding_text(len(prefix.encode("utf-8")), 0) else: - self.emit([]) - return - - # Number keys or unknown — reset - if ecodes.KEY_1 <= keycode <= ecodes.KEY_0: - self.buffer = "" - self.emit([]) - - async def listen_device(self, device: evdev.InputDevice): - """Async listener for a single keyboard device.""" - try: - async for event in device.async_read_loop(): - if event.type == ecodes.EV_KEY: - self.process_key(event.code, event.value) - except Exception as e: - print(f"[predict] Device {device.name} disconnected: {e}", file=sys.stderr) - - async def run(self): - """Start listening on all keyboards.""" - keyboards = self.find_keyboards() - if not keyboards: - print(json.dumps({"error": "No keyboard found. Are you in the input group? " - "sudo usermod -aG input $USER, then log out and back in."}), - flush=True) - sys.exit(1) - - # Write PID file - with open(PIDFILE, "w") as f: - f.write(str(os.getpid())) - - print(f"[predict] Daemon started (PID {os.getpid()})", file=sys.stderr) - - asyncio.get_running_loop().add_signal_handler(signal.SIGUSR1, self.reset) - - # Initialize with empty state - self.emit([], force=True) - - # Listen on all keyboards concurrently - tasks = [self.listen_device(kb) for kb in keyboards] - await asyncio.gather(*tasks) - - -def cleanup(_sig=None, _frame=None): - """Clean up on exit.""" - try: - os.remove(PIDFILE) - except FileNotFoundError: - pass - try: - os.remove(SUGGEST_FILE) - except FileNotFoundError: - pass - sys.exit(0) + # Terminals and other apps without surrounding text: erase + # the typed prefix with real BackSpaces first. + now = int(time.monotonic() * 1000) & 0xFFFFFFFF + backspace = self.xkb.key_for(XK_BACKSPACE, KEY_BACKSPACE) + for _ in prefix: + self._forward(now, backspace, KEY_PRESSED) + self._forward(now, backspace, KEY_RELEASED) + self.im.commit_string(text + " ") + else: + self.im.commit_string(text) + self.im.commit(self.serial) + self.typed = "" + self.before_cursor = "" + self.selected = None + self.items = [] + self.popup.hide() + + def run(self): + # The pidfile is written only once the compositor has handed us the + # input method (an `unavailable` would have arrived during the + # roundtrips in __init__), so it always names the instance holding it. + Path(PIDFILE).write_text(str(os.getpid())) + say(ready=True) + while self.display.dispatch(block=True) != -1: + pass def main(): - signal.signal(signal.SIGTERM, cleanup) - signal.signal(signal.SIGINT, cleanup) + try: + import cairo # noqa: F401 + import gi + gi.require_version("Pango", "1.0") + gi.require_version("PangoCairo", "1.0") + import pywayland # noqa: F401 + except (ImportError, ValueError) as err: + say(error=f"Missing dependency ({err}): sudo pacman -S python-pywayland python-cairo python-gobject pango") + sys.exit(1) + if not os.environ.get("WAYLAND_DISPLAY"): + say(error="No Wayland session (WAYLAND_DISPLAY is unset).") + sys.exit(1) - daemon = PredictDaemon() try: - asyncio.run(daemon.run()) - except KeyboardInterrupt: - cleanup() + ime = InputMethod(WordDictionary(), EmojiIndex()) + ime.run() + finally: + remove_pidfile() if __name__ == "__main__": + # Default (kernel) action for SIGTERM/SIGINT, deliberately. While idle + # the daemon sits inside libwayland's poll(), which restarts on EINTR, + # so a Python-level handler would not run until the next Wayland event: + # `stoa-predict kill` would wait in vain and the next start would be + # refused as "unavailable". Nothing needs cleaning up on the way out — + # the compositor drops the grab and the popup when the connection + # closes, and `stoa-predict kill` removes the pidfile. + signal.signal(signal.SIGTERM, signal.SIG_DFL) + signal.signal(signal.SIGINT, signal.SIG_DFL) main() diff --git a/scripts/stoa-predict.sh b/scripts/stoa-predict.sh index 8d7fc42..e6070b8 100755 --- a/scripts/stoa-predict.sh +++ b/scripts/stoa-predict.sh @@ -3,17 +3,17 @@ # ║ STOA LINUX — Text Prediction Controller ║ # ║ "Words have power." — Marcus Aurelius ║ # ║ ║ -# ║ Toggle, select, and manage the prediction daemon. ║ -# ║ The popup is the Noctalia stoa/predict plugin; its service ║ -# ║ runs `stoa-predict run` and reads suggestions from stdout. ║ -# ║ Requires: python-evdev, wtype ║ +# ║ Turns the prediction input method on and off. The daemon ║ +# ║ (stoa-predict.py) is a Wayland input method: its popup sits ║ +# ║ next to the text cursor and it types the chosen word ║ +# ║ itself. The Noctalia stoa/predict plugin owns it — its ║ +# ║ service runs `stoa-predict run` and reads its stdout. ║ +# ║ Requires: python-pywayland, python-cairo, python-gobject ║ # ╚══════════════════════════════════════════════════════════════╝ # # Usage: # stoa-predict toggle — start/stop prediction (Super+Shift+S) # stoa-predict start | stop — same, one direction -# stoa-predict select — accept suggestion at index (0-4) -# stoa-predict select-emoji — accept emoji at index # stoa-predict run — the daemon itself; started by the plugin # stoa-predict kill — stop the daemon; used by the plugin @@ -21,7 +21,6 @@ # world-writable /tmp. Falls back to /tmp only when unset (non-systemd). _STOA_RUNTIME="${XDG_RUNTIME_DIR:-/tmp}" PIDFILE="${_STOA_RUNTIME}/stoa-predict.pid" -SUGGEST_FILE="${_STOA_RUNTIME}/stoa-predict.json" SCRIPT_DIR="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)" PREDICT_PY="${SCRIPT_DIR}/stoa-predict.py" @@ -39,101 +38,38 @@ _plugin() { noctalia msg plugin "$PLUGIN_SERVICE" all "$1" } -_is_running() { - [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE" 2>/dev/null)" 2>/dev/null +# Stop the daemon and wait until it is gone: the compositor hands the input +# method to one client at a time, and a new instance started while the old +# one is still connected is refused ("unavailable"). +_kill() { + local pid tries=40 + pid=$(cat "$PIDFILE" 2>/dev/null) + if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then + kill "$pid" 2>/dev/null + while [ "$tries" -gt 0 ] && kill -0 "$pid" 2>/dev/null; do + sleep 0.05 + tries=$((tries - 1)) + done + fi + rm -f "$PIDFILE" } -# Run by the plugin service through noctalia.runStream: stdout carries one -# JSON object per line. A failed precondition is reported the same way, as -# {"error": "..."}, so the service can show it. +# Run by the plugin service through noctalia.runStream. stdout carries one +# JSON object per line ({"ready": true} or {"error": "..."}); the daemon +# checks its own dependencies and reports them the same way. _run() { # The service is the daemon's only owner. One still alive here was # orphaned (the shell restarted under it), and nothing reads its stdout. _kill - if ! groups 2>/dev/null | grep -qw input; then - echo '{"error":"Add yourself to the input group: sudo usermod -aG input $USER, then log out and back in."}' - return 1 - fi - if ! python3 -c "import evdev" 2>/dev/null; then - echo '{"error":"python-evdev is not installed: sudo pacman -S python-evdev"}' - return 1 - fi exec python3 "$PREDICT_PY" } -# Called by the plugin service when prediction is switched off. -_kill() { - if _is_running; then - kill "$(cat "$PIDFILE" 2>/dev/null)" 2>/dev/null - fi - rm -f "$PIDFILE" "$SUGGEST_FILE" -} - -# The suggestion was typed with wtype, which evdev never sees: tell the -# daemon to drop the prefix (it answers with an empty, hidden update). -_reset_daemon() { - _is_running && kill -USR1 "$(cat "$PIDFILE" 2>/dev/null)" 2>/dev/null -} - -_select() { - local index="${1:-0}" - [ ! -f "$SUGGEST_FILE" ] && return - - local data - data=$(cat "$SUGGEST_FILE" 2>/dev/null) - [ -z "$data" ] && return - - local prefix word - prefix=$(echo "$data" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('prefix',''))" 2>/dev/null) - word=$(echo "$data" | python3 -c "import sys,json; d=json.load(sys.stdin); w=d.get('words',[]); print(w[$index] if $index/dev/null) - - [ -z "$word" ] && return - - # Erase the typed prefix with backspaces, then type the full word. - # Build a single wtype invocation so all keystrokes land in one batch - # — looping one `wtype -k BackSpace` per char dropped events on fast typers. - local prefix_len=${#prefix} - if [ "$prefix_len" -gt 0 ] && command -v wtype &>/dev/null; then - local wtype_args=() - local i - for ((i = 0; i < prefix_len; i++)); do - wtype_args+=(-k BackSpace) - done - wtype_args+=(-s 30 -- "${word} ") - wtype "${wtype_args[@]}" - fi - - _reset_daemon -} - -_select_emoji() { - local index="${1:-0}" - [ ! -f "$SUGGEST_FILE" ] && return - - local data - data=$(cat "$SUGGEST_FILE" 2>/dev/null) - [ -z "$data" ] && return - - local emoji - emoji=$(echo "$data" | python3 -c "import sys,json; d=json.load(sys.stdin); e=d.get('emojis',[]); print(e[$index]['emoji'] if $index/dev/null) - - [ -z "$emoji" ] && return - - if command -v wtype &>/dev/null; then - wtype -- "$emoji" - fi - - _reset_daemon -} - case "${1:-}" in toggle|start|stop) _plugin "$1" ;; run) _run ;; kill) _kill ;; - select) _select "${2:-0}" ;; - select-emoji) _select_emoji "${2:-0}" ;; *) - echo "Usage: stoa-predict {toggle|start|stop|select N|select-emoji N|run|kill}" + echo "Usage: stoa-predict {toggle|start|stop|run|kill}" exit 1 ;; esac diff --git a/setup/post-install.sh b/setup/post-install.sh index c498473..28e35bd 100755 --- a/setup/post-install.sh +++ b/setup/post-install.sh @@ -143,7 +143,7 @@ GAMING_PKGS="steam lib32-vulkan-icd-loader vulkan-icd-loader lib32-mesa" SCREENSHOT_PKGS="grim slurp wf-recorder" # Stoatools (OCR, paste, resize, rename, locksmith, archive) -STOATOOLS_PKGS="tesseract tesseract-data-eng tesseract-data-por lsof wtype python-evdev words yad" +STOATOOLS_PKGS="tesseract tesseract-data-eng tesseract-data-por lsof wtype python-pywayland python-cairo python-gobject words yad" # Touchpad gestures + mouse DPI/polling + RGB # GESTURE_PKGS="libinput-gestures" @@ -367,9 +367,9 @@ else echo -e " ${S}[~] Packages skipped.${R}" fi echo "" -# ── Input group (required for stoa-predict) ── +# ── Input group (required for libinput-gestures, which reads /dev/input) ── if ! groups 2>/dev/null | grep -qw input; then - echo -e " ${F}Adding user to 'input' group (for text prediction)...${R}" + echo -e " ${F}Adding user to 'input' group (for touchpad gestures)...${R}" sudo usermod -aG input "$(whoami)" echo -e " ${O}[✓] Added to input group (takes effect after next login).${R}" else diff --git a/theme/noctalia-plugins/stoa-predict/panel.luau b/theme/noctalia-plugins/stoa-predict/panel.luau deleted file mode 100644 index 2ca82b1..0000000 --- a/theme/noctalia-plugins/stoa-predict/panel.luau +++ /dev/null @@ -1,89 +0,0 @@ --- ╔══════════════════════════════════════════════════════════════╗ --- ║ STOA LINUX — Text prediction popup ║ --- ╚══════════════════════════════════════════════════════════════╝ --- --- Up to five words and three emojis in one row at the bottom of the --- screen, the same strip the eww `predict` window drew. The panel never --- takes keyboard focus (see plugin.toml), so the window being typed in --- keeps it and `stoa-predict select N` types the word there with wtype. --- --- Data comes from the service through noctalia.state ("predict.data"). --- Lua 5.4-compatible subset of Luau, like the other Stoa plugins. - -local BIN = noctalia.expandPath("~/.local/bin/stoa-predict") - -local isOpen = false -local data = nil - -local function current() - local value = noctalia.state.get("predict.data") - if type(value) == "table" then - return value - end - return { prefix = "", words = {}, emojis = {}, visible = false } -end - -local function select(kind, index) - noctalia.runAsync({ BIN, kind, tostring(index) }) -end - -local function render() - if not isOpen then - return - end - data = data or current() - - local children = {} - local words = data.words or {} - local emojis = data.emojis or {} - - for i, word in ipairs(words) do - if i > 5 then break end - local variant = "ghost" - if i == 1 then variant = "primary" end - children[#children + 1] = ui.button({ - key = "word-" .. i, - text = word, - variant = variant, - controlSize = "sm", - onClick = function() select("select", i - 1) end, - }) - end - - if #words > 0 and #emojis > 0 then - children[#children + 1] = ui.separator({ orientation = "vertical", spacing = 4 }) - end - - for i, item in ipairs(emojis) do - if i > 3 then break end - if type(item) == "table" and type(item.emoji) == "string" then - children[#children + 1] = ui.button({ - key = "emoji-" .. i, - text = item.emoji, - tooltip = item.name, - variant = "ghost", - controlSize = "sm", - onClick = function() select("select-emoji", i - 1) end, - }) - end - end - - panel.render(ui.row({ gap = 4, align = "center", justify = "center", paddingH = 8 }, children)) -end - -noctalia.state.watch("predict.data", function(value) - if type(value) == "table" then - data = value - end - render() -end) - -function onOpen() - isOpen = true - data = current() - render() -end - -function onClose() - isOpen = false -end diff --git a/theme/noctalia-plugins/stoa-predict/plugin.toml b/theme/noctalia-plugins/stoa-predict/plugin.toml index dc00cf5..40fd5d4 100644 --- a/theme/noctalia-plugins/stoa-predict/plugin.toml +++ b/theme/noctalia-plugins/stoa-predict/plugin.toml @@ -3,51 +3,33 @@ # ║ "Choose your words with care." — Epictetus ║ # ╚══════════════════════════════════════════════════════════════╝ # -# Replaces the eww `predict` window. The word engine is unchanged -# (scripts/stoa-predict.py reads evdev and looks words up); only the -# popup moved into the shell: +# Owns the prediction input method (scripts/stoa-predict.py). The +# daemon is a Wayland input method (input-method-v2, like fcitx): it +# draws its own popup next to the text cursor, takes ↑/↓/←/→/Enter while +# the popup is up and types the chosen word through the text-input +# protocol, so the shell only has to start it, stop it and report. # -# service.luau runs `stoa-predict run` with noctalia.runStream and -# reads one JSON object per stdout line — no process per -# keystroke, where the eww popup forked `eww update`. -# Opens the popup while there are suggestions. -# panel.luau the popup: word and emoji buttons at the bottom of the -# screen. A click runs `stoa-predict select N`, which -# types the word with wtype. +# This plugin used to draw the suggestions itself, in a panel at the +# bottom of the screen fed by an evdev daemon. A shell panel cannot be +# placed at another app's text cursor nor take the arrow keys without +# stealing focus, which is why the popup moved into the input method. # # Super+Shift+S runs `stoa-predict toggle`, which sends `toggle` to the # service over IPC: noctalia msg plugin stoa/predict:service all toggle id = "stoa/predict" name = "Stoa Text Prediction" -version = "1.0.0" +version = "2.0.0" author = "stoa" icon = "keyboard" -description = "System-wide word and emoji suggestions while you type" +description = "Word and emoji suggestions next to the text cursor while you type" tags = ["input", "typing"] -dependencies = ["python-evdev", "wtype"] +dependencies = ["python-pywayland", "python-cairo", "python-gobject"] -# 30 = the `layer` panel option (v5.0.1), the newest thing used here. -# The popup also needs keyboard_focus (10), persistent (11) and the -# argv form of runAsync (24); all older than 30. -plugin_api = 30 +# The service only needs runStream, runAsync, notify and json, all older +# than 9; 9 matches the other Stoa plugins. +plugin_api = 9 [[service]] id = "service" entry = "service.luau" - -# The popup must never take the keyboard: the user is typing in another -# window and a click on a suggestion has to land there. keyboard_focus = -# "none" requires dismiss_on_outside_click = false; persistent keeps the -# popup up when another shell panel opens. Overlay stays above -# fullscreen windows, as the eww window's :stacking "overlay" did. -[[panel]] -id = "popup" -entry = "panel.luau" -width = 560 -height = 56 -position = "bottom_center" -layer = "overlay" -keyboard_focus = "none" -dismiss_on_outside_click = false -persistent = true diff --git a/theme/noctalia-plugins/stoa-predict/service.luau b/theme/noctalia-plugins/stoa-predict/service.luau index e7cf627..0052a60 100644 --- a/theme/noctalia-plugins/stoa-predict/service.luau +++ b/theme/noctalia-plugins/stoa-predict/service.luau @@ -2,25 +2,15 @@ -- ║ STOA LINUX — Text prediction service ║ -- ╚══════════════════════════════════════════════════════════════╝ -- --- Owns the prediction daemon. `stoa-predict run` checks the input group --- and python-evdev, then execs scripts/stoa-predict.py, which prints one --- JSON object per line whenever the suggestions change: --- {"prefix":"stoi","words":["stoic",...],"emojis":[{"emoji":"…","name":"…"}], --- "visible":true} --- or, when a precondition fails, {"error":"…"}. The command line ends with --- an `{"exited":true}` echo so the service learns when the daemon is gone. --- --- The latest suggestions go to noctalia.state ("predict.data") for the --- popup panel, which is opened while `visible` is true and closed --- otherwise. --- --- The panel is opened with `noctalia msg panel-open/-close`, not --- noctalia.togglePanel: a [[service]] runtime is created without the --- panel-toggle callback (src/scripting/plugin_service_host.cpp builds its --- ScriptRuntime with none), so togglePanel is a silent no-op here. Both --- IPC verbs are idempotent for a persistent panel (PersistentPanelHost:: --- open returns early when it is already open), so a lost update cannot --- leave the popup inverted. +-- Starts and stops the prediction input method. `stoa-predict run` +-- execs scripts/stoa-predict.py, which registers as the Wayland input +-- method and prints one JSON object per line on stdout: +-- {"ready":true} the input method is live +-- {"error":"…"} it could not start (missing package, +-- another input method running, …) +-- The command line ends with an `{"exited":true}` echo so the service +-- learns when the daemon is gone. Everything the user sees while typing +-- (the popup, the arrow keys) belongs to the daemon. -- -- IPC (what `stoa-predict toggle|start|stop` sends): -- noctalia msg plugin stoa/predict:service all toggle @@ -29,36 +19,12 @@ -- plugins, so the CI lua step can parse it. local BIN = "$HOME/.local/bin/stoa-predict" -local PANEL = "stoa/predict:popup" local running = false -local announced = false -local panelShown = false - -local function emptyData() - return { prefix = "", words = {}, emojis = {}, visible = false } -end - -local function setPanel(open) - if open == panelShown then - return - end - panelShown = open - local verb = "panel-close" - if open then verb = "panel-open" end - noctalia.runAsync({ "noctalia", "msg", verb, PANEL }) -end - -local function publish(data) - noctalia.state.set("predict.data", data) - setPanel(data.visible == true) -end local function finished() running = false - announced = false noctalia.state.set("predict.running", false) - publish(emptyData()) end local function onLine(line) @@ -68,31 +34,11 @@ local function onLine(line) end if type(parsed.error) == "string" then noctalia.notifyError("Text prediction", parsed.error) - return - end - if parsed.exited then + elseif parsed.ready then + noctalia.notify("Text prediction", "On — ↓ picks a suggestion, Super+Shift+S turns it off") + elseif parsed.exited then finished() - return end - - if not announced then - announced = true - noctalia.notify("Text prediction", "On — Super+Shift+S to turn off") - end - - local words = parsed.words - if type(words) ~= "table" then words = {} end - local emojis = parsed.emojis - if type(emojis) ~= "table" then emojis = {} end - local prefix = parsed.prefix - if type(prefix) ~= "string" then prefix = "" end - - publish({ - prefix = prefix, - words = words, - emojis = emojis, - visible = parsed.visible == true and (#words > 0 or #emojis > 0), - }) end local function start() @@ -135,5 +81,4 @@ function onExit() end end -noctalia.state.set("predict.data", emptyData()) noctalia.state.set("predict.running", false)