Skip to content

armgit / muxin

Public Imported from GitHub
0

All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.

Handle IME composition in embedded terminals (#5)

Leon Zhang08f561150513
diff --git a/src/ui/terminal/ime.rs b/src/ui/terminal/ime.rs
new file mode 100644
index 0000000..4f779e6
--- /dev/null
+++ b/src/ui/terminal/ime.rs
@@ -0,0 +1,216 @@
+//! The terminal's input-method buffer. Preedit stays local; only committed
+//! text goes to the program, which owns editing the terminal's actual contents.
+
+use std::ops::Range;
+
+use gpui::{App, Bounds, Context, ElementInputHandler, EntityInputHandler, InputHandler, Pixels, Point, UTF16Selection, Window};
+
+use super::{Metrics, TerminalView, render};
+
+#[derive(Clone, Default)]
+pub(super) struct Composition {
+ pub text: String,
+ /// UTF-8 byte offsets, always on character boundaries.
+ pub selected: Range<usize>,
+}
+
+impl Composition {
+ pub fn clear(&mut self) {
+ self.text.clear();
+ self.selected = 0..0;
+ }
+
+ pub fn range_from_utf16(&self, range: Range<usize>) -> Range<usize> {
+ byte_range(&self.text, range)
+ }
+
+ pub fn range_to_utf16(&self, range: Range<usize>) -> Range<usize> {
+ self.text[..range.start].encode_utf16().count()..self.text[..range.end].encode_utf16().count()
+ }
+
+ pub fn update(&mut self, range: Option<Range<usize>>, text: &str, selected: Option<Range<usize>>) {
+ let range = range.map(|r| self.range_from_utf16(r)).unwrap_or(0..self.text.len());
+ // The selected range is relative to the newly inserted text, not the
+ // old buffer (whose UTF-16/UTF-8 lengths can be entirely different).
+ let selected = selected.map(|r| byte_range(text, r)).unwrap_or(text.len()..text.len());
+ self.text.replace_range(range.clone(), text);
+ self.selected = range.start + selected.start..range.start + selected.end;
+ }
+}
+
+/// Clamp platform ranges to valid UTF-8 boundaries, including a range inside
+/// a surrogate pair or a stale/out-of-bounds range from an input method.
+fn byte_range(text: &str, range: Range<usize>) -> Range<usize> {
+ let offset = |target| {
+ let mut utf16 = 0;
+ for (byte, ch) in text.char_indices() {
+ utf16 += ch.len_utf16();
+ if utf16 > target {
+ return byte;
+ }
+ }
+ text.len()
+ };
+ let start = offset(range.start);
+ start..offset(range.end).max(start)
+}
+
+/// Keep terminal key repeat instead of macOS's press-and-hold accent picker.
+pub(super) struct TerminalInputHandler(pub ElementInputHandler<TerminalView>);
+
+impl InputHandler for TerminalInputHandler {
+ fn selected_text_range(&mut self, ignore_disabled_input: bool, window: &mut Window, cx: &mut App) -> Option<UTF16Selection> {
+ self.0.selected_text_range(ignore_disabled_input, window, cx)
+ }
+
+ fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>> {
+ self.0.marked_text_range(window, cx)
+ }
+
+ fn text_for_range(&mut self, range: Range<usize>, adjusted_range: &mut Option<Range<usize>>, window: &mut Window, cx: &mut App) -> Option<String> {
+ self.0.text_for_range(range, adjusted_range, window, cx)
+ }
+
+ fn replace_text_in_range(&mut self, range: Option<Range<usize>>, text: &str, window: &mut Window, cx: &mut App) {
+ self.0.replace_text_in_range(range, text, window, cx);
+ }
+
+ fn replace_and_mark_text_in_range(
+ &mut self,
+ range: Option<Range<usize>>,
+ text: &str,
+ selected: Option<Range<usize>>,
+ window: &mut Window,
+ cx: &mut App,
+ ) {
+ self.0.replace_and_mark_text_in_range(range, text, selected, window, cx);
+ }
+
+ fn unmark_text(&mut self, window: &mut Window, cx: &mut App) {
+ self.0.unmark_text(window, cx);
+ }
+
+ fn bounds_for_range(&mut self, range: Range<usize>, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
+ self.0.bounds_for_range(range, window, cx)
+ }
+
+ fn character_index_for_point(&mut self, point: Point<Pixels>, window: &mut Window, cx: &mut App) -> Option<usize> {
+ self.0.character_index_for_point(point, window, cx)
+ }
+
+ fn apple_press_and_hold_enabled(&mut self) -> bool {
+ false
+ }
+}
+
+impl EntityInputHandler for TerminalView {
+ fn text_for_range(
+ &mut self,
+ range: Range<usize>,
+ adjusted_range: &mut Option<Range<usize>>,
+ _: &mut Window,
+ _: &mut Context<Self>,
+ ) -> Option<String> {
+ let range = self.ime.range_from_utf16(range);
+ *adjusted_range = Some(self.ime.range_to_utf16(range.clone()));
+ Some(self.ime.text[range].to_string())
+ }
+
+ fn selected_text_range(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) -> Option<UTF16Selection> {
+ (!self.exited).then(|| UTF16Selection { range: self.ime.range_to_utf16(self.ime.selected.clone()), reversed: false })
+ }
+
+ fn marked_text_range(&self, _: &mut Window, _: &mut Context<Self>) -> Option<Range<usize>> {
+ (!self.ime.text.is_empty()).then(|| 0..self.ime.text.encode_utf16().count())
+ }
+
+ fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
+ self.ime.clear();
+ cx.notify();
+ }
+
+ fn replace_text_in_range(&mut self, _: Option<Range<usize>>, text: &str, _: &mut Window, cx: &mut Context<Self>) {
+ // The range belongs to our local preedit, never to the PTY's screen.
+ // Inserting text is ordinary typing, not a bracketed clipboard paste.
+ self.ime.clear();
+ self.write_input(text.as_bytes().to_vec(), cx);
+ cx.notify();
+ }
+
+ fn replace_and_mark_text_in_range(
+ &mut self,
+ range: Option<Range<usize>>,
+ text: &str,
+ selected: Option<Range<usize>>,
+ _: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if !self.exited {
+ self.ime.update(range, text, selected);
+ self.prepare_input(cx);
+ }
+ }
+
+ fn bounds_for_range(&mut self, range: Range<usize>, _: Bounds<Pixels>, window: &mut Window, cx: &mut Context<Self>) -> Option<Bounds<Pixels>> {
+ let layout = render::input_layout(&self.shared, &self.ime, Metrics::current(cx), window, cx);
+ Some(layout.bounds_for_range(self.ime.range_from_utf16(range)))
+ }
+
+ fn character_index_for_point(&mut self, point: Point<Pixels>, window: &mut Window, cx: &mut Context<Self>) -> Option<usize> {
+ let layout = render::input_layout(&self.shared, &self.ime, Metrics::current(cx), window, cx);
+ let byte = layout.line.index_for_x(point.x - layout.origin.x)?;
+ Some(self.ime.range_to_utf16(byte..byte).start)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn pinyin_preedit_is_replaced_until_commit() {
+ let mut ime = Composition::default();
+ ime.update(None, "n", Some(1..1));
+ ime.update(None, "ni", Some(2..2));
+ ime.update(None, "你", Some(1..1));
+ assert_eq!(ime.text, "你");
+ assert_eq!(ime.selected, 3..3);
+ assert_eq!(ime.range_to_utf16(ime.selected.clone()), 1..1);
+ ime.clear();
+ assert!(ime.text.is_empty());
+ assert_eq!(ime.selected, 0..0);
+ }
+
+ #[test]
+ fn selection_is_relative_to_replacement_even_after_multibyte_text() {
+ let mut ime = Composition::default();
+ ime.update(None, "你hao", None);
+ ime.update(Some(1..4), "好😀", Some(1..3));
+ assert_eq!(ime.text, "你好😀");
+ assert_eq!(&ime.text[ime.selected.clone()], "😀");
+ assert_eq!(ime.range_to_utf16(ime.selected.clone()), 2..4);
+ }
+
+ #[test]
+ #[allow(clippy::reversed_empty_ranges)] // Deliberately exercise an invalid IME range.
+ fn input_method_ranges_never_split_utf8_or_panic() {
+ let ime = Composition { text: "a😀中".into(), selected: 0..0 };
+ assert_eq!(&ime.text[ime.range_from_utf16(1..3)], "😀");
+ assert_eq!(&ime.text[ime.range_from_utf16(3..4)], "中");
+ assert_eq!(ime.range_from_utf16(2..2), 1..1);
+ assert_eq!(ime.range_from_utf16(usize::MAX..usize::MAX), 8..8);
+ assert_eq!(ime.range_from_utf16(4..0), 8..8);
+ }
+
+ #[test]
+ fn deleting_or_cancelling_preedit_leaves_no_stale_selection() {
+ let mut ime = Composition::default();
+ ime.update(None, "中文", Some(0..2));
+ ime.update(None, "", Some(usize::MAX..usize::MAX));
+ assert!(ime.text.is_empty());
+ assert_eq!(ime.selected, 0..0);
+ ime.update(None, "again", None);
+ ime.clear();
+ assert_eq!(ime.range_to_utf16(ime.selected.clone()), 0..0);
+ }
+}
diff --git a/src/ui/terminal/keys.rs b/src/ui/terminal/keys.rs
index c1e90b2..ce89598 100644
--- a/src/ui/terminal/keys.rs
+++ b/src/ui/terminal/keys.rs
@@ -5,6 +5,15 @@
use alacritty_terminal::term::TermMode;
use gpui::Keystroke;
+/// Printable keys belong to the platform input method. Terminal escape
+/// sequences and Control/Meta shortcuts continue through `to_bytes`.
+pub fn is_text_input(ks: &Keystroke) -> bool {
+ let m = &ks.modifiers;
+ !m.platform && !m.control && !m.alt && !m.function
+ && (ks.key == "space" || ks.key.chars().count() == 1
+ || ks.key_char.as_ref().is_some_and(|text| !text.is_empty() && !text.chars().any(char::is_control)))
+}
+
pub fn to_bytes(ks: &Keystroke, mode: TermMode) -> Option<Vec<u8>> {
let m = &ks.modifiers;
if m.platform {
@@ -132,4 +141,39 @@ mod tests {
assert!(to_bytes(&ks("cmd-c"), none).is_none());
assert_eq!(paste("a\nb", TermMode::BRACKETED_PASTE), b"\x1b[200~a\rb\x1b[201~");
}
+
+ #[test]
+ fn text_goes_to_ime_but_terminal_controls_do_not() {
+ for key in ["a", "shift-a", "1", "/", "space", "shift-space"] {
+ assert!(is_text_input(&ks(key)), "{key}");
+ }
+ for key in ["enter", "shift-enter", "backspace", "escape", "tab", "up", "ctrl-c", "ctrl-space", "alt-b", "cmd-v"] {
+ assert!(!is_text_input(&ks(key)), "{key}");
+ }
+ // macOS supplies key_char for these named keys as well. In
+ // particular Shift+Enter must keep its terminal escape sequence.
+ for (key, text) in [("enter", "\n"), ("shift-enter", "\n"), ("tab", "\t")] {
+ let mut stroke = ks(key);
+ stroke.key_char = Some(text.into());
+ assert!(!is_text_input(&stroke), "{key}");
+ }
+ }
+
+ #[test]
+ fn function_modified_letters_keep_the_terminal_path() {
+ for key in ["a", "j"] {
+ let mut stroke = ks(&format!("fn-{key}"));
+ for text in [None, Some(key.to_string())] {
+ stroke.key_char = text;
+ assert!(!is_text_input(&stroke), "fn-{key}");
+ assert_eq!(to_bytes(&stroke, TermMode::empty()).unwrap(), key.as_bytes());
+ }
+ }
+ }
+
+ #[test]
+ fn chinese_paste_preserves_utf8_and_bracketed_paste_mode() {
+ assert_eq!(paste("你好😀", TermMode::empty()), "你好😀".as_bytes());
+ assert_eq!(paste("你好\n世界", TermMode::BRACKETED_PASTE), "\x1b[200~你好\r世界\x1b[201~".as_bytes());
+ }
}
diff --git a/src/ui/terminal/mod.rs b/src/ui/terminal/mod.rs
index f596f89..d5ec8c6 100644
--- a/src/ui/terminal/mod.rs
+++ b/src/ui/terminal/mod.rs
@@ -5,6 +5,7 @@
mod boxdraw;
mod colors;
+mod ime;
mod keys;
mod render;
@@ -211,6 +212,7 @@ pub struct TerminalView {
/// The blinking cursor's phase, and the last key press (which shows it).
cursor_on: bool,
typed_at: Instant,
+ ime: ime::Composition,
_tasks: Vec<Task<()>>,
_subscriptions: Vec<gpui::Subscription>,
}
@@ -357,6 +359,7 @@ impl TerminalView {
scroll_rest: 0.,
cursor_on: true,
typed_at: Instant::now(),
+ ime: ime::Composition::default(),
_tasks: vec![events, blink],
_subscriptions: subscriptions,
}
@@ -413,6 +416,9 @@ impl TerminalView {
}
fn report_focus(&mut self, focused: bool, cx: &mut Context<Self>) {
+ if !focused {
+ self.ime.clear();
+ }
if self.mode().contains(TermMode::FOCUS_IN_OUT) {
self.shared.write(if focused { b"\x1b[I".as_slice() } else { b"\x1b[O".as_slice() });
}
@@ -422,6 +428,25 @@ impl TerminalView {
// -----------------------------------------------------------------------
// Keyboard
+ fn prepare_input(&mut self, cx: &mut Context<Self>) {
+ self.typed_at = Instant::now();
+ self.cursor_on = true;
+ let mut term = self.shared.term.lock();
+ term.scroll_display(Scroll::Bottom);
+ term.selection = None;
+ drop(term);
+ cx.notify();
+ }
+
+ fn write_input(&mut self, bytes: Vec<u8>, cx: &mut Context<Self>) {
+ if self.exited || bytes.is_empty() {
+ return;
+ }
+ self.ime.clear();
+ self.prepare_input(cx);
+ self.shared.write(bytes);
+ }
+
fn key_down(&mut self, e: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
self.typed_at = Instant::now();
if !self.cursor_on {
@@ -443,14 +468,13 @@ impl TerminalView {
if self.exited {
return;
}
+ // Let the platform input method compose/commit printable text. Raw
+ // key bytes here would swallow the first pinyin key or send it twice.
+ if keys::is_text_input(ks) {
+ return;
+ }
if let Some(bytes) = keys::to_bytes(ks, self.mode()) {
- // Typing goes back to the live screen and drops any local selection.
- {
- let mut term = self.shared.term.lock();
- term.scroll_display(Scroll::Bottom);
- term.selection = None;
- }
- self.shared.write(bytes);
+ self.write_input(bytes, cx);
cx.stop_propagation();
cx.notify();
}
@@ -470,7 +494,7 @@ impl TerminalView {
fn paste(&mut self, cx: &mut Context<Self>) -> bool {
let Some(text) = cx.read_from_clipboard().and_then(|c| c.text()) else { return false };
if !self.exited {
- self.shared.write(keys::paste(&text, self.mode()));
+ self.write_input(keys::paste(&text, self.mode()), cx);
}
true
}
@@ -631,6 +655,6 @@ impl Render for TerminalView {
.on_action(cx.listener(|_, _: &IncreaseFontSize, _, cx| theme_mod::update_terminal(cx, |a| a.terminal_font_size += 1.)))
.on_action(cx.listener(|_, _: &DecreaseFontSize, _, cx| theme_mod::update_terminal(cx, |a| a.terminal_font_size -= 1.)))
.on_action(cx.listener(|_, _: &ResetFontSize, _, cx| theme_mod::update_terminal(cx, |a| a.terminal_font_size = theme_mod::TERMINAL_FONT_SIZE)))
- .child(render::grid(self.shared.clone(), palette, focused, self.cursor_on || !focused, Metrics::current(cx)))
+ .child(render::grid(cx.entity(), palette, focused, self.cursor_on || !focused, Metrics::current(cx)))
}
}
diff --git a/src/ui/terminal/render.rs b/src/ui/terminal/render.rs
index 59af35c..aac5c2d 100644
--- a/src/ui/terminal/render.rs
+++ b/src/ui/terminal/render.rs
@@ -2,19 +2,21 @@
//! runs pinned to the cell grid (`force_width`), then the cursor.
use std::sync::{Arc, OnceLock};
+use std::ops::Range;
use alacritty_terminal::grid::Dimensions;
use alacritty_terminal::term::cell::Flags;
use alacritty_terminal::vte::ansi::{Color, CursorShape, NamedColor};
use gpui::{
- App, Bounds, ContentMask, Font, FontFeatures, FontStyle, FontWeight, Hsla, Pixels, Point, ShapedLine, SharedString, StrikethroughStyle,
+ App, Bounds, ContentMask, ElementInputHandler, Entity, Font, FontFeatures, FontStyle, FontWeight, Hsla, Pixels, Point, ShapedLine, SharedString, StrikethroughStyle,
TextRun, UnderlineStyle, Window, canvas, fill, point, prelude::*, px, size,
};
use super::boxdraw::{self, Shape};
use super::colors::{Palette, dim};
-use super::{Geometry, Metrics, PAD_X, PAD_Y, Shared};
-use crate::ui::theme::mono_font;
+use super::ime::{Composition, TerminalInputHandler};
+use super::{Geometry, Metrics, PAD_X, PAD_Y, Shared, TerminalView};
+use crate::ui::theme::{ActiveTheme, mono_font};
/// The terminal font when none is chosen, and what's used when the chosen
/// one isn't installed: SF Mono, then Menlo, then the app's monospace font.
@@ -85,12 +87,70 @@ pub(super) struct Frame {
shapes: Vec<Shape>,
cursor: Vec<(Bounds<Pixels>, Hsla)>,
bounds: Bounds<Pixels>,
+ preedit: Option<InputLayout>,
}
/// `cursor`: draw the cursor (false in a blink's off phase).
-pub(super) fn grid(shared: Arc<Shared>, palette: Palette, focused: bool, cursor: bool, metrics: Metrics) -> impl IntoElement {
- canvas(move |bounds, window, cx| prepaint(&shared, &palette, focused, cursor, metrics, bounds, window, cx), |_, frame, window, cx| paint(frame, window, cx))
- .size_full()
+pub(super) fn grid(view: Entity<TerminalView>, palette: Palette, focused: bool, cursor: bool, metrics: Metrics) -> impl IntoElement {
+ let entity = view.clone();
+ canvas(
+ move |bounds, window, cx| {
+ let view = entity.read(cx);
+ let mut frame = prepaint(&view.shared, &palette, focused, cursor && view.ime.text.is_empty(), metrics, bounds, window);
+ if focused && !view.ime.text.is_empty() {
+ frame.preedit = Some(input_layout(&view.shared, &view.ime, metrics, window, cx));
+ }
+ frame
+ },
+ move |bounds, frame, window, cx| {
+ let focus = view.read(cx).focus.clone();
+ // Registration must happen during paint, and only the focused
+ // terminal receives the platform's text-input callbacks.
+ window.handle_input(&focus, TerminalInputHandler(ElementInputHandler::new(bounds, view)), cx);
+ paint(frame, window, cx);
+ },
+ ).size_full()
+}
+
+/// A local preedit overlay, also used to position the native candidate window.
+pub(super) struct InputLayout {
+ pub line: ShapedLine,
+ pub origin: Point<Pixels>,
+ line_h: Pixels,
+ selected: Range<usize>,
+ bg: Hsla,
+ fg: Hsla,
+ selection: Hsla,
+}
+
+impl InputLayout {
+ pub fn bounds_for_range(&self, range: Range<usize>) -> Bounds<Pixels> {
+ let start = self.line.x_for_index(range.start);
+ let end = self.line.x_for_index(range.end);
+ Bounds::new(self.origin + point(start, px(0.)), size((end - start).max(px(1.)), self.line_h))
+ }
+}
+
+pub(super) fn input_layout(shared: &Shared, ime: &Composition, metrics: Metrics, window: &Window, cx: &App) -> InputLayout {
+ let palette = Palette::new(&cx.theme());
+ let text = SharedString::from(ime.text.clone());
+ let run = TextRun {
+ len: text.len(), font: base_font(window), color: palette.fg, background_color: None,
+ underline: Some(UnderlineStyle { thickness: px(1.), color: None, wavy: false }), strikethrough: None,
+ };
+ let line = window.text_system().shape_line(text, px(metrics.size), &[run], None);
+ let g = *shared.geometry.lock().unwrap();
+ let term = shared.term.lock();
+ let cursor = term.renderable_content().cursor.point;
+ let row = (cursor.line.0 + term.grid().display_offset() as i32).clamp(0, g.rows.saturating_sub(1) as i32);
+ let col = cursor.column.0.min(g.cols.saturating_sub(1));
+ let left = f32::from(g.origin.x);
+ let right = left + g.cols as f32 * g.cell_w;
+ // Shift a long preedit left at the right edge rather than hiding the
+ // candidate anchor outside the terminal. The normal content mask clips it.
+ let x = (left + col as f32 * g.cell_w).min((right - f32::from(line.width)).max(left));
+ let origin = point(px(x), g.origin.y + px(row as f32 * g.line_h));
+ InputLayout { line, origin, line_h: px(g.line_h.max(1.)), selected: ime.selected.clone(), bg: palette.bg, fg: palette.fg, selection: palette.selection }
}
fn base_font(window: &Window) -> Font {
@@ -130,7 +190,7 @@ pub(super) fn family(window: &Window) -> SharedString {
}
#[allow(clippy::too_many_arguments)]
-fn prepaint(shared: &Shared, palette: &Palette, focused: bool, show_cursor: bool, m: Metrics, bounds: Bounds<Pixels>, window: &mut Window, _cx: &mut App) -> Frame {
+fn prepaint(shared: &Shared, palette: &Palette, focused: bool, show_cursor: bool, m: Metrics, bounds: Bounds<Pixels>, window: &mut Window) -> Frame {
let (cell_w, line_h) = cell_size(window, m);
let cols = ((f32::from(bounds.size.width) - 2. * PAD_X) / cell_w).floor().max(2.) as usize;
let rows = ((f32::from(bounds.size.height) - 2. * PAD_Y) / line_h).floor().max(1.) as usize;
@@ -207,7 +267,7 @@ fn prepaint(shared: &Shared, palette: &Palette, focused: bool, show_cursor: bool
};
let at = |row: usize, col: usize| origin + point(px(col as f32 * cell_w), px(row as f32 * line_h));
- let mut frame = Frame { line_h: px(line_h), rects: Vec::new(), lines: Vec::new(), shapes: Vec::new(), cursor: Vec::new(), bounds };
+ let mut frame = Frame { line_h: px(line_h), rects: Vec::new(), lines: Vec::new(), shapes: Vec::new(), cursor: Vec::new(), bounds, preedit: None };
// Backgrounds, merged along each row.
let mut run: Option<(usize, usize, usize, Hsla)> = None; // row, start col, end col (exclusive), color
@@ -344,6 +404,16 @@ fn paint(frame: Frame, window: &mut Window, cx: &mut App) {
for (b, color) in frame.cursor {
window.paint_quad(fill(b, color));
}
+ if let Some(preedit) = frame.preedit {
+ // Paint after the grid so its contents cannot show through the
+ // marked text. Nothing here is written into alacritty's buffer.
+ window.paint_quad(fill(Bounds::new(preedit.origin, size(preedit.line.width + px(2.), preedit.line_h)), preedit.bg));
+ if !preedit.selected.is_empty() {
+ window.paint_quad(fill(preedit.bounds_for_range(preedit.selected.clone()), preedit.selection));
+ }
+ let _ = preedit.line.paint(preedit.origin, preedit.line_h, window, cx);
+ window.paint_quad(fill(preedit.bounds_for_range(preedit.selected.end..preedit.selected.end), preedit.fg));
+ }
});
}