RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Files: compose with the input method in every text field
vgxl5fc64516a7a2
diff --git a/TESTING.md b/TESTING.mdindex 1e44e26..5c2a5f4 100644--- a/TESTING.md+++ b/TESTING.md@@ -29,8 +29,9 @@ Compare failures with a clean HEAD worktree before calling them regressions.Integration dependencies: Python 3 + Pillow, C compiler, `wayland-scanner`,wayland-protocols and GLES2; D-Bus suites also need PyGObject,`dbus-run-session` and `busctl`. Check each suite for extra dependencies.-App checks include [calculator](tests/calculator.py), [editor](tests/editor.py)-and [editor visuals](tests/editor_visuals.py).+App checks include [calculator](tests/calculator.py), [editor](tests/editor.py),+[editor visuals](tests/editor_visuals.py) and+[Files input methods](tests/files_ime.py).Application colors: `python3 tests/app_colors.py` checks snapshot exports andopt-in following with a private bus, scratch HOME/XDG directories, and realdiff --git a/src/files/AGENTS.md b/src/files/AGENTS.mdindex 5b1a370..f0cd9cb 100644--- a/src/files/AGENTS.md+++ b/src/files/AGENTS.md@@ -27,9 +27,12 @@ The window is `Client.zig` (Wayland globals, seat, buffers), re-exported by## Terminal drawer`app_terminal.zig` owns the per-window controller; `terminal/` owns libvterm,-the PTY, shell integration, cells and text-input-v3. Support and limits are in-`docs/files-terminal.md`; `zig build test-files-terminal` runs isolated PTY-and headless fixtures. The pinned library is compiled only into Files/tests.+the PTY, shell integration and cells. `ime.zig` is the text-input-v3 client for+both the drawer and the app's single-line fields (search, location bar, dialog+fields, chooser name); `app_terminal.zig` only owns the drawer's preedit.+Support and limits are in `docs/files-terminal.md`;+`zig build test-files-terminal` runs isolated PTY and headless fixtures. The+pinned library is compiled only into Files/tests.* Poll slots 19–21 are PTY, integration socket and pidfd. Parsing/writes have a64 KiB budget per loop; POLLOUT is enabled only with queued work. Hidden@@ -48,6 +51,18 @@ and headless fixtures. The pinned library is compiled only into Files/tests.separately so fallback shaping cannot move later cells. Preserve thecaller's Cairo damage clip. The test encoder drain exists only with FT_TEST.+## Text input++`ime.zig` is the text-input-v3 client for the terminal drawer and every+single-line field (`activeEditor`: search, location bar, dialog fields, chooser+name). It enables only while one is focused, advertises the text around the+selection and the caret rectangle, applies delete + commit to the active+`Editor`, and leaves preedit in `App.preedit`/`preedit_editor` for+`renderEditor` to draw. Re-enable and drop preedit when the target field+changes; a `done` applies only when its serial and the advertised field+(cursor, anchor, text revision) still match. Terminal commits go to the PTY+through `ft_key`, never through paste.+## File types and associations* **Types come from `src/mime_db.zig`, not GIO.** It reads shared-mime-infodiff --git a/src/files/Client.zig b/src/files/Client.zigindex ae600c6..f76d4ed 100644--- a/src/files/Client.zig+++ b/src/files/Client.zig@@ -109,7 +109,7 @@ xkb_context: ?*c.xkb_context = null,xkb_state: ?*c.xkb_state = null,key_repeat: key_repeat_mod.KeyRepeat = .{},compose: @import("ui").compose.Compose = .{},-ime: @import("terminal/ime.zig").Ime = undefined,+ime: @import("ime.zig").Ime = undefined,/// LC_CTYPE of the session; picks the Compose table (´+c is ç in pt_BR).locale: []const u8 = "",app: app_mod.App,diff --git a/src/files/app.zig b/src/files/app.zigindex c5ef6ee..1d40250 100644--- a/src/files/app.zig+++ b/src/files/app.zig@@ -258,6 +258,10 @@ pub const App = struct {location: Editor = .{},text_dragging: bool = false,edit_revision: usize = 0,+ /// Local composition text from the text-input-v3 client, drawn at the+ /// caret of `preedit_editor` until the input method commits it.+ preedit: std.ArrayList(u8) = .empty,+ preedit_editor: ?*Editor = null,text_paste_requested: bool = false,clipboard_text: std.ArrayList(u8) = .empty,clipboard_is_text: bool = false,@@ -390,6 +394,7 @@ pub const App = struct {if (self.status_notice) |sn| self.allocator.free(sn);if (self.snapshot) |snap| snap.destroy();+ self.preedit.deinit(self.allocator);self.search.deinit(self.allocator);self.clipboard_text.deinit(self.allocator);self.history.deinit();@@ -969,6 +974,7 @@ pub const App = struct {pub const fieldOptions = app_paint.fieldOptions;pub const textArea = app_paint.textArea;pub const editorTextArea = app_paint.editorTextArea;+ pub const editorCaretRect = app_paint.editorCaretRect;pub const pointerCursor = app_paint.pointerCursor;pub const singleClickIconAt = app_paint.singleClickIconAt;pub const renameCard = app_paint.renameCard;diff --git a/src/files/app_paint.zig b/src/files/app_paint.zigindex 7d9fb48..3332ca8 100644--- a/src/files/app_paint.zig+++ b/src/files/app_paint.zig@@ -386,10 +386,27 @@ pub fn placeCaret(self: *App, x: f64, extend: bool) void {edit.move(p, extend);}+/// The focused field's caret in app coordinates. text-input-v3 anchors the+/// input method's candidate window on this rectangle.+pub fn editorCaretRect(self: *App) ?header.Rect {+ const edit = self.activeEditor() orelse return null;+ const area = self.editorTextArea();+ const surf = c.cairo_image_surface_create(c.CAIRO_FORMAT_ARGB32, 1, 1) orelse return null;+ defer c.cairo_surface_destroy(surf);+ const cr = c.cairo_create(surf) orelse return null;+ defer c.cairo_destroy(cr);+ // Measure at the buffer scale, as renderEditor and placeCaret do.+ c.cairo_scale(cr, @floatFromInt(self.scale), @floatFromInt(self.scale));+ const metrics = fontMetrics(cr, fieldFontSize());+ const ink_h = metrics.ascent + metrics.descent;+ const pen = measureText(cr, edit.text.items[0..@min(edit.cursor, edit.text.items.len)], fieldFontSize(), false);+ return .{ .x = area.x - edit.scroll + pen, .y = area.y + (area.h - ink_h) / 2, .w = 2, .h = ink_h };+}+/// A whole text field: the shared frame (ui/widgets/field.zig), then the-/// editor's text, selection and caret in the theme's colours.+/// editor's text, selection, any input-method preedit and the caret in the+/// theme's colours.pub fn renderEditor(self: *App, cr: *c.cairo_t, edit: *Editor, rect: header.Rect, focused: bool, search: bool) void {- _ = self;if (shell_ui.Layer.begin(cr, .{ .x = @floatCast(rect.x), .y = @floatCast(rect.y), .w = @floatCast(rect.w), .h = @floatCast(rect.h) })) |begun| {var layer = begun;_ = ui_field.paintFrame(&layer.renderer, layer.local(), fieldOptions(search), .{ .focused = focused });@@ -403,11 +420,15 @@ pub fn renderEditor(self: *App, cr: *c.cairo_t, edit: *Editor, rect: header.Rectconst ink_h = metrics.ascent + metrics.descent;const top = area.y + (area.h - ink_h) / 2;const view_w = area.w;- const text_w = measureText(cr, text, fieldFontSize(), false);- const pen = measureText(cr, text[0..@min(edit.cursor, text.len)], fieldFontSize(), false);+ const preedit: []const u8 = if (focused and self.preedit_editor == edit) self.preedit.items else "";+ const caret = @min(edit.cursor, text.len);+ const pen = measureText(cr, text[0..caret], fieldFontSize(), false);+ const preedit_w = if (preedit.len > 0) measureText(cr, preedit, fieldFontSize(), false) else 0;+ const text_w = measureText(cr, text, fieldFontSize(), false) + preedit_w;if (focused) {const margin = @min(view_w / 4, 12);- if (pen - edit.scroll > view_w - margin) edit.scroll = pen - view_w + margin;+ const end = pen + preedit_w;+ if (end - edit.scroll > view_w - margin) edit.scroll = end - view_w + margin;if (pen - edit.scroll < margin) edit.scroll = pen - margin;edit.scroll = @round(std.math.clamp(edit.scroll, 0, @max(0, text_w - view_w + margin)));}@@ -423,10 +444,22 @@ pub fn renderEditor(self: *App, cr: *c.cairo_t, edit: *Editor, rect: header.Rectc.cairo_rectangle(cr, x + left, top, right - left, ink_h);c.cairo_fill(cr);}- const placeholder = search and text.len == 0;+ const placeholder = search and text.len == 0 and preedit.len == 0;// Half-strength white, not the shell's blue-grey `faint`.setSource(cr, if (placeholder) withAlpha(t.fg, 0.5) else t.fg);- drawText(cr, if (placeholder) tr("Search this folder") else text, x, top + metrics.ascent, fieldFontSize(), false);+ if (preedit.len == 0) {+ drawText(cr, if (placeholder) tr("Search this folder") else text, x, top + metrics.ascent, fieldFontSize(), false);+ } else {+ // Compose at the caret: the preedit is not part of the text yet, so+ // the suffix is drawn after it and the composition is underlined.+ drawText(cr, text[0..caret], x, top + metrics.ascent, fieldFontSize(), false);+ setSource(cr, t.accent);+ drawText(cr, preedit, x + pen, top + metrics.ascent, fieldFontSize(), false);+ c.cairo_rectangle(cr, x + pen, top + ink_h - 1, preedit_w, 1);+ c.cairo_fill(cr);+ setSource(cr, t.fg);+ drawText(cr, text[caret..], x + pen + preedit_w, top + metrics.ascent, fieldFontSize(), false);+ }if (focused) {setSource(cr, t.caretColor());c.cairo_rectangle(cr, x + pen, top, t.caret_width, ink_h);diff --git a/src/files/ime.zig b/src/files/ime.zignew file mode 100644index 0000000..ef75642--- /dev/null+++ b/src/files/ime.zig@@ -0,0 +1,304 @@+//! text-input-v3 for Files: the terminal drawer and the app's single-line+//! text fields (search, location bar, dialog fields and the chooser name).+//! Terminal commits go to the PTY and its preedit stays in the drawer; field+//! commits edit the active `Editor`, whose preedit is drawn at the caret+//! until the input method commits it.+const std = @import("std");+const wl = @import("wayland").client.wl;+const zwp = @import("wayland").client.zwp;+const app_mod = @import("app.zig");+const App = app_mod.App;+const Editor = @import("editor.zig").Editor;+const tc = @import("terminal/model.zig").c;++/// Where the current composition goes.+const Target = enum { none, terminal, editor };++pub const Ime = struct {+ app: *App,+ manager: ?*zwp.TextInputManagerV3 = null,+ input: ?*zwp.TextInputV3 = null,+ entered: bool = false,+ enabled: bool = false,+ serial: u32 = 0,+ revision: usize = 0,+ target: Target = .none,+ session: ?*tc.FT = null,+ editor: ?*Editor = null,+ cursor: usize = 0,+ anchor: usize = 0,+ before: usize = 0,+ after: usize = 0,+ method_change: bool = false,+ rectangle: [4]i32 = @splat(0),+ commit_text: std.ArrayList(u8) = .empty,+ preedit_text: std.ArrayList(u8) = .empty,+ has_commit: bool = false,+ has_preedit: bool = false,+ invalid: bool = false,+ // The last field state the cursor rectangle was measured from. Measuring+ // text needs a Cairo layout, so it runs only when one of these moves.+ field_scroll: f64 = 0,+ field_window: [2]i32 = .{ 0, 0 },+ field_sidebar: i32 = 0,+ field_view_y: i32 = 0,+ field_scale: i32 = 1,+ field_dialog: ?app_mod.DialogKind = null,++ pub fn setup(self: *Ime, seat: *wl.Seat) !void {+ if (self.manager) |manager| {+ self.input = try manager.getTextInput(seat);+ self.input.?.setListener(*Ime, event, self);+ }+ }+ pub fn deinit(self: *Ime) void {+ if (self.input) |input| input.destroy();+ if (self.manager) |manager| manager.destroy();+ self.commit_text.deinit(self.app.allocator);+ self.preedit_text.deinit(self.app.allocator);+ }+ fn clear(self: *Ime) void {+ self.commit_text.clearRetainingCapacity();+ self.preedit_text.clearRetainingCapacity();+ self.has_commit = false;+ self.has_preedit = false;+ self.invalid = false;+ self.before = 0;+ self.after = 0;+ }+ /// Drops local preedit from both the drawer and the app's fields.+ fn clearPreedit(self: *Ime) void {+ const app = self.app;+ if (app.preedit.items.len > 0 or app.preedit_editor != null) {+ app.preedit.clearRetainingCapacity();+ app.preedit_editor = null;+ app.invalidate();+ }+ if (app.terminal.preedit.items.len > 0) {+ app.terminal.preedit.clearRetainingCapacity();+ app.terminalDamage();+ }+ }+ /// The field that should receive composition right now.+ fn currentTarget(self: *Ime) Target {+ const app = self.app;+ if (app.menu != null) return .none;+ if (app.dialog != null) return if (app.activeEditor() != null) .editor else .none;+ if (app.focus == .terminal) return if (app.terminal.visible and app.terminal.session != null) .terminal else .none;+ return if (app.activeEditor() != null) .editor else .none;+ }+ fn event(_: *zwp.TextInputV3, ev: zwp.TextInputV3.Event, self: *Ime) void {+ switch (ev) {+ .enter => self.entered = true,+ .leave => {+ self.entered = false;+ self.enabled = false;+ self.clear();+ self.clearPreedit();+ self.app.invalidate();+ },+ .preedit_string => |e| {+ self.preedit_text.clearRetainingCapacity();+ self.has_preedit = true;+ if (e.text) |s| {+ const bytes = std.mem.span(s);+ if (bytes.len <= 4096 and std.unicode.utf8ValidateSlice(bytes)) self.preedit_text.appendSlice(self.app.allocator, bytes) catch {} else self.invalid = true;+ }+ },+ .commit_string => |e| {+ self.commit_text.clearRetainingCapacity();+ self.has_commit = true;+ if (e.text) |s| {+ const bytes = std.mem.span(s);+ if (bytes.len <= 4096 and std.unicode.utf8ValidateSlice(bytes)) self.commit_text.appendSlice(self.app.allocator, bytes) catch {} else self.invalid = true;+ }+ },+ .delete_surrounding_text => |e| {+ self.before = e.before_length;+ self.after = e.after_length;+ },+ .done => |e| {+ defer self.clear();+ if (self.invalid or e.serial != self.serial or !self.enabled) return;+ if (self.target == .terminal) self.applyTerminal();+ if (self.target == .editor) self.applyEditor();+ },+ }+ }+ fn applyTerminal(self: *Ime) void {+ const app = self.app;+ if (self.before != 0 or self.after != 0 or app.dialog != null or app.menu != null or+ app.focus != .terminal or !app.terminal.visible or+ self.session != app.terminal.session or self.revision != app.edit_revision) return;+ if (self.commit_text.items.len > 0) {+ // An IME commit is typed text, never paste or shell syntax.+ if (self.session) |session| tc.ft_key(session, 0, self.commit_text.items.ptr, self.commit_text.items.len, 0);+ }+ app.terminal.preedit.clearRetainingCapacity();+ if (self.has_preedit) app.terminal.preedit.appendSlice(app.allocator, self.preedit_text.items) catch {};+ app.terminalDamage();+ }+ fn applyEditor(self: *Ime) void {+ const app = self.app;+ const edit = app.activeEditor() orelse return;+ // Another field took focus, or the app changed the text after the+ // surrounding state this commit answers.+ const dialog_kind: ?app_mod.DialogKind = if (app.dialog) |*dlg| dlg.kind else null;+ if (edit != self.editor or dialog_kind != self.field_dialog or app.menu != null or+ self.revision != app.edit_revision or edit.cursor != self.cursor or edit.anchor != self.anchor) return;+ if (self.before > 0 or self.after > 0) {+ const text = edit.text.items;+ const selected = edit.selection();+ if (self.before > selected[0] or self.after > text.len - selected[1]) return;+ const start = selected[0] - self.before;+ const end = selected[1] + self.after;+ if ((start < text.len and text[start] & 0xc0 == 0x80) or (end < text.len and text[end] & 0xc0 == 0x80)) return;+ edit.select_all = false;+ edit.anchor = start;+ edit.cursor = end;+ }+ const insert = self.has_commit or self.before > 0 or self.after > 0 or+ (self.has_preedit and self.preedit_text.items.len > 0 and edit.cursor != edit.anchor);+ if (insert) {+ edit.insert(app.allocator, self.commit_text.items) catch {+ app.preedit.clearRetainingCapacity();+ app.preedit_editor = null;+ app.invalidate();+ return;+ };+ app.edit_revision += 1;+ self.method_change = true;+ if (app.focus == .filename) app.overwrite_pending = false;+ if (app.dialog == null and app.focus == .search) app.rebuildView();+ }+ app.preedit.clearRetainingCapacity();+ if (self.has_preedit and self.preedit_text.items.len > 0) {+ app.preedit.appendSlice(app.allocator, self.preedit_text.items) catch {};+ app.preedit_editor = edit;+ } else app.preedit_editor = null;+ app.invalidate();+ }+ /// The active field's caret rectangle in surface coordinates.+ fn fieldRectangle(self: *Ime, titlebar: i32) ?[4]i32 {+ const caret = self.app.editorCaretRect() orelse return null;+ return .{+ @intFromFloat(caret.x),+ @as(i32, @intFromFloat(caret.y)) + titlebar,+ @intFromFloat(@max(1, caret.w)),+ @intFromFloat(@max(1, caret.h)),+ };+ }+ pub fn sync(self: *Ime, titlebar: i32) void {+ const input = self.input orelse return;+ // enable/disable belong to the surface obtained from enter.+ const target: Target = if (self.entered) self.currentTarget() else .none;+ if (target == .none) {+ if (self.enabled) {+ input.disable();+ input.commit();+ self.serial +%= 1;+ }+ self.enabled = false;+ self.target = .none;+ self.session = null;+ self.editor = null;+ self.clear();+ self.clearPreedit();+ return;+ }+ if (target == .terminal) {+ const session = self.app.terminal.session orelse return;+ var row: c_int = 0;+ var col: c_int = 0;+ var shape: c_int = 0;+ _ = tc.ft_cursor(session, &row, &col, &shape);+ const body = self.app.terminalBody();+ const rect: [4]i32 = .{+ @intFromFloat(body.x + @as(f64, @floatFromInt(col)) * self.app.terminal.cell_w),+ @as(i32, @intFromFloat(body.y + @as(f64, @floatFromInt(row)) * self.app.terminal.cell_h)) + titlebar,+ @intFromFloat(self.app.terminal.cell_w),+ @intFromFloat(self.app.terminal.cell_h),+ };+ if (self.enabled and self.target == .terminal and self.session == session and+ self.revision == self.app.edit_revision and std.meta.eql(rect, self.rectangle)) return;+ if (!self.enabled or self.target != .terminal or self.session != session) {+ input.enable();+ self.clear();+ self.clearPreedit();+ }+ self.enabled = true;+ self.target = .terminal;+ self.session = session;+ self.editor = null;+ self.revision = self.app.edit_revision;+ self.rectangle = rect;+ input.setSurroundingText("", 0, 0);+ input.setContentType(.{ .multiline = true }, .terminal);+ } else {+ const edit = self.app.activeEditor() orelse return;+ const dialog_kind: ?app_mod.DialogKind = if (self.app.dialog) |*dlg| dlg.kind else null;+ const same = self.enabled and self.target == .editor and self.editor == edit and+ self.field_dialog == dialog_kind and+ self.revision == self.app.edit_revision and self.cursor == edit.cursor and+ self.anchor == edit.anchor and self.field_scroll == edit.scroll and+ self.field_window[0] == self.app.w and self.field_window[1] == self.app.h and+ self.field_sidebar == self.app.sidebarWidth() and self.field_view_y == self.app.scroll_y and+ self.field_scale == self.app.scale;+ if (same) return;+ const rect = self.fieldRectangle(titlebar) orelse return;+ if (!self.enabled or self.target != .editor or self.editor != edit or self.field_dialog != dialog_kind) {+ input.enable();+ self.clear();+ self.clearPreedit();+ }+ self.enabled = true;+ self.target = .editor;+ self.session = null;+ self.editor = edit;+ self.field_dialog = dialog_kind;+ self.revision = self.app.edit_revision;+ self.cursor = edit.cursor;+ self.anchor = edit.anchor;+ self.field_scroll = edit.scroll;+ self.field_window = .{ self.app.w, self.app.h };+ self.field_sidebar = self.app.sidebarWidth();+ self.field_view_y = self.app.scroll_y;+ self.field_scale = self.app.scale;+ self.rectangle = rect;+ setEditorSurrounding(input, edit);+ input.setContentType(.{}, .normal);+ }+ input.setTextChangeCause(if (self.method_change) .input_method else .other);+ self.method_change = false;+ input.setCursorRectangle(self.rectangle[0], self.rectangle[1], @max(1, self.rectangle[2]), @max(1, self.rectangle[3]));+ input.commit();+ self.serial +%= 1;+ }+};++/// Advertises the field's text around the selection. Indices are byte+/// offsets and must sit on code point boundaries; text-input-v3 messages are+/// bounded, so a long value is windowed like the Editor app's.+fn setEditorSurrounding(input: *zwp.TextInputV3, edit: *Editor) void {+ const text = edit.text.items;+ const selected = edit.selection();+ var cursor = edit.cursor;+ var anchor = edit.anchor;+ if (edit.select_all) {+ cursor = text.len;+ anchor = 0;+ }+ if (selected[1] - selected[0] > 3800) {+ // Re-enabling drops the previously advertised surrounding text.+ input.enable();+ return;+ }+ const spare = (3800 - (selected[1] - selected[0])) / 2;+ var start = selected[0] -| spare;+ while (start < text.len and text[start] & 0xc0 == 0x80) start += 1;+ var end = @min(text.len, start + 3800);+ while (end < text.len and text[end] & 0xc0 == 0x80) end -= 1;+ var surrounding: [4000:0]u8 = @splat(0);+ @memcpy(surrounding[0 .. end - start], text[start..end]);+ input.setSurroundingText(&surrounding, @intCast(cursor - start), @intCast(anchor - start));+}diff --git a/src/files/terminal/ime.zig b/src/files/terminal/ime.zigdeleted file mode 100644index 304cbfa..0000000--- a/src/files/terminal/ime.zig+++ /dev/null@@ -1,118 +0,0 @@-//! text-input-v3 for terminal input. Terminal output is never surrounding-//! editable text: commits go to the PTY and preedit stays local until done.-const std = @import("std");-const wl = @import("wayland").client.wl;-const zwp = @import("wayland").client.zwp;-const App = @import("../app.zig").App;-const tc = @import("model.zig").c;-pub const Ime = struct {- app: *App,- manager: ?*zwp.TextInputManagerV3 = null,- input: ?*zwp.TextInputV3 = null,- entered: bool = false,- enabled: bool = false,- serial: u32 = 0,- revision: usize = 0,- session: ?*tc.FT = null,- rectangle: [4]i32 = @splat(0),- commit_text: std.ArrayList(u8) = .empty,- preedit_text: std.ArrayList(u8) = .empty,- has_preedit: bool = false,- invalid: bool = false,-- pub fn setup(self: *Ime, seat: *wl.Seat) !void {- if (self.manager) |manager| {- self.input = try manager.getTextInput(seat);- self.input.?.setListener(*Ime, event, self);- }- }- pub fn deinit(self: *Ime) void {- if (self.input) |input| input.destroy();- if (self.manager) |manager| manager.destroy();- self.commit_text.deinit(self.app.allocator);- self.preedit_text.deinit(self.app.allocator);- }- fn clear(self: *Ime) void {- self.commit_text.clearRetainingCapacity();- self.preedit_text.clearRetainingCapacity();- self.has_preedit = false;- self.invalid = false;- }- fn event(_: *zwp.TextInputV3, ev: zwp.TextInputV3.Event, self: *Ime) void {- switch (ev) {- .enter => self.entered = true,- .leave => {- self.entered = false;- self.enabled = false;- self.clear();- self.app.terminal.preedit.clearRetainingCapacity();- self.app.terminalDamage();- },- .preedit_string => |e| {- self.preedit_text.clearRetainingCapacity();- self.has_preedit = true;- if (e.text) |s| {- const bytes = std.mem.span(s);- if (bytes.len <= 4096 and std.unicode.utf8ValidateSlice(bytes)) self.preedit_text.appendSlice(self.app.allocator, bytes) catch {} else self.invalid = true;- }- },- .commit_string => |e| {- if (e.text) |s| {- const bytes = std.mem.span(s);- if (bytes.len + self.commit_text.items.len <= 4096 and std.unicode.utf8ValidateSlice(bytes)) self.commit_text.appendSlice(self.app.allocator, bytes) catch {} else self.invalid = true;- }- },- .delete_surrounding_text => |e| {- if (e.before_length != 0 or e.after_length != 0) self.invalid = true;- },- .done => |e| {- defer self.clear();- if (self.invalid or e.serial != self.serial or !self.enabled or self.app.dialog != null or self.app.menu != null or self.app.focus != .terminal or !self.app.terminal.visible or self.session != self.app.terminal.session or self.revision != self.app.edit_revision) return;- if (self.commit_text.items.len > 0) {- // An IME commit is typed text, never paste or shell syntax.- if (self.session) |session| tc.ft_key(session, 0, self.commit_text.items.ptr, self.commit_text.items.len, 0);- }- self.app.terminal.preedit.clearRetainingCapacity();- if (self.has_preedit) self.app.terminal.preedit.appendSlice(self.app.allocator, self.preedit_text.items) catch {};- self.app.terminalDamage();- },- }- }- pub fn sync(self: *Ime, titlebar: i32) void {- const input = self.input orelse return;- const enabled = self.entered and self.app.focus == .terminal and self.app.terminal.visible and self.app.dialog == null and self.app.menu == null and self.app.terminal.session != null;- if (!enabled) {- if (self.enabled) {- input.disable();- input.commit();- self.serial +%= 1;- self.clear();- self.app.terminal.preedit.clearRetainingCapacity();- self.app.terminalDamage();- }- self.enabled = false;- return;- }- const session = self.app.terminal.session.?;- var row: c_int = 0;- var col: c_int = 0;- var shape: c_int = 0;- _ = tc.ft_cursor(session, &row, &col, &shape);- const body = self.app.terminalBody();- const rect: [4]i32 = .{ @intFromFloat(body.x + @as(f64, @floatFromInt(col)) * self.app.terminal.cell_w), @as(i32, @intFromFloat(body.y + @as(f64, @floatFromInt(row)) * self.app.terminal.cell_h)) + titlebar, @intFromFloat(self.app.terminal.cell_w), @intFromFloat(self.app.terminal.cell_h) };- if (self.enabled and self.session == session and self.revision == self.app.edit_revision and std.meta.eql(rect, self.rectangle)) return;- if (!self.enabled or self.session != session) {- input.enable();- self.clear();- }- self.enabled = true;- self.revision = self.app.edit_revision;- self.session = session;- self.rectangle = rect;- input.setSurroundingText("", 0, 0);- input.setContentType(.{ .multiline = true }, .terminal);- input.setCursorRectangle(rect[0], rect[1], @max(1, rect[2]), @max(1, rect[3]));- input.commit();- self.serial +%= 1;- }-};diff --git a/tests/files_ime.py b/tests/files_ime.pynew file mode 100644index 0000000..6ba81f8--- /dev/null+++ b/tests/files_ime.py@@ -0,0 +1,168 @@+#!/usr/bin/env python3+"""text-input-v3 (what fcitx5 speaks) in Files' own single-line fields.++The terminal drawer had an input method; search, the location bar, dialog+fields and the chooser name must compose too. Drives a real protocol peer+against a private headless compositor and checks the filesystem after each+commit.+"""+import os+from pathlib import Path+import subprocess+import tempfile+import time++from ipc_client import IPCClient, ROOT, spawn_compositor, stop_process+from files_browser import wait_for+++def run():+ os.umask(0o077)+ with tempfile.TemporaryDirectory(prefix="rediwm-files-ime-") as directory:+ tmp = Path(directory)+ home = tmp / "Home"+ docs = home / "Documents" / "文档"+ docs.mkdir(parents=True)+ (docs / "中文.txt").write_text("中文内容")+ (home / "alpha.txt").write_text("alpha")++ from input_protocols import compile_client+ compile_client(tmp)++ compositor, _ = spawn_compositor(+ tmp, scale=os.environ.get("REDIWM_TEST_SCALE", "1"),+ config_content="[compositor]\nxwayland = false\n")+ clients = []+ try:+ sock = wait_for(lambda: next(tmp.glob("rediwm-*.sock"), None), "IPC unavailable")+ display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))+ env = dict(os.environ, HOME=str(home), XDG_RUNTIME_DIR=str(tmp),+ XDG_CONFIG_HOME=str(tmp / "config"), XDG_DATA_HOME=str(tmp / "data"),+ XDG_CACHE_HOME=str(tmp / "cache"), XDG_STATE_HOME=str(tmp / "state"),+ REDIWM_FILES_DEVICES="0", DBUS_SESSION_BUS_ADDRESS="",+ WAYLAND_DISPLAY=display)+ env.pop("REDIWM_SOCKET", None)++ ime_log = tmp / "ime.log"+ with ime_log.open("w") as log:+ ime = subprocess.Popen([str(tmp / "protocol-client"), "ime"], env=env,+ stdin=subprocess.PIPE, stdout=log, stderr=log, text=True)+ clients.append(ime)+ wait_for(lambda: "ready" in ime_log.read_text(), "IME peer did not start")++ def ime_text():+ return ime_log.read_text()++ def ime_send(command):+ previous = ime_text().count("ack " + command)+ ime.stdin.write(command + "\n")+ ime.stdin.flush()+ wait_for(lambda: ime_text().count("ack " + command) > previous,+ "IME " + command.split(" ", 1)[0])++ def ime_surrounds():+ return ime_text().count("surround ")++ def wait_surround(text):+ wait_for(lambda: ("surround " + text) in ime_text(),+ "IME was not told about " + text)++ ime_send("method")++ files_log = (tmp / "rediwm-files.log").open("w")+ files = subprocess.Popen([str(ROOT / "zig-out/bin/rediwm-files"), str(home)],+ env=env, stdout=files_log, stderr=files_log)+ files_log.close()+ clients.append(files)++ with IPCClient(sock) as ipc:+ def window():+ return next((w for w in ipc.get_windows() if w["app_id"] == "rediwm-files"), None)++ def title(value):+ wait_for(lambda: (w := window()) and w["title"] == value + " — RediWM Files",+ "window did not show " + value)++ def key(code, ctrl=False):+ if ctrl:+ ipc.key(29, True)+ ipc.key_down_up(code)+ if ctrl:+ ipc.key(29, False)+ time.sleep(.15)++ win = wait_for(window, "Files did not map")+ ipc.focus_window(win["id"])+ time.sleep(.3)+ assert window()["is_focused"]++ # Location bar: composition replaces the selected path, the+ # committed UTF-8 path navigates, and the IM gets the new+ # surrounding text back.+ before = ime_surrounds()+ key(38, ctrl=True) # Ctrl+L+ wait_for(lambda: ime_surrounds() > before, "location bar was not advertised to the IME")+ assert "activate\n" in ime_text(), "Files did not enable text input"+ ime_send("preedit-text 拼") # Local composition, not field text.+ time.sleep(.2)+ ime_send("commit-text " + str(docs))+ wait_surround(str(docs))+ key(28)+ title("文档")++ # Search box: the committed query must filter, so F2 below+ # renames the only match, 中文.txt.+ before = ime_surrounds()+ key(33, ctrl=True) # Ctrl+F+ wait_for(lambda: ime_surrounds() > before, "search box was not advertised to the IME")+ ime_send("preedit-text 中")+ time.sleep(.2)+ ime_send("commit-text 中文")+ wait_surround("中文")+ key(28) # Leave the search field; the match is selected.+ time.sleep(.3)++ # Rename dialog: the selected stem is replaced by composed text.+ before = ime_surrounds()+ key(60) # F2+ wait_for(lambda: ime_surrounds() > before, "rename field was not advertised to the IME")+ wait_surround("中文.txt")+ ime_send("preedit-text 新") # Replacing the selected stem drops it first.+ time.sleep(.2)+ ime_send("commit-text 中文文件")+ wait_surround("中文文件.txt")+ key(28)+ wait_for(lambda: (docs / "中文文件.txt").exists(), "IME rename did not apply")+ assert not (docs / "中文.txt").exists()+ print("PASS: text-input-v3 composition in the location bar, search box and rename dialog")++ # The terminal drawer keeps its own composition path: the+ # commit is typed into the PTY, not pasted or shell syntax.+ before = ime_surrounds()+ key(62) # F4 opens the drawer.+ wait_for(lambda: ime_surrounds() > before,+ "terminal drawer was not advertised to the IME")+ time.sleep(1) # Let the shell reach its prompt.+ scratch = home / "terminal-中文"+ ime_send("commit-text touch " + str(scratch))+ time.sleep(.2)+ key(28) # Enter runs the committed command.+ wait_for(scratch.exists, "terminal IME commit did not reach the shell")+ print("PASS: the Files terminal still types IME commits into the PTY")++ if output := os.environ.get("REDIWM_FILES_IME_SCREENSHOT"):+ ipc.action("screenshot", {"path": output})+ assert files.poll() is None, "Files exited"+ except Exception:+ for path in (tmp / "ime.log", tmp / "rediwm-files.log", tmp / "compositor.log"):+ if path.exists():+ print(path.name + ":\n" + path.read_text()[-4000:])+ raise+ finally:+ for process in reversed(clients):+ stop_process(process)+ stop_process(compositor)+++if __name__ == "__main__":+ run()diff --git a/tests/input_protocol_client.c b/tests/input_protocol_client.cindex 1238191..5e0cc1c 100644--- a/tests/input_protocol_client.c+++ b/tests/input_protocol_client.c@@ -191,6 +191,12 @@ static void command(char *line) {} else if(!strcmp(line,"commit-only")) {zwp_input_method_v2_commit_string(method,"final");zwp_input_method_v2_commit(method,done_serial);+ } else if(!strncmp(line,"preedit-text ",13)) {+ zwp_input_method_v2_set_preedit_string(method,line+13,0,(uint32_t)strlen(line+13));+ zwp_input_method_v2_commit(method,done_serial);+ } else if(!strncmp(line,"commit-text ",12)) {+ zwp_input_method_v2_commit_string(method,line+12);+ zwp_input_method_v2_commit(method,done_serial);} else if(!strcmp(line,"grab")) {virtual_keyboard=zwp_virtual_keyboard_manager_v1_create_virtual_keyboard(virtual_manager,seat);grab=zwp_input_method_v2_grab_keyboard(method);