Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

desktop(terminal): a committed IME word stays on screen until its echo lands

Dev jacob3ceea8dc1924
diff --git a/desktop/test/ime_echo_hold_test.dart b/desktop/test/ime_echo_hold_test.dart
new file mode 100644
index 000000000..9f714f969
--- /dev/null
+++ b/desktop/test/ime_echo_hold_test.dart
@@ -0,0 +1,101 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:xterm/src/ui/ime_echo_hold.dart';
+
+Future<void> _endInputEvent() => Future<void>.microtask(() {});
+
+void main() {
+ late ImeEchoHold hold;
+ var expired = 0;
+
+ setUp(() {
+ expired = 0;
+ hold = ImeEchoHold(onExpired: () => expired++);
+ });
+
+ tearDown(() => hold.dispose());
+
+ test('ordinary typing is never held', () {
+ expect(hold.insert('hunter2'), isFalse);
+ expect(hold.delete(1), isFalse);
+ expect(hold.isEmpty, isTrue);
+ expect(hold.preview(null, 0), isNull);
+ });
+
+ test('holds a commit and draws the next composition after it', () async {
+ hold.beginCommit();
+ expect(hold.insert('alo '), isTrue);
+ await _endInputEvent();
+
+ expect(hold.preview(null, 0), (text: 'alo ', backtrackCells: 0));
+ expect(hold.preview('may', 0), (text: 'alo may', backtrackCells: 0));
+ // Typing that follows a held commit joins it, in order.
+ expect(hold.insert('m'), isTrue);
+ expect(hold.text, 'alo m');
+ });
+
+ test('a composition reaching back replaces the end of the held text', () {
+ hold.beginCommit();
+ hold.insert('tu');
+
+ expect(hold.preview('ư', 1), (text: 'tư', backtrackCells: 0));
+ });
+
+ test('a composition reaching past the held text covers shown cells', () {
+ hold.beginCommit();
+ hold.insert('o');
+
+ expect(hold.preview('ươ', 3), (text: 'ươ', backtrackCells: 2));
+ });
+
+ test('a commit that deletes shown cells paints over them', () {
+ hold.beginCommit();
+ hold.delete(1);
+ hold.insert('ư');
+
+ expect(hold.preview(null, 0), (text: 'ư', backtrackCells: 1));
+ });
+
+ test('lets go of each part as the terminal echoes it', () {
+ hold.beginCommit();
+ hold.insert('alo mày');
+
+ expect(hold.echoed('› '), isFalse);
+ expect(hold.echoed('› alo'), isTrue);
+ expect(hold.text, ' mày');
+ expect(hold.echoed('› alo mày'), isTrue);
+ expect(hold.isEmpty, isTrue);
+ expect(expired, 0);
+ });
+
+ testWidgets('an unanswered hold expires, and twice turns holding off', (
+ tester,
+ ) async {
+ for (var miss = 0; miss < 2; miss++) {
+ hold.beginCommit();
+ hold.insert('alo');
+ await tester.pump(ImeEchoHold.defaultTimeout);
+ expect(hold.isEmpty, isTrue);
+ }
+ expect(expired, 2);
+
+ hold.beginCommit();
+ expect(hold.insert('alo'), isFalse);
+ });
+
+ testWidgets('an echo forgives earlier misses', (tester) async {
+ hold.beginCommit();
+ hold.insert('alo');
+ await tester.pump(ImeEchoHold.defaultTimeout);
+
+ hold.beginCommit();
+ hold.insert('mày');
+ hold.echoed('› mày');
+ hold.beginCommit();
+ hold.insert('ơi');
+ await tester.pump(ImeEchoHold.defaultTimeout);
+
+ hold.beginCommit();
+ expect(hold.insert('nhé'), isTrue);
+ hold.clear();
+ });
+}
diff --git a/desktop/test/prompt_placeholder_test.dart b/desktop/test/prompt_placeholder_test.dart
new file mode 100644
index 000000000..175fb094c
--- /dev/null
+++ b/desktop/test/prompt_placeholder_test.dart
@@ -0,0 +1,39 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:xterm/src/ui/prompt_placeholder.dart';
+import 'package:xterm/xterm.dart';
+
+/// The cursor sits after `› ` (column 2), the way an empty agent prompt shows.
+int placeholderEndAfterPrompt(String rest) {
+ final terminal = Terminal(maxLines: 200, reflowEnabled: false)
+ ..resize(80, 12);
+ terminal.write('› $rest\x1b[1;3H');
+ return promptPlaceholderEnd(
+ terminal.buffer.currentLine,
+ terminal.buffer.cursorX,
+ );
+}
+
+void main() {
+ test('covers a dim placeholder up to its last character', () {
+ expect(
+ placeholderEndAfterPrompt('\x1b[2mAsk Codex to do anything\x1b[0m'),
+ 2 + 'Ask Codex to do anything'.length,
+ );
+ });
+
+ test('ignores the plain blanks a prompt pads its row with', () {
+ expect(
+ placeholderEndAfterPrompt('\x1b[2mTry "edit"\x1b[0m '),
+ 2 + 'Try "edit"'.length,
+ );
+ });
+
+ test('never covers real text after the cursor', () {
+ expect(placeholderEndAfterPrompt('rest of the line'), 2);
+ expect(placeholderEndAfterPrompt('\x1b[2mdim\x1b[0m and real'), 2);
+ });
+
+ test('covers nothing on an empty row', () {
+ expect(placeholderEndAfterPrompt(''), 2);
+ });
+}
diff --git a/desktop/test/terminal_view_ime_echo_test.dart b/desktop/test/terminal_view_ime_echo_test.dart
new file mode 100644
index 000000000..cb1145837
--- /dev/null
+++ b/desktop/test/terminal_view_ime_echo_test.dart
@@ -0,0 +1,166 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:xterm/src/ui/ime_echo_hold.dart';
+import 'package:xterm/xterm.dart';
+
+/// A remote terminal echoes a committed word a round trip later. These replay
+/// Telex typing (`alo mayf` → "alo mày") with the echo arriving late.
+void main() {
+ late Terminal terminal;
+ late List<String> outbound;
+
+ Future<TerminalViewState> pumpView(WidgetTester tester) async {
+ terminal = Terminal(maxLines: 200, reflowEnabled: false)..resize(80, 12);
+ outbound = [];
+ terminal.onOutput = outbound.add;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SizedBox(
+ width: 900,
+ height: 260,
+ child: TerminalView(terminal, autofocus: true),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ return tester.state<TerminalViewState>(find.byType(TerminalView));
+ }
+
+ Future<void> type(
+ WidgetTester tester,
+ String text, {
+ TextRange composing = TextRange.empty,
+ }) async {
+ tester.testTextInput.updateEditingValue(
+ TextEditingValue(
+ text: text,
+ selection: TextSelection.collapsed(offset: text.length),
+ composing: composing,
+ ),
+ );
+ await tester.pump();
+ }
+
+ testWidgets('keeps a committed word on screen until its echo lands', (
+ tester,
+ ) async {
+ final view = await pumpView(tester);
+
+ await type(tester, 'alo', composing: const TextRange(start: 0, end: 3));
+ expect(view.debugComposingText, 'alo');
+
+ await type(tester, 'alo ');
+ expect(outbound, ['alo ']);
+ expect(view.debugComposingText, 'alo ');
+
+ // The next word composes after the held one, not over it.
+ await type(tester, 'alo may', composing: const TextRange(start: 4, end: 7));
+ expect(view.debugComposingText, 'alo may');
+
+ terminal.write('alo ');
+ await tester.pump();
+ expect(view.debugComposingText, 'may');
+
+ await type(tester, 'alo mày ');
+ expect(outbound, ['alo ', 'mày ']);
+ expect(view.debugComposingText, 'mày ');
+
+ terminal.write('mày ');
+ await tester.pump();
+ expect(view.debugComposingText, isNull);
+ });
+
+ testWidgets('Return lets go of a held word', (tester) async {
+ final view = await pumpView(tester);
+
+ await type(tester, 'alo', composing: const TextRange(start: 0, end: 3));
+ await type(tester, 'alo');
+ expect(view.debugComposingText, 'alo');
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+
+ expect(view.debugComposingText, isNull);
+ });
+
+ testWidgets('typing without an input method shows nothing extra', (
+ tester,
+ ) async {
+ final view = await pumpView(tester);
+
+ await type(tester, 'hunter2');
+
+ expect(outbound, ['hunter2']);
+ expect(view.debugComposingText, isNull);
+ });
+
+ group('the caret follows the preview', () {
+ List<Rect> cursorBlocks(TerminalViewState view) {
+ final blocks = <Rect>[];
+ expect(
+ view.renderTerminal,
+ paints..everything((method, arguments) {
+ if (method != #drawRect) return true;
+ // Filled with focus, outlined without: either way, the cursor colour.
+ final paint = arguments[1] as Paint;
+ if (paint.color.toARGB32() ==
+ TerminalThemes.defaultTheme.cursor.toARGB32()) {
+ blocks.add(arguments[0] as Rect);
+ }
+ return true;
+ }),
+ );
+ return blocks;
+ }
+
+ Future<void> expectCaretMovedBy(
+ WidgetTester tester,
+ String composing,
+ int cells,
+ ) async {
+ final view = await pumpView(tester);
+ terminal.write('› ');
+ await tester.pump();
+ final atCursor = cursorBlocks(view).single;
+
+ await type(
+ tester,
+ composing,
+ composing: TextRange(start: 0, end: composing.length),
+ );
+
+ final width = view.renderTerminal.cellSize.width;
+ expect(
+ cursorBlocks(view).single,
+ atCursor.shift(Offset(cells * width, 0)),
+ );
+ }
+
+ // A lone Telex `a` stays composing until the next key; under the block
+ // it looked as if nothing had been typed.
+ testWidgets('after a one-letter composition', (tester) async {
+ await expectCaretMovedBy(tester, 'a', 1);
+ });
+
+ testWidgets('after a wide character', (tester) async {
+ await expectCaretMovedBy(tester, '你', 2);
+ });
+ });
+
+ testWidgets('a word the terminal never echoes lets go after a while', (
+ tester,
+ ) async {
+ final view = await pumpView(tester);
+
+ await type(tester, 'alo', composing: const TextRange(start: 0, end: 3));
+ await type(tester, 'alo');
+ expect(view.debugComposingText, 'alo');
+
+ await tester.pump(ImeEchoHold.defaultTimeout);
+
+ expect(view.debugComposingText, isNull);
+ });
+}
diff --git a/desktop/third_party/xterm/README.autonomous.md b/desktop/third_party/xterm/README.autonomous.md
index 6764ff514..934e9df26 100644
--- a/desktop/third_party/xterm/README.autonomous.md
+++ b/desktop/third_party/xterm/README.autonomous.md
@@ -112,6 +112,26 @@ fix and the regression in `test/terminal_session_test.dart` passes against it.
`_onScroll`. Regression: the reparent test in
`test/terminal_alt_buffer_scroll_test.dart`.
+- **A committed IME word stays painted until the terminal echoes it**
+ (`lib/src/ui/ime_echo_hold.dart`, `lib/src/terminal_view.dart`). Upstream
+ clears the pre-edit preview the moment a composition commits, but a remote
+ terminal echoes it a round trip later — about half a second from a browser
+ through the relay — so a word typed with Telex vanished, and an agent's
+ placeholder reappeared, before the echo brought it back. The commit is now
+ held where the echo will land, the next composition is drawn after it, and
+ each part lets go as the terminal shows it, on Return or another terminal key,
+ or after two seconds. Plain typing never starts a hold, so a prompt that does
+ not echo shows nothing new; a view whose echo never matches stops holding
+ after two expiries. While a preview shows, a prompt's dim placeholder after
+ the cursor ("Ask Codex to do anything", drawn with SGR 2) is painted over
+ with its own background (`lib/src/ui/prompt_placeholder.dart`,
+ `TerminalPainter.paintCellCover`), as the program does once the text echoes;
+ a row with any non-dim text after the cursor is left alone. The cursor is
+ drawn after the preview, not on its first cell, where the block hid a lone
+ composing letter (Telex `a` waits for the next key). Regressions:
+ `test/ime_echo_hold_test.dart`, `test/terminal_view_ime_echo_test.dart`,
+ `test/prompt_placeholder_test.dart`.
+
Each of these has to survive an upstream bump — the tests named are what catch
it if one is dropped.
diff --git a/desktop/third_party/xterm/lib/src/terminal_view.dart b/desktop/third_party/xterm/lib/src/terminal_view.dart
index 50fcc7e9a..22f780683 100644
--- a/desktop/third_party/xterm/lib/src/terminal_view.dart
+++ b/desktop/third_party/xterm/lib/src/terminal_view.dart
@@ -11,6 +11,7 @@ import 'package:xterm/src/ui/controller.dart';
import 'package:xterm/src/ui/cursor_type.dart';
import 'package:xterm/src/ui/custom_text_edit.dart';
import 'package:xterm/src/ui/gesture/gesture_handler.dart';
+import 'package:xterm/src/ui/ime_echo_hold.dart';
import 'package:xterm/src/ui/input_map.dart';
import 'package:xterm/src/ui/keyboard_listener.dart';
import 'package:xterm/src/ui/keyboard_visibility.dart';
@@ -188,10 +189,18 @@ class TerminalViewState extends State<TerminalView> {
final _viewportKey = GlobalKey();
+ /// What is painted over the terminal: [_echoHold], then [_composition].
String? _composingText;
int _composingBacktrackCells = 0;
+ /// The input method's live pre-edit, as its client reports it.
+ String? _composition;
+
+ int _compositionBacktrackCells = 0;
+
+ late final _echoHold = ImeEchoHold(onExpired: _showPreview);
+
late TerminalController _controller;
late ScrollController _scrollController;
@@ -221,6 +230,9 @@ class TerminalViewState extends State<TerminalView> {
// or editing buffer into the newly selected terminal.
_composingText = null;
_composingBacktrackCells = 0;
+ _composition = null;
+ _compositionBacktrackCells = 0;
+ _echoHold.reset();
final currentTerminal = widget.terminal;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !identical(widget.terminal, currentTerminal)) return;
@@ -252,6 +264,7 @@ class TerminalViewState extends State<TerminalView> {
@override
void dispose() {
widget.terminal.removeListener(_onTerminalChanged);
+ _echoHold.dispose();
if (widget.focusNode == null) {
_focusNode.dispose();
}
@@ -320,12 +333,14 @@ class TerminalViewState extends State<TerminalView> {
for (var index = 0; index < count; index++) {
widget.terminal.keyInput(TerminalKey.backspace);
}
+ if (_echoHold.delete(count)) _showPreview();
},
onComposing: _onComposing,
onAction: (action) {
_scrollToBottom();
if (action == TextInputAction.done ||
action == TextInputAction.newline) {
+ _dropEchoHold();
widget.terminal.keyInput(TerminalKey.enter);
_customTextEditKey.currentState?.resetEditingState();
}
@@ -452,18 +467,38 @@ class TerminalViewState extends State<TerminalView> {
if (!consumed) {
widget.terminal.textInput(text);
}
+ if (_echoHold.insert(text)) _showPreview();
_scrollToBottom();
}
void _onComposing(String? text, int backtrackCells) {
- if (text != null && _terminalAlreadyEchoes(text)) {
- text = null;
- backtrackCells = 0;
+ final committed = _composition;
+ // Clearing a live composition is how its commit begins: the delete and
+ // insert that carry it to the terminal follow in the same input event.
+ if (text == null &&
+ committed != null &&
+ !_terminalAlreadyEchoes(committed)) {
+ _echoHold.beginCommit();
}
- if (!mounted ||
- (_composingText == text &&
- _composingBacktrackCells == backtrackCells)) {
+ _composition = text;
+ _compositionBacktrackCells = backtrackCells;
+ _showPreview();
+ }
+
+ /// Paints the commit still awaiting its echo, then the live composition.
+ void _showPreview() {
+ if (!mounted) return;
+ var composing = _composition;
+ if (composing != null &&
+ _echoHold.isEmpty &&
+ _terminalAlreadyEchoes(composing)) {
+ composing = null;
+ }
+ final preview = _echoHold.preview(composing, _compositionBacktrackCells);
+ final text = preview?.text;
+ final backtrackCells = preview?.backtrackCells ?? 0;
+ if (_composingText == text && _composingBacktrackCells == backtrackCells) {
return;
}
setState(() {
@@ -472,25 +507,32 @@ class TerminalViewState extends State<TerminalView> {
});
}
+ /// A key the terminal answers itself — Return, an arrow, a control chord —
+ /// moves on from the text being held, which the echo may never show.
+ void _dropEchoHold() {
+ if (_echoHold.isEmpty) return;
+ _echoHold.clear();
+ _showPreview();
+ }
+
/// The native macOS input client keeps a marked range while a remote TUI
/// has already echoed the exact same characters. Keeping our own preview in
/// that case duplicates the cells and makes them look underlined/stale until
/// the next keyframe. A real CJK pre-edit has not reached the PTY yet, so it
/// does not match the cells before the cursor and remains visible.
- bool _terminalAlreadyEchoes(String text) {
- if (text.isEmpty) return false;
+ bool _terminalAlreadyEchoes(String text) =>
+ text.isNotEmpty && _textBeforeCursor().endsWith(text);
+
+ String _textBeforeCursor() {
final buffer = widget.terminal.buffer;
- if (buffer.cursorX <= 0) return false;
- return buffer.currentLine.getText(0, buffer.cursorX).endsWith(text);
+ if (buffer.cursorX <= 0) return '';
+ return buffer.currentLine.getText(0, buffer.cursorX);
}
void _onTerminalChanged() {
- final text = _composingText;
- if (!mounted || text == null || !_terminalAlreadyEchoes(text)) return;
- setState(() {
- _composingText = null;
- _composingBacktrackCells = 0;
- });
+ if (_composingText == null) return;
+ _echoHold.echoed(_textBeforeCursor());
+ _showPreview();
}
@visibleForTesting
@@ -591,6 +633,7 @@ class TerminalViewState extends State<TerminalView> {
!keyboard.isMetaPressed;
if (isTextInput && linuxMeta) {
widget.terminal.textInput('\x1b${event.character}');
+ _dropEchoHold();
_scrollToBottom();
return KeyEventResult.handled;
}
@@ -664,6 +707,7 @@ class TerminalViewState extends State<TerminalView> {
if (handled) {
_scrollToBottom();
+ _dropEchoHold();
if (key == TerminalKey.enter) {
_customTextEditKey.currentState?.resetEditingState();
}
diff --git a/desktop/third_party/xterm/lib/src/ui/ime_echo_hold.dart b/desktop/third_party/xterm/lib/src/ui/ime_echo_hold.dart
new file mode 100644
index 000000000..290d7194e
--- /dev/null
+++ b/desktop/third_party/xterm/lib/src/ui/ime_echo_hold.dart
@@ -0,0 +1,166 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:xterm/src/utils/unicode_v11.dart';
+
+/// Text painted over the terminal, starting [backtrackCells] before the cursor.
+typedef ImePreview = ({String text, int backtrackCells});
+
+/// Text an input method committed that the terminal has not echoed yet.
+///
+/// A composition's preview vanished the moment it committed, while a remote
+/// terminal echoes the word a round trip later — about half a second from a
+/// browser through the relay. For that half second the word just typed was
+/// gone (an agent's placeholder even came back), then it reappeared. Held
+/// here, it stays painted where the echo will land, the next composition is
+/// drawn after it, and each part lets go as soon as the terminal shows it.
+///
+/// Ordinary typing never starts a hold: only what follows a commit while it is
+/// still held joins it, so a prompt that does not echo (a password) shows
+/// nothing an IME preview had not already shown. A terminal whose echo cannot
+/// be matched — a hold that expires twice without seeing any — stops holding,
+/// so a mismatch costs one late preview, never a doubled word on every commit.
+class ImeEchoHold {
+ ImeEchoHold({required this.onExpired, this.timeout = defaultTimeout});
+
+ static const defaultTimeout = Duration(seconds: 2);
+ static const _maxMisses = 2;
+
+ /// Called after an unanswered hold let go, for the view to repaint.
+ final VoidCallback onExpired;
+ final Duration timeout;
+
+ List<int> _runes = const [];
+ int _backtrackCells = 0;
+ bool _committing = false;
+ int _misses = 0;
+ Timer? _timer;
+
+ bool get isEmpty => _runes.isEmpty;
+
+ @visibleForTesting
+ String get text => String.fromCharCodes(_runes);
+
+ /// A composition just ended: the edits that follow in the same input event
+ /// are its commit.
+ void beginCommit() {
+ if (_misses >= _maxMisses) return;
+ _committing = true;
+ scheduleMicrotask(() {
+ _committing = false;
+ // A commit that only deleted leaves nothing to wait for.
+ if (isEmpty) clear();
+ });
+ }
+
+ /// [count] runes were deleted before the cursor. Returns whether it held.
+ bool delete(int count) {
+ if (!_committing && isEmpty) return false;
+ final kept = _runes.length - count;
+ if (kept < 0) {
+ // Deletes past the held text erase cells the terminal already shows,
+ // which the preview then covers.
+ _backtrackCells += -kept;
+ }
+ _runes = _runes.sublist(0, kept.clamp(0, _runes.length));
+ _touch();
+ return true;
+ }
+
+ /// [typed] was sent to the terminal. Returns whether it held.
+ bool insert(String typed) {
+ if (!_committing && isEmpty) return false;
+ _runes = [..._runes, ...typed.runes];
+ _touch();
+ return true;
+ }
+
+ /// Lets go of whatever the terminal now shows before its cursor: the whole
+ /// hold, or the longest part it starts with. Returns whether it changed.
+ bool echoed(String beforeCursor) {
+ if (isEmpty) return false;
+ for (var end = _runes.length; end > 0; end--) {
+ if (!beforeCursor.endsWith(String.fromCharCodes(_runes, 0, end))) {
+ continue;
+ }
+ _runes = _runes.sublist(end);
+ _backtrackCells = 0;
+ _misses = 0;
+ if (isEmpty) {
+ clear();
+ } else {
+ _restartTimer();
+ }
+ return true;
+ }
+ return false;
+ }
+
+ /// The held text, then [composing] — which, reaching back
+ /// [composingBacktrack] cells, replaces the end of the held text, or past
+ /// it, cells the terminal already shows.
+ ImePreview? preview(String? composing, int composingBacktrack) {
+ final backtrack = composing == null ? 0 : composingBacktrack;
+ if (isEmpty) return _nonEmpty(composing ?? '', backtrack);
+ final heldCells = runesCells(_runes);
+ if (backtrack > heldCells) {
+ return _nonEmpty(
+ composing ?? '',
+ _backtrackCells + backtrack - heldCells,
+ );
+ }
+ final kept = _dropTrailingCells(_runes, backtrack);
+ return _nonEmpty(
+ String.fromCharCodes(kept) + (composing ?? ''),
+ _backtrackCells,
+ );
+ }
+
+ void clear() {
+ _timer?.cancel();
+ _timer = null;
+ _runes = const [];
+ _backtrackCells = 0;
+ }
+
+ /// A new terminal: forget what the last one taught.
+ void reset() {
+ clear();
+ _committing = false;
+ _misses = 0;
+ }
+
+ void dispose() => _timer?.cancel();
+
+ void _touch() {
+ if (isEmpty && !_committing) {
+ clear();
+ return;
+ }
+ _timer ??= Timer(timeout, _expire);
+ }
+
+ void _restartTimer() {
+ _timer?.cancel();
+ _timer = Timer(timeout, _expire);
+ }
+
+ void _expire() {
+ _timer = null;
+ _misses++;
+ clear();
+ onExpired();
+ }
+
+ static ImePreview? _nonEmpty(String text, int backtrackCells) =>
+ text.isEmpty ? null : (text: text, backtrackCells: backtrackCells);
+
+ static List<int> _dropTrailingCells(List<int> runes, int cells) {
+ var end = runes.length;
+ var dropped = 0;
+ while (end > 0 && dropped < cells) {
+ dropped += runeCells(runes[--end]);
+ }
+ return runes.sublist(0, end);
+ }
+}
diff --git a/desktop/third_party/xterm/lib/src/ui/painter.dart b/desktop/third_party/xterm/lib/src/ui/painter.dart
index 7adc94536..ceb8d0f62 100644
--- a/desktop/third_party/xterm/lib/src/ui/painter.dart
+++ b/desktop/third_party/xterm/lib/src/ui/painter.dart
@@ -556,22 +556,37 @@ class TerminalPainter {
/// [offset].
@pragma('vm:prefer-inline')
void paintCellBackground(Canvas canvas, Offset offset, CellData cellData) {
- late Color color;
- final colorType = cellData.background & CellColor.typeMask;
+ final color = _cellBackgroundColor(cellData);
+ if (color == null) return;
+ _fillCell(canvas, offset, cellData, color);
+ }
+
+ /// Paints over a cell, glyph and all, with the background it sits on.
+ void paintCellCover(Canvas canvas, Offset offset, CellData cellData) {
+ _fillCell(
+ canvas,
+ offset,
+ cellData,
+ _cellBackgroundColor(cellData) ?? _theme.background,
+ );
+ }
+ /// Null for the default background, which the terminal already shows.
+ Color? _cellBackgroundColor(CellData cellData) {
if (cellData.flags & CellFlags.inverse != 0) {
- color = resolveForegroundColor(cellData.foreground);
- } else if (colorType == CellColor.normal) {
- return;
- } else {
- color = resolveBackgroundColor(cellData.background);
+ return resolveForegroundColor(cellData.foreground);
}
+ if (cellData.background & CellColor.typeMask == CellColor.normal) {
+ return null;
+ }
+ return resolveBackgroundColor(cellData.background);
+ }
- final paint = Paint()..color = color;
+ void _fillCell(Canvas canvas, Offset offset, CellData cellData, Color color) {
final doubleWidth = cellData.content >> CellContent.widthShift == 2;
final widthScale = doubleWidth ? 2 : 1;
final size = Size(_cellSize.width * widthScale + 1, _cellSize.height);
- canvas.drawRect(offset & size, paint);
+ canvas.drawRect(offset & size, Paint()..color = color);
}
/// Get the effective foreground color for a cell from information encoded in
diff --git a/desktop/third_party/xterm/lib/src/ui/prompt_placeholder.dart b/desktop/third_party/xterm/lib/src/ui/prompt_placeholder.dart
new file mode 100644
index 000000000..cb14faf77
--- /dev/null
+++ b/desktop/third_party/xterm/lib/src/ui/prompt_placeholder.dart
@@ -0,0 +1,23 @@
+import 'package:xterm/src/core/buffer/cell_flags.dart';
+import 'package:xterm/src/core/buffer/line.dart';
+
+/// Where the dim placeholder an agent's prompt shows after the cursor ends —
+/// "Ask Codex to do anything", `Try "edit <filepath> to..."` — or [from]
+/// when the rest of the row is anything else.
+///
+/// Both agents draw it faint (SGR 2) and clear it once the first typed
+/// character echoes. Until then an input-method preview painted at the
+/// cursor covered only its own width and left the placeholder's tail beside
+/// it ("aloCodex to do anything"). A row that is not faint throughout after
+/// the cursor holds real text and is never treated as a placeholder; blanks,
+/// which prompts pad their row with, count either way.
+int promptPlaceholderEnd(BufferLine line, int from) {
+ var end = from;
+ for (var column = from; column < line.length; column++) {
+ final codePoint = line.getCodePoint(column);
+ if (codePoint == 0 || codePoint == 0x20) continue;
+ if (line.getAttributes(column) & CellFlags.faint == 0) return from;
+ end = column + 1;
+ }
+ return end;
+}
diff --git a/desktop/third_party/xterm/lib/src/ui/render.dart b/desktop/third_party/xterm/lib/src/ui/render.dart
index 037c98c01..40cef728e 100644
--- a/desktop/third_party/xterm/lib/src/ui/render.dart
+++ b/desktop/third_party/xterm/lib/src/ui/render.dart
@@ -6,16 +6,19 @@ import 'package:flutter/widgets.dart';
import 'package:xterm/src/core/buffer/cell_offset.dart';
import 'package:xterm/src/core/buffer/range.dart';
import 'package:xterm/src/core/buffer/segment.dart';
+import 'package:xterm/src/core/cell.dart';
import 'package:xterm/src/core/mouse/button.dart';
import 'package:xterm/src/core/mouse/button_state.dart';
import 'package:xterm/src/terminal.dart';
import 'package:xterm/src/ui/controller.dart';
import 'package:xterm/src/ui/cursor_type.dart';
import 'package:xterm/src/ui/painter.dart';
+import 'package:xterm/src/ui/prompt_placeholder.dart';
import 'package:xterm/src/ui/selection_mode.dart';
import 'package:xterm/src/ui/terminal_size.dart';
import 'package:xterm/src/ui/terminal_text_style.dart';
import 'package:xterm/src/ui/terminal_theme.dart';
+import 'package:xterm/src/utils/unicode_v11.dart';
typedef EditableRectCallback = void Function(Rect rect, Rect caretRect);
@@ -615,14 +618,14 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
if (_terminal.buffer.absoluteCursorY >= effectFirstLine &&
_terminal.buffer.absoluteCursorY <= effectLastLine) {
- if (_isComposingText) {
- _paintComposingText(canvas, offset + cursorOffset);
- }
+ final caret = _isComposingText
+ ? _paintComposingText(canvas, offset + cursorOffset)
+ : offset + cursorOffset;
if (_shouldShowCursor) {
_painter.paintCursor(
canvas,
- offset + cursorOffset,
+ caret,
cursorType: _cursorType,
hasFocus: _focusNode.hasFocus,
);
@@ -651,11 +654,14 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
}
/// Paints the text that is currently being composed in IME to [canvas] at
- /// [offset]. [offset] is usually the cursor position.
- void _paintComposingText(Canvas canvas, Offset offset) {
+ /// [offset], usually the cursor position, and returns where the caret
+ /// belongs: after it, as in any text field. Left at the cursor, the block
+ /// covered the preview's first character — a lone Telex `a`, still
+ /// composing until the next key, looked like nothing had been typed.
+ Offset _paintComposingText(Canvas canvas, Offset offset) {
final composingText = _composingText;
if (composingText == null) {
- return;
+ return offset;
}
var startColumn = _terminal.buffer.cursorX - _composingBacktrackCells;
@@ -664,13 +670,19 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
startColumn += _terminal.viewWidth;
startLine--;
}
+ final lastColumn = _terminal.viewWidth - 1;
+ final firstColumn = startColumn.clamp(0, lastColumn);
final renderOrigin = offset - cursorOffset;
- final composingOffset = renderOrigin +
+ Offset cellOffset(int column) =>
+ renderOrigin +
Offset(
- startColumn.clamp(0, _terminal.viewWidth - 1).toDouble() *
- _painter.cellSize.width,
+ column * _painter.cellSize.width,
startLine * _painter.cellSize.height + _lineOffset,
);
+ final composingOffset = cellOffset(firstColumn);
+ final caret = cellOffset(
+ (firstColumn + runesCells(composingText.runes)).clamp(0, lastColumn),
+ );
final style = _painter.textStyle.toTextStyle(
color: _painter.resolveForegroundColor(_terminal.cursor.foreground),
@@ -700,8 +712,29 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
)..layout(
maxWidth: (size.width - composingOffset.dx).clamp(0.0, size.width));
+ _coverPromptPlaceholder(canvas, renderOrigin);
textPainter.paint(canvas, composingOffset);
textPainter.dispose();
+ return caret;
+ }
+
+ /// Hides a prompt's dim placeholder behind an input-method preview, as the
+ /// program will once the typed text echoes (see [promptPlaceholderEnd]).
+ void _coverPromptPlaceholder(Canvas canvas, Offset renderOrigin) {
+ final buffer = _terminal.buffer;
+ final lineIndex = buffer.absoluteCursorY;
+ final line = buffer.lines[lineIndex];
+ final end = promptPlaceholderEnd(line, buffer.cursorX);
+ final cell = CellData.empty();
+ final top = lineIndex * _painter.cellSize.height + _lineOffset;
+ for (var column = buffer.cursorX; column < end; column++) {
+ line.getCellData(column, cell);
+ _painter.paintCellCover(
+ canvas,
+ renderOrigin + Offset(column * _painter.cellSize.width, top),
+ cell,
+ );
+ }
}
void _paintSelection(
diff --git a/desktop/third_party/xterm/lib/src/utils/unicode_v11.dart b/desktop/third_party/xterm/lib/src/utils/unicode_v11.dart
index fd95ba0b8..701596e60 100644
--- a/desktop/third_party/xterm/lib/src/utils/unicode_v11.dart
+++ b/desktop/third_party/xterm/lib/src/utils/unicode_v11.dart
@@ -510,3 +510,14 @@ class UnicodeV11 {
}
final unicodeV11 = UnicodeV11();
+
+/// Columns [rune] takes on the grid: two for a wide character, none for a
+/// combining mark or a control.
+int runeCells(int rune) {
+ final width = unicodeV11.wcwidth(rune);
+ return width > 0 ? width : 0;
+}
+
+/// Columns [runes] take on the grid together.
+int runesCells(Iterable<int> runes) =>
+ runes.fold(0, (cells, rune) => cells + runeCells(rune));