From 8f758bc721eba9806c626f02897f37d380df8460 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:32:21 +0000 Subject: [PATCH] xterm: answer OSC 10/11/12 queries; OSC 8 links, OSC 52 and OSC 7 OSC 10/11/12 ; ? is answered with rgb:rrrr/gggg/bbbb from the view's theme (RenderTerminal reports it through Terminal.setReportedColors), terminated like the query (BEL or ST). OSC 8 hyperlinks are stored on the cells (a 16-bit id in the attributes; Terminal.hyperlinkAt), survive SGR resets and end with an empty URI. OSC 52 sets reach Terminal.onClipboardSet decoded; clipboard reads are not supported. OSC 7 reaches onWorkingDirectoryChange. OSC bodies keep their semicolons (titles, URIs), and an OSC cut short by another escape no longer swallows that escape's first byte. Co-Authored-By: Claude Opus 5.5 --- app/test/third_party_xterm/osc_test.dart | 105 ++++++++++++++++++ .../xterm/lib/src/core/buffer/buffer.dart | 4 +- app/third_party/xterm/lib/src/core/cell.dart | 4 + .../xterm/lib/src/core/cursor.dart | 11 +- .../xterm/lib/src/core/escape/emitter.dart | 9 ++ .../xterm/lib/src/core/escape/handler.dart | 16 +++ .../xterm/lib/src/core/escape/parser.dart | 101 ++++++++++++----- .../xterm/lib/src/core/hyperlinks.dart | 34 ++++++ app/third_party/xterm/lib/src/terminal.dart | 82 +++++++++++++- app/third_party/xterm/lib/src/ui/render.dart | 13 +++ .../xterm/lib/src/utils/debugger.dart | 20 ++++ 11 files changed, 366 insertions(+), 33 deletions(-) create mode 100644 app/test/third_party_xterm/osc_test.dart create mode 100644 app/third_party/xterm/lib/src/core/hyperlinks.dart diff --git a/app/test/third_party_xterm/osc_test.dart b/app/test/third_party_xterm/osc_test.dart new file mode 100644 index 00000000..87df44c1 --- /dev/null +++ b/app/test/third_party_xterm/osc_test.dart @@ -0,0 +1,105 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'xterm_fixture.dart'; + +void main() { + group('OSC 10/11/12 colour queries', () { + FixtureTerminal themed() { + final t = FixtureTerminal(); + t.terminal.setReportedColors( + foreground: 0xFFC0C0C0, + background: 0xFF102030, + cursor: 0xFFFF8000, + ); + return t; + } + + test('answer with the theme colours and the query terminator', () { + final t = themed()..feed('\x1b]11;?\x1b\\'); + expect(t.takeReplies(), '\x1b]11;rgb:1010/2020/3030\x1b\\'); + t.feed('\x1b]10;?\x07'); + expect(t.takeReplies(), '\x1b]10;rgb:c0c0/c0c0/c0c0\x07'); + t.feed('\x1b]12;?\x07'); + expect(t.takeReplies(), '\x1b]12;rgb:ffff/8080/0000\x07'); + }); + + test('a multi-colour query answers each colour in turn', () { + final t = themed()..feed('\x1b]10;?;?\x07'); + expect( + t.takeReplies(), + '\x1b]10;rgb:c0c0/c0c0/c0c0\x07\x1b]11;rgb:1010/2020/3030\x07', + ); + }); + + test('setting a colour sends nothing and prints nothing', () { + final t = themed()..feed('\x1b]11;#000000\x07x'); + expect(t.takeReplies(), ''); + expect(t.row(0), 'x'); + }); + }); + + group('OSC 8 hyperlinks', () { + test('link cells without printing the sequence', () { + final t = FixtureTerminal() + ..feed('a\x1b]8;id=1;https://example.com/a;b\x1b\\link\x1b]8;;\x1b\\z'); + expect(t.row(0), 'alinkz'); + final line = t.buffer.lines[0]; + expect(t.terminal.hyperlinkAt(line, 0), isNull); + for (var x = 1; x <= 4; x++) { + expect(t.terminal.hyperlinkAt(line, x), 'https://example.com/a;b'); + } + expect(t.terminal.hyperlinkAt(line, 5), isNull); + }); + + test('a link survives SGR changes and ends with an empty URI', () { + final t = FixtureTerminal() + ..feed('\x1b]8;;https://x.test\x07\x1b[1ma\x1b[0mb\x1b]8;;\x07c'); + final line = t.buffer.lines[0]; + expect(t.terminal.hyperlinkAt(line, 0), 'https://x.test'); + expect(t.terminal.hyperlinkAt(line, 1), 'https://x.test'); + expect(t.terminal.hyperlinkAt(line, 2), isNull); + expect(t.cell(1, 0).flags & 0xFFFF, 0, reason: 'no SGR attributes'); + }); + }); + + group('OSC 52 clipboard', () { + test('a set reaches the callback decoded', () { + final t = FixtureTerminal(); + final sets = <(String, String)>[]; + t.terminal.onClipboardSet = (text, selection) => + sets.add((text, selection)); + t.feed('\x1b]52;c;aGVsbG8gd8O2cmxk\x07x'); + expect(sets, [('hello wörld', 'c')]); + expect(t.row(0), 'x'); + }); + + test('a read request and invalid data are ignored', () { + final t = FixtureTerminal(); + var calls = 0; + t.terminal.onClipboardSet = (_, _) => calls++; + t.feed('\x1b]52;c;?\x07\x1b]52;c;not base64!\x07'); + expect(calls, 0); + expect(t.takeReplies(), ''); + }); + }); + + test('OSC 7 reports the working directory', () { + final t = FixtureTerminal(); + final dirs = []; + t.terminal.onWorkingDirectoryChange = dirs.add; + t.feed('\x1b]7;file://host/home/me/a;b\x1b\\'); + expect(dirs, ['file://host/home/me/a;b']); + expect(t.row(0), ''); + }); + + test('titles keep their semicolons; an aborted OSC prints nothing', () { + final t = FixtureTerminal(); + final titles = []; + t.terminal.onTitleChange = titles.add; + t.feed('\x1b]2;vim; a.txt\x07'); + t.feed('\x1b]2;cut\x1b[1mB'); + expect(titles, ['vim; a.txt']); + expect(t.row(0), 'B'); + expect(t.cell(0, 0).flags, isNot(0)); + }); +} diff --git a/app/third_party/xterm/lib/src/core/buffer/buffer.dart b/app/third_party/xterm/lib/src/core/buffer/buffer.dart index 44e7df0b..ecc504e3 100644 --- a/app/third_party/xterm/lib/src/core/buffer/buffer.dart +++ b/app/third_party/xterm/lib/src/core/buffer/buffer.dart @@ -346,7 +346,9 @@ class Buffer { _cursorY = 0; _savedCursorX = 0; _savedCursorY = 0; - _savedCursorStyle.reset(); + _savedCursorStyle + ..reset() + ..attrs = 0; charset.reset(); resetVerticalMargins(); } diff --git a/app/third_party/xterm/lib/src/core/cell.dart b/app/third_party/xterm/lib/src/core/cell.dart index 0ef0afd7..700f0c3e 100644 --- a/app/third_party/xterm/lib/src/core/cell.dart +++ b/app/third_party/xterm/lib/src/core/cell.dart @@ -51,6 +51,10 @@ abstract class CellAttr { static const underlineStyleMask = 7 << underlineStyleShift; static const overline = 1 << 11; + + /// The OSC 8 hyperlink id (see `Terminal.hyperlinkOf`); 0 without a link. + static const linkShift = 16; + static const linkMask = 0xFFFF << linkShift; } abstract class CellColor { diff --git a/app/third_party/xterm/lib/src/core/cursor.dart b/app/third_party/xterm/lib/src/core/cursor.dart index 0bb3c17e..99428315 100644 --- a/app/third_party/xterm/lib/src/core/cursor.dart +++ b/app/third_party/xterm/lib/src/core/cursor.dart @@ -141,10 +141,19 @@ class CursorStyle { background = 0; // | CellColor.normal; } + /// SGR 0: colours and attributes back to normal. An open OSC 8 hyperlink + /// is not an SGR attribute and stays open. void reset() { foreground = 0; background = 0; - attrs = 0; + attrs &= CellAttr.linkMask; + } + + /// The OSC 8 hyperlink id written with the text, 0 for none. + int get linkId => (attrs & CellAttr.linkMask) >> CellAttr.linkShift; + + set linkId(int id) { + attrs = (attrs & ~CellAttr.linkMask) | ((id & 0xFFFF) << CellAttr.linkShift); } } diff --git a/app/third_party/xterm/lib/src/core/escape/emitter.dart b/app/third_party/xterm/lib/src/core/escape/emitter.dart index faf5d401..e697f73a 100644 --- a/app/third_party/xterm/lib/src/core/escape/emitter.dart +++ b/app/third_party/xterm/lib/src/core/escape/emitter.dart @@ -27,6 +27,15 @@ class EscapeEmitter { return '\x1b[200~$text\x1b[201~'; } + /// The reply to an OSC [which] (10, 11 or 12) colour query: `OSC Ps ; + /// rgb:rrrr/gggg/bbbb` with [terminator] (BEL or ST, as the query had). + String dynamicColor(int which, int rgb, String terminator) { + String channel(int shift) => + (((rgb >> shift) & 0xFF) * 0x101).toRadixString(16).padLeft(4, '0'); + return '\x1b]$which;rgb:${channel(16)}/${channel(8)}/${channel(0)}' + '$terminator'; + } + String size(int rows, int cols) { return '\x1b[8;$rows;${cols}t'; } diff --git a/app/third_party/xterm/lib/src/core/escape/handler.dart b/app/third_party/xterm/lib/src/core/escape/handler.dart index c6658a1e..68781a22 100644 --- a/app/third_party/xterm/lib/src/core/escape/handler.dart +++ b/app/third_party/xterm/lib/src/core/escape/handler.dart @@ -242,5 +242,21 @@ abstract class EscapeHandler { void setIconName(String name); + /// `OSC 7 ; URI ST`: the program's working directory, as a `file:` URI. + void setWorkingDirectory(String uri); + + /// `OSC 8 ; params ; URI ST`: text written from now on links to [uri]; + /// an empty [uri] ends the link. [params] is `key=value` pairs separated + /// by `:`, such as `id=x`. + void setHyperlink(String params, String uri); + + /// `OSC 10/11/12 ; ? ST`: report the foreground (10), background (11) or + /// cursor (12) colour, terminated with BEL when [bel] or ST otherwise. + void queryDynamicColor(int which, {required bool bel}); + + /// `OSC 52 ; Pc ; Pd ST`: set the clipboard selections [selection] (for + /// example `c`) to the base64 [data]. `?` asks to read the clipboard. + void setClipboard(String selection, String data); + void unknownOSC(String code, List args); } diff --git a/app/third_party/xterm/lib/src/core/escape/parser.dart b/app/third_party/xterm/lib/src/core/escape/parser.dart index 30a5744b..0f795be7 100644 --- a/app/third_party/xterm/lib/src/core/escape/parser.dart +++ b/app/third_party/xterm/lib/src/core/escape/parser.dart @@ -956,40 +956,78 @@ class EscapeParser { return false; } - if (_osc.isEmpty) { + final body = _oscBody.toString(); + _oscBody.clear(); + if (_oscAborted || body.isEmpty) { return true; } - // Common OSCs - if (_osc.length >= 2) { - final ps = _osc[0]; - final pt = _osc[1]; + final split = body.indexOf(';'); + final ps = split < 0 ? body : body.substring(0, split); + // Everything after the first separator; titles, URIs and clipboard + // data may contain more semicolons. + final pt = split < 0 ? '' : body.substring(split + 1); + final bel = _oscEndedWithBel; - switch (ps) { - case '0': - handler.setTitle(pt); - handler.setIconName(pt); - return true; - case '1': - handler.setIconName(pt); - return true; - case '2': - handler.setTitle(pt); - return true; - } + switch (ps) { + case '0': + handler.setTitle(pt); + handler.setIconName(pt); + return true; + case '1': + handler.setIconName(pt); + return true; + case '2': + handler.setTitle(pt); + return true; + case '7': + handler.setWorkingDirectory(pt); + return true; + case '8': + // `OSC 8 ; params ; URI ST`; an empty URI ends the link. + final uriAt = pt.indexOf(';'); + if (uriAt < 0) return true; + handler.setHyperlink(pt.substring(0, uriAt), pt.substring(uriAt + 1)); + return true; + case '10': + case '11': + case '12': + // `OSC 10 ; ? ST` queries the foreground; `OSC 10 ; ? ; ? ST` also + // the next dynamic colour (11), and so on. Setting them is ignored. + var color = int.parse(ps); + for (final spec in pt.split(';')) { + if (spec == '?' && color <= 12) { + handler.queryDynamicColor(color, bel: bel); + } + color++; + } + return true; + case '52': + final dataAt = pt.indexOf(';'); + if (dataAt < 0) return true; + handler.setClipboard(pt.substring(0, dataAt), pt.substring(dataAt + 1)); + return true; } // Private extensions - handler.unknownOSC(_osc[0], _osc.sublist(1)); + handler.unknownOSC(ps, split < 0 ? const [] : pt.split(';')); return true; } - final _osc = []; + /// The body of the OSC being parsed, without the terminator. + final _oscBody = StringBuffer(); + + /// Whether the last OSC ended with BEL rather than ST; a reply uses the + /// same terminator as the query. + var _oscEndedWithBel = false; + + /// Whether the last OSC was cut short by an ESC that was not ST. + var _oscAborted = false; bool _consumeOsc() { - _osc.clear(); - final param = StringBuffer(); + _oscBody.clear(); + _oscAborted = false; while (true) { if (_queue.isEmpty) { @@ -1000,7 +1038,7 @@ class EscapeParser { // OSC terminates with BEL if (char == Ascii.BEL) { - _osc.add(param.toString()); + _oscEndedWithBel = true; return true; } @@ -1010,21 +1048,24 @@ class EscapeParser { return false; } - if (_queue.consume() == Ascii.backslash) { - _osc.add(param.toString()); + if (_queue.peek() == Ascii.backslash) { + _queue.consume(); + _oscEndedWithBel = false; + } else { + // Any other escape cancels the OSC and starts a new sequence. + _queue.rollback(1); + _oscAborted = true; } return true; } - /// Parse next parameter - if (char == Ascii.semicolon) { - _osc.add(param.toString()); - param.clear(); - continue; + if (char == Ascii.CAN || char == Ascii.SUB) { + _oscAborted = true; + return true; } - param.writeCharCode(char); + _oscBody.writeCharCode(char); } } } diff --git a/app/third_party/xterm/lib/src/core/hyperlinks.dart b/app/third_party/xterm/lib/src/core/hyperlinks.dart new file mode 100644 index 00000000..b6349dec --- /dev/null +++ b/app/third_party/xterm/lib/src/core/hyperlinks.dart @@ -0,0 +1,34 @@ +/// The OSC 8 hyperlinks a terminal has seen. Cells store a 16-bit id (see +/// `CellAttr.linkMask`); this maps ids to their targets. Ids are never +/// reused, because cells in the scrollback may still refer to them; once +/// all ids are taken, new links are not recorded. +class HyperlinkTable { + static const maxLinks = 0xFFFF; + + final _uris = ['']; + + final _ids = {}; + + /// The id for a link to [uri] with OSC 8 [params], 0 when [uri] is empty + /// (the link ends) or the table is full. The same `id=` parameter and URI + /// share an id; links without an `id=` share one per URI. + int idFor(String params, String uri) { + if (uri.isEmpty) return 0; + final key = '${_idParam(params)}\u0000$uri'; + final known = _ids[key]; + if (known != null) return known; + if (_uris.length > maxLinks) return 0; + _uris.add(uri); + return _ids[key] = _uris.length - 1; + } + + /// The target of link [id], or null for 0 or an unknown id. + String? uriOf(int id) => id <= 0 || id >= _uris.length ? null : _uris[id]; + + static String _idParam(String params) { + for (final pair in params.split(':')) { + if (pair.startsWith('id=')) return pair.substring(3); + } + return ''; + } +} diff --git a/app/third_party/xterm/lib/src/terminal.dart b/app/third_party/xterm/lib/src/terminal.dart index ed15f168..12206578 100644 --- a/app/third_party/xterm/lib/src/terminal.dart +++ b/app/third_party/xterm/lib/src/terminal.dart @@ -1,10 +1,13 @@ +import 'dart:convert' show base64, utf8; import 'dart:math' show max; import 'package:xterm/src/base/observable.dart'; import 'package:xterm/src/core/buffer/buffer.dart'; import 'package:xterm/src/core/buffer/cell_offset.dart'; import 'package:xterm/src/core/buffer/line.dart'; +import 'package:xterm/src/core/cell.dart'; import 'package:xterm/src/core/cursor.dart'; +import 'package:xterm/src/core/hyperlinks.dart'; import 'package:xterm/src/core/escape/emitter.dart'; import 'package:xterm/src/core/escape/handler.dart'; import 'package:xterm/src/core/escape/parser.dart'; @@ -65,6 +68,35 @@ class Terminal with Observable implements TerminalState, EscapeHandler { /// escape sequence. void Function(String code, List args)? onPrivateOSC; + /// Called when the program reports its working directory with OSC 7, as + /// a `file://host/path` URI. + void Function(String uri)? onWorkingDirectoryChange; + + /// Called when the program sets the clipboard with OSC 52. [selection] + /// names the targets (`c` clipboard, `p` primary, ...; may be empty). + /// Reading the clipboard through OSC 52 is not supported. + void Function(String text, String selection)? onClipboardSet; + + /// The colours OSC 10, 11 and 12 queries report (0xRRGGBB). A view sets + /// them from its theme; see [setReportedColors]. + int reportedForeground = 0xFFFFFF; + int reportedBackground = 0x000000; + int reportedCursor = 0xFFFFFF; + + /// Sets the colours reported to OSC 10 (foreground), 11 (background) and + /// 12 (cursor) queries, each 0xRRGGBB. + void setReportedColors({ + required int foreground, + required int background, + required int cursor, + }) { + reportedForeground = foreground & 0xFFFFFF; + reportedBackground = background & 0xFFFFFF; + reportedCursor = cursor & 0xFFFFFF; + } + + final _hyperlinks = HyperlinkTable(); + /// Flag to toggle os specific behaviors. final TerminalTargetPlatform platform; @@ -530,7 +562,9 @@ class Terminal with Observable implements TerminalState, EscapeHandler { /// The state shared by RIS and DECSTR. void _resetModes() { - _cursorStyle.reset(); + _cursorStyle + ..reset() + ..attrs = 0; // an open hyperlink ends too _insertMode = false; _originMode = false; _autoWrapMode = true; @@ -1022,4 +1056,50 @@ class Terminal with Observable implements TerminalState, EscapeHandler { void unknownOSC(String ps, List pt) { onPrivateOSC?.call(ps, pt); } + + @override + void setWorkingDirectory(String uri) { + onWorkingDirectoryChange?.call(uri); + } + + @override + void setHyperlink(String params, String uri) { + _cursorStyle.linkId = _hyperlinks.idFor(params, uri); + } + + /// The OSC 8 hyperlink target of the cell at [x] in [line], or null. + String? hyperlinkAt(BufferLine line, int x) { + if (x < 0 || x >= line.length) return null; + return hyperlinkOf(line.getAttributes(x)); + } + + /// The OSC 8 hyperlink target recorded in cell attributes [attrs]. + String? hyperlinkOf(int attrs) => + _hyperlinks.uriOf((attrs & CellAttr.linkMask) >> CellAttr.linkShift); + + @override + void queryDynamicColor(int which, {required bool bel}) { + final color = switch (which) { + 10 => reportedForeground, + 11 => reportedBackground, + _ => reportedCursor, + }; + onOutput?.call( + _emitter.dynamicColor(which, color, bel ? '\x07' : '\x1b\\'), + ); + } + + @override + void setClipboard(String selection, String data) { + // Reading the clipboard (`?`) is deliberately not supported: a program + // could otherwise read whatever the user copied elsewhere. + if (data == '?') return; + final String text; + try { + text = utf8.decode(base64.decode(data), allowMalformed: true); + } on FormatException { + return; + } + onClipboardSet?.call(text, selection); + } } diff --git a/app/third_party/xterm/lib/src/ui/render.dart b/app/third_party/xterm/lib/src/ui/render.dart index 547d76f1..7154b8a4 100644 --- a/app/third_party/xterm/lib/src/ui/render.dart +++ b/app/third_party/xterm/lib/src/ui/render.dart @@ -57,6 +57,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { if (attached) _terminal.removeListener(_onTerminalChange); _terminal = terminal; if (attached) _terminal.addListener(_onTerminalChange); + _reportThemeColors(); _resizeTerminalIfNeeded(); markNeedsLayout(); } @@ -108,9 +109,20 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { set theme(TerminalTheme value) { if (value == _painter.theme) return; _painter.theme = value; + _reportThemeColors(); markNeedsPaint(); } + /// Lets OSC 10/11/12 colour queries answer with this view's theme. + void _reportThemeColors() { + final theme = _painter.theme; + _terminal.setReportedColors( + foreground: theme.foreground.toARGB32(), + background: theme.background.toARGB32(), + cursor: theme.cursor.toARGB32(), + ); + } + FocusNode _focusNode; set focusNode(FocusNode value) { if (value == _focusNode) return; @@ -179,6 +191,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { @override void attach(PipelineOwner owner) { super.attach(owner); + _reportThemeColors(); _offset.addListener(_onScroll); _terminal.addListener(_onTerminalChange); _controller.addListener(_onControllerUpdate); diff --git a/app/third_party/xterm/lib/src/utils/debugger.dart b/app/third_party/xterm/lib/src/utils/debugger.dart index ca9125aa..8ab4daf3 100644 --- a/app/third_party/xterm/lib/src/utils/debugger.dart +++ b/app/third_party/xterm/lib/src/utils/debugger.dart @@ -471,6 +471,26 @@ class _TerminalDebuggerHandler implements EscapeHandler { onCommand('setCursorUnderline'); } + @override + void setWorkingDirectory(String uri) { + onCommand('setWorkingDirectory $uri'); + } + + @override + void setHyperlink(String params, String uri) { + onCommand('setHyperlink $params $uri'); + } + + @override + void queryDynamicColor(int which, {required bool bel}) { + onCommand('queryDynamicColor $which'); + } + + @override + void setClipboard(String selection, String data) { + onCommand('setClipboard $selection'); + } + @override void setCursorShape(int shape) { onCommand('setCursorShape $shape');