From a6e04895ba74afa261c85d127af3d305090c1b90 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:17:41 +0000 Subject: [PATCH 01/17] Vendor pristine xterm.dart 4.0.0 under app/third_party/xterm Unmodified copy of lib/, LICENSE (MIT), pubspec.yaml and CHANGELOG.md from pub.dev xterm 4.0.0; the upstream README is kept as UPSTREAM_README.md. Committed on its own so later patches are reviewable as diffs. Co-Authored-By: Claude Opus 5.5 --- app/third_party/xterm/CHANGELOG.md | 277 ++++ app/third_party/xterm/LICENSE | 21 + app/third_party/xterm/UPSTREAM_README.md | 125 ++ app/third_party/xterm/lib/core.dart | 22 + .../xterm/lib/src/base/disposable.dart | 41 + app/third_party/xterm/lib/src/base/event.dart | 42 + .../xterm/lib/src/base/observable.dart | 17 + .../xterm/lib/src/core/buffer/buffer.dart | 604 +++++++++ .../xterm/lib/src/core/buffer/cell_flags.dart | 9 + .../lib/src/core/buffer/cell_offset.dart | 55 + .../xterm/lib/src/core/buffer/line.dart | 418 ++++++ .../xterm/lib/src/core/buffer/range.dart | 55 + .../lib/src/core/buffer/range_block.dart | 111 ++ .../xterm/lib/src/core/buffer/range_line.dart | 66 + .../xterm/lib/src/core/buffer/segment.dart | 58 + app/third_party/xterm/lib/src/core/cell.dart | 66 + .../xterm/lib/src/core/charset.dart | 95 ++ app/third_party/xterm/lib/src/core/color.dart | 19 + .../xterm/lib/src/core/cursor.dart | 137 ++ .../xterm/lib/src/core/escape/emitter.dart | 33 + .../xterm/lib/src/core/escape/handler.dart | 215 +++ .../xterm/lib/src/core/escape/parser.dart | 1154 +++++++++++++++++ .../xterm/lib/src/core/input/handler.dart | 210 +++ .../xterm/lib/src/core/input/keys.dart | 835 ++++++++++++ .../lib/src/core/input/keytab/keytab.dart | 113 ++ .../src/core/input/keytab/keytab_default.dart | 213 +++ .../src/core/input/keytab/keytab_escape.dart | 21 + .../src/core/input/keytab/keytab_parse.dart | 186 +++ .../src/core/input/keytab/keytab_record.dart | 134 ++ .../src/core/input/keytab/keytab_token.dart | 179 +++ .../lib/src/core/input/keytab/qt_keyname.dart | 477 +++++++ .../xterm/lib/src/core/mouse/button.dart | 29 + .../lib/src/core/mouse/button_state.dart | 5 + .../xterm/lib/src/core/mouse/handler.dart | 114 ++ .../xterm/lib/src/core/mouse/mode.dart | 36 + .../xterm/lib/src/core/mouse/reporter.dart | 48 + .../xterm/lib/src/core/platform.dart | 17 + .../xterm/lib/src/core/reflow.dart | 197 +++ .../xterm/lib/src/core/snapshot.dart | 3 + app/third_party/xterm/lib/src/core/state.dart | 44 + app/third_party/xterm/lib/src/core/tabs.dart | 68 + app/third_party/xterm/lib/src/terminal.dart | 906 +++++++++++++ .../xterm/lib/src/terminal_view.dart | 533 ++++++++ .../xterm/lib/src/ui/char_metrics.dart | 21 + .../xterm/lib/src/ui/controller.dart | 174 +++ .../xterm/lib/src/ui/cursor_type.dart | 7 + .../xterm/lib/src/ui/custom_text_edit.dart | 281 ++++ .../lib/src/ui/gesture/gesture_detector.dart | 162 +++ .../lib/src/ui/gesture/gesture_handler.dart | 191 +++ .../lib/src/ui/infinite_scroll_view.dart | 115 ++ .../xterm/lib/src/ui/input_map.dart | 288 ++++ .../xterm/lib/src/ui/keyboard_listener.dart | 49 + .../xterm/lib/src/ui/keyboard_visibility.dart | 58 + app/third_party/xterm/lib/src/ui/painter.dart | 279 ++++ .../xterm/lib/src/ui/palette_builder.dart | 118 ++ .../xterm/lib/src/ui/paragraph_cache.dart | 51 + .../xterm/lib/src/ui/pointer_input.dart | 29 + app/third_party/xterm/lib/src/ui/render.dart | 552 ++++++++ .../xterm/lib/src/ui/scroll_handler.dart | 133 ++ .../xterm/lib/src/ui/selection_mode.dart | 5 + .../xterm/lib/src/ui/shortcut/actions.dart | 71 + .../xterm/lib/src/ui/shortcut/shortcuts.dart | 34 + .../xterm/lib/src/ui/terminal_size.dart | 24 + .../xterm/lib/src/ui/terminal_text_style.dart | 87 ++ .../xterm/lib/src/ui/terminal_theme.dart | 57 + app/third_party/xterm/lib/src/ui/themes.dart | 56 + .../xterm/lib/src/utils/ascii.dart | 403 ++++++ .../xterm/lib/src/utils/byte_consumer.dart | 107 ++ .../xterm/lib/src/utils/char_code.dart | 5 + .../xterm/lib/src/utils/circular_buffer.dart | 315 +++++ .../xterm/lib/src/utils/debugger.dart | 595 +++++++++ .../xterm/lib/src/utils/debugger_view.dart | 170 +++ .../xterm/lib/src/utils/hash_values.dart | 111 ++ .../xterm/lib/src/utils/lookup_table.dart | 34 + .../xterm/lib/src/utils/unicode_v11.dart | 512 ++++++++ app/third_party/xterm/lib/suggestion.dart | 199 +++ app/third_party/xterm/lib/ui.dart | 10 + app/third_party/xterm/lib/utils.dart | 2 + app/third_party/xterm/lib/xterm.dart | 3 + app/third_party/xterm/lib/zmodem.dart | 312 +++++ app/third_party/xterm/pubspec.yaml | 61 + 81 files changed, 13689 insertions(+) create mode 100644 app/third_party/xterm/CHANGELOG.md create mode 100644 app/third_party/xterm/LICENSE create mode 100644 app/third_party/xterm/UPSTREAM_README.md create mode 100644 app/third_party/xterm/lib/core.dart create mode 100644 app/third_party/xterm/lib/src/base/disposable.dart create mode 100644 app/third_party/xterm/lib/src/base/event.dart create mode 100644 app/third_party/xterm/lib/src/base/observable.dart create mode 100644 app/third_party/xterm/lib/src/core/buffer/buffer.dart create mode 100644 app/third_party/xterm/lib/src/core/buffer/cell_flags.dart create mode 100644 app/third_party/xterm/lib/src/core/buffer/cell_offset.dart create mode 100644 app/third_party/xterm/lib/src/core/buffer/line.dart create mode 100644 app/third_party/xterm/lib/src/core/buffer/range.dart create mode 100644 app/third_party/xterm/lib/src/core/buffer/range_block.dart create mode 100644 app/third_party/xterm/lib/src/core/buffer/range_line.dart create mode 100644 app/third_party/xterm/lib/src/core/buffer/segment.dart create mode 100644 app/third_party/xterm/lib/src/core/cell.dart create mode 100644 app/third_party/xterm/lib/src/core/charset.dart create mode 100644 app/third_party/xterm/lib/src/core/color.dart create mode 100644 app/third_party/xterm/lib/src/core/cursor.dart create mode 100644 app/third_party/xterm/lib/src/core/escape/emitter.dart create mode 100644 app/third_party/xterm/lib/src/core/escape/handler.dart create mode 100644 app/third_party/xterm/lib/src/core/escape/parser.dart create mode 100644 app/third_party/xterm/lib/src/core/input/handler.dart create mode 100644 app/third_party/xterm/lib/src/core/input/keys.dart create mode 100644 app/third_party/xterm/lib/src/core/input/keytab/keytab.dart create mode 100644 app/third_party/xterm/lib/src/core/input/keytab/keytab_default.dart create mode 100644 app/third_party/xterm/lib/src/core/input/keytab/keytab_escape.dart create mode 100644 app/third_party/xterm/lib/src/core/input/keytab/keytab_parse.dart create mode 100644 app/third_party/xterm/lib/src/core/input/keytab/keytab_record.dart create mode 100644 app/third_party/xterm/lib/src/core/input/keytab/keytab_token.dart create mode 100644 app/third_party/xterm/lib/src/core/input/keytab/qt_keyname.dart create mode 100644 app/third_party/xterm/lib/src/core/mouse/button.dart create mode 100644 app/third_party/xterm/lib/src/core/mouse/button_state.dart create mode 100644 app/third_party/xterm/lib/src/core/mouse/handler.dart create mode 100644 app/third_party/xterm/lib/src/core/mouse/mode.dart create mode 100644 app/third_party/xterm/lib/src/core/mouse/reporter.dart create mode 100644 app/third_party/xterm/lib/src/core/platform.dart create mode 100644 app/third_party/xterm/lib/src/core/reflow.dart create mode 100644 app/third_party/xterm/lib/src/core/snapshot.dart create mode 100644 app/third_party/xterm/lib/src/core/state.dart create mode 100644 app/third_party/xterm/lib/src/core/tabs.dart create mode 100644 app/third_party/xterm/lib/src/terminal.dart create mode 100644 app/third_party/xterm/lib/src/terminal_view.dart create mode 100644 app/third_party/xterm/lib/src/ui/char_metrics.dart create mode 100644 app/third_party/xterm/lib/src/ui/controller.dart create mode 100644 app/third_party/xterm/lib/src/ui/cursor_type.dart create mode 100644 app/third_party/xterm/lib/src/ui/custom_text_edit.dart create mode 100644 app/third_party/xterm/lib/src/ui/gesture/gesture_detector.dart create mode 100644 app/third_party/xterm/lib/src/ui/gesture/gesture_handler.dart create mode 100644 app/third_party/xterm/lib/src/ui/infinite_scroll_view.dart create mode 100644 app/third_party/xterm/lib/src/ui/input_map.dart create mode 100644 app/third_party/xterm/lib/src/ui/keyboard_listener.dart create mode 100644 app/third_party/xterm/lib/src/ui/keyboard_visibility.dart create mode 100644 app/third_party/xterm/lib/src/ui/painter.dart create mode 100644 app/third_party/xterm/lib/src/ui/palette_builder.dart create mode 100644 app/third_party/xterm/lib/src/ui/paragraph_cache.dart create mode 100644 app/third_party/xterm/lib/src/ui/pointer_input.dart create mode 100644 app/third_party/xterm/lib/src/ui/render.dart create mode 100644 app/third_party/xterm/lib/src/ui/scroll_handler.dart create mode 100644 app/third_party/xterm/lib/src/ui/selection_mode.dart create mode 100644 app/third_party/xterm/lib/src/ui/shortcut/actions.dart create mode 100644 app/third_party/xterm/lib/src/ui/shortcut/shortcuts.dart create mode 100644 app/third_party/xterm/lib/src/ui/terminal_size.dart create mode 100644 app/third_party/xterm/lib/src/ui/terminal_text_style.dart create mode 100644 app/third_party/xterm/lib/src/ui/terminal_theme.dart create mode 100644 app/third_party/xterm/lib/src/ui/themes.dart create mode 100644 app/third_party/xterm/lib/src/utils/ascii.dart create mode 100644 app/third_party/xterm/lib/src/utils/byte_consumer.dart create mode 100644 app/third_party/xterm/lib/src/utils/char_code.dart create mode 100644 app/third_party/xterm/lib/src/utils/circular_buffer.dart create mode 100644 app/third_party/xterm/lib/src/utils/debugger.dart create mode 100644 app/third_party/xterm/lib/src/utils/debugger_view.dart create mode 100644 app/third_party/xterm/lib/src/utils/hash_values.dart create mode 100644 app/third_party/xterm/lib/src/utils/lookup_table.dart create mode 100644 app/third_party/xterm/lib/src/utils/unicode_v11.dart create mode 100644 app/third_party/xterm/lib/suggestion.dart create mode 100644 app/third_party/xterm/lib/ui.dart create mode 100644 app/third_party/xterm/lib/utils.dart create mode 100644 app/third_party/xterm/lib/xterm.dart create mode 100644 app/third_party/xterm/lib/zmodem.dart create mode 100644 app/third_party/xterm/pubspec.yaml diff --git a/app/third_party/xterm/CHANGELOG.md b/app/third_party/xterm/CHANGELOG.md new file mode 100644 index 00000000..2fcd6152 --- /dev/null +++ b/app/third_party/xterm/CHANGELOG.md @@ -0,0 +1,277 @@ +## [4.0.0] - 2024-02-27 +* Update for Flutter 3.19 [#190]. Thanks [@domesticmouse]. +* Fix designate charset logic [#186]. Thanks [@djnalluri]. + +## [3.6.1-pre] - 2023-04-28 +* Add Termianl.onPrivateOSC callback +* Copy shortcut on Windows default to Ctrl+Shift+V (#173) + +## [3.6.0-pre] - 2023-04-27 +* Basic ZMODEM support + +## [3.5.0] - 2023-04-20 +* Support customizing word separators for selection [#160]. Thanks [@itzhoujun]. +* Fix incorrect tab stop handling [#161]. Thanks [@itzhoujun]. +* Added support for Ctrl+Home, Ctrl+End etc [#169]. Thanks [@nuc134r]. + +## [3.4.1] - 2023-01-27 +* Fix Flutter 3.7 incompatibilities [#151], thanks [@jpnurmi]. + +## [3.4.0] - 2022-11-4 +* Mouse input is enabled by default. +* Support scrolling in alternate buffer. +* Fix `deleteLines` behavior. +* Fix `eraseDisplayFromCursor` removes characters before the cursor. + +## [3.3.0] - 2022-10-30 +* Sync ShortcutManager's shortcuts in didUpdateWidget [#140], thanks [@jpnurmi]. +* fix: terminal font size not respecting system level font scale [#138], thanks [@LucasAschenbach]. +* Fix selection color [#135], thanks [@jpnurmi]. +* fix: dispose controllers of TerminalView [#132], thanks [@tauu]. +* feat: add hardwareKeyboardOnly flag to TerminalView [#131], thanks [@tauu]. +* feat: initial mouse support [#130], thanks [@tauu]. +* feat: limited window manipulation support [#129], thanks [@tauu]. +* fix: workaround to draw underlined spaces [#128], thanks [@tauu]. +* feat: block selection [#127], thanks [@tauu]. +* feat: enable changing the inputHandler of a terminal [#126], thanks [@tauu]. +* fix: export TerminalTargetPlatform [#125], thanks [@tauu]. +* fix: only dispose the FocusNodes which TerminalView creates [#124], thanks [@tauu]. +* feat: expose readOnly flag of CustomTextEdit in TerminalView [#123], thanks [@tauu]. +* fix: supports numpad enter key [#137]. +* feat: expose `reflowEnabled` flag [#104]. +* docs: add virtual keyboard example [#141]. + +## [3.2.7] - 2022-9-13 +* Fix lint issues. + +## [3.2.6] - 2022-9-13 +* First stable release of xterm.dart v3. + +## [3.2.6-alpha] - 2022-9-13 +* Fix new line width in reflow. + +## [3.2.5-alpha] - 2022-9-12 +* Fix intent related issue. + +## [3.2.4-alpha] - 2022-9-12 +* Use flutter native shortcut intents. + +## [3.2.3-alpha] - 2022-9-12 +* Export shortcut related classes. + +## [3.2.2-alpha] - 2022-9-12 +* Implement default keyboard shortcuts. + +## [3.2.1-alpha] - 2022-9-12 +* Disable optional line scroll mode that is under development. + +## [3.2.0-alpha] - 2022-9-12 +* Enhanced selection handing. +* More tests. + +## [3.1.0-alpha] - 2022-9-4 +* Update dependencies & merge into master + +## [3.0.6-alpha] - 2022-4-4 +* Export `TerminalViewState` +* Added `onTap` callback to `TerminalView` + +## [3.0.5-alpha] - 2022-4-4 +* Avoid resize when `RenderBox.size` is zero. +* Added `charInput` and `textInput`method. +* Added `requestKeyboard`, `closeKeyboard` and `hasInputConnection`method. +* Export `KeyboardVisibilty` + +## [3.0.4-alpha] - 2022-4-1 +* Improved text editing +* Added composing state painting +* Adapt to `MediaQuery.padding` + +## [3.0.3-alpha] - 2022-3-28 +* Improved scroll handing +* Improved resize handing +* Fix focus repaint +* Fix OSC title update + +## [3.0.2-alpha] - 2022-3-28 +* Re-design `KeyboardVisibilty` + +## [3.0.1-alpha] - 2022-3-27 +* Add `KeyboardVisibilty` + +## [3.0.0-alpha] - 2022-3-26 +* Initial release of v3. + +## [2.6.0] - 2021-12-28 +* Add scrollBehavior field to the TerminalView class [#55]. +* Feature: Search [#60]. Thanks [@devmil]. +* Fixes for occasional unintended multi character input [#61]. Thanks [@devmil]. +* Fixes ALT + L for a Mac (German Layout) [#62]. Thanks [@devmil]. +* Fixes example build problem of flutter-windows for new version of flutter [#63]. Thanks [@linhanyu]. +* Fixes inverse color text (when background == 0) [#66]. Thanks [@devmil]. +* Fixes assert of scrollController.position [#67]. Thanks [@linhanyu]. +* Change interface of ssh.dart example to satisfied new dartssh [#69]. Thanks [@linhanyu]. +* add configuration options for keyboard [#74]. Thanks [@jda258]. +* Adds check if the TerminalIsolate has already been started [#77]. Thanks [@devmil]. + +## [2.5.0-pre] - 2021-8-4 +* Support select word / whole row via double tap [#40]. Thanks [@devmil]. +* Adds "selectAll" to TerminalUiInteraction [#43]. Thanks [@devmil]. +* Fixes sgr processing [#44],[#45]. Thanks [@devmil]. +* Adds blinking Cursor support [#46]. Thanks [@devmil]. +* Fixes Zoom adaptions on non active buffer [#47]. Thanks [@devmil]. +* Adds Padding option to TerminalView [#48]. Thanks [@devmil]. +* Removes no longer supported LogicalKeyboardKey [#49]. Thanks [@devmil]. +* Adds the composing state [#50]. Thanks [@devmil]. +* Fix scroll problem in mobile device [#51]. Thanks [@linhanyu]. + +## [2.4.0-pre] - 2021-6-13 +* Update the signature of TerminalBackend.resize() to also receive dimensions in + pixels[(#39)](https://github.com/TerminalStudio/xterm.dart/pull/39). Thanks [@michaellee8](https://github.com/michaellee8). + +## [2.3.1-pre] - 2021-6-1 +* Export `theme/terminal_style.dart` + +## [2.3.0-pre] - 2021-6-1 +* Add `import 'package:xterm/isolate.dart';` + +## [2.2.1-pre] - 2021-6-1 +* Make BufferLine work on web. + +## [2.2.0-pre] - 2021-4-12 + +## [2.1.0-pre] - 2021-3-20 +* Better support for resizing and scrolling. +* Reflow support (in progress [#13](https://github.com/TerminalStudio/xterm.dart/pull/13)), thanks [@devmil](https://github.com/devmil). + +## [2.0.0] - 2021-3-7 +* Clean up for release + +## [2.0.0-pre] - 2021-3-7 +* Migrate to nnbd + +## [1.3.0] - 2021-2-24 +* Performance improvement. + +## [1.2.0] - 2021-2-15 + +* Pass TerminalView's autofocus to the InputListener that it creates. [#10](https://github.com/TerminalStudio/xterm.dart/pull/10), thanks [@timburks](https://github.com/timburks) + +## [1.2.0-pre] - 2021-1-20 + +* add the ability to use fonts from the google_fonts package [#9](https://github.com/TerminalStudio/xterm.dart/pull/9) + +## [1.1.1+1] - 2020-10-4 + +* Update readme + + +## [1.1.1] - 2020-10-4 + +* Add brightWhite to TerminalTheme + +## [1.1.0] - 2020-9-29 + +* Fix web support. + +## [1.0.2] - 2020-9-29 + +* Update link. + +## [1.0.1] - 2020-9-29 + +* Disable debug print. + +## [1.0.0] - 2020-9-28 + +* Update readme. + +## [1.0.0-dev] - 2020-9-28 + +* Major issues are fixed. + +## [0.1.0] - 2020-8-9 + +* Bug fixes + +## [0.0.4] - 2020-8-1 + +* Revert version constrain + +## [0.0.3] - 2020-8-1 + +* Update version constrain + + +## [0.0.2] - 2020-8-1 + +* Update readme + + +## [0.0.1] - 2020-8-1 + +* First version + + +[@devmil]: https://github.com/devmil +[@michaellee8]: https://github.com/michaellee8 +[@linhanyu]: https://github.com/linhanyu +[@jda258]: https://github.com/jda258 +[@jpnurmi]: https://github.com/jpnurmi +[@LucasAschenbach]: https://github.com/LucasAschenbach +[@tauu]: https://github.com/tauu +[@itzhoujun]: https://github.com/itzhoujun +[@nuc134r]: https://github.com/nuc134r +[@djnalluri]: https://github.com/djnalluri +[@domesticmouse]: https://github.com/domesticmouse + + +[#40]: https://github.com/TerminalStudio/xterm.dart/pull/40 +[#43]: https://github.com/TerminalStudio/xterm.dart/pull/43 +[#44]: https://github.com/TerminalStudio/xterm.dart/pull/44 +[#45]: https://github.com/TerminalStudio/xterm.dart/pull/45 +[#46]: https://github.com/TerminalStudio/xterm.dart/pull/46 +[#47]: https://github.com/TerminalStudio/xterm.dart/pull/47 +[#48]: https://github.com/TerminalStudio/xterm.dart/pull/48 +[#49]: https://github.com/TerminalStudio/xterm.dart/pull/49 +[#50]: https://github.com/TerminalStudio/xterm.dart/pull/50 +[#51]: https://github.com/TerminalStudio/xterm.dart/pull/51 + + +[#55]: https://github.com/TerminalStudio/xterm.dart/pull/55 +[#60]: https://github.com/TerminalStudio/xterm.dart/pull/60 +[#61]: https://github.com/TerminalStudio/xterm.dart/pull/61 +[#62]: https://github.com/TerminalStudio/xterm.dart/pull/62 +[#63]: https://github.com/TerminalStudio/xterm.dart/pull/63 +[#66]: https://github.com/TerminalStudio/xterm.dart/pull/66 +[#67]: https://github.com/TerminalStudio/xterm.dart/pull/67 +[#69]: https://github.com/TerminalStudio/xterm.dart/pull/69 +[#74]: https://github.com/TerminalStudio/xterm.dart/pull/74 +[#77]: https://github.com/TerminalStudio/xterm.dart/pull/77 + +[#104]: https://github.com/TerminalStudio/xterm.dart/issues/104 +[#123]: https://github.com/TerminalStudio/xterm.dart/pull/123 +[#124]: https://github.com/TerminalStudio/xterm.dart/pull/124 +[#125]: https://github.com/TerminalStudio/xterm.dart/pull/125 +[#126]: https://github.com/TerminalStudio/xterm.dart/pull/126 +[#127]: https://github.com/TerminalStudio/xterm.dart/pull/127 +[#128]: https://github.com/TerminalStudio/xterm.dart/pull/128 +[#129]: https://github.com/TerminalStudio/xterm.dart/pull/129 +[#130]: https://github.com/TerminalStudio/xterm.dart/pull/130 +[#131]: https://github.com/TerminalStudio/xterm.dart/pull/131 +[#132]: https://github.com/TerminalStudio/xterm.dart/pull/132 +[#135]: https://github.com/TerminalStudio/xterm.dart/pull/135 +[#137]: https://github.com/TerminalStudio/xterm.dart/issues/137 +[#138]: https://github.com/TerminalStudio/xterm.dart/pull/138 +[#140]: https://github.com/TerminalStudio/xterm.dart/pull/140 +[#141]: https://github.com/TerminalStudio/xterm.dart/pull/141 + +[#151]: https://github.com/TerminalStudio/xterm.dart/pull/151 + +[#160]: https://github.com/TerminalStudio/xterm.dart/pull/160 +[#161]: https://github.com/TerminalStudio/xterm.dart/pull/161 +[#169]: https://github.com/TerminalStudio/xterm.dart/pull/169 + +[#186]: https://github.com/TerminalStudio/xterm.dart/pull/186 +[#190]: https://github.com/TerminalStudio/xterm.dart/pull/190 + diff --git a/app/third_party/xterm/LICENSE b/app/third_party/xterm/LICENSE new file mode 100644 index 00000000..7a5fd3e8 --- /dev/null +++ b/app/third_party/xterm/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 xuty + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/app/third_party/xterm/UPSTREAM_README.md b/app/third_party/xterm/UPSTREAM_README.md new file mode 100644 index 00000000..5fb41fcb --- /dev/null +++ b/app/third_party/xterm/UPSTREAM_README.md @@ -0,0 +1,125 @@ + +## xterm.dart + +

+ + Actions + + + Package version + + GitHub repo size + GitHub issues + GitHub pull requests +

+ + +**xterm.dart** is a fast and fully-featured terminal emulator for Flutter applications, with support for mobile and desktop platforms. + +> This package requires Flutter version >=3.0.0 + +## Screenshots + + + + + + + + + + +
+ + + +
+ + + +
+ +## Features + +- 📦 **Works out of the box** No special configuration required. +- 🚀 **Fast** Renders at 60fps. +- 😀 **Wide character support** Supports CJK and emojis. +- ✂️ **Customizable** +- ✔ **Frontend independent**: The terminal core can work without flutter frontend. + +**What's new in 3.0.0:** + +- 📱 Enhanced support for **mobile** platforms. +- ⌨️ Integrates with Flutter's **shortcut** system. +- 🎨 Allows changing **theme** at runtime. +- 💪 Better **performance**. No tree rebuilds anymore. +- 🈂️ Works with **IMEs**. + +## Getting Started + +**1.** Add this to your package's pubspec.yaml file: + +```yml +dependencies: + ... + xterm: ^3.2.6 +``` + +**2.** Create the terminal: + +```dart +import 'package:xterm/xterm.dart'; +... +terminal = Terminal(); +``` + +Listen to user interaction with the terminal by simply adding a `onOutput` callback: + +```dart +terminal = Terminal(); + +terminal.onOutput = (output) { + print('output: $output'); +} +``` + +**3.** Create the view, attach the terminal to the view: + +```dart +import 'package:xterm/flutter.dart'; +... +child: TerminalView(terminal), +``` + +**4.** Write something to the terminal: + +```dart +terminal.write('Hello, world!'); +``` + +**Done!** + +## More examples + +- Write a simple terminal in ~100 lines of code: + https://github.com/TerminalStudio/xterm.dart/blob/master/example/lib/main.dart + +- Write a SSH client in ~100 lines of code with [dartssh2]: + https://github.com/TerminalStudio/xterm.dart/blob/master/example/lib/ssh.dart + + + +For a complete project built with xterm.dart, check out [TerminalStudio]. + +## Features and bugs + +Please file feature requests and bugs at the [issue tracker](https://github.com/TerminalStudio/xterm.dart/issues). + +Contributions are always welcome! + +## License + +This project is licensed under an MIT license. + +[dartssh2]: https://pub.dev/packages/dartssh2 +[TerminalStudio]: https://github.com/TerminalStudio/studio \ No newline at end of file diff --git a/app/third_party/xterm/lib/core.dart b/app/third_party/xterm/lib/core.dart new file mode 100644 index 00000000..ffe7f1cc --- /dev/null +++ b/app/third_party/xterm/lib/core.dart @@ -0,0 +1,22 @@ +export 'src/core/buffer/buffer.dart'; +export 'src/core/buffer/cell_flags.dart'; +export 'src/core/buffer/cell_offset.dart'; +export 'src/core/buffer/line.dart'; +export 'src/core/buffer/range.dart'; +export 'src/core/buffer/range_block.dart'; +export 'src/core/buffer/range_line.dart'; +export 'src/core/buffer/segment.dart'; +export 'src/core/cell.dart'; +export 'src/core/color.dart'; +export 'src/core/cursor.dart'; +export 'src/core/escape/handler.dart'; +export 'src/core/escape/parser.dart'; +export 'src/core/input/handler.dart'; +export 'src/core/input/keys.dart'; +export 'src/core/mouse/button.dart'; +export 'src/core/mouse/button_state.dart'; +export 'src/core/mouse/handler.dart'; +export 'src/core/mouse/mode.dart'; +export 'src/core/platform.dart'; +export 'src/core/state.dart'; +export 'src/terminal.dart'; diff --git a/app/third_party/xterm/lib/src/base/disposable.dart b/app/third_party/xterm/lib/src/base/disposable.dart new file mode 100644 index 00000000..c6dc023c --- /dev/null +++ b/app/third_party/xterm/lib/src/base/disposable.dart @@ -0,0 +1,41 @@ +import 'package:xterm/src/base/event.dart'; + +mixin Disposable { + final _disposables = []; + + bool get disposed => _disposed; + bool _disposed = false; + + Event get onDisposed => _onDisposed.event; + final _onDisposed = EventEmitter(); + + void register(Disposable disposable) { + assert(!_disposed); + _disposables.add(disposable); + } + + void registerCallback(void Function() callback) { + assert(!_disposed); + _disposables.add(_DisposeCallback(callback)); + } + + void dispose() { + _disposed = true; + for (final disposable in _disposables) { + disposable.dispose(); + } + _onDisposed.emit(null); + } +} + +class _DisposeCallback with Disposable { + final void Function() callback; + + _DisposeCallback(this.callback); + + @override + void dispose() { + super.dispose(); + callback(); + } +} diff --git a/app/third_party/xterm/lib/src/base/event.dart b/app/third_party/xterm/lib/src/base/event.dart new file mode 100644 index 00000000..3987332e --- /dev/null +++ b/app/third_party/xterm/lib/src/base/event.dart @@ -0,0 +1,42 @@ +import 'package:xterm/src/base/disposable.dart'; + +typedef EventListener = void Function(T event); + +class Event { + final EventEmitter emitter; + + Event(this.emitter); + + void call(EventListener listener) { + emitter(listener); + } +} + +class EventEmitter { + final _listeners = >[]; + + EventSubscription call(EventListener listener) { + _listeners.add(listener); + return EventSubscription(this, listener); + } + + void emit(T event) { + for (final listener in _listeners) { + listener(event); + } + } + + Event get event => Event(this); +} + +class EventSubscription with Disposable { + final EventEmitter emitter; + final EventListener listener; + + EventSubscription(this.emitter, this.listener); + + @override + void dispose() { + emitter._listeners.remove(listener); + } +} diff --git a/app/third_party/xterm/lib/src/base/observable.dart b/app/third_party/xterm/lib/src/base/observable.dart new file mode 100644 index 00000000..ac2b78a5 --- /dev/null +++ b/app/third_party/xterm/lib/src/base/observable.dart @@ -0,0 +1,17 @@ +mixin Observable { + final listeners = {}; + + void addListener(void Function() listener) { + listeners.add(listener); + } + + void removeListener(void Function() listener) { + listeners.remove(listener); + } + + void notifyListeners() { + for (var listener in listeners) { + listener(); + } + } +} diff --git a/app/third_party/xterm/lib/src/core/buffer/buffer.dart b/app/third_party/xterm/lib/src/core/buffer/buffer.dart new file mode 100644 index 00000000..10789382 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/buffer/buffer.dart @@ -0,0 +1,604 @@ +import 'dart:math' show max, min; + +import 'package:xterm/src/core/buffer/cell_offset.dart'; +import 'package:xterm/src/core/buffer/line.dart'; +import 'package:xterm/src/core/buffer/range_line.dart'; +import 'package:xterm/src/core/buffer/range.dart'; +import 'package:xterm/src/core/charset.dart'; +import 'package:xterm/src/core/cursor.dart'; +import 'package:xterm/src/core/reflow.dart'; +import 'package:xterm/src/core/state.dart'; +import 'package:xterm/src/utils/circular_buffer.dart'; +import 'package:xterm/src/utils/unicode_v11.dart'; + +class Buffer { + final TerminalState terminal; + + final int maxLines; + + final bool isAltBuffer; + + /// Characters that break selection when calling [getWordBoundary]. If null, + /// defaults to [defaultWordSeparators]. + final Set? wordSeparators; + + Buffer( + this.terminal, { + required this.maxLines, + required this.isAltBuffer, + this.wordSeparators, + }) { + for (int i = 0; i < terminal.viewHeight; i++) { + lines.push(_newEmptyLine()); + } + + resetVerticalMargins(); + } + + int _cursorX = 0; + + int _cursorY = 0; + + late int _marginTop; + + late int _marginBottom; + + var _savedCursorX = 0; + + var _savedCursorY = 0; + + final _savedCursorStyle = CursorStyle(); + + final charset = Charset(); + + /// Width of the viewport in columns. Also the index of the last column. + int get viewWidth => terminal.viewWidth; + + /// Height of the viewport in rows. Also the index of the last line. + int get viewHeight => terminal.viewHeight; + + /// lines of the buffer. the length of [lines] should always be equal or + /// greater than [viewHeight]. + late final lines = IndexAwareCircularBuffer(maxLines); + + /// Total number of lines in the buffer. Always equal or greater than + /// [viewHeight]. + int get height => lines.length; + + /// Horizontal position of the cursor relative to the top-left cornor of the + /// screen, starting from 0. + int get cursorX => _cursorX.clamp(0, terminal.viewWidth - 1); + + /// Vertical position of the cursor relative to the top-left cornor of the + /// screen, starting from 0. + int get cursorY => _cursorY; + + /// Index of the first line in the scroll region. + int get marginTop => _marginTop; + + /// Index of the last line in the scroll region. + int get marginBottom => _marginBottom; + + /// The number of lines above the viewport. + int get scrollBack => height - viewHeight; + + /// Vertical position of the cursor relative to the top of the buffer, + /// starting from 0. + int get absoluteCursorY => _cursorY + scrollBack; + + /// Absolute index of the first line in the scroll region. + int get absoluteMarginTop => _marginTop + scrollBack; + + /// Absolute index of the last line in the scroll region. + int get absoluteMarginBottom => _marginBottom + scrollBack; + + /// Writes data to the _terminal. Terminal sequences or special characters are + /// not interpreted and directly added to the buffer. + /// + /// See also: [Terminal.write] + void write(String text) { + for (var char in text.runes) { + writeChar(char); + } + } + + /// Writes a single character to the _terminal. Escape sequences or special + /// characters are not interpreted and directly added to the buffer. + /// + /// See also: [Terminal.writeChar] + void writeChar(int codePoint) { + codePoint = charset.translate(codePoint); + + final cellWidth = unicodeV11.wcwidth(codePoint); + if (_cursorX >= terminal.viewWidth) { + index(); + setCursorX(0); + if (terminal.autoWrapMode) { + currentLine.isWrapped = true; + } + } + + final line = currentLine; + line.setCell(_cursorX, codePoint, cellWidth, terminal.cursor); + + if (_cursorX < viewWidth) { + _cursorX++; + } + + if (cellWidth == 2) { + writeChar(0); + } + } + + /// The line at the current cursor position. + BufferLine get currentLine { + return lines[absoluteCursorY]; + } + + void backspace() { + if (_cursorX == 0 && currentLine.isWrapped) { + currentLine.isWrapped = false; + moveCursor(viewWidth - 1, -1); + } else if (_cursorX == viewWidth) { + moveCursor(-2, 0); + } else { + moveCursor(-1, 0); + } + } + + /// Erases the viewport from the cursor position to the end of the buffer, + /// including the cursor position. + void eraseDisplayFromCursor() { + eraseLineFromCursor(); + + for (var i = absoluteCursorY + 1; i < height; i++) { + final line = lines[i]; + line.isWrapped = false; + line.eraseRange(0, viewWidth, terminal.cursor); + } + } + + /// Erases the viewport from the top-left corner to the cursor, including the + /// cursor. + void eraseDisplayToCursor() { + eraseLineToCursor(); + + for (var i = 0; i < _cursorY; i++) { + final line = lines[i + scrollBack]; + line.isWrapped = false; + line.eraseRange(0, viewWidth, terminal.cursor); + } + } + + /// Erases the whole viewport. + void eraseDisplay() { + for (var i = 0; i < viewHeight; i++) { + final line = lines[i + scrollBack]; + line.isWrapped = false; + line.eraseRange(0, viewWidth, terminal.cursor); + } + } + + /// Erases the line from the cursor to the end of the line, including the + /// cursor position. + void eraseLineFromCursor() { + currentLine.isWrapped = false; + currentLine.eraseRange(_cursorX, viewWidth, terminal.cursor); + } + + /// Erases the line from the start of the line to the cursor, including the + /// cursor. + void eraseLineToCursor() { + currentLine.isWrapped = false; + currentLine.eraseRange(0, _cursorX, terminal.cursor); + } + + /// Erases the line at the current cursor position. + void eraseLine() { + currentLine.isWrapped = false; + currentLine.eraseRange(0, viewWidth, terminal.cursor); + } + + /// Erases [count] cells starting at the cursor position. + void eraseChars(int count) { + final start = _cursorX; + currentLine.eraseRange(start, start + count, terminal.cursor); + } + + void scrollDown(int lines) { + for (var i = absoluteMarginBottom; i >= absoluteMarginTop; i--) { + if (i >= absoluteMarginTop + lines) { + this.lines[i] = this.lines[i - lines]; + } else { + this.lines[i] = _newEmptyLine(); + } + } + } + + void scrollUp(int lines) { + for (var i = absoluteMarginTop; i <= absoluteMarginBottom; i++) { + if (i <= absoluteMarginBottom - lines) { + this.lines[i] = this.lines[i + lines]; + } else { + this.lines[i] = _newEmptyLine(); + } + } + } + + /// https://vt100.net/docs/vt100-ug/chapter3.html#IND IND – Index + /// + /// ESC D + /// + /// [index] causes the active position to move downward one line without + /// changing the column position. If the active position is at the bottom + /// margin, a scroll up is performed. + void index() { + if (isInVerticalMargin) { + if (_cursorY == _marginBottom) { + if (marginTop == 0 && !isAltBuffer) { + lines.insert(absoluteMarginBottom + 1, _newEmptyLine()); + } else { + scrollUp(1); + } + } else { + moveCursorY(1); + } + return; + } + + // the cursor is not in the scrollable region + if (_cursorY >= viewHeight - 1) { + // we are at the bottom + if (isAltBuffer) { + scrollUp(1); + } else { + lines.push(_newEmptyLine()); + } + } else { + // there're still lines so we simply move cursor down. + moveCursorY(1); + } + } + + void lineFeed() { + index(); + if (terminal.lineFeedMode) { + setCursorX(0); + } + } + + /// https://terminalguide.namepad.de/seq/a_esc_cm/ + void reverseIndex() { + if (isInVerticalMargin) { + if (_cursorY == _marginTop) { + scrollDown(1); + } else { + moveCursorY(-1); + } + } else { + moveCursorY(-1); + } + } + + void cursorGoForward() { + _cursorX = min(_cursorX + 1, viewWidth); + } + + void setCursorX(int cursorX) { + _cursorX = cursorX.clamp(0, viewWidth - 1); + } + + void setCursorY(int cursorY) { + _cursorY = cursorY.clamp(0, viewHeight - 1); + } + + void moveCursorX(int offset) { + setCursorX(_cursorX + offset); + } + + void moveCursorY(int offset) { + setCursorY(_cursorY + offset); + } + + void setCursor(int cursorX, int cursorY) { + var maxCursorY = viewHeight - 1; + + if (terminal.originMode) { + cursorY += _marginTop; + maxCursorY = _marginBottom; + } + + _cursorX = cursorX.clamp(0, viewWidth - 1); + _cursorY = cursorY.clamp(0, maxCursorY); + } + + void moveCursor(int offsetX, int offsetY) { + final cursorX = _cursorX + offsetX; + final cursorY = _cursorY + offsetY; + setCursor(cursorX, cursorY); + } + + /// Save cursor position, charmap and text attributes. + void saveCursor() { + _savedCursorX = _cursorX; + _savedCursorY = _cursorY; + _savedCursorStyle.foreground = terminal.cursor.foreground; + _savedCursorStyle.background = terminal.cursor.background; + _savedCursorStyle.attrs = terminal.cursor.attrs; + charset.save(); + } + + /// Restore cursor position, charmap and text attributes. + void restoreCursor() { + _cursorX = _savedCursorX; + _cursorY = _savedCursorY; + terminal.cursor.foreground = _savedCursorStyle.foreground; + terminal.cursor.background = _savedCursorStyle.background; + terminal.cursor.attrs = _savedCursorStyle.attrs; + charset.restore(); + } + + /// Sets the vertical scrolling margin to [top] and [bottom]. + /// Both values must be between 0 and [viewHeight] - 1. + void setVerticalMargins(int top, int bottom) { + _marginTop = top.clamp(0, viewHeight - 1); + _marginBottom = bottom.clamp(0, viewHeight - 1); + + _marginTop = min(_marginTop, _marginBottom); + _marginBottom = max(_marginTop, _marginBottom); + } + + bool get isInVerticalMargin { + return _cursorY >= _marginTop && _cursorY <= _marginBottom; + } + + void resetVerticalMargins() { + setVerticalMargins(0, viewHeight - 1); + } + + void deleteChars(int count) { + final start = _cursorX.clamp(0, viewWidth); + count = min(count, viewWidth - start); + currentLine.removeCells(start, count, terminal.cursor); + } + + /// Remove all lines above the top of the viewport. + void clearScrollback() { + if (height <= viewHeight) { + return; + } + + lines.trimStart(scrollBack); + } + + /// Clears the viewport and scrollback buffer. Then fill with empty lines. + void clear() { + lines.clear(); + for (int i = 0; i < viewHeight; i++) { + lines.push(_newEmptyLine()); + } + } + + void insertBlankChars(int count) { + currentLine.insertCells(_cursorX, count, terminal.cursor); + } + + void insertLines(int count) { + if (!isInVerticalMargin) { + return; + } + + setCursorX(0); + + // Number of lines from the cursor to the bottom of the scrollable region + // including the cursor itself. + final linesBelow = absoluteMarginBottom - absoluteCursorY + 1; + + // Number of empty lines to insert. + final linesToInsert = min(count, linesBelow); + + // Number of lines to move up. + final linesToMove = linesBelow - linesToInsert; + + for (var i = 0; i < linesToMove; i++) { + final index = absoluteMarginBottom - i; + lines[index] = lines.swap(index - linesToInsert, _newEmptyLine()); + } + + for (var i = linesToMove; i < linesToInsert; i++) { + lines[absoluteCursorY + i] = _newEmptyLine(); + } + } + + /// Remove [count] lines starting at the current cursor position. Lines below + /// the removed lines are shifted up. This only affects the scrollable region. + /// Lines outside the scrollable region are not affected. + void deleteLines(int count) { + if (!isInVerticalMargin) { + return; + } + + setCursorX(0); + + count = min(count, absoluteMarginBottom - absoluteCursorY + 1); + + final linesToMove = absoluteMarginBottom - absoluteCursorY + 1 - count; + + for (var i = 0; i < linesToMove; i++) { + final index = absoluteCursorY + i; + lines[index] = lines[index + count]; + } + + for (var i = 0; i < count; i++) { + lines[absoluteMarginBottom - i] = _newEmptyLine(); + } + } + + void resize(int oldWidth, int oldHeight, int newWidth, int newHeight) { + // 1. Adjust the height. + if (newHeight > oldHeight) { + // Grow larger + for (var i = 0; i < newHeight - oldHeight; i++) { + if (newHeight > lines.length) { + lines.push(_newEmptyLine(newWidth)); + } else { + _cursorY++; + } + } + } else { + // Shrink smaller + for (var i = 0; i < oldHeight - newHeight; i++) { + if (_cursorY > newHeight - 1) { + _cursorY--; + } else { + lines.pop(); + } + } + } + + // Ensure cursor is within the screen. + _cursorX = _cursorX.clamp(0, newWidth - 1); + _cursorY = _cursorY.clamp(0, newHeight - 1); + + // 2. Adjust the width. + if (newWidth != oldWidth) { + if (terminal.reflowEnabled && !isAltBuffer) { + final reflowResult = reflow(lines, oldWidth, newWidth); + + while (reflowResult.length < newHeight) { + reflowResult.add(_newEmptyLine(newWidth)); + } + + lines.replaceWith(reflowResult); + } else { + lines.forEach((item) => item.resize(newWidth)); + } + } + } + + /// Create a new [CellAnchor] at the specified [x] and [y] coordinates. + CellAnchor createAnchor(int x, int y) { + return lines[y].createAnchor(x); + } + + /// Create a new [CellAnchor] at the specified [x] and [y] coordinates. + CellAnchor createAnchorFromOffset(CellOffset offset) { + return lines[offset.y].createAnchor(offset.x); + } + + CellAnchor createAnchorFromCursor() { + return createAnchor(cursorX, absoluteCursorY); + } + + /// Create a new empty [BufferLine] with the current [viewWidth] if [width] + /// is not specified. + BufferLine _newEmptyLine([int? width]) { + final line = BufferLine(width ?? viewWidth); + return line; + } + + static final defaultWordSeparators = { + 0, + r' '.codeUnitAt(0), + r'.'.codeUnitAt(0), + r':'.codeUnitAt(0), + r'-'.codeUnitAt(0), + r'\'.codeUnitAt(0), + r'"'.codeUnitAt(0), + r'*'.codeUnitAt(0), + r'+'.codeUnitAt(0), + r'/'.codeUnitAt(0), + r'\'.codeUnitAt(0), + }; + + BufferRangeLine? getWordBoundary(CellOffset position) { + var separators = wordSeparators ?? defaultWordSeparators; + if (position.y >= lines.length) { + return null; + } + + var line = lines[position.y]; + var start = position.x; + var end = position.x; + + do { + if (start == 0) { + break; + } + final char = line.getCodePoint(start - 1); + if (separators.contains(char)) { + break; + } + start--; + } while (true); + + do { + if (end >= viewWidth) { + break; + } + final char = line.getCodePoint(end); + if (separators.contains(char)) { + break; + } + end++; + } while (true); + + if (start == end) { + return null; + } + + return BufferRangeLine( + CellOffset(start, position.y), + CellOffset(end, position.y), + ); + } + + /// Get the plain text content of the buffer including the scrollback. + /// Accepts an optional [range] to get a specific part of the buffer. + String getText([BufferRange? range]) { + range ??= BufferRangeLine( + CellOffset(0, 0), + CellOffset(viewWidth - 1, height - 1), + ); + + range = range.normalized; + + final builder = StringBuffer(); + + for (var segment in range.toSegments()) { + if (segment.line < 0 || segment.line >= height) { + continue; + } + final line = lines[segment.line]; + if (!(segment.line == range.begin.y || + segment.line == 0 || + line.isWrapped)) { + builder.write("\n"); + } + builder.write(line.getText(segment.start, segment.end)); + } + + return builder.toString(); + } + + /// Returns a debug representation of the buffer. + @override + String toString() { + final builder = StringBuffer(); + final lineNumberLength = lines.length.toString().length; + + for (var i = 0; i < lines.length; i++) { + final line = lines[i]; + + builder.write('${i.toString().padLeft(lineNumberLength)}: |${lines[i]}|'); + + if (line.isWrapped) { + builder.write(' (⏎)'); + } + + builder.write('\n'); + } + + return builder.toString(); + } +} diff --git a/app/third_party/xterm/lib/src/core/buffer/cell_flags.dart b/app/third_party/xterm/lib/src/core/buffer/cell_flags.dart new file mode 100644 index 00000000..97c5b8aa --- /dev/null +++ b/app/third_party/xterm/lib/src/core/buffer/cell_flags.dart @@ -0,0 +1,9 @@ +abstract class CellFlags { + static const bold = 1 << 0; + static const faint = 1 << 1; + static const italic = 1 << 2; + static const underline = 1 << 3; + static const blink = 1 << 4; + static const inverse = 1 << 5; + static const invisible = 1 << 6; +} diff --git a/app/third_party/xterm/lib/src/core/buffer/cell_offset.dart b/app/third_party/xterm/lib/src/core/buffer/cell_offset.dart new file mode 100644 index 00000000..36eb426f --- /dev/null +++ b/app/third_party/xterm/lib/src/core/buffer/cell_offset.dart @@ -0,0 +1,55 @@ +import 'package:xterm/src/core/buffer/range.dart'; + +class CellOffset { + final int x; + + final int y; + + const CellOffset(this.x, this.y); + + bool isEqual(CellOffset other) { + return other.x == x && other.y == y; + } + + bool isBefore(CellOffset other) { + return y < other.y || (y == other.y && x < other.x); + } + + bool isAfter(CellOffset other) { + return y > other.y || (y == other.y && x > other.x); + } + + bool isBeforeOrSame(CellOffset other) { + return y < other.y || (y == other.y && x <= other.x); + } + + bool isAfterOrSame(CellOffset other) { + return y > other.y || (y == other.y && x >= other.x); + } + + bool isAtSameRow(CellOffset other) { + return y == other.y; + } + + bool isAtSameColumn(CellOffset other) { + return x == other.x; + } + + bool isWithin(BufferRange range) { + return range.contains(this); + } + + @override + String toString() => 'CellOffset($x, $y)'; + + @override + int get hashCode => x.hashCode ^ y.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is CellOffset && + runtimeType == other.runtimeType && + x == other.x && + y == other.y; +} diff --git a/app/third_party/xterm/lib/src/core/buffer/line.dart b/app/third_party/xterm/lib/src/core/buffer/line.dart new file mode 100644 index 00000000..6e72114d --- /dev/null +++ b/app/third_party/xterm/lib/src/core/buffer/line.dart @@ -0,0 +1,418 @@ +import 'dart:math' show min; +import 'dart:typed_data'; + +import 'package:xterm/src/core/buffer/cell_offset.dart'; +import 'package:xterm/src/core/cell.dart'; +import 'package:xterm/src/core/cursor.dart'; +import 'package:xterm/src/utils/circular_buffer.dart'; +import 'package:xterm/src/utils/unicode_v11.dart'; + +const _cellSize = 4; + +const _cellForeground = 0; + +const _cellBackground = 1; + +const _cellAttributes = 2; + +const _cellContent = 3; + +class BufferLine with IndexedItem { + BufferLine( + this._length, { + this.isWrapped = false, + }) : _data = Uint32List(_calcCapacity(_length) * _cellSize); + + int _length; + + Uint32List _data; + + Uint32List get data => _data; + + var isWrapped = false; + + int get length => _length; + + final _anchors = []; + + List get anchors => _anchors; + + int getForeground(int index) { + return _data[index * _cellSize + _cellForeground]; + } + + int getBackground(int index) { + return _data[index * _cellSize + _cellBackground]; + } + + int getAttributes(int index) { + return _data[index * _cellSize + _cellAttributes]; + } + + int getContent(int index) { + return _data[index * _cellSize + _cellContent]; + } + + int getCodePoint(int index) { + return _data[index * _cellSize + _cellContent] & CellContent.codepointMask; + } + + int getWidth(int index) { + return _data[index * _cellSize + _cellContent] >> CellContent.widthShift; + } + + void getCellData(int index, CellData cellData) { + final offset = index * _cellSize; + cellData.foreground = _data[offset + _cellForeground]; + cellData.background = _data[offset + _cellBackground]; + cellData.flags = _data[offset + _cellAttributes]; + cellData.content = _data[offset + _cellContent]; + } + + CellData createCellData(int index) { + final cellData = CellData.empty(); + final offset = index * _cellSize; + _data[offset + _cellForeground] = cellData.foreground; + _data[offset + _cellBackground] = cellData.background; + _data[offset + _cellAttributes] = cellData.flags; + _data[offset + _cellContent] = cellData.content; + return cellData; + } + + void setForeground(int index, int value) { + _data[index * _cellSize + _cellForeground] = value; + } + + void setBackground(int index, int value) { + _data[index * _cellSize + _cellBackground] = value; + } + + void setAttributes(int index, int value) { + _data[index * _cellSize + _cellAttributes] = value; + } + + void setContent(int index, int value) { + _data[index * _cellSize + _cellContent] = value; + } + + void setCodePoint(int index, int char) { + final width = unicodeV11.wcwidth(char); + setContent(index, char | (width << CellContent.widthShift)); + } + + void setCell(int index, int char, int witdh, CursorStyle style) { + final offset = index * _cellSize; + _data[offset + _cellForeground] = style.foreground; + _data[offset + _cellBackground] = style.background; + _data[offset + _cellAttributes] = style.attrs; + _data[offset + _cellContent] = char | (witdh << CellContent.widthShift); + } + + void setCellData(int index, CellData cellData) { + final offset = index * _cellSize; + _data[offset + _cellForeground] = cellData.foreground; + _data[offset + _cellBackground] = cellData.background; + _data[offset + _cellAttributes] = cellData.flags; + _data[offset + _cellContent] = cellData.content; + } + + void eraseCell(int index, CursorStyle style) { + final offset = index * _cellSize; + _data[offset + _cellForeground] = style.foreground; + _data[offset + _cellBackground] = style.background; + _data[offset + _cellAttributes] = style.attrs; + _data[offset + _cellContent] = 0; + } + + void resetCell(int index) { + final offset = index * _cellSize; + _data[offset + _cellForeground] = 0; + _data[offset + _cellBackground] = 0; + _data[offset + _cellAttributes] = 0; + _data[offset + _cellContent] = 0; + } + + /// Erase cells whose index satisfies [start] <= index < [end]. Erased cells + /// are filled with [style]. + void eraseRange(int start, int end, CursorStyle style) { + // reset cell one to the left if start is second cell of a wide char + if (start > 0 && getWidth(start - 1) == 2) { + eraseCell(start - 1, style); + } + + // reset cell one to the right if end is second cell of a wide char + if (end < _length && getWidth(end - 1) == 2) { + eraseCell(end - 1, style); + } + + end = min(end, _length); + for (var i = start; i < end; i++) { + eraseCell(i, style); + } + } + + /// Remove [count] cells starting at [start]. Cells that are empty after the + /// removal are filled with [style]. + void removeCells(int start, int count, [CursorStyle? style]) { + assert(start >= 0 && start < _length); + assert(count >= 0 && start + count <= _length); + + style ??= CursorStyle.empty; + + if (start + count < _length) { + final moveStart = start * _cellSize; + final moveEnd = (_length - count) * _cellSize; + final moveOffset = count * _cellSize; + for (var i = moveStart; i < moveEnd; i++) { + _data[i] = _data[i + moveOffset]; + } + } + + for (var i = _length - count; i < _length; i++) { + eraseCell(i, style); + } + + if (start > 0 && getWidth(start - 1) == 2) { + eraseCell(start - 1, style); + } + + // Update anchors, remove anchors that are inside the removed range. + for (var i = 0; i < _anchors.length; i++) { + final anchor = _anchors[i]; + if (anchor.x >= start) { + if (anchor.x < start + count) { + anchor.dispose(); + } else { + anchor.reposition(anchor.x - count); + } + } + } + } + + /// Inserts [count] cells at [start]. New cells are initialized with [style]. + void insertCells(int start, int count, [CursorStyle? style]) { + style ??= CursorStyle.empty; + + if (start > 0 && getWidth(start - 1) == 2) { + eraseCell(start - 1, style); + } + + if (start + count < _length) { + final moveStart = start * _cellSize; + final moveEnd = (_length - count) * _cellSize; + final moveOffset = count * _cellSize; + for (var i = moveEnd - 1; i >= moveStart; i--) { + _data[i + moveOffset] = _data[i]; + } + } + + final end = min(start + count, _length); + for (var i = start; i < end; i++) { + eraseCell(i, style); + } + + if (getWidth(_length - 1) == 2) { + eraseCell(_length - 1, style); + } + + // Update anchors, move anchors that are after the inserted range. + for (var i = 0; i < _anchors.length; i++) { + final anchor = _anchors[i]; + if (anchor.x >= start + count) { + anchor.reposition(anchor.x + count); + + // Remove anchors that are now outside the buffer. + if (anchor.x >= _length) { + anchor.dispose(); + } + } + } + } + + void resize(int length) { + assert(length >= 0); + + if (length == _length) { + return; + } + + if (length > _length) { + final newBufferSize = _calcCapacity(length) * _cellSize; + + if (newBufferSize > _data.length) { + final newBuffer = Uint32List(newBufferSize); + newBuffer.setRange(0, _data.length, _data); + _data = newBuffer; + } + } + + _length = length; + + for (var i = 0; i < _anchors.length; i++) { + final anchor = _anchors[i]; + if (anchor.x > _length) { + anchor.reposition(_length); + } + } + } + + /// Returns the offset of the last cell that has content from the start of + /// the line. + int getTrimmedLength([int? cols]) { + final maxCols = _data.length ~/ _cellSize; + + if (cols == null || cols > maxCols) { + cols = maxCols; + } + + if (cols <= 0) { + return 0; + } + + for (var i = cols - 1; i >= 0; i--) { + var codePoint = getCodePoint(i); + + if (codePoint != 0) { + // we are at the last cell in this line that has content. + // the length of this line is the index of this cell + 1 + // the only exception is that if that last cell is wider + // than 1 then we have to add the diff + final lastCellWidth = getWidth(i); + return i + lastCellWidth; + } + } + return 0; + } + + /// Copies [len] cells from [src] starting at [srcCol] to [dstCol] at this + /// line. + void copyFrom(BufferLine src, int srcCol, int dstCol, int len) { + resize(dstCol + len); + + // data.setRange( + // dstCol * _cellSize, + // (dstCol + len) * _cellSize, + // Uint32List.sublistView(src.data, srcCol * _cellSize, len * _cellSize), + // ); + + var srcOffset = srcCol * _cellSize; + var dstOffset = dstCol * _cellSize; + + for (var i = 0; i < len * _cellSize; i++) { + _data[dstOffset++] = src._data[srcOffset++]; + } + } + + static int _calcCapacity(int length) { + assert(length >= 0); + + var capacity = 64; + + if (length < 256) { + while (capacity < length) { + capacity *= 2; + } + } else { + capacity = 256; + while (capacity < length) { + capacity += 32; + } + } + + return capacity; + } + + String getText([int? from, int? to]) { + if (from == null || from < 0) { + from = 0; + } + + if (to == null || to > _length) { + to = _length; + } + + final builder = StringBuffer(); + for (var i = from; i < to; i++) { + final codePoint = getCodePoint(i); + final width = getWidth(i); + if (codePoint != 0 && i + width <= to) { + builder.writeCharCode(codePoint); + } + } + + return builder.toString(); + } + + CellAnchor createAnchor(int offset) { + final anchor = CellAnchor(offset, owner: this); + _anchors.add(anchor); + return anchor; + } + + void dispose() { + for (final anchor in _anchors) { + anchor.dispose(); + } + } + + @override + String toString() { + return getText(); + } +} + +/// A handle to a cell in a [BufferLine] that can be used to track the location +/// of the cell. Anchors are guaranteed to be stable, retaining their relative +/// position to each other after mutations to the buffer. +class CellAnchor { + CellAnchor(int offset, {BufferLine? owner}) + : _offset = offset, + _owner = owner; + + int _offset; + + int get x { + return _offset; + } + + int get y { + assert(attached); + return _owner!.index; + } + + CellOffset get offset { + assert(attached); + return CellOffset(_offset, _owner!.index); + } + + BufferLine? _owner; + + BufferLine? get line => _owner; + + bool get attached => _owner?.attached ?? false; + + void reparent(BufferLine owner, int offset) { + _owner?._anchors.remove(this); + _owner = owner; + _owner?._anchors.add(this); + _offset = offset; + } + + void reposition(int offset) { + _offset = offset; + } + + void dispose() { + _owner?._anchors.remove(this); + _owner = null; + } + + @override + String toString() { + if (attached) { + return 'CellAnchor($x, $y)'; + } else { + return 'CellAnchor($x, detached)'; + } + } +} diff --git a/app/third_party/xterm/lib/src/core/buffer/range.dart b/app/third_party/xterm/lib/src/core/buffer/range.dart new file mode 100644 index 00000000..2401f15f --- /dev/null +++ b/app/third_party/xterm/lib/src/core/buffer/range.dart @@ -0,0 +1,55 @@ +import 'package:xterm/src/core/buffer/cell_offset.dart'; +import 'package:xterm/src/core/buffer/segment.dart'; + +abstract class BufferRange { + final CellOffset begin; + + final CellOffset end; + + const BufferRange(this.begin, this.end); + + BufferRange.collapsed(this.begin) : end = begin; + + bool get isNormalized { + return begin.isBefore(end) || begin.isEqual(end); + } + + bool get isCollapsed { + return begin.isEqual(end); + } + + BufferRange get normalized; + + /// Convert this range to segments of single lines. + Iterable toSegments(); + + /// Returns true if the given[position] is within this range. + bool contains(CellOffset position); + + /// Returns the smallest range that contains both this range and the given + /// [range]. + BufferRange merge(BufferRange range); + + /// Returns the smallest range that contains both this range and the given + /// [position]. + BufferRange extend(CellOffset position); + + @override + operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + if (other is! BufferRange) { + return false; + } + + return begin == other.begin && end == other.end; + } + + @override + int get hashCode => begin.hashCode ^ end.hashCode; + + @override + String toString() => 'Range($begin, $end)'; +} diff --git a/app/third_party/xterm/lib/src/core/buffer/range_block.dart b/app/third_party/xterm/lib/src/core/buffer/range_block.dart new file mode 100644 index 00000000..33c18365 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/buffer/range_block.dart @@ -0,0 +1,111 @@ +import 'dart:math'; + +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'; + +class BufferRangeBlock extends BufferRange { + BufferRangeBlock(super.begin, super.end); + + BufferRangeBlock.collapsed(super.begin) : super.collapsed(); + + @override + bool get isNormalized { + // A block range is normalized if begin is the top left corner of the range + // and end the bottom right corner. + return (begin.isBefore(end) && begin.x <= end.x) || begin.isEqual(end); + } + + @override + BufferRangeBlock get normalized { + if (isNormalized) { + return this; + } + // Determine new normalized begin and end offset, such that begin is the + // top left corner and end is the bottom right corner of the block. + final normalBegin = CellOffset(min(begin.x, end.x), min(begin.y, end.y)); + final normalEnd = CellOffset(max(begin.x, end.x), max(begin.y, end.y)); + return BufferRangeBlock(normalBegin, normalEnd); + } + + @override + Iterable toSegments() sync* { + var begin = this.begin; + var end = this.end; + + if (!isNormalized) { + end = this.begin; + begin = this.end; + } + + final startX = min(begin.x, end.x); + final endX = max(begin.x, end.x); + for (var i = begin.y; i <= end.y; i++) { + yield BufferSegment(this, i, startX, endX); + } + } + + @override + bool contains(CellOffset position) { + var begin = this.begin; + var end = this.end; + + if (!isNormalized) { + end = this.begin; + begin = this.end; + } + if (!(begin.y <= position.y && position.y <= end.y)) { + return false; + } + + final startX = min(begin.x, end.x); + final endX = max(begin.x, end.x); + return startX <= position.x && position.x <= endX; + } + + @override + BufferRangeBlock merge(BufferRange range) { + // Enlarge the block such that both borders of the range + // are within the selected block. + return extend(range.begin).extend(range.end); + } + + @override + BufferRangeBlock extend(CellOffset position) { + // If the position is within the block, there is nothing to do. + if (contains(position)) { + return this; + } + // Otherwise normalize the block and push the borders outside up to + // the position to which the block has to extended. + final normal = normalized; + final extendBegin = CellOffset( + min(normal.begin.x, position.x), + min(normal.begin.y, position.y), + ); + final extendEnd = CellOffset( + max(normal.end.x, position.x), + max(normal.end.y, position.y), + ); + return BufferRangeBlock(extendBegin, extendEnd); + } + + @override + operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + if (other is! BufferRangeBlock) { + return false; + } + + return begin == other.begin && end == other.end; + } + + @override + int get hashCode => begin.hashCode ^ end.hashCode; + + @override + String toString() => 'Block Range($begin, $end)'; +} diff --git a/app/third_party/xterm/lib/src/core/buffer/range_line.dart b/app/third_party/xterm/lib/src/core/buffer/range_line.dart new file mode 100644 index 00000000..83218eb9 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/buffer/range_line.dart @@ -0,0 +1,66 @@ +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'; + +class BufferRangeLine extends BufferRange { + BufferRangeLine(super.begin, super.end); + + BufferRangeLine.collapsed(super.begin) : super.collapsed(); + + @override + BufferRangeLine get normalized { + return isNormalized ? this : BufferRangeLine(end, begin); + } + + @override + Iterable toSegments() sync* { + final self = normalized; + for (var i = self.begin.y; i <= self.end.y; i++) { + var startX = i == self.begin.y ? self.begin.x : null; + var endX = i == self.end.y ? self.end.x : null; + yield BufferSegment(this, i, startX, endX); + } + } + + @override + bool contains(CellOffset position) { + final self = normalized; + return self.begin.isBeforeOrSame(position) && + self.end.isAfterOrSame(position); + } + + @override + BufferRangeLine merge(BufferRange range) { + final self = normalized; + final begin = self.begin.isBefore(range.begin) ? self.begin : range.begin; + final end = self.end.isAfter(range.end) ? self.end : range.end; + return BufferRangeLine(begin, end); + } + + @override + BufferRangeLine extend(CellOffset position) { + final self = normalized; + final begin = self.begin.isAfter(position) ? position : self.begin; + final end = self.end.isBefore(position) ? position : self.end; + return BufferRangeLine(begin, end); + } + + @override + operator ==(Object other) { + if (identical(this, other)) { + return true; + } + + if (other is! BufferRangeLine) { + return false; + } + + return begin == other.begin && end == other.end; + } + + @override + int get hashCode => begin.hashCode ^ end.hashCode; + + @override + String toString() => 'Line Range($begin, $end)'; +} diff --git a/app/third_party/xterm/lib/src/core/buffer/segment.dart b/app/third_party/xterm/lib/src/core/buffer/segment.dart new file mode 100644 index 00000000..9314ab6c --- /dev/null +++ b/app/third_party/xterm/lib/src/core/buffer/segment.dart @@ -0,0 +1,58 @@ +import 'package:xterm/src/core/buffer/cell_offset.dart'; +import 'package:xterm/src/core/buffer/range.dart'; + +/// A BufferSegment represents a range within a line. +class BufferSegment { + /// The range that this segment belongs to. + final BufferRange range; + + /// The line that this segment resides on. + final int line; + + /// The start position of this segment. [null] means the start of the line. + final int? start; + + /// The end position of this segment. [null] means the end of the line. + /// Should be greater than or equal to [start]. + final int? end; + + const BufferSegment(this.range, this.line, this.start, this.end) + : assert((start != null && end != null) ? start <= end : true); + + bool isWithin(CellOffset position) { + if (position.y != line) { + return false; + } + + if (start != null && position.x < start!) { + return false; + } + + if (end != null && position.x > end!) { + return false; + } + + return true; + } + + @override + String toString() { + final start = this.start != null ? this.start.toString() : 'start'; + final end = this.end != null ? this.end.toString() : 'end'; + return 'Segment($line, $start -> $end)'; + } + + @override + int get hashCode => + range.hashCode ^ line.hashCode ^ start.hashCode ^ end.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is BufferSegment && + runtimeType == other.runtimeType && + range == other.range && + line == other.line && + start == other.start && + end == other.end; +} diff --git a/app/third_party/xterm/lib/src/core/cell.dart b/app/third_party/xterm/lib/src/core/cell.dart new file mode 100644 index 00000000..c52039ff --- /dev/null +++ b/app/third_party/xterm/lib/src/core/cell.dart @@ -0,0 +1,66 @@ +import 'package:xterm/src/utils/hash_values.dart'; + +class CellData { + CellData({ + required this.foreground, + required this.background, + required this.flags, + required this.content, + }); + + factory CellData.empty() { + return CellData( + foreground: 0, + background: 0, + flags: 0, + content: 0, + ); + } + + int foreground; + + int background; + + int flags; + + int content; + + int getHash() { + return hashValues(foreground, background, flags, content); + } + + @override + String toString() { + return 'CellData{foreground: $foreground, background: $background, flags: $flags, content: $content}'; + } +} + +abstract class CellAttr { + static const bold = 1 << 0; + static const faint = 1 << 1; + static const italic = 1 << 2; + static const underline = 1 << 3; + static const blink = 1 << 4; + static const inverse = 1 << 5; + static const invisible = 1 << 6; + static const strikethrough = 1 << 7; +} + +abstract class CellColor { + static const valueMask = 0xFFFFFF; + + static const typeShift = 25; + static const typeMask = 3 << typeShift; + + static const normal = 0 << typeShift; + static const named = 1 << typeShift; + static const palette = 2 << typeShift; + static const rgb = 3 << typeShift; +} + +abstract class CellContent { + static const codepointMask = 0x1fffff; + + static const widthShift = 22; + // static const widthMask = 3 << widthShift; +} diff --git a/app/third_party/xterm/lib/src/core/charset.dart b/app/third_party/xterm/lib/src/core/charset.dart new file mode 100644 index 00000000..3659810a --- /dev/null +++ b/app/third_party/xterm/lib/src/core/charset.dart @@ -0,0 +1,95 @@ +typedef CharsetTranslator = int Function(int); + +final _charsets = { + '0'.codeUnitAt(0): decSpecGraphicsTranslator, + 'B'.codeUnitAt(0): asciiTranslator, +}; + +class Charset { + var _charsetMap = {}; + var _currentIndex = 0; + + var _savedCharsetMap = {}; + var _savedIndex = 0; + + var _cached = asciiTranslator; + + void _updateCache() { + _cached = _charsetMap[_currentIndex] ?? asciiTranslator; + } + + int translate(int codePoint) { + return _cached(codePoint); + } + + void designate(int index, int name) { + final charset = _charsets[name]; + if (charset != null) { + _charsetMap[index] = charset; + _updateCache(); + } + } + + void use(int index) { + _currentIndex = index; + _updateCache(); + } + + void save() { + _savedCharsetMap = Map.from(_charsetMap); + _savedIndex = _currentIndex; + } + + void restore() { + _charsetMap = _savedCharsetMap; + _currentIndex = _savedIndex; + _updateCache(); + } +} + +const decSpecGraphics = { + 0x5f: 0x00A0, // NO-BREAK SPACE + 0x60: 0x25C6, // BLACK DIAMOND + 0x61: 0x2592, // MEDIUM SHADE + 0x62: 0x2409, // SYMBOL FOR HORIZONTAL TABULATION + 0x63: 0x240C, // SYMBOL FOR FORM FEED + 0x64: 0x240D, // SYMBOL FOR CARRIAGE RETURN + 0x65: 0x240A, // SYMBOL FOR LINE FEED + 0x66: 0x00B0, // DEGREE SIGN + 0x67: 0x00B1, // PLUS-MINUS SIGN + 0x68: 0x2424, // SYMBOL FOR NEWLINE + 0x69: 0x240B, // SYMBOL FOR VERTICAL TABULATION + 0x6a: 0x2518, // BOX DRAWINGS LIGHT UP AND LEFT + 0x6b: 0x2510, // BOX DRAWINGS LIGHT DOWN AND LEFT + 0x6c: 0x250C, // BOX DRAWINGS LIGHT DOWN AND RIGHT + 0x6d: 0x2514, // BOX DRAWINGS LIGHT UP AND RIGHT + 0x6e: 0x253C, // BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL + 0x6f: 0x23BA, // HORIZONTAL SCAN LINE-1 + 0x70: 0x23BB, // HORIZONTAL SCAN LINE-3 + 0x71: 0x2500, // BOX DRAWINGS LIGHT HORIZONTAL + 0x72: 0x23BC, // HORIZONTAL SCAN LINE-7 + 0x73: 0x23BD, // HORIZONTAL SCAN LINE-9 + 0x74: 0x251C, // BOX DRAWINGS LIGHT VERTICAL AND RIGHT + 0x75: 0x2524, // BOX DRAWINGS LIGHT VERTICAL AND LEFT + 0x76: 0x2534, // BOX DRAWINGS LIGHT UP AND HORIZONTAL + 0x77: 0x252C, // BOX DRAWINGS LIGHT DOWN AND HORIZONTAL + 0x78: 0x2502, // BOX DRAWINGS LIGHT VERTICAL + 0x79: 0x2264, // LESS-THAN OR EQUAL TO + 0x7a: 0x2265, // GREATER-THAN OR EQUAL TO + 0x7b: 0x03C0, // GREEK SMALL LETTER PI + 0x7c: 0x2260, // NOT EQUAL TO + 0x7d: 0x00A3, // POUND SIGN + 0x7e: 0x00B7, // MIDDLE DOT +}; + +int asciiTranslator(int codePoint) { + return codePoint; +} + +int decSpecGraphicsTranslator(int codePoint) { + if (codePoint >= 127) { + return codePoint; + } + + return decSpecGraphics[codePoint] ?? codePoint; +} diff --git a/app/third_party/xterm/lib/src/core/color.dart b/app/third_party/xterm/lib/src/core/color.dart new file mode 100644 index 00000000..716219c3 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/color.dart @@ -0,0 +1,19 @@ +abstract class NamedColor { + static const black = 0; + static const red = 1; + static const green = 2; + static const yellow = 3; + static const blue = 4; + static const magenta = 5; + static const cyan = 6; + static const white = 7; + + static const brightBlack = 8; + static const brightRed = 9; + static const brightGreen = 10; + static const brightYellow = 11; + static const brightBlue = 12; + static const brightMagenta = 13; + static const brightCyan = 14; + static const brightWhite = 15; +} diff --git a/app/third_party/xterm/lib/src/core/cursor.dart b/app/third_party/xterm/lib/src/core/cursor.dart new file mode 100644 index 00000000..ce08610d --- /dev/null +++ b/app/third_party/xterm/lib/src/core/cursor.dart @@ -0,0 +1,137 @@ +import 'package:xterm/src/core/cell.dart'; + +class CursorStyle { + int foreground; + + int background; + + int attrs; + + CursorStyle({this.foreground = 0, this.background = 0, this.attrs = 0}); + + static final empty = CursorStyle(); + + void setBold() { + attrs |= CellAttr.bold; + } + + void setFaint() { + attrs |= CellAttr.faint; + } + + void setItalic() { + attrs |= CellAttr.italic; + } + + void setUnderline() { + attrs |= CellAttr.underline; + } + + void setBlink() { + attrs |= CellAttr.blink; + } + + void setInverse() { + attrs |= CellAttr.inverse; + } + + void setInvisible() { + attrs |= CellAttr.invisible; + } + + void setStrikethrough() { + attrs |= CellAttr.strikethrough; + } + + void unsetBold() { + attrs &= ~CellAttr.bold; + } + + void unsetFaint() { + attrs &= ~CellAttr.faint; + } + + void unsetItalic() { + attrs &= ~CellAttr.italic; + } + + void unsetUnderline() { + attrs &= ~CellAttr.underline; + } + + void unsetBlink() { + attrs &= ~CellAttr.blink; + } + + void unsetInverse() { + attrs &= ~CellAttr.inverse; + } + + void unsetInvisible() { + attrs &= ~CellAttr.invisible; + } + + void unsetStrikethrough() { + attrs &= ~CellAttr.strikethrough; + } + + bool get isBold => (attrs & CellAttr.bold) != 0; + + bool get isFaint => (attrs & CellAttr.faint) != 0; + + bool get isItalis => (attrs & CellAttr.italic) != 0; + + bool get isUnderline => (attrs & CellAttr.underline) != 0; + + bool get isBlink => (attrs & CellAttr.blink) != 0; + + bool get isInverse => (attrs & CellAttr.inverse) != 0; + + bool get isInvisible => (attrs & CellAttr.invisible) != 0; + + void setForegroundColor16(int color) { + foreground = color | CellColor.named; + } + + void setForegroundColor256(int color) { + foreground = color | CellColor.palette; + } + + void setForegroundColorRgb(int r, int g, int b) { + foreground = (r << 16) | (g << 8) | b | CellColor.rgb; + } + + void resetForegroundColor() { + foreground = 0; // | CellColor.normal; + } + + void setBackgroundColor16(int color) { + background = color | CellColor.named; + } + + void setBackgroundColor256(int color) { + background = color | CellColor.palette; + } + + void setBackgroundColorRgb(int r, int g, int b) { + background = (r << 16) | (g << 8) | b | CellColor.rgb; + } + + void resetBackgroundColor() { + background = 0; // | CellColor.normal; + } + + void reset() { + foreground = 0; + background = 0; + attrs = 0; + } +} + +class CursorPosition { + int x; + + int y; + + CursorPosition(this.x, this.y); +} diff --git a/app/third_party/xterm/lib/src/core/escape/emitter.dart b/app/third_party/xterm/lib/src/core/escape/emitter.dart new file mode 100644 index 00000000..faf5d401 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/escape/emitter.dart @@ -0,0 +1,33 @@ +class EscapeEmitter { + const EscapeEmitter(); + + String primaryDeviceAttributes() { + return '\x1b[?1;2c'; + } + + String secondaryDeviceAttributes() { + const model = 0; + const version = 0; + return '\x1b[>$model;$version;0c'; + } + + String tertiaryDeviceAttributes() { + return '\x1bP!|00000000\x1b\\'; + } + + String operatingStatus() { + return '\x1b[0n'; + } + + String cursorPosition(int x, int y) { + return '\x1b[$y;${x}R'; + } + + String bracketedPaste(String text) { + return '\x1b[200~$text\x1b[201~'; + } + + 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 new file mode 100644 index 00000000..166fb485 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/escape/handler.dart @@ -0,0 +1,215 @@ +import 'package:xterm/src/core/mouse/mode.dart'; + +abstract class EscapeHandler { + void writeChar(int char); + + /* SBC */ + + void bell(); + + void backspaceReturn(); + + void tab(); + + void lineFeed(); + + void carriageReturn(); + + void shiftOut(); + + void shiftIn(); + + void unknownSBC(int char); + + /* ANSI sequence */ + + void saveCursor(); + + void restoreCursor(); + + void index(); + + void nextLine(); + + void setTapStop(); + + void reverseIndex(); + + void designateCharset(int charset, int name); + + void unkownEscape(int char); + + /* CSI */ + + void repeatPreviousCharacter(int n); + + void setCursor(int x, int y); + + void setCursorX(int x); + + void setCursorY(int y); + + void sendPrimaryDeviceAttributes(); + + void clearTabStopUnderCursor(); + + void clearAllTabStops(); + + void moveCursorX(int offset); + + void moveCursorY(int n); + + void sendSecondaryDeviceAttributes(); + + void sendTertiaryDeviceAttributes(); + + void sendOperatingStatus(); + + void sendCursorPosition(); + + void setMargins(int i, [int? bottom]); + + void cursorNextLine(int amount); + + void cursorPrecedingLine(int amount); + + void eraseDisplayBelow(); + + void eraseDisplayAbove(); + + void eraseDisplay(); + + void eraseScrollbackOnly(); + + void eraseLineRight(); + + void eraseLineLeft(); + + void eraseLine(); + + void insertLines(int amount); + + void deleteLines(int amount); + + void deleteChars(int amount); + + void scrollUp(int amount); + + void scrollDown(int amount); + + void eraseChars(int amount); + + void insertBlankChars(int amount); + + void unknownCSI(int finalByte); + + /* Modes */ + + void setInsertMode(bool enabled); + + void setLineFeedMode(bool enabled); + + void setUnknownMode(int mode, bool enabled); + + /* DEC Private modes */ + + void setCursorKeysMode(bool enabled); + + void setReverseDisplayMode(bool enabled); + + void setOriginMode(bool enabled); + + void setColumnMode(bool enabled); + + void setAutoWrapMode(bool enabled); + + void setMouseMode(MouseMode mode); + + void setCursorBlinkMode(bool enabled); + + void setCursorVisibleMode(bool enabled); + + void useAltBuffer(); + + void useMainBuffer(); + + void clearAltBuffer(); + + void setAppKeypadMode(bool enabled); + + void setReportFocusMode(bool enabled); + + void setMouseReportMode(MouseReportMode mode); + + void setAltBufferMouseScrollMode(bool enabled); + + void setBracketedPasteMode(bool enabled); + + void setUnknownDecMode(int mode, bool enabled); + + void resize(int cols, int rows); + + void sendSize(); + + /* Select Graphic Rendition (SGR) */ + + void resetCursorStyle(); + + void setCursorBold(); + + void setCursorFaint(); + + void setCursorItalic(); + + void setCursorUnderline(); + + void setCursorBlink(); + + void setCursorInverse(); + + void setCursorInvisible(); + + void setCursorStrikethrough(); + + void unsetCursorBold(); + + void unsetCursorFaint(); + + void unsetCursorItalic(); + + void unsetCursorUnderline(); + + void unsetCursorBlink(); + + void unsetCursorInverse(); + + void unsetCursorInvisible(); + + void unsetCursorStrikethrough(); + + void setForegroundColor16(int color); + + void setForegroundColor256(int index); + + void setForegroundColorRgb(int r, int g, int b); + + void resetForeground(); + + void setBackgroundColor16(int color); + + void setBackgroundColor256(int index); + + void setBackgroundColorRgb(int r, int g, int b); + + void resetBackground(); + + void unsupportedStyle(int param); + + /* OSC */ + + void setTitle(String name); + + void setIconName(String name); + + 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 new file mode 100644 index 00000000..0c7e74a9 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/escape/parser.dart @@ -0,0 +1,1154 @@ +import 'package:xterm/src/core/color.dart'; +import 'package:xterm/src/core/mouse/mode.dart'; +import 'package:xterm/src/core/escape/handler.dart'; +import 'package:xterm/src/utils/ascii.dart'; +import 'package:xterm/src/utils/byte_consumer.dart'; +import 'package:xterm/src/utils/char_code.dart'; +import 'package:xterm/src/utils/lookup_table.dart'; + +/// [EscapeParser] translates control characters and escape sequences into +/// function calls that the terminal can handle. +/// +/// Design goals: +/// * Zero object allocation during processing. +/// * No internal state. Same input will always produce same output. +class EscapeParser { + final EscapeHandler handler; + + EscapeParser(this.handler); + + final _queue = ByteConsumer(); + + /// Start of sequence or character being processed. Useful for debugging. + var tokenBegin = 0; + + /// End of sequence or character being processed. Useful for debugging. + int get tokenEnd => _queue.totalConsumed; + + void write(String chunk) { + _queue.unrefConsumedBlocks(); + _queue.add(chunk); + _process(); + } + + void _process() { + while (_queue.isNotEmpty) { + tokenBegin = _queue.totalConsumed; + final char = _queue.consume(); + + if (char == Ascii.ESC) { + final processed = _processEscape(); + if (!processed) { + _queue.rollback(tokenEnd - tokenBegin); + return; + } + } else { + _processChar(char); + } + } + } + + void _processChar(int char) { + if (char > _sbcHandlers.maxIndex) { + handler.writeChar(char); + return; + } + + final sbcHandler = _sbcHandlers[char]; + if (sbcHandler == null) { + handler.unkownEscape(char); + return; + } + + sbcHandler(); + } + + /// Processes a sequence of characters that starts with an escape character. + /// Returns [true] if the sequence was processed, [false] if it was not. + bool _processEscape() { + if (_queue.isEmpty) return false; + + final escapeChar = _queue.consume(); + final escapeHandler = _escHandlers[escapeChar]; + + if (escapeHandler == null) { + handler.unkownEscape(escapeChar); + return true; + } + + return escapeHandler(); + } + + late final _sbcHandlers = FastLookupTable<_SbcHandler>({ + 0x07: handler.bell, + 0x08: handler.backspaceReturn, + 0x09: handler.tab, + 0x0a: handler.lineFeed, + 0x0b: handler.lineFeed, + 0x0c: handler.lineFeed, + 0x0d: handler.carriageReturn, + 0x0e: handler.shiftOut, + 0x0f: handler.shiftIn, + }); + + late final _escHandlers = FastLookupTable<_EscHandler>({ + '['.charCode: _escHandleCSI, + ']'.charCode: _escHandleOSC, + '7'.charCode: _escHandleSaveCursor, + '8'.charCode: _escHandleRestoreCursor, + 'D'.charCode: _escHandleIndex, + 'E'.charCode: _escHandleNextLine, + 'H'.charCode: _escHandleTabSet, + 'M'.charCode: _escHandleReverseIndex, + // 'P'.charCode: _unsupportedHandler, // Sixel + // 'c'.charCode: _unsupportedHandler, + // '#'.charCode: _unsupportedHandler, + '('.charCode: _escHandleDesignateCharset0, // SCS - G0 + ')'.charCode: _escHandleDesignateCharset1, // SCS - G1 + // '*'.charCode: _voidHandler(1), // TODO: G2 (vt220) + // '+'.charCode: _voidHandler(1), // TODO: G3 (vt220) + '>'.charCode: _escHandleResetAppKeypadMode, // TODO: Normal Keypad + '='.charCode: _escHandleSetAppKeypadMode, // TODO: Application Keypad + }); + + /// `ESC 7` Save Cursor (DECSC) + /// + /// https://terminalguide.namepad.de/seq/a_esc_a7/ + bool _escHandleSaveCursor() { + handler.saveCursor(); + return true; + } + + /// `ESC 8` Restore Cursor (DECRC) + /// + /// https://terminalguide.namepad.de/seq/a_esc_a8/ + bool _escHandleRestoreCursor() { + handler.restoreCursor(); + return true; + } + + /// `ESC D` Index (IND) + /// + /// https://terminalguide.namepad.de/seq/a_esc_cd/ + bool _escHandleIndex() { + handler.index(); + return true; + } + + /// `ESC E` Next Line (NEL) + /// + /// https://terminalguide.namepad.de/seq/a_esc_ce/ + bool _escHandleNextLine() { + handler.nextLine(); + return true; + } + + /// `ESC H` Horizontal Tab Set (HTS) + /// + /// https://terminalguide.namepad.de/seq/a_esc_ch/ + bool _escHandleTabSet() { + handler.setTapStop(); + return true; + } + + /// `ESC M` Reverse Index (RI) + /// + /// https://terminalguide.namepad.de/seq/a_esc_cm/ + bool _escHandleReverseIndex() { + handler.reverseIndex(); + return true; + } + + bool _escHandleDesignateCharset0() { + if (_queue.isEmpty) return false; + int name = _queue.consume(); + handler.designateCharset(0, name); + return true; + } + + bool _escHandleDesignateCharset1() { + if (_queue.isEmpty) return false; + int name = _queue.consume(); + handler.designateCharset(1, name); + return true; + } + + /// `ESC >` Reset Application Keypad Mode (DECKPNM) + /// + /// https://terminalguide.namepad.de/seq/a_esc_x3c_greater_than/ + bool _escHandleSetAppKeypadMode() { + handler.setAppKeypadMode(true); + return true; + } + + /// `ESC =` Set Application Keypad Mode (DECKPAM) + /// + /// https://terminalguide.namepad.de/seq/a_esc_x3d_equals/ + bool _escHandleResetAppKeypadMode() { + handler.setAppKeypadMode(false); + return true; + } + + bool _escHandleCSI() { + final consumed = _consumeCsi(); + if (!consumed) return false; + + final csiHandler = _csiHandlers[_csi.finalByte]; + + if (csiHandler == null) { + handler.unknownCSI(_csi.finalByte); + } else { + csiHandler(); + } + + return true; + } + + /// The last parsed [_Csi]. This is a mutable singletion by design to reduce + /// object allocations. + final _csi = _Csi(finalByte: 0, params: []); + + /// Parse a CSI from the head of the queue. Return false if the CSI isn't + /// complete. After a CSI is successfully parsed, [_csi] is updated. + bool _consumeCsi() { + if (_queue.isEmpty) { + return false; + } + + _csi.params.clear(); + + // test whether the csi is a `CSI ? Ps ...` or `CSI Ps ...` + final prefix = _queue.peek(); + if (prefix >= Ascii.colon && prefix <= Ascii.questionMark) { + _csi.prefix = prefix; + _queue.consume(); + } else { + _csi.prefix = null; + } + + var param = 0; + var hasParam = false; + while (true) { + // The sequence isn't completed, just ignore it. + if (_queue.isEmpty) { + return false; + } + + final char = _queue.consume(); + + if (char == Ascii.semicolon) { + if (hasParam) { + _csi.params.add(param); + } + param = 0; + continue; + } + + if (char >= Ascii.num0 && char <= Ascii.num9) { + hasParam = true; + param *= 10; + param += char - Ascii.num0; + continue; + } + + if (char > Ascii.NULL && char < Ascii.num0) { + // intermediates.add(char); + continue; + } + + if (char >= Ascii.atSign && char <= Ascii.tilde) { + if (hasParam) { + _csi.params.add(param); + } + + _csi.finalByte = char; + return true; + } + } + } + + late final _csiHandlers = FastLookupTable<_CsiHandler>({ + // 'a'.codeUnitAt(0): _csiHandleCursorHorizontalRelative, + 'b'.codeUnitAt(0): _csiHandleRepeatPreviousCharacter, + 'c'.codeUnitAt(0): _csiHandleSendDeviceAttributes, + 'd'.codeUnitAt(0): _csiHandleLinePositionAbsolute, + 'f'.codeUnitAt(0): _csiHandleCursorPosition, + 'g'.codeUnitAt(0): _csiHandelClearTabStop, + 'h'.codeUnitAt(0): _csiHandleMode, + 'l'.codeUnitAt(0): _csiHandleMode, + 'm'.codeUnitAt(0): _csiHandleSgr, + 'n'.codeUnitAt(0): _csiHandleDeviceStatusReport, + 'r'.codeUnitAt(0): _csiHandleSetMargins, + 't'.codeUnitAt(0): _csiWindowManipulation, + 'A'.codeUnitAt(0): _csiHandleCursorUp, + 'B'.codeUnitAt(0): _csiHandleCursorDown, + 'C'.codeUnitAt(0): _csiHandleCursorForward, + 'D'.codeUnitAt(0): _csiHandleCursorBackward, + 'E'.codeUnitAt(0): _csiHandleCursorNextLine, + 'F'.codeUnitAt(0): _csiHandleCursorPrecedingLine, + 'G'.codeUnitAt(0): _csiHandleCursorHorizontalAbsolute, + 'H'.codeUnitAt(0): _csiHandleCursorPosition, + 'J'.codeUnitAt(0): _csiHandleEraseDisplay, + 'K'.codeUnitAt(0): _csiHandleEraseLine, + 'L'.codeUnitAt(0): _csiHandleInsertLines, + 'M'.codeUnitAt(0): _csiHandleDeleteLines, + 'P'.codeUnitAt(0): _csiHandleDelete, + 'S'.codeUnitAt(0): _csiHandleScrollUp, + 'T'.codeUnitAt(0): _csiHandleScrollDown, + 'X'.codeUnitAt(0): _csiHandleEraseCharacters, + '@'.codeUnitAt(0): _csiHandleInsertBlankCharacters, + }); + + /// `ESC [ Ps a` Cursor Horizontal Position Relative (HPR) + /// + /// https://terminalguide.namepad.de/seq/csi_sa/ + // void _csiHandleCursorHorizontalRelative() { + // if (_csi.params.isEmpty) { + // handler.cursorHorizontal(1); + // } else { + // handler.cursorHorizontal(_csi.params[0]); + // } + // } + + /// `ESC [ Ps b` Repeat Previous Character (REP) + /// + /// https://terminalguide.namepad.de/seq/csi_sb/ + void _csiHandleRepeatPreviousCharacter() { + var amount = 1; + + if (_csi.params.isNotEmpty) { + amount = _csi.params[0]; + if (amount == 0) amount = 1; + } + + handler.repeatPreviousCharacter(amount); + } + + /// `ESC [ Ps c` Device Attributes (DA) + /// + /// https://terminalguide.namepad.de/seq/csi_sc/ + void _csiHandleSendDeviceAttributes() { + switch (_csi.prefix) { + case Ascii.greaterThan: + return handler.sendSecondaryDeviceAttributes(); + case Ascii.equal: + return handler.sendTertiaryDeviceAttributes(); + default: + handler.sendPrimaryDeviceAttributes(); + } + } + + /// `ESC [ Ps d` Cursor Vertical Position Absolute (VPA) + /// + /// https://terminalguide.namepad.de/seq/csi_sd/ + void _csiHandleLinePositionAbsolute() { + var y = 1; + + if (_csi.params.isNotEmpty) { + y = _csi.params[0]; + } + + handler.setCursorY(y - 1); + } + + /// `ESC [ Ps ; Ps f` Alias: Set Cursor Position + /// + /// https://terminalguide.namepad.de/seq/csi_sf/ + void _csiHandleCursorPosition() { + var row = 1; + var col = 1; + + if (_csi.params.length == 2) { + row = _csi.params[0]; + col = _csi.params[1]; + } + + handler.setCursor(col - 1, row - 1); + } + + /// `ESC [ Ps g` Tab Clear (TBC) + /// + /// https://terminalguide.namepad.de/seq/csi_sg/ + void _csiHandelClearTabStop() { + var cmd = 0; + + if (_csi.params.length == 1) { + cmd = _csi.params[0]; + } + + switch (cmd) { + case 0: + return handler.clearTabStopUnderCursor(); + default: + return handler.clearAllTabStops(); + } + } + + /// - `ESC [ [ Pm ] h Set Mode (SM)` https://terminalguide.namepad.de/seq/csi_sm/ + /// - `ESC [ ? [ Pm ] h` Set Mode (?) (SM) https://terminalguide.namepad.de/seq/csi_sh__p/ + /// - `ESC [ [ Pm ] l` Reset Mode (RM) https://terminalguide.namepad.de/seq/csi_rm/ + /// - `ESC [ ? [ Pm ] l` Reset Mode (?) (RM) https://terminalguide.namepad.de/seq/csi_sl__p/ + void _csiHandleMode() { + final isEnabled = _csi.finalByte == Ascii.h; + + final isDecModes = _csi.prefix == Ascii.questionMark; + + if (isDecModes) { + for (var mode in _csi.params) { + _setDecMode(mode, isEnabled); + } + } else { + for (var mode in _csi.params) { + _setMode(mode, isEnabled); + } + } + } + + /// `ESC [ [ Ps ] m` Select Graphic Rendition (SGR) + /// + /// https://terminalguide.namepad.de/seq/csi_sm/ + void _csiHandleSgr() { + final params = _csi.params; + + if (params.isEmpty) { + return handler.resetCursorStyle(); + } + + // This is a workaround for a bug in the analyzer. + // ignore: dead_code + for (var i = 0; i < _csi.params.length; i++) { + final param = params[i]; + switch (param) { + case 0: + handler.resetCursorStyle(); + continue; + case 1: + handler.setCursorBold(); + continue; + case 2: + handler.setCursorFaint(); + continue; + case 3: + handler.setCursorItalic(); + continue; + case 4: + handler.setCursorUnderline(); + continue; + case 5: + handler.setCursorBlink(); + continue; + case 7: + handler.setCursorInverse(); + continue; + case 8: + handler.setCursorInvisible(); + continue; + case 9: + handler.setCursorStrikethrough(); + continue; + + case 21: + handler.unsetCursorBold(); + continue; + case 22: + handler.unsetCursorFaint(); + continue; + case 23: + handler.unsetCursorItalic(); + continue; + case 24: + handler.unsetCursorUnderline(); + continue; + case 25: + handler.unsetCursorBlink(); + continue; + case 27: + handler.unsetCursorInverse(); + continue; + case 28: + handler.unsetCursorInvisible(); + continue; + case 29: + handler.unsetCursorStrikethrough(); + continue; + + case 30: + handler.setForegroundColor16(NamedColor.black); + continue; + case 31: + handler.setForegroundColor16(NamedColor.red); + continue; + case 32: + handler.setForegroundColor16(NamedColor.green); + continue; + case 33: + handler.setForegroundColor16(NamedColor.yellow); + continue; + case 34: + handler.setForegroundColor16(NamedColor.blue); + continue; + case 35: + handler.setForegroundColor16(NamedColor.magenta); + continue; + case 36: + handler.setForegroundColor16(NamedColor.cyan); + continue; + case 37: + handler.setForegroundColor16(NamedColor.white); + continue; + case 38: + final mode = params[i + 1]; + switch (mode) { + case 2: + final r = params[i + 2]; + final g = params[i + 3]; + final b = params[i + 4]; + handler.setForegroundColorRgb(r, g, b); + i += 4; + break; + case 5: + final index = params[i + 2]; + handler.setForegroundColor256(index); + i += 2; + break; + } + continue; + case 39: + handler.resetForeground(); + continue; + + case 40: + handler.setBackgroundColor16(NamedColor.black); + continue; + case 41: + handler.setBackgroundColor16(NamedColor.red); + continue; + case 42: + handler.setBackgroundColor16(NamedColor.green); + continue; + case 43: + handler.setBackgroundColor16(NamedColor.yellow); + continue; + case 44: + handler.setBackgroundColor16(NamedColor.blue); + continue; + case 45: + handler.setBackgroundColor16(NamedColor.magenta); + continue; + case 46: + handler.setBackgroundColor16(NamedColor.cyan); + continue; + case 47: + handler.setBackgroundColor16(NamedColor.white); + continue; + case 48: + final mode = params[i + 1]; + switch (mode) { + case 2: + final r = params[i + 2]; + final g = params[i + 3]; + final b = params[i + 4]; + handler.setBackgroundColorRgb(r, g, b); + i += 4; + break; + case 5: + final index = params[i + 2]; + handler.setBackgroundColor256(index); + i += 2; + break; + } + continue; + case 49: + handler.resetBackground(); + continue; + + case 90: + handler.setForegroundColor16(NamedColor.brightBlack); + continue; + case 91: + handler.setForegroundColor16(NamedColor.brightRed); + continue; + case 92: + handler.setForegroundColor16(NamedColor.brightGreen); + continue; + case 93: + handler.setForegroundColor16(NamedColor.brightYellow); + continue; + case 94: + handler.setForegroundColor16(NamedColor.brightBlue); + continue; + case 95: + handler.setForegroundColor16(NamedColor.brightMagenta); + continue; + case 96: + handler.setForegroundColor16(NamedColor.brightCyan); + continue; + case 97: + handler.setForegroundColor16(NamedColor.brightWhite); + continue; + + case 100: + handler.setBackgroundColor16(NamedColor.brightBlack); + continue; + case 101: + handler.setBackgroundColor16(NamedColor.brightRed); + continue; + case 102: + handler.setBackgroundColor16(NamedColor.brightGreen); + continue; + case 103: + handler.setBackgroundColor16(NamedColor.brightYellow); + continue; + case 104: + handler.setBackgroundColor16(NamedColor.brightBlue); + continue; + case 105: + handler.setBackgroundColor16(NamedColor.brightMagenta); + continue; + case 106: + handler.setBackgroundColor16(NamedColor.brightCyan); + continue; + case 107: + handler.setBackgroundColor16(NamedColor.brightWhite); + continue; + + default: + handler.unsupportedStyle(param); + continue; + } + } + } + + /// `ESC [ Ps n` Device Status Report [Dispatch] (DSR) + /// + /// https://terminalguide.namepad.de/seq/csi_sn/ + void _csiHandleDeviceStatusReport() { + if (_csi.params.isEmpty) return; + + switch (_csi.params[0]) { + case 5: + return handler.sendOperatingStatus(); + case 6: + return handler.sendCursorPosition(); + } + } + + /// `ESC [ Ps ; Ps r` Set Top and Bottom Margins (DECSTBM) + /// + /// https://terminalguide.namepad.de/seq/csi_sr/ + void _csiHandleSetMargins() { + var top = 1; + int? bottom; + + if (_csi.params.length > 2) return; + + if (_csi.params.isNotEmpty) { + top = _csi.params[0]; + + if (_csi.params.length == 2) { + bottom = _csi.params[1] - 1; + } + } + + handler.setMargins(top - 1, bottom); + } + + /// `ESC [ Ps t` Window operations [DISPATCH] + /// + /// https://terminalguide.namepad.de/seq/csi_st/ + void _csiWindowManipulation() { + // The sequence needs at least one parameter. + if (_csi.params.isEmpty) { + return; + } + // Most the commands in this group are either of the scope of this package, + // or should be disabled for security risks. + switch (_csi.params.first) { + // Window handling is currently not in the scope of the package. + case 1: // Restore Terminal Window (show window if minimized) + case 2: // Minimize Terminal Window + case 3: // Set Terminal Window Position + case 4: // Set Terminal Window Size in Pixels + case 5: // Raise Terminal Window + case 6: // Lower Terminal Window + case 7: // Refresh/Redraw Terminal Window + return; + case 8: // Set Terminal Window Size (in characters) + // This CSI contains 2 more parameters: width and height. + if (_csi.params.length != 3) { + return; + } + final rows = _csi.params[1]; + final cols = _csi.params[2]; + handler.resize(cols, rows); + return; + // Window handling is currently no in the scope of the package. + case 9: // Maximize Terminal Window + case 10: // Alias: Maximize Terminal Window + case 11: // Report Terminal Window State + case 13: // Report Terminal Window Position + case 14: // Report Terminal Window Size in Pixels + case 15: // Report Screen Size in Pixels + case 16: // Report Cell Size in Pixels + return; + case 18: // Report Terminal Size (in characters) + handler.sendSize(); + return; + // Screen handling is currently no in the scope of the package. + case 19: // Report Screen Size (in characters) + // Disabled as these can a security risk. + case 20: // Get Icon Title + case 21: // Get Terminal Title + // Not implemented. + case 22: // Push Terminal Title + case 23: // Pop Terminal Title + return; + // Unknown CSI. + default: + return; + } + } + + /// `ESC [ Ps A` Cursor Up (CUU) + /// + /// https://terminalguide.namepad.de/seq/csi_ca/ + void _csiHandleCursorUp() { + var amount = 1; + + if (_csi.params.isNotEmpty) { + amount = _csi.params[0]; + if (amount == 0) amount = 1; + } + + handler.moveCursorY(-amount); + } + + /// `ESC [ Ps B` Cursor Down (CUD) + /// + /// https://terminalguide.namepad.de/seq/csi_cb/ + void _csiHandleCursorDown() { + var amount = 1; + + if (_csi.params.isNotEmpty) { + amount = _csi.params[0]; + if (amount == 0) amount = 1; + } + + handler.moveCursorY(amount); + } + + /// `ESC [ Ps C` Cursor Right (CUF) + /// + /// Cursor Right (CUF) + void _csiHandleCursorForward() { + var amount = 1; + + if (_csi.params.isNotEmpty) { + amount = _csi.params[0]; + if (amount == 0) amount = 1; + } + + handler.moveCursorX(amount); + } + + /// `ESC [ Ps D` Cursor Left (CUB) + /// + /// https://terminalguide.namepad.de/seq/csi_cd/ + void _csiHandleCursorBackward() { + var amount = 1; + + if (_csi.params.isNotEmpty) { + amount = _csi.params[0]; + if (amount == 0) amount = 1; + } + + handler.moveCursorX(-amount); + } + + /// `ESC [ Ps E` Cursor Next Line (CNL) + /// + /// https://terminalguide.namepad.de/seq/csi_ce/ + void _csiHandleCursorNextLine() { + var amount = 1; + + if (_csi.params.isNotEmpty) { + amount = _csi.params[0]; + if (amount == 0) amount = 1; + } + + handler.cursorNextLine(amount); + } + + /// `ESC [ Ps F` Cursor Previous Line (CPL) + /// + /// https://terminalguide.namepad.de/seq/csi_cf/ + void _csiHandleCursorPrecedingLine() { + var amount = 1; + + if (_csi.params.isNotEmpty) { + amount = _csi.params[0]; + if (amount == 0) amount = 1; + } + + handler.cursorPrecedingLine(amount); + } + + void _csiHandleCursorHorizontalAbsolute() { + var x = 1; + + if (_csi.params.isNotEmpty) { + x = _csi.params[0]; + if (x == 0) x = 1; + } + + handler.setCursorX(x - 1); + } + + /// ESC [ Ps J Erase Display [Dispatch] (ED) + /// + /// https://terminalguide.namepad.de/seq/csi_cj/ + void _csiHandleEraseDisplay() { + var cmd = 0; + + if (_csi.params.length == 1) { + cmd = _csi.params[0]; + } + + switch (cmd) { + case 0: + return handler.eraseDisplayBelow(); + case 1: + return handler.eraseDisplayAbove(); + case 2: + return handler.eraseDisplay(); + case 3: + return handler.eraseScrollbackOnly(); + } + } + + /// `ESC [ Ps K` Erase Line [Dispatch] (EL) + /// + /// https://terminalguide.namepad.de/seq/csi_ck/ + void _csiHandleEraseLine() { + var cmd = 0; + + if (_csi.params.length == 1) { + cmd = _csi.params[0]; + } + + switch (cmd) { + case 0: + return handler.eraseLineRight(); + case 1: + return handler.eraseLineLeft(); + case 2: + return handler.eraseLine(); + } + } + + /// `ESC [ Ps L` Insert Line (IL) + /// + /// https://terminalguide.namepad.de/seq/csi_cl/ + void _csiHandleInsertLines() { + var amount = 1; + + if (_csi.params.isNotEmpty) { + amount = _csi.params[0]; + } + + handler.insertLines(amount); + } + + /// ESC [ Ps M Delete Line (DL) + /// + /// https://terminalguide.namepad.de/seq/csi_cm/ + void _csiHandleDeleteLines() { + var amount = 1; + + if (_csi.params.isNotEmpty) { + amount = _csi.params[0]; + } + + handler.deleteLines(amount); + } + + /// ESC [ Ps P Delete Character (DCH) + /// + /// https://terminalguide.namepad.de/seq/csi_cp/ + void _csiHandleDelete() { + var amount = 1; + + if (_csi.params.isNotEmpty) { + amount = _csi.params[0]; + } + + handler.deleteChars(amount); + } + + /// `ESC [ Ps S` Scroll Up (SU) + /// + /// https://terminalguide.namepad.de/seq/csi_cs/ + void _csiHandleScrollUp() { + var amount = 1; + + if (_csi.params.isNotEmpty) { + amount = _csi.params[0]; + } + + handler.scrollUp(amount); + } + + /// `ESC [ Ps T `Scroll Down (SD) + /// + /// https://terminalguide.namepad.de/seq/csi_ct_1param/ + void _csiHandleScrollDown() { + var amount = 1; + + if (_csi.params.isNotEmpty) { + amount = _csi.params[0]; + } + + handler.scrollDown(amount); + } + + /// `ESC [ Ps X` Erase Character (ECH) + /// + /// https://terminalguide.namepad.de/seq/csi_cx/ + void _csiHandleEraseCharacters() { + var amount = 1; + + if (_csi.params.isNotEmpty) { + amount = _csi.params[0]; + } + + handler.eraseChars(amount); + } + + /// `ESC [ Ps @` Insert Blanks (ICH) + /// + /// https://terminalguide.namepad.de/seq/csi_x40_at/ + /// + /// Inserts amount spaces at current cursor position moving existing cell + /// contents to the right. The contents of the amount right-most columns in + /// the scroll region are lost. The cursor position is not changed. + void _csiHandleInsertBlankCharacters() { + var amount = 1; + + if (_csi.params.isNotEmpty) { + amount = _csi.params[0]; + } + + handler.insertBlankChars(amount); + } + + void _setMode(int mode, bool enabled) { + switch (mode) { + case 4: + return handler.setInsertMode(enabled); + case 20: + return handler.setLineFeedMode(enabled); + default: + return handler.setUnknownMode(mode, enabled); + } + } + + void _setDecMode(int mode, bool enabled) { + switch (mode) { + case 1: + return handler.setCursorKeysMode(enabled); + case 3: + return handler.setColumnMode(enabled); + case 5: + return handler.setReverseDisplayMode(enabled); + case 6: + return handler.setOriginMode(enabled); + case 7: + return handler.setAutoWrapMode(enabled); + case 9: + return enabled + ? handler.setMouseMode(MouseMode.clickOnly) + : handler.setMouseMode(MouseMode.none); + case 12: + case 13: + return handler.setCursorBlinkMode(enabled); + case 25: + return handler.setCursorVisibleMode(enabled); + case 47: + if (enabled) { + return handler.useAltBuffer(); + } else { + return handler.useMainBuffer(); + } + case 66: + return handler.setAppKeypadMode(enabled); + case 1000: + case 10061000: + return enabled + ? handler.setMouseMode(MouseMode.upDownScroll) + : handler.setMouseMode(MouseMode.none); + case 1001: + return enabled + ? handler.setMouseMode(MouseMode.upDownScroll) + : handler.setMouseMode(MouseMode.none); + case 1002: + return enabled + ? handler.setMouseMode(MouseMode.upDownScrollDrag) + : handler.setMouseMode(MouseMode.none); + case 1003: + return enabled + ? handler.setMouseMode(MouseMode.upDownScrollMove) + : handler.setMouseMode(MouseMode.none); + case 1004: + return handler.setReportFocusMode(enabled); + case 1005: + return enabled + ? handler.setMouseReportMode(MouseReportMode.utf) + : handler.setMouseReportMode(MouseReportMode.normal); + case 1006: + return enabled + ? handler.setMouseReportMode(MouseReportMode.sgr) + : handler.setMouseReportMode(MouseReportMode.normal); + case 1007: + return handler.setAltBufferMouseScrollMode(enabled); + case 1015: + return enabled + ? handler.setMouseReportMode(MouseReportMode.urxvt) + : handler.setMouseReportMode(MouseReportMode.normal); + case 1047: + if (enabled) { + handler.useAltBuffer(); + } else { + handler.clearAltBuffer(); + handler.useMainBuffer(); + } + return; + case 1048: + if (enabled) { + return handler.saveCursor(); + } else { + return handler.restoreCursor(); + } + case 1049: + if (enabled) { + handler.saveCursor(); + handler.clearAltBuffer(); + handler.useAltBuffer(); + } else { + handler.useMainBuffer(); + } + return; + case 2004: + return handler.setBracketedPasteMode(enabled); + default: + return handler.setUnknownDecMode(mode, enabled); + } + } + + /// Parse a OSC sequence from the queue. Returns true if a sequence was + /// found and handled. + bool _escHandleOSC() { + final consumed = _consumeOsc(); + if (!consumed) { + return false; + } + + if (_osc.isEmpty) { + return true; + } + + // Common OSCs + if (_osc.length >= 2) { + final ps = _osc[0]; + final pt = _osc[1]; + + 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; + } + } + + // Private extensions + handler.unknownOSC(_osc[0], _osc.sublist(1)); + + return true; + } + + final _osc = []; + + bool _consumeOsc() { + _osc.clear(); + final param = StringBuffer(); + + while (true) { + if (_queue.isEmpty) { + return false; + } + + final char = _queue.consume(); + + // OSC terminates with BEL + if (char == Ascii.BEL) { + _osc.add(param.toString()); + return true; + } + + /// OSC terminates with ST + if (char == Ascii.ESC) { + if (_queue.isEmpty) { + return false; + } + + if (_queue.consume() == Ascii.backslash) { + _osc.add(param.toString()); + } + + return true; + } + + /// Parse next parameter + if (char == Ascii.semicolon) { + _osc.add(param.toString()); + param.clear(); + continue; + } + + param.writeCharCode(char); + } + } +} + +class _Csi { + _Csi({ + required this.params, + required this.finalByte, + // required this.intermediates, + }); + + int? prefix; + + List params; + + int finalByte; + // final List intermediates; + + @override + String toString() { + return params.join(';') + String.fromCharCode(finalByte); + } +} + +/// Function that handles a sequence of characters that starts with an escape. +/// Returns [true] if the sequence was processed, [false] if it was not. +typedef _EscHandler = bool Function(); + +typedef _SbcHandler = void Function(); + +typedef _CsiHandler = void Function(); diff --git a/app/third_party/xterm/lib/src/core/input/handler.dart b/app/third_party/xterm/lib/src/core/input/handler.dart new file mode 100644 index 00000000..6a8ed70b --- /dev/null +++ b/app/third_party/xterm/lib/src/core/input/handler.dart @@ -0,0 +1,210 @@ +import 'package:xterm/src/core/input/keys.dart'; +import 'package:xterm/src/core/input/keytab/keytab.dart'; +import 'package:xterm/src/core/state.dart'; +import 'package:xterm/src/core/platform.dart'; + +/// The key event received from the keyboard, along with the state of the +/// modifier keys and state of the terminal. Typically consumed by the +/// [TerminalInputHandler] to produce a escape sequence that can be recognized +/// by the terminal. +/// +/// See also: +/// - [TerminalInputHandler] +class TerminalKeyboardEvent { + final TerminalKey key; + + final bool shift; + + final bool ctrl; + + final bool alt; + + final TerminalState state; + + final bool altBuffer; + + final TerminalTargetPlatform platform; + + TerminalKeyboardEvent({ + required this.key, + required this.shift, + required this.ctrl, + required this.alt, + required this.state, + required this.altBuffer, + required this.platform, + }); + + TerminalKeyboardEvent copyWith({ + TerminalKey? key, + bool? shift, + bool? ctrl, + bool? alt, + TerminalState? state, + bool? altBuffer, + TerminalTargetPlatform? platform, + }) { + return TerminalKeyboardEvent( + key: key ?? this.key, + shift: shift ?? this.shift, + ctrl: ctrl ?? this.ctrl, + alt: alt ?? this.alt, + state: state ?? this.state, + altBuffer: altBuffer ?? this.altBuffer, + platform: platform ?? this.platform, + ); + } +} + +/// TerminalInputHandler contains the logic for translating a [TerminalKeyboardEvent] +/// into escape sequences that can be recognized by the terminal. +abstract class TerminalInputHandler { + /// Translates a [TerminalKeyboardEvent] into an escape sequence. If the event + /// cannot be translated, null is returned. + String? call(TerminalKeyboardEvent event); +} + +/// A [TerminalInputHandler] that chains multiple handlers together. If any +/// handler returns a non-null value, it is returned. Otherwise, null is +/// returned. +class CascadeInputHandler implements TerminalInputHandler { + final List _handlers; + + const CascadeInputHandler(this._handlers); + + @override + String? call(TerminalKeyboardEvent event) { + for (var handler in _handlers) { + final result = handler(event); + if (result != null) { + return result; + } + } + return null; + } +} + +/// The default input handler for the terminal. That is composed of a +/// [KeytabInputHandler], a [CtrlInputHandler], and a [AltInputHandler]. +/// +/// It's possible to override the default input handler behavior by chaining +/// another input handler before or after the default input handler using +/// [CascadeInputHandler]. +/// +/// See also: +/// * [CascadeInputHandler] +const defaultInputHandler = CascadeInputHandler([ + KeytabInputHandler(), + CtrlInputHandler(), + AltInputHandler(), +]); + +/// A [TerminalInputHandler] that translates key events according to a keytab +/// file. If no keytab is provided, [Keytab.defaultKeytab] is used. +class KeytabInputHandler implements TerminalInputHandler { + const KeytabInputHandler([this.keytab]); + + final Keytab? keytab; + + @override + String? call(TerminalKeyboardEvent event) { + final keytab = this.keytab ?? Keytab.defaultKeytab; + + final record = keytab.find( + event.key, + ctrl: event.ctrl, + alt: event.alt, + shift: event.shift, + newLineMode: event.state.lineFeedMode, + appCursorKeys: event.state.appKeypadMode, + appKeyPad: event.state.appKeypadMode, + appScreen: event.altBuffer, + macos: event.platform == TerminalTargetPlatform.macos, + ); + + if (record == null) { + return null; + } + + var result = record.action.unescapedValue(); + result = insertModifiers(event, result); + return result; + } + + String insertModifiers(TerminalKeyboardEvent event, String action) { + String? code; + + if (event.shift && event.alt && event.ctrl) { + code = '8'; + } else if (event.ctrl && event.alt) { + code = '7'; + } else if (event.shift && event.ctrl) { + code = '6'; + } else if (event.ctrl) { + code = '5'; + } else if (event.shift && event.alt) { + code = '4'; + } else if (event.alt) { + code = '3'; + } else if (event.shift) { + code = '2'; + } + + if (code != null) { + return action.replaceAll('*', code); + } + + return action; + } +} + +/// A [TerminalInputHandler] that translates ctrl + key events into escape +/// sequences. For example, ctrl + a becomes ^A. +class CtrlInputHandler implements TerminalInputHandler { + const CtrlInputHandler(); + + @override + String? call(TerminalKeyboardEvent event) { + if (!event.ctrl || event.shift || event.alt) { + return null; + } + + final key = event.key; + + if (key.index >= TerminalKey.keyA.index && + key.index <= TerminalKey.keyZ.index) { + final input = key.index - TerminalKey.keyA.index + 1; + return String.fromCharCode(input); + } + + return null; + } +} + +/// A [TerminalInputHandler] that translates alt + key events into escape +/// sequences. For example, alt + a becomes ^[a. +class AltInputHandler implements TerminalInputHandler { + const AltInputHandler(); + + @override + String? call(TerminalKeyboardEvent event) { + if (!event.alt || event.ctrl || event.shift) { + return null; + } + + if (event.platform == TerminalTargetPlatform.macos) { + return null; + } + + final key = event.key; + + if (key.index >= TerminalKey.keyA.index && + key.index <= TerminalKey.keyZ.index) { + final charCode = key.index - TerminalKey.keyA.index + 65; + final input = [0x1b, charCode]; + return String.fromCharCodes(input); + } + + return null; + } +} diff --git a/app/third_party/xterm/lib/src/core/input/keys.dart b/app/third_party/xterm/lib/src/core/input/keys.dart new file mode 100644 index 00000000..ed26c2da --- /dev/null +++ b/app/third_party/xterm/lib/src/core/input/keys.dart @@ -0,0 +1,835 @@ +enum TerminalKey { + /// Represents the logical "None" key on the keyboard. + none, + + /// Represents the logical "Hyper" key on the keyboard. + hyper, + + /// Represents the logical "Super Key" key on the keyboard. + superKey, + + /// Represents the logical "Fn Lock" key on the keyboard. + fnLock, + + /// Represents the logical "Suspend" key on the keyboard. + suspend, + + /// Represents the logical "Resume" key on the keyboard. + resume, + + /// Represents the logical "Turbo" key on the keyboard. + turbo, + + /// Represents the logical "Privacy Screen Toggle" key on the keyboard. + privacyScreenToggle, + + /// Represents the logical "Sleep" key on the keyboard. + sleep, + + /// Represents the logical "Wake Up" key on the keyboard. + wakeUp, + + /// Represents the logical "Display Toggle Int Ext" key on the keyboard. + displayToggleIntExt, + + /// Represents the logical "Usb Reserved" key on the keyboard. + usbReserved, + + /// Represents the logical "Usb Error Roll Over" key on the keyboard. + usbErrorRollOver, + + /// Represents the logical "Usb Post Fail" key on the keyboard. + usbPostFail, + + /// Represents the logical "Usb Error Undefined" key on the keyboard. + usbErrorUndefined, + + /// Represents the logical "Key A" key on the keyboard. + keyA, + + /// Represents the logical "Key B" key on the keyboard. + keyB, + + /// Represents the logical "Key C" key on the keyboard. + keyC, + + /// Represents the logical "Key D" key on the keyboard. + keyD, + + /// Represents the logical "Key E" key on the keyboard. + keyE, + + /// Represents the logical "Key F" key on the keyboard. + keyF, + + /// Represents the logical "Key G" key on the keyboard. + keyG, + + /// Represents the logical "Key H" key on the keyboard. + keyH, + + /// Represents the logical "Key I" key on the keyboard. + keyI, + + /// Represents the logical "Key J" key on the keyboard. + keyJ, + + /// Represents the logical "Key K" key on the keyboard. + keyK, + + /// Represents the logical "Key L" key on the keyboard. + keyL, + + /// Represents the logical "Key M" key on the keyboard. + keyM, + + /// Represents the logical "Key N" key on the keyboard. + keyN, + + /// Represents the logical "Key O" key on the keyboard. + keyO, + + /// Represents the logical "Key P" key on the keyboard. + keyP, + + /// Represents the logical "Key Q" key on the keyboard. + keyQ, + + /// Represents the logical "Key R" key on the keyboard. + keyR, + + /// Represents the logical "Key S" key on the keyboard. + keyS, + + /// Represents the logical "Key T" key on the keyboard. + keyT, + + /// Represents the logical "Key U" key on the keyboard. + keyU, + + /// Represents the logical "Key V" key on the keyboard. + keyV, + + /// Represents the logical "Key W" key on the keyboard. + keyW, + + /// Represents the logical "Key X" key on the keyboard. + keyX, + + /// Represents the logical "Key Y" key on the keyboard. + keyY, + + /// Represents the logical "Key Z" key on the keyboard. + keyZ, + + /// Represents the logical "Digit 1" key on the keyboard. + digit1, + + /// Represents the logical "Digit 2" key on the keyboard. + digit2, + + /// Represents the logical "Digit 3" key on the keyboard. + digit3, + + /// Represents the logical "Digit 4" key on the keyboard. + digit4, + + /// Represents the logical "Digit 5" key on the keyboard. + digit5, + + /// Represents the logical "Digit 6" key on the keyboard. + digit6, + + /// Represents the logical "Digit 7" key on the keyboard. + digit7, + + /// Represents the logical "Digit 8" key on the keyboard. + digit8, + + /// Represents the logical "Digit 9" key on the keyboard. + digit9, + + /// Represents the logical "Digit 0" key on the keyboard. + digit0, + + /// Represents the logical "Enter" key on the keyboard. + enter, + + /// Represents the logical "Escape" key on the keyboard. + escape, + + /// Represents the logical "Backspace" key on the keyboard. + backspace, + + /// Represents the logical "Tab" key on the keyboard. + tab, + + /// Represents the logical "Space" key on the keyboard. + space, + + /// Represents the logical "Minus" key on the keyboard. + minus, + + /// Represents the logical "Equal" key on the keyboard. + equal, + + /// Represents the logical "Bracket Left" key on the keyboard. + bracketLeft, + + /// Represents the logical "Bracket Right" key on the keyboard. + bracketRight, + + /// Represents the logical "Backslash" key on the keyboard. + backslash, + + /// Represents the logical "Semicolon" key on the keyboard. + semicolon, + + /// Represents the logical "Quote" key on the keyboard. + quote, + + /// Represents the logical "Backquote" key on the keyboard. + backquote, + + /// Represents the logical "Comma" key on the keyboard. + comma, + + /// Represents the logical "Period" key on the keyboard. + period, + + /// Represents the logical "Slash" key on the keyboard. + slash, + + /// Represents the logical "Caps Lock" key on the keyboard. + capsLock, + + /// Represents the logical "F1" key on the keyboard. + f1, + + /// Represents the logical "F2" key on the keyboard. + f2, + + /// Represents the logical "F3" key on the keyboard. + f3, + + /// Represents the logical "F4" key on the keyboard. + f4, + + /// Represents the logical "F5" key on the keyboard. + f5, + + /// Represents the logical "F6" key on the keyboard. + f6, + + /// Represents the logical "F7" key on the keyboard. + f7, + + /// Represents the logical "F8" key on the keyboard. + f8, + + /// Represents the logical "F9" key on the keyboard. + f9, + + /// Represents the logical "F10" key on the keyboard. + f10, + + /// Represents the logical "F11" key on the keyboard. + f11, + + /// Represents the logical "F12" key on the keyboard. + f12, + + /// Represents the logical "Print Screen" key on the keyboard. + printScreen, + + /// Represents the logical "Scroll Lock" key on the keyboard. + scrollLock, + + /// Represents the logical "Pause" key on the keyboard. + pause, + + /// Represents the logical "Insert" key on the keyboard. + insert, + + /// Represents the logical "Home" key on the keyboard. + home, + + /// Represents the logical "Page Up" key on the keyboard. + pageUp, + + /// Represents the logical "Delete" key on the keyboard. + delete, + + /// Represents the logical "End" key on the keyboard. + end, + + /// Represents the logical "Page Down" key on the keyboard. + pageDown, + + /// Represents the logical "Arrow Right" key on the keyboard. + arrowRight, + + /// Represents the logical "Arrow Left" key on the keyboard. + arrowLeft, + + /// Represents the logical "Arrow Down" key on the keyboard. + arrowDown, + + /// Represents the logical "Arrow Up" key on the keyboard. + arrowUp, + + /// Represents the logical "Num Lock" key on the keyboard. + numLock, + + /// Represents the logical "Numpad Divide" key on the keyboard. + numpadDivide, + + /// Represents the logical "Numpad Multiply" key on the keyboard. + numpadMultiply, + + /// Represents the logical "Numpad Subtract" key on the keyboard. + numpadSubtract, + + /// Represents the logical "Numpad Add" key on the keyboard. + numpadAdd, + + /// Represents the logical "Numpad Enter" key on the keyboard. + numpadEnter, + + /// Represents the logical "Numpad 1" key on the keyboard. + numpad1, + + /// Represents the logical "Numpad 2" key on the keyboard. + numpad2, + + /// Represents the logical "Numpad 3" key on the keyboard. + numpad3, + + /// Represents the logical "Numpad 4" key on the keyboard. + numpad4, + + /// Represents the logical "Numpad 5" key on the keyboard. + numpad5, + + /// Represents the logical "Numpad 6" key on the keyboard. + numpad6, + + /// Represents the logical "Numpad 7" key on the keyboard. + numpad7, + + /// Represents the logical "Numpad 8" key on the keyboard. + numpad8, + + /// Represents the logical "Numpad 9" key on the keyboard. + numpad9, + + /// Represents the logical "Numpad 0" key on the keyboard. + numpad0, + + /// Represents the logical "Numpad Decimal" key on the keyboard. + numpadDecimal, + + /// Represents the logical "Intl Backslash" key on the keyboard. + intlBackslash, + + /// Represents the logical "Context Menu" key on the keyboard. + contextMenu, + + /// Represents the logical "Power" key on the keyboard. + power, + + /// Represents the logical "Numpad Equal" key on the keyboard. + numpadEqual, + + /// Represents the logical "F13" key on the keyboard. + f13, + + /// Represents the logical "F14" key on the keyboard. + f14, + + /// Represents the logical "F15" key on the keyboard. + f15, + + /// Represents the logical "F16" key on the keyboard. + f16, + + /// Represents the logical "F17" key on the keyboard. + f17, + + /// Represents the logical "F18" key on the keyboard. + f18, + + /// Represents the logical "F19" key on the keyboard. + f19, + + /// Represents the logical "F20" key on the keyboard. + f20, + + /// Represents the logical "F21" key on the keyboard. + f21, + + /// Represents the logical "F22" key on the keyboard. + f22, + + /// Represents the logical "F23" key on the keyboard. + f23, + + /// Represents the logical "F24" key on the keyboard. + f24, + + /// Represents the logical "Open" key on the keyboard. + open, + + /// Represents the logical "Help" key on the keyboard. + help, + + /// Represents the logical "Select" key on the keyboard. + select, + + /// Represents the logical "Again" key on the keyboard. + again, + + /// Represents the logical "Undo" key on the keyboard. + undo, + + /// Represents the logical "Cut" key on the keyboard. + cut, + + /// Represents the logical "Copy" key on the keyboard. + copy, + + /// Represents the logical "Paste" key on the keyboard. + paste, + + /// Represents the logical "Find" key on the keyboard. + find, + + /// Represents the logical "Audio Volume Mute" key on the keyboard. + audioVolumeMute, + + /// Represents the logical "Audio Volume Up" key on the keyboard. + audioVolumeUp, + + /// Represents the logical "Audio Volume Down" key on the keyboard. + audioVolumeDown, + + /// Represents the logical "Numpad Comma" key on the keyboard. + numpadComma, + + /// Represents the logical "Intl Ro" key on the keyboard. + intlRo, + + /// Represents the logical "Kana Mode" key on the keyboard. + kanaMode, + + /// Represents the logical "Intl Yen" key on the keyboard. + intlYen, + + /// Represents the logical "Convert" key on the keyboard. + convert, + + /// Represents the logical "Non Convert" key on the keyboard. + nonConvert, + + /// Represents the logical "Lang 1" key on the keyboard. + lang1, + + /// Represents the logical "Lang 2" key on the keyboard. + lang2, + + /// Represents the logical "Lang 3" key on the keyboard. + lang3, + + /// Represents the logical "Lang 4" key on the keyboard. + lang4, + + /// Represents the logical "Lang 5" key on the keyboard. + lang5, + + /// Represents the logical "Abort" key on the keyboard. + abort, + + /// Represents the logical "Props" key on the keyboard. + props, + + /// Represents the logical "Numpad Paren Left" key on the keyboard. + numpadParenLeft, + + /// Represents the logical "Numpad Paren Right" key on the keyboard. + numpadParenRight, + + /// Represents the logical "Numpad Backspace" key on the keyboard. + numpadBackspace, + + /// Represents the logical "Numpad Memory Store" key on the keyboard. + numpadMemoryStore, + + /// Represents the logical "Numpad Memory Recall" key on the keyboard. + numpadMemoryRecall, + + /// Represents the logical "Numpad Memory Clear" key on the keyboard. + numpadMemoryClear, + + /// Represents the logical "Numpad Memory Add" key on the keyboard. + numpadMemoryAdd, + + /// Represents the logical "Numpad Memory Subtract" key on the keyboard. + numpadMemorySubtract, + + /// Represents the logical "Numpad Sign Change" key on the keyboard. + numpadSignChange, + + /// Represents the logical "Numpad Clear" key on the keyboard. + numpadClear, + + /// Represents the logical "Numpad Clear Entry" key on the keyboard. + numpadClearEntry, + + /// Represents the logical "Control Left" key on the keyboard. + controlLeft, + + /// Represents the logical "Shift Left" key on the keyboard. + shiftLeft, + + /// Represents the logical "Alt Left" key on the keyboard. + altLeft, + + /// Represents the logical "Meta Left" key on the keyboard. + metaLeft, + + /// Represents the logical "Control Right" key on the keyboard. + controlRight, + + /// Represents the logical "Shift Right" key on the keyboard. + shiftRight, + + /// Represents the logical "Alt Right" key on the keyboard. + altRight, + + /// Represents the logical "Meta Right" key on the keyboard. + metaRight, + + /// Represents the logical "Info" key on the keyboard. + info, + + /// Represents the logical "Closed Caption Toggle" key on the keyboard. + closedCaptionToggle, + + /// Represents the logical "Brightness Up" key on the keyboard. + brightnessUp, + + /// Represents the logical "Brightness Down" key on the keyboard. + brightnessDown, + + /// Represents the logical "Brightness Toggle" key on the keyboard. + brightnessToggle, + + /// Represents the logical "Brightness Minimum" key on the keyboard. + brightnessMinimum, + + /// Represents the logical "Brightness Maximum" key on the keyboard. + brightnessMaximum, + + /// Represents the logical "Brightness Auto" key on the keyboard. + brightnessAuto, + + /// Represents the logical "Media Last" key on the keyboard. + mediaLast, + + /// Represents the logical "Launch Phone" key on the keyboard. + launchPhone, + + /// Represents the logical "Program Guide" key on the keyboard. + programGuide, + + /// Represents the logical "Exit" key on the keyboard. + exit, + + /// Represents the logical "Channel Up" key on the keyboard. + channelUp, + + /// Represents the logical "Channel Down" key on the keyboard. + channelDown, + + /// Represents the logical "Media Play" key on the keyboard. + mediaPlay, + + /// Represents the logical "Media Pause" key on the keyboard. + mediaPause, + + /// Represents the logical "Media Record" key on the keyboard. + mediaRecord, + + /// Represents the logical "Media Fast Forward" key on the keyboard. + mediaFastForward, + + /// Represents the logical "Media Rewind" key on the keyboard. + mediaRewind, + + /// Represents the logical "Media Track Next" key on the keyboard. + mediaTrackNext, + + /// Represents the logical "Media Track Previous" key on the keyboard. + mediaTrackPrevious, + + /// Represents the logical "Media Stop" key on the keyboard. + mediaStop, + + /// Represents the logical "Eject" key on the keyboard. + eject, + + /// Represents the logical "Media Play Pause" key on the keyboard. + mediaPlayPause, + + /// Represents the logical "Speech Input Toggle" key on the keyboard. + speechInputToggle, + + /// Represents the logical "Bass Boost" key on the keyboard. + bassBoost, + + /// Represents the logical "Media Select" key on the keyboard. + mediaSelect, + + /// Represents the logical "Launch Word Processor" key on the keyboard. + launchWordProcessor, + + /// Represents the logical "Launch Spreadsheet" key on the keyboard. + launchSpreadsheet, + + /// Represents the logical "Launch Mail" key on the keyboard. + launchMail, + + /// Represents the logical "Launch Contacts" key on the keyboard. + launchContacts, + + /// Represents the logical "Launch Calendar" key on the keyboard. + launchCalendar, + + /// Represents the logical "Launch App2" key on the keyboard. + launchApp2, + + /// Represents the logical "Launch App1" key on the keyboard. + launchApp1, + + /// Represents the logical "Launch Internet Browser" key on the keyboard. + launchInternetBrowser, + + /// Represents the logical "Log Off" key on the keyboard. + logOff, + + /// Represents the logical "Lock Screen" key on the keyboard. + lockScreen, + + /// Represents the logical "Launch Control Panel" key on the keyboard. + launchControlPanel, + + /// Represents the logical "Select Task" key on the keyboard. + selectTask, + + /// Represents the logical "Launch Documents" key on the keyboard. + launchDocuments, + + /// Represents the logical "Spell Check" key on the keyboard. + spellCheck, + + /// Represents the logical "Launch Keyboard Layout" key on the keyboard. + launchKeyboardLayout, + + /// Represents the logical "Launch Screen Saver" key on the keyboard. + launchScreenSaver, + + /// Represents the logical "Launch Assistant" key on the keyboard. + launchAssistant, + + /// Represents the logical "Launch Audio Browser" key on the keyboard. + launchAudioBrowser, + + /// Represents the logical "New Key" key on the keyboard. + newKey, + + /// Represents the logical "Close" key on the keyboard. + close, + + /// Represents the logical "Save" key on the keyboard. + save, + + /// Represents the logical "Print" key on the keyboard. + print, + + /// Represents the logical "Browser Search" key on the keyboard. + browserSearch, + + /// Represents the logical "Browser Home" key on the keyboard. + browserHome, + + /// Represents the logical "Browser Back" key on the keyboard. + browserBack, + + /// Represents the logical "Browser Forward" key on the keyboard. + browserForward, + + /// Represents the logical "Browser Stop" key on the keyboard. + browserStop, + + /// Represents the logical "Browser Refresh" key on the keyboard. + browserRefresh, + + /// Represents the logical "Browser Favorites" key on the keyboard. + browserFavorites, + + /// Represents the logical "Zoom In" key on the keyboard. + zoomIn, + + /// Represents the logical "Zoom Out" key on the keyboard. + zoomOut, + + /// Represents the logical "Zoom Toggle" key on the keyboard. + zoomToggle, + + /// Represents the logical "Redo" key on the keyboard. + redo, + + /// Represents the logical "Mail Reply" key on the keyboard. + mailReply, + + /// Represents the logical "Mail Forward" key on the keyboard. + mailForward, + + /// Represents the logical "Mail Send" key on the keyboard. + mailSend, + + /// Represents the logical "Keyboard Layout Select" key on the keyboard. + keyboardLayoutSelect, + + /// Represents the logical "Show All Windows" key on the keyboard. + showAllWindows, + + /// Represents the logical "Game Button 1" key on the keyboard. + gameButton1, + + /// Represents the logical "Game Button 2" key on the keyboard. + gameButton2, + + /// Represents the logical "Game Button 3" key on the keyboard. + gameButton3, + + /// Represents the logical "Game Button 4" key on the keyboard. + gameButton4, + + /// Represents the logical "Game Button 5" key on the keyboard. + gameButton5, + + /// Represents the logical "Game Button 6" key on the keyboard. + gameButton6, + + /// Represents the logical "Game Button 7" key on the keyboard. + gameButton7, + + /// Represents the logical "Game Button 8" key on the keyboard. + gameButton8, + + /// Represents the logical "Game Button 9" key on the keyboard. + gameButton9, + + /// Represents the logical "Game Button 10" key on the keyboard. + gameButton10, + + /// Represents the logical "Game Button 11" key on the keyboard. + gameButton11, + + /// Represents the logical "Game Button 12" key on the keyboard. + gameButton12, + + /// Represents the logical "Game Button 13" key on the keyboard. + gameButton13, + + /// Represents the logical "Game Button 14" key on the keyboard. + gameButton14, + + /// Represents the logical "Game Button 15" key on the keyboard. + gameButton15, + + /// Represents the logical "Game Button 16" key on the keyboard. + gameButton16, + + /// Represents the logical "Game Button A" key on the keyboard. + gameButtonA, + + /// Represents the logical "Game Button B" key on the keyboard. + gameButtonB, + + /// Represents the logical "Game Button C" key on the keyboard. + gameButtonC, + + /// Represents the logical "Game Button Left 1" key on the keyboard. + gameButtonLeft1, + + /// Represents the logical "Game Button Left 2" key on the keyboard. + gameButtonLeft2, + + /// Represents the logical "Game Button Mode" key on the keyboard. + gameButtonMode, + + /// Represents the logical "Game Button Right 1" key on the keyboard. + gameButtonRight1, + + /// Represents the logical "Game Button Right 2" key on the keyboard. + gameButtonRight2, + + /// Represents the logical "Game Button Select" key on the keyboard. + gameButtonSelect, + + /// Represents the logical "Game Button Start" key on the keyboard. + gameButtonStart, + + /// Represents the logical "Game Button Thumb Left" key on the keyboard. + gameButtonThumbLeft, + + /// Represents the logical "Game Button Thumb Right" key on the keyboard. + gameButtonThumbRight, + + /// Represents the logical "Game Button X" key on the keyboard. + gameButtonX, + + /// Represents the logical "Game Button Y" key on the keyboard. + gameButtonY, + + /// Represents the logical "Game Button Z" key on the keyboard. + gameButtonZ, + + /// Represents the logical "Fn" key on the keyboard. + fn, + + /// Represents the logical "Shift" key on the keyboard. + /// + /// This key represents the union of the keys {shiftLeft, shiftRight} when + /// comparing keys. This key will never be generated directly, its main use is + /// in defining key maps. + shift, + + /// Represents the logical "Meta" key on the keyboard. + /// + /// This key represents the union of the keys {metaLeft, metaRight} when + /// comparing keys. This key will never be generated directly, its main use is + /// in defining key maps. + meta, + + /// Represents the logical "Alt" key on the keyboard. + /// + /// This key represents the union of the keys {altLeft, altRight} when + /// comparing keys. This key will never be generated directly, its main use is + /// in defining key maps. + alt, + + /// Represents the logical "Control" key on the keyboard. + /// + /// This key represents the union of the keys {controlLeft, controlRight} when + /// comparing keys. This key will never be generated directly, its main use is + /// in defining key maps. + control, + + // Missing flutter keys. + + backtab, + returnKey, +} diff --git a/app/third_party/xterm/lib/src/core/input/keytab/keytab.dart b/app/third_party/xterm/lib/src/core/input/keytab/keytab.dart new file mode 100644 index 00000000..0999366f --- /dev/null +++ b/app/third_party/xterm/lib/src/core/input/keytab/keytab.dart @@ -0,0 +1,113 @@ +import 'package:xterm/src/core/input/keys.dart'; +import 'package:xterm/src/core/input/keytab/keytab_default.dart'; +import 'package:xterm/src/core/input/keytab/keytab_parse.dart'; +import 'package:xterm/src/core/input/keytab/keytab_record.dart'; +import 'package:xterm/src/core/input/keytab/keytab_token.dart'; + +class Keytab { + Keytab({ + required this.name, + required this.records, + }); + + factory Keytab.parse(String source) { + final tokens = tokenize(source).toList(); + final parser = KeytabParser()..addTokens(tokens); + return parser.result; + } + + static final defaultKeytab = Keytab.parse(kDefaultKeytab); + + final String? name; + + final List records; + + KeytabRecord? find( + TerminalKey key, { + bool ctrl = false, + bool alt = false, + bool shift = false, + bool newLineMode = false, + bool appCursorKeys = false, + bool appKeyPad = false, + bool keyPad = false, + bool appScreen = false, + bool macos = false, + // bool meta, + }) { + for (var record in records) { + if (record.key != key) { + continue; + } + + if (record.anyModifier == true) { + if (ctrl == false && alt == false && shift == false) { + continue; + } + } else if (record.anyModifier == false) { + if (ctrl != false || alt != false || shift != false) { + continue; + } + } else { + if (record.ctrl != null && record.ctrl != ctrl) { + continue; + } + + if (record.shift != null && record.shift != shift) { + continue; + } + + if (record.alt != null && record.alt != alt) { + continue; + } + } + + if (record.newLine != null && record.newLine != newLineMode) { + continue; + } + + if (record.appCursorKeys != null && + record.appCursorKeys != appCursorKeys) { + continue; + } + + if (record.appKeyPad != null && record.appKeyPad != appKeyPad) { + continue; + } + + if (record.keyPad != null && record.keyPad != keyPad) { + continue; + } + + if (record.appScreen != null && record.appScreen != appScreen) { + continue; + } + + if (record.macos != null && record.macos != macos) { + continue; + } + + // TODO: support VT52 + if (record.ansi == false) { + continue; + } + + return record; + } + + return null; + } + + @override + String toString() { + final buffer = StringBuffer(); + + buffer.writeln('keyboard "$name"'); + + for (var record in records) { + buffer.writeln(record); + } + + return buffer.toString(); + } +} diff --git a/app/third_party/xterm/lib/src/core/input/keytab/keytab_default.dart b/app/third_party/xterm/lib/src/core/input/keytab/keytab_default.dart new file mode 100644 index 00000000..b451ca44 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/input/keytab/keytab_default.dart @@ -0,0 +1,213 @@ +import 'package:xterm/src/core/input/keytab/keytab_parse.dart'; +import 'package:xterm/src/core/input/keytab/keytab_token.dart'; + +const kDefaultKeytab = r''' +# [README.default.Keytab] Default Keyboard Table +# +# To customize your keyboard, copy this file to something ending with +# .keytab and change it to meet you needs. +# +# Please read the README-KeyTab and the doc/user/README.keyboard files +# in this case. +# +# -------------------------------------------------------------- + +keyboard "Default (XFree 4)" + +# -------------------------------------------------------------- +# +# Note that this particular table is a "risc" version made to +# ease customization without bothering with obsolete details. +# See VT100.keytab for the more hairy stuff. +# +# -------------------------------------------------------------- + +# common keys + +key Escape : "\E" + +key Tab -Shift : "\t" +key Tab +Shift+Ansi : "\E[Z" +key Tab +Shift-Ansi : "\t" +key Backtab +Ansi : "\E[Z" +key Backtab -Ansi : "\t" + +key Return-Shift-NewLine : "\r" +key Return-Shift+NewLine : "\r\n" + +key Return+Shift : "\EOM" + +key Backspace +Alt : "\x17" + +# Backspace and Delete codes are preserving CTRL-H. +# +# Backspace without CTRL sends '^?'; this matches XTerm behaviour, so that +# pressing Alt+Backspace will send \E + Del, which is the expected behaviour +# in some apps (e.g. emacs), and it was the behaviour before the commit +# that add the Backspace +Control rule +key Backspace -Control : "\x7f" + +# Match xterm behaviour: Backspace sends '^H' when Control is pressed +# BS, hex \x08, \b +key Backspace +Control : "\b" + +# Arrow keys in VT52 mode +# shift up/down are reserved for scrolling. +# shift left/right are reserved for switching between tabs (this is hardcoded). + +key Up -Shift-Ansi : "\EA" +key Down -Shift-Ansi : "\EB" +key Right-Shift-Ansi : "\EC" +key Left -Shift-Ansi : "\ED" + +# Arrow keys in ANSI mode with Application - and Normal Cursor Mode) + +key Up -Shift-AnyMod+Ansi+AppCuKeys : "\EOA" +key Down -Shift-AnyMod+Ansi+AppCuKeys : "\EOB" +key Right -Shift-AnyMod+Ansi+AppCuKeys : "\EOC" +key Left -Shift-AnyMod+Ansi+AppCuKeys : "\EOD" + +key Up -Shift-AnyMod+Ansi-AppCuKeys : "\E[A" +key Down -Shift-AnyMod+Ansi-AppCuKeys : "\E[B" +key Right -Shift-AnyMod+Ansi-AppCuKeys : "\E[C" +key Left -Shift-AnyMod+Ansi-AppCuKeys : "\E[D" + +key Up -Shift+AnyMod+Ansi : "\E[1;5A" +key Down -Shift+AnyMod+Ansi : "\E[1;5B" + +# Right / Left with Control +key Right -Shift-Alt+Control+Ansi : "\E[1;5C" +key Left -Shift-Alt+Control+Ansi : "\E[1;5D" + +# Right / Left with Alt not on a Mac +key Right -Shift+Alt-Control+Ansi-Mac : "\E[1;5C" +key Left -Shift+Alt-Control+Ansi-Mac : "\E[1;5D" + +# Right / Left with Alt on a Mac +key Right -Shift+Alt-Control+Ansi+Mac : "\Ef" +key Left -Shift+Alt-Control+Ansi+Mac : "\Eb" + +key Up +Shift+AppScreen : "\E[1;*A" +key Down +Shift+AppScreen : "\E[1;*B" +key Left +Shift+AppScreen : "\E[1;*D" +key Right +Shift+AppScreen : "\E[1;*C" + +# Keypad keys with NumLock ON +# (see https://web.archive.org/web/20070807181942/http://www.nw.com/nw/WWW/products/wizcon/vt100.html +# https://vt100.net/docs/vt100-ug/chapter3.html) +# +# Not enabled for now because it breaks the keypad in Vim. +# +#key 0 +KeyPad+AppKeyPad : "\EOp" +#key 1 +KeyPad+AppKeyPad : "\EOq" +#key 2 +KeyPad+AppKeyPad : "\EOr" +#key 3 +KeyPad+AppKeyPad : "\EOs" +#key 4 +KeyPad+AppKeyPad : "\EOt" +#key 5 +KeyPad+AppKeyPad : "\EOu" +#key 6 +KeyPad+AppKeyPad : "\EOv" +#key 7 +KeyPad+AppKeyPad : "\EOw" +#key 8 +KeyPad+AppKeyPad : "\EOx" +#key 9 +KeyPad+AppKeyPad : "\EOy" +#key + +KeyPad+AppKeyPad : "\EOl" +#key - +KeyPad+AppKeyPad : "\EOm" +#key . +KeyPad+AppKeyPad : "\EOn" +#key * +KeyPad+AppKeyPad : "\EOM" +#key Enter +KeyPad+AppKeyPad : "\r" + +# Keypad keys with NumLock Off +key Up -Shift+Ansi+AppCuKeys+KeyPad : "\EOA" +key Down -Shift+Ansi+AppCuKeys+KeyPad : "\EOB" +key Right -Shift+Ansi+AppCuKeys+KeyPad : "\EOC" +key Left -Shift+Ansi+AppCuKeys+KeyPad : "\EOD" + +key Up -Shift+Ansi-AppCuKeys+KeyPad : "\E[A" +key Down -Shift+Ansi-AppCuKeys+KeyPad : "\E[B" +key Right -Shift+Ansi-AppCuKeys+KeyPad : "\E[C" +key Left -Shift+Ansi-AppCuKeys+KeyPad : "\E[D" + +key Home +AppCuKeys+KeyPad : "\EOH" +key End +AppCuKeys+KeyPad : "\EOF" +key Home -AppCuKeys+KeyPad : "\E[H" +key End -AppCuKeys+KeyPad : "\E[F" + +key Insert +KeyPad : "\E[2~" +key Delete +KeyPad : "\E[3~" +key PgUp -Shift+KeyPad : "\E[5~" +key PgDown -Shift+KeyPad : "\E[6~" + +# the key labelled 5 on the Keypad, is Qt::Key_Clear (a very intuitive +# and discoverable name...) +key Clear +KeyPad : "\E[E" + +# other grey PC keys + +key Enter+NewLine : "\r\n" +key Enter-NewLine : "\r" + +key NumEnter+NewLine : "\r\n" +key NumEnter-NewLine : "\r" + +key Home -AnyMod-AppCuKeys : "\E[H" +key End -AnyMod-AppCuKeys : "\E[F" +key Home -AnyMod+AppCuKeys : "\EOH" +key End -AnyMod+AppCuKeys : "\EOF" +key Home +AnyMod : "\E[1;*H" +key End +AnyMod : "\E[1;*F" + +key Insert -AnyMod : "\E[2~" +key Delete -AnyMod : "\E[3~" +key Insert +AnyMod : "\E[2;*~" +key Delete +AnyMod : "\E[3;*~" + +key PgUp -Shift-AnyMod : "\E[5~" +key PgDown -Shift-AnyMod : "\E[6~" +key PgUp -Shift+AnyMod : "\E[5;*~" +key PgDown -Shift+AnyMod : "\E[6;*~" + +# Function keys +key F1 -AnyMod : "\EOP" +key F2 -AnyMod : "\EOQ" +key F3 -AnyMod : "\EOR" +key F4 -AnyMod : "\EOS" +key F5 -AnyMod : "\E[15~" +key F6 -AnyMod : "\E[17~" +key F7 -AnyMod : "\E[18~" +key F8 -AnyMod : "\E[19~" +key F9 -AnyMod : "\E[20~" +key F10 -AnyMod : "\E[21~" +key F11 -AnyMod : "\E[23~" +key F12 -AnyMod : "\E[24~" + +key F1 +AnyMod : "\EO*P" +key F2 +AnyMod : "\EO*Q" +key F3 +AnyMod : "\EO*R" +key F4 +AnyMod : "\EO*S" +key F5 +AnyMod : "\E[15;*~" +key F6 +AnyMod : "\E[17;*~" +key F7 +AnyMod : "\E[18;*~" +key F8 +AnyMod : "\E[19;*~" +key F9 +AnyMod : "\E[20;*~" +key F10 +AnyMod : "\E[21;*~" +key F11 +AnyMod : "\E[23;*~" +key F12 +AnyMod : "\E[24;*~" + +# Work around dead keys + +key Space +Control : "\x00" + +# Some keys are used by konsole to cause operations. +# The scroll* operations refer to the history buffer. + +key Up +Shift-AppScreen : scrollLineUp +key PgUp +Shift-AppScreen : scrollPageUp +key Home +Shift-AppScreen : scrollUpToTop +key Down +Shift-AppScreen : scrollLineDown +key PgDown +Shift-AppScreen : scrollPageDown +key End +Shift-AppScreen : scrollDownToBottom +'''; + +void main() { + final tokens = tokenize(kDefaultKeytab).toList(); + final parser = KeytabParser()..addTokens(tokens); + print(parser.result); +} diff --git a/app/third_party/xterm/lib/src/core/input/keytab/keytab_escape.dart b/app/third_party/xterm/lib/src/core/input/keytab/keytab_escape.dart new file mode 100644 index 00000000..5375bc34 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/input/keytab/keytab_escape.dart @@ -0,0 +1,21 @@ +final _esc = String.fromCharCode(0x1b); + +String keytabUnescape(String str) { + str = str + .replaceAll(r'\E', _esc) + .replaceAll(r'\\', '\\') + .replaceAll(r'\"', '"') + .replaceAll(r'\t', '\t') + .replaceAll(r'\r', '\r') + .replaceAll(r'\n', '\n') + .replaceAll(r'\b', '\b'); + + final hexPattern = RegExp(r'\\x([0-9a-fA-F][0-9a-fA-F])'); + str = str.replaceAllMapped(hexPattern, (match) { + final hexString = match.group(1)!; + final hexValue = int.parse(hexString, radix: 16); + return String.fromCharCode(hexValue); + }); + + return str; +} diff --git a/app/third_party/xterm/lib/src/core/input/keytab/keytab_parse.dart b/app/third_party/xterm/lib/src/core/input/keytab/keytab_parse.dart new file mode 100644 index 00000000..96f80358 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/input/keytab/keytab_parse.dart @@ -0,0 +1,186 @@ +import 'package:xterm/src/core/input/keytab/keytab.dart'; +import 'package:xterm/src/core/input/keytab/keytab_record.dart'; +import 'package:xterm/src/core/input/keytab/keytab_token.dart'; +import 'package:xterm/src/core/input/keytab/qt_keyname.dart'; + +class ParseError {} + +class TokensReader { + TokensReader(this.tokens); + + final List tokens; + + var _pos = 0; + + bool get done => _pos > tokens.length - 1; + + KeytabToken? take() { + final result = peek(); + _pos += 1; + return result; + } + + KeytabToken? peek() { + if (done) return null; + return tokens[_pos]; + } +} + +class KeytabParser { + String? _name; + final _records = []; + + void addTokens(List tokens) { + final reader = TokensReader(tokens); + + while (!reader.done) { + if (reader.peek()!.type == KeytabTokenType.keyboard) { + _parseName(reader); + continue; + } + + if (reader.peek()!.type == KeytabTokenType.keyDefine) { + _parseKeyDefine(reader); + continue; + } + + throw ParseError(); + } + } + + Keytab get result { + return Keytab(name: _name, records: _records); + } + + void _parseName(TokensReader reader) { + if (reader.take()!.type != KeytabTokenType.keyboard) { + throw ParseError(); + } + + final name = reader.take()!; + if (name.type != KeytabTokenType.input) { + throw ParseError(); + } + + _name = name.value; + } + + void _parseKeyDefine(TokensReader reader) { + if (reader.take()!.type != KeytabTokenType.keyDefine) { + throw ParseError(); + } + + final keyName = reader.take()!; + + if (keyName.type != KeytabTokenType.keyName) { + throw ParseError(); + } + + final key = qtKeynameMap[keyName.value]; + if (key == null) { + throw ParseError(); + } + + bool? alt; + bool? ctrl; + bool? shift; + bool? anyModifier; + bool? ansi; + bool? appScreen; + bool? keyPad; + bool? appCursorKeys; + bool? appKeyPad; + bool? newLine; + bool? mac; + + while (reader.peek()!.type == KeytabTokenType.modeStatus) { + bool modeStatus; + switch (reader.take()!.value) { + case '+': + modeStatus = true; + break; + case '-': + modeStatus = false; + break; + default: + throw ParseError(); + } + + final mode = reader.take(); + if (mode!.type != KeytabTokenType.mode) { + throw ParseError(); + } + + switch (mode.value) { + case 'Alt': + alt = modeStatus; + break; + case 'Control': + ctrl = modeStatus; + break; + case 'Shift': + shift = modeStatus; + break; + case 'AnyMod': + anyModifier = modeStatus; + break; + case 'Ansi': + ansi = modeStatus; + break; + case 'AppScreen': + appScreen = modeStatus; + break; + case 'KeyPad': + keyPad = modeStatus; + break; + case 'AppCuKeys': + appCursorKeys = modeStatus; + break; + case 'AppKeyPad': + appKeyPad = modeStatus; + break; + case 'NewLine': + newLine = modeStatus; + break; + case 'Mac': + mac = modeStatus; + break; + default: + throw ParseError(); + } + } + + if (reader.take()!.type != KeytabTokenType.colon) { + throw ParseError(); + } + + final actionToken = reader.take()!; + KeytabAction action; + if (actionToken.type == KeytabTokenType.input) { + action = KeytabAction(KeytabActionType.input, actionToken.value); + } else if (actionToken.type == KeytabTokenType.shortcut) { + action = KeytabAction(KeytabActionType.shortcut, actionToken.value); + } else { + throw ParseError(); + } + + final record = KeytabRecord( + qtKeyName: keyName.value, + key: key, + action: action, + alt: alt, + ctrl: ctrl, + shift: shift, + anyModifier: anyModifier, + ansi: ansi, + appScreen: appScreen, + keyPad: keyPad, + appCursorKeys: appCursorKeys, + appKeyPad: appKeyPad, + newLine: newLine, + macos: mac, + ); + + _records.add(record); + } +} diff --git a/app/third_party/xterm/lib/src/core/input/keytab/keytab_record.dart b/app/third_party/xterm/lib/src/core/input/keytab/keytab_record.dart new file mode 100644 index 00000000..7ba3caeb --- /dev/null +++ b/app/third_party/xterm/lib/src/core/input/keytab/keytab_record.dart @@ -0,0 +1,134 @@ +import 'package:xterm/src/core/input/keys.dart'; +import 'package:xterm/src/core/input/keytab/keytab_escape.dart'; + +enum KeytabActionType { + input, + shortcut, +} + +class KeytabAction { + KeytabAction(this.type, this.value); + + final KeytabActionType type; + + final String value; + + String unescapedValue() { + if (type == KeytabActionType.input) { + return keytabUnescape(value); + } else { + return value; + } + } + + @override + String toString() { + switch (type) { + case KeytabActionType.input: + return '"$value"'; + case KeytabActionType.shortcut: + return value; + } + } +} + +class KeytabRecord { + KeytabRecord({ + required this.qtKeyName, + required this.key, + required this.action, + required this.alt, + required this.ctrl, + required this.shift, + required this.anyModifier, + required this.ansi, + required this.appScreen, + required this.keyPad, + required this.appCursorKeys, + required this.appKeyPad, + required this.newLine, + required this.macos, + }); + + String qtKeyName; + TerminalKey key; + KeytabAction action; + + bool? alt; + bool? ctrl; + bool? shift; + bool? anyModifier; + bool? ansi; + bool? appScreen; + bool? keyPad; + bool? appCursorKeys; + bool? appKeyPad; + bool? newLine; + bool? macos; + + @override + String toString() { + final buffer = StringBuffer(); + buffer.write('$qtKeyName '); + + if (alt != null) { + buffer.write(_toMode(alt!, 'Alt')); + } + + if (ctrl != null) { + buffer.write(_toMode(ctrl!, 'Control')); + } + + if (shift != null) { + buffer.write(_toMode(shift!, 'Shift')); + } + + if (anyModifier != null) { + buffer.write(_toMode(anyModifier!, 'AnyMod')); + } + + if (ansi != null) { + buffer.write(_toMode(ansi!, 'Ansi')); + } + + if (appScreen != null) { + buffer.write(_toMode(appScreen!, 'AppScreen')); + } + + if (keyPad != null) { + buffer.write(_toMode(keyPad!, 'KeyPad')); + } + + if (appCursorKeys != null) { + buffer.write(_toMode(appCursorKeys!, 'AppCuKeys')); + } + + if (appKeyPad != null) { + buffer.write(_toMode(appKeyPad!, 'AppKeyPad')); + } + + if (newLine != null) { + buffer.write(_toMode(newLine!, 'NewLine')); + } + + if (macos != null) { + buffer.write(_toMode(macos!, 'Mac')); + } + + buffer.write(' : $action'); + + return buffer.toString(); + } + + static String _toMode(bool status, String mode) { + if (status == true) { + return '+$mode'; + } + + if (status == false) { + return '-$mode'; + } + + return ''; + } +} diff --git a/app/third_party/xterm/lib/src/core/input/keytab/keytab_token.dart b/app/third_party/xterm/lib/src/core/input/keytab/keytab_token.dart new file mode 100644 index 00000000..a8ab8706 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/input/keytab/keytab_token.dart @@ -0,0 +1,179 @@ +import 'dart:math' show min; + +enum KeytabTokenType { + keyDefine, + keyboard, + keyName, + mode, + modeStatus, + colon, + input, + shortcut, +} + +class KeytabToken { + KeytabToken(this.type, this.value); + + final KeytabTokenType type; + final String value; + + @override + String toString() { + return '$type<$value>'; + } +} + +class LineReader { + LineReader(this.line); + + final String line; + + var _pos = 0; + + bool get done => _pos > line.length - 1; + + String? take([int count = 1]) { + final result = peek(count); + _pos += count; + return result; + } + + String? peek([int count = 1]) { + if (done) return null; + final end = min(_pos + count, line.length); + final result = line.substring(_pos, end); + return result; + } + + void skipWhitespace() { + while (peek() == ' ' || peek() == '\t') { + _pos += 1; + } + } + + String readString() { + final buffer = StringBuffer(); + final pattern = RegExp(r'\w|_'); + + while (!done && line[_pos].contains(pattern)) { + buffer.write(line[_pos]); + _pos++; + } + + return buffer.toString(); + } + + String readUntil(Pattern pattern, {bool inclusive = false}) { + final buffer = StringBuffer(); + + while (!done && !line[_pos].contains(pattern)) { + buffer.write(line[_pos]); + _pos++; + } + + if (!done && inclusive) { + buffer.write(line[_pos]); + _pos++; + } + + return buffer.toString(); + } +} + +class TokenizeError {} + +Iterable tokenize(String source) sync* { + final lines = source.split('\n'); + + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim(); + line = line.replaceFirst(RegExp('#.*'), ''); + + if (line == '') { + continue; + } + + if (_isKeyboardNameDefine(line)) { + yield* _parseKeyboardNameDefine(line); + } + + if (_isKeyDefine(line)) { + yield* _parseKeyDefine(line); + } + } +} + +bool _isKeyboardNameDefine(String line) { + return line.startsWith('keyboard '); +} + +bool _isKeyDefine(String line) { + return line.startsWith('key '); +} + +Iterable _parseKeyboardNameDefine(String line) sync* { + final reader = LineReader(line.trim()); + + if (reader.readString() == 'keyboard') { + yield KeytabToken(KeytabTokenType.keyboard, 'keyboard'); + } else { + throw TokenizeError(); + } + + reader.skipWhitespace(); + + yield _readInput(reader); +} + +Iterable _parseKeyDefine(String line) sync* { + final reader = LineReader(line.trim()); + + if (reader.readString() == 'key') { + yield KeytabToken(KeytabTokenType.keyDefine, 'key'); + } else { + throw TokenizeError(); + } + + reader.skipWhitespace(); + + final keyName = reader.readString(); + yield KeytabToken(KeytabTokenType.keyName, keyName); + + reader.skipWhitespace(); + + while (reader.peek() == '+' || reader.peek() == '-') { + final modeStatus = reader.take()!; + yield KeytabToken(KeytabTokenType.modeStatus, modeStatus); + final mode = reader.readString(); + yield KeytabToken(KeytabTokenType.mode, mode); + reader.skipWhitespace(); + } + + if (reader.take() == ':') { + yield KeytabToken(KeytabTokenType.colon, ':'); + } else { + throw TokenizeError(); + } + + reader.skipWhitespace(); + + if (reader.peek() == '"') { + yield _readInput(reader); + } else { + final action = reader.readString(); + yield KeytabToken(KeytabTokenType.shortcut, action); + } +} + +KeytabToken _readInput(LineReader reader) { + reader.skipWhitespace(); + + if (reader.take() != '"') { + throw TokenizeError(); + } + + final value = reader.readUntil('"'); + reader.take(); + + return KeytabToken(KeytabTokenType.input, value); +} diff --git a/app/third_party/xterm/lib/src/core/input/keytab/qt_keyname.dart b/app/third_party/xterm/lib/src/core/input/keytab/qt_keyname.dart new file mode 100644 index 00000000..4eca3e63 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/input/keytab/qt_keyname.dart @@ -0,0 +1,477 @@ +import 'package:xterm/src/core/input/keys.dart'; + +/// See: https://doc.qt.io/qt-5/qt.html#Key-enum +const qtKeynameMap = { + 'Escape': TerminalKey.escape, + 'Tab': TerminalKey.tab, + 'Backtab': TerminalKey.backtab, + 'Backspace': TerminalKey.backspace, + 'Return': TerminalKey.returnKey, + 'Enter': TerminalKey.enter, + 'NumEnter': TerminalKey.numpadEnter, + 'Insert': TerminalKey.insert, + 'Delete': TerminalKey.delete, + 'Pause': TerminalKey.pause, + 'Print': TerminalKey.print, +// 'SysReq': TerminalKey.sysReq, + 'Clear': TerminalKey.numpadClear, + 'Home': TerminalKey.home, + 'End': TerminalKey.end, + 'Left': TerminalKey.arrowLeft, + 'Up': TerminalKey.arrowUp, + 'Right': TerminalKey.arrowRight, + 'Down': TerminalKey.arrowDown, + 'PageUp': TerminalKey.pageUp, + 'PageDown': TerminalKey.pageDown, + 'PgUp': TerminalKey.pageUp, + 'PgDown': TerminalKey.pageDown, + 'Shift': TerminalKey.shift, + 'Control': TerminalKey.control, + 'Meta': TerminalKey.meta, + 'Alt': TerminalKey.alt, +// 'AltGr': TerminalKey.altGr, + 'CapsLock': TerminalKey.capsLock, + 'NumLock': TerminalKey.numLock, + 'ScrollLock': TerminalKey.scrollLock, + 'F1': TerminalKey.f1, + 'F2': TerminalKey.f2, + 'F3': TerminalKey.f3, + 'F4': TerminalKey.f4, + 'F5': TerminalKey.f5, + 'F6': TerminalKey.f6, + 'F7': TerminalKey.f7, + 'F8': TerminalKey.f8, + 'F9': TerminalKey.f9, + 'F10': TerminalKey.f10, + 'F11': TerminalKey.f11, + 'F12': TerminalKey.f12, + 'F13': TerminalKey.f13, + 'F14': TerminalKey.f14, + 'F15': TerminalKey.f15, + 'F16': TerminalKey.f16, + 'F17': TerminalKey.f17, + 'F18': TerminalKey.f18, + 'F19': TerminalKey.f19, + 'F20': TerminalKey.f20, + 'F21': TerminalKey.f21, + 'F22': TerminalKey.f22, + 'F23': TerminalKey.f23, + 'F24': TerminalKey.f24, +// 'F25': TerminalKey.f25, +// 'F26': TerminalKey.f26, +// 'F27': TerminalKey.f27, +// 'F28': TerminalKey.f28, +// 'F29': TerminalKey.f29, +// 'F30': TerminalKey.f30, +// 'F31': TerminalKey.f31, +// 'F32': TerminalKey.f32, +// 'F33': TerminalKey.f33, +// 'F34': TerminalKey.f34, +// 'F35': TerminalKey.f35, +// 'Super_L': TerminalKey.super_L, +// 'Super_R': TerminalKey.super_R, +// 'Menu': TerminalKey.menu, +// 'Hyper_L': TerminalKey.hyper_L, +// 'Hyper_R': TerminalKey.hyper_R, + 'Help': TerminalKey.help, +// 'Direction_L': TerminalKey.direction_L, +// 'Direction_R': TerminalKey.direction_R, + 'Space': TerminalKey.space, + // 'Any': TerminalKey.any, + // 'Exclam': TerminalKey.exclam, + // 'QuoteDbl': TerminalKey.quoteDbl, + // 'NumberSign': TerminalKey.numberSign, + // 'Dollar': TerminalKey.dollar, + // 'Percent': TerminalKey.percent, + // 'Ampersand': TerminalKey.ampersand, + // 'Apostrophe': TerminalKey.apostrophe, + 'ParenLeft': TerminalKey.numpadParenLeft, + 'ParenRight': TerminalKey.numpadParenRight, + // 'Asterisk': TerminalKey.asterisk, + // 'Plus': TerminalKey.plus, + 'Comma': TerminalKey.comma, + 'Minus': TerminalKey.minus, + 'Period': TerminalKey.period, + 'Slash': TerminalKey.slash, + '0': TerminalKey.digit0, + '1': TerminalKey.digit1, + '2': TerminalKey.digit2, + '3': TerminalKey.digit3, + '4': TerminalKey.digit4, + '5': TerminalKey.digit5, + '6': TerminalKey.digit6, + '7': TerminalKey.digit7, + '8': TerminalKey.digit8, + '9': TerminalKey.digit9, +// 'Colon': TerminalKey.colon, + 'Semicolon': TerminalKey.semicolon, +// 'Less': TerminalKey.less, +// 'Equal': TerminalKey.equal, +// 'Greater': TerminalKey.greater, +// 'Question': TerminalKey.question, +// 'At': TerminalKey.at, + 'A': TerminalKey.keyA, + 'B': TerminalKey.keyB, + 'C': TerminalKey.keyC, + 'D': TerminalKey.keyD, + 'E': TerminalKey.keyE, + 'F': TerminalKey.keyF, + 'G': TerminalKey.keyG, + 'H': TerminalKey.keyH, + 'I': TerminalKey.keyI, + 'J': TerminalKey.keyJ, + 'K': TerminalKey.keyK, + 'L': TerminalKey.keyL, + 'M': TerminalKey.keyM, + 'N': TerminalKey.keyN, + 'O': TerminalKey.keyO, + 'P': TerminalKey.keyP, + 'Q': TerminalKey.keyQ, + 'R': TerminalKey.keyR, + 'S': TerminalKey.keyS, + 'T': TerminalKey.keyT, + 'U': TerminalKey.keyU, + 'V': TerminalKey.keyV, + 'W': TerminalKey.keyW, + 'X': TerminalKey.keyX, + 'Y': TerminalKey.keyY, + 'Z': TerminalKey.keyZ, + 'BracketLeft': TerminalKey.bracketLeft, + 'Backslash': TerminalKey.backslash, + 'BracketRight': TerminalKey.bracketRight, +// 'AsciiCircum': TerminalKey.asciiCircum, + // 'Underscore': TerminalKey.underscore, + // 'QuoteLeft': TerminalKey.quoteLeft, +// 'BraceLeft': TerminalKey.braceLeft, + // 'Bar': TerminalKey.bar, +// 'BraceRight': TerminalKey.braceRight, + // 'AsciiTilde': TerminalKey.asciiTilde, +// 'nobreakspace': TerminalKey.nobreakspace, +// 'exclamdown': TerminalKey.exclamdown, +// 'cent': TerminalKey.cent, +// 'sterling': TerminalKey.sterling, +// 'currency': TerminalKey.currency, +// 'yen': TerminalKey.yen, +// 'brokenbar': TerminalKey.brokenbar, +// 'section': TerminalKey.section, +// 'diaeresis': TerminalKey.diaeresis, +// 'copyright': TerminalKey.copyright, +// 'ordfeminine': TerminalKey.ordfeminine, +// 'guillemotleft': TerminalKey.guillemotleft, +// 'notsign': TerminalKey.notsign, +// 'hyphen': TerminalKey.hyphen, +// 'registered': TerminalKey.registered, +// 'macron': TerminalKey.macron, +// 'degree': TerminalKey.degree, +// 'plusminus': TerminalKey.plusminus, +// 'twosuperior': TerminalKey.twosuperior, +// 'threesuperior': TerminalKey.threesuperior, +// 'acute': TerminalKey.acute, +// // 'mu': TerminalKey.mu, +// 'paragraph': TerminalKey.paragraph, +// 'periodcentered': TerminalKey.periodcentered, +// 'cedilla': TerminalKey.cedilla, +// 'onesuperior': TerminalKey.onesuperior, +// 'masculine': TerminalKey.masculine, +// 'guillemotright': TerminalKey.guillemotright, +// 'onequarter': TerminalKey.onequarter, +// 'onehalf': TerminalKey.onehalf, +// 'threequarters': TerminalKey.threequarters, +// 'questiondown': TerminalKey.questiondown, +// 'Agrave': TerminalKey.agrave, +// 'Aacute': TerminalKey.aacute, +// 'Acircumflex': TerminalKey.acircumflex, +// 'Atilde': TerminalKey.atilde, +// 'Adiaeresis': TerminalKey.adiaeresis, +// 'Aring': TerminalKey.aring, +// 'AE': TerminalKey.aE, +// 'Ccedilla': TerminalKey.ccedilla, +// 'Egrave': TerminalKey.egrave, +// 'Eacute': TerminalKey.eacute, +// 'Ecircumflex': TerminalKey.ecircumflex, +// 'Ediaeresis': TerminalKey.ediaeresis, +// 'Igrave': TerminalKey.igrave, +// 'Iacute': TerminalKey.iacute, +// 'Icircumflex': TerminalKey.icircumflex, +// 'Idiaeresis': TerminalKey.idiaeresis, +// 'ETH': TerminalKey.eTH, +// 'Ntilde': TerminalKey.ntilde, +// 'Ograve': TerminalKey.ograve, +// 'Oacute': TerminalKey.oacute, +// 'Ocircumflex': TerminalKey.ocircumflex, +// 'Otilde': TerminalKey.otilde, +// 'Odiaeresis': TerminalKey.odiaeresis, +// 'multiply': TerminalKey.multiply, +// 'Ooblique': TerminalKey.ooblique, +// 'Ugrave': TerminalKey.ugrave, +// 'Uacute': TerminalKey.uacute, +// 'Ucircumflex': TerminalKey.ucircumflex, +// 'Udiaeresis': TerminalKey.udiaeresis, +// 'Yacute': TerminalKey.yacute, +// 'THORN': TerminalKey.tHORN, +// 'ssharp': TerminalKey.ssharp, +// 'division': TerminalKey.division, +// 'ydiaeresis': TerminalKey.ydiaeresis, +// 'Multi_key': TerminalKey.multi_key, +// 'Codeinput': TerminalKey.codeinput, +// 'SingleCandidate': TerminalKey.singleCandidate, +// 'MultipleCandidate': TerminalKey.multipleCandidate, +// 'PreviousCandidate': TerminalKey.previousCandidate, +// 'Mode_switch': TerminalKey.mode_switch, +// 'Kanji': TerminalKey.kanji, +// 'Muhenkan': TerminalKey.muhenkan, +// 'Henkan': TerminalKey.henkan, +// 'Romaji': TerminalKey.romaji, +// 'Hiragana': TerminalKey.hiragana, +// 'Katakana': TerminalKey.katakana, +// 'Hiragana_Katakana': TerminalKey.hiragana_Katakana, +// 'Zenkaku': TerminalKey.zenkaku, +// 'Hankaku': TerminalKey.hankaku, +// 'Zenkaku_Hankaku': TerminalKey.zenkaku_Hankaku, +// 'Touroku': TerminalKey.touroku, +// 'Massyo': TerminalKey.massyo, +// 'Kana_Lock': TerminalKey.kana_Lock, +// 'Kana_Shift': TerminalKey.kana_Shift, +// 'Eisu_Shift': TerminalKey.eisu_Shift, +// 'Eisu_toggle': TerminalKey.eisu_toggle, +// 'Hangul': TerminalKey.hangul, +// 'Hangul_Start': TerminalKey.hangul_Start, +// 'Hangul_End': TerminalKey.hangul_End, +// 'Hangul_Hanja': TerminalKey.hangul_Hanja, +// 'Hangul_Jamo': TerminalKey.hangul_Jamo, +// 'Hangul_Romaja': TerminalKey.hangul_Romaja, +// 'Hangul_Jeonja': TerminalKey.hangul_Jeonja, +// 'Hangul_Banja': TerminalKey.hangul_Banja, +// 'Hangul_PreHanja': TerminalKey.hangul_PreHanja, +// 'Hangul_PostHanja': TerminalKey.hangul_PostHanja, +// 'Hangul_Special': TerminalKey.hangul_Special, +// 'Dead_Grave': TerminalKey.dead_Grave, +// 'Dead_Acute': TerminalKey.dead_Acute, +// 'Dead_Circumflex': TerminalKey.dead_Circumflex, +// 'Dead_Tilde': TerminalKey.dead_Tilde, +// 'Dead_Macron': TerminalKey.dead_Macron, +// 'Dead_Breve': TerminalKey.dead_Breve, +// 'Dead_Abovedot': TerminalKey.dead_Abovedot, +// 'Dead_Diaeresis': TerminalKey.dead_Diaeresis, +// 'Dead_Abovering': TerminalKey.dead_Abovering, +// 'Dead_Doubleacute': TerminalKey.dead_Doubleacute, +// 'Dead_Caron': TerminalKey.dead_Caron, +// 'Dead_Cedilla': TerminalKey.dead_Cedilla, +// 'Dead_Ogonek': TerminalKey.dead_Ogonek, +// 'Dead_Iota': TerminalKey.dead_Iota, +// 'Dead_Voiced_Sound': TerminalKey.dead_Voiced_Sound, +// 'Dead_Semivoiced_Sound': TerminalKey.dead_Semivoiced_Sound, +// 'Dead_Belowdot': TerminalKey.dead_Belowdot, +// 'Dead_Hook': TerminalKey.dead_Hook, +// 'Dead_Horn': TerminalKey.dead_Horn, +// 'Dead_Stroke': TerminalKey.dead_Stroke, +// 'Dead_Abovecomma': TerminalKey.dead_Abovecomma, +// 'Dead_Abovereversedcomma': TerminalKey.dead_Abovereversedcomma, +// 'Dead_Doublegrave': TerminalKey.dead_Doublegrave, +// 'Dead_Belowring': TerminalKey.dead_Belowring, +// 'Dead_Belowmacron': TerminalKey.dead_Belowmacron, +// 'Dead_Belowcircumflex': TerminalKey.dead_Belowcircumflex, +// 'Dead_Belowtilde': TerminalKey.dead_Belowtilde, +// 'Dead_Belowbreve': TerminalKey.dead_Belowbreve, +// 'Dead_Belowdiaeresis': TerminalKey.dead_Belowdiaeresis, +// 'Dead_Invertedbreve': TerminalKey.dead_Invertedbreve, +// 'Dead_Belowcomma': TerminalKey.dead_Belowcomma, +// 'Dead_Currency': TerminalKey.dead_Currency, +// 'Dead_a': TerminalKey.dead_a, +// 'Dead_A': TerminalKey.dead_A, +// 'Dead_e': TerminalKey.dead_e, +// 'Dead_E': TerminalKey.dead_E, +// 'Dead_i': TerminalKey.dead_i, +// 'Dead_I': TerminalKey.dead_I, +// 'Dead_o': TerminalKey.dead_o, +// 'Dead_O': TerminalKey.dead_O, +// 'Dead_u': TerminalKey.dead_u, +// 'Dead_U': TerminalKey.dead_U, +// 'Dead_Small_Schwa': TerminalKey.dead_Small_Schwa, +// 'Dead_Capital_Schwa': TerminalKey.dead_Capital_Schwa, +// 'Dead_Greek': TerminalKey.dead_Greek, +// 'Dead_Lowline': TerminalKey.dead_Lowline, +// 'Dead_Aboveverticalline': TerminalKey.dead_Aboveverticalline, +// 'Dead_Belowverticalline': TerminalKey.dead_Belowverticalline, +// 'Dead_Longsolidusoverlay': TerminalKey.dead_Longsolidusoverlay, +// 'Back': TerminalKey.back, +// 'Forward': TerminalKey.forward, +// 'Stop': TerminalKey.stop, +// 'Refresh': TerminalKey.refresh, + 'VolumeDown': TerminalKey.audioVolumeDown, + 'VolumeMute': TerminalKey.audioVolumeMute, + 'VolumeUp': TerminalKey.audioVolumeUp, + 'BassBoost': TerminalKey.bassBoost, +// 'BassUp': TerminalKey.bassUp, +// 'BassDown': TerminalKey.bassDown, +// 'TrebleUp': TerminalKey.trebleUp, +// 'TrebleDown': TerminalKey.trebleDown, + 'MediaPlay': TerminalKey.mediaPlay, + 'MediaStop': TerminalKey.mediaStop, +// 'MediaPrevious': TerminalKey.mediaPrevious, +// 'MediaNext': TerminalKey.mediaNext, + 'MediaRecord': TerminalKey.mediaRecord, + 'MediaPause': TerminalKey.mediaPause, + 'MediaTogglePlayPause': TerminalKey.mediaPlayPause, + 'HomePage': TerminalKey.browserHome, +// 'Favorites': TerminalKey.favorites, +// 'Search': TerminalKey.search, +// 'Standby': TerminalKey.standby, +// 'OpenUrl': TerminalKey.openUrl, +// 'LaunchMail': TerminalKey.launchMail, +// 'LaunchMedia': TerminalKey.launchMedia, +// 'Launch0': TerminalKey.launch0, +// 'Launch1': TerminalKey.launch1, +// 'Launch2': TerminalKey.launch2, +// 'Launch3': TerminalKey.launch3, +// 'Launch4': TerminalKey.launch4, +// 'Launch5': TerminalKey.launch5, +// 'Launch6': TerminalKey.launch6, +// 'Launch7': TerminalKey.launch7, +// 'Launch8': TerminalKey.launch8, +// 'Launch9': TerminalKey.launch9, +// 'LaunchA': TerminalKey.launchA, +// 'LaunchB': TerminalKey.launchB, +// 'LaunchC': TerminalKey.launchC, +// 'LaunchD': TerminalKey.launchD, +// 'LaunchE': TerminalKey.launchE, +// 'LaunchF': TerminalKey.launchF, +// 'LaunchG': TerminalKey.launchG, +// 'LaunchH': TerminalKey.launchH, + 'MonBrightnessUp': TerminalKey.brightnessUp, + 'MonBrightnessDown': TerminalKey.brightnessDown, +// 'KeyboardLightOnOff': TerminalKey.keyboardLightOnOff, +// 'KeyboardBrightnessUp': TerminalKey.keyboardBrightnessUp, +// 'KeyboardBrightnessDown': TerminalKey.keyboardBrightnessDown, + 'PowerOff': TerminalKey.power, + 'WakeUp': TerminalKey.wakeUp, + 'Eject': TerminalKey.eject, +// 'ScreenSaver': TerminalKey.screenSaver, +// 'WWW': TerminalKey.wWW, +// 'Memo': TerminalKey.memo, +// 'LightBulb': TerminalKey.lightBulb, +// 'Shop': TerminalKey.shop, +// 'History': TerminalKey.history, +// 'AddFavorite': TerminalKey.addFavorite, +// 'HotLinks': TerminalKey.hotLinks, +// 'BrightnessAdjust': TerminalKey.brightnessAdjust, +// 'Finance': TerminalKey.finance, +// 'Community': TerminalKey.community, +// 'AudioRewind': TerminalKey.audioRewind, +// 'BackForward': TerminalKey.backForward, +// 'ApplicationLeft': TerminalKey.applicationLeft, +// 'ApplicationRight': TerminalKey.applicationRight, +// 'Book': TerminalKey.book, +// 'CD': TerminalKey.cD, +// 'Calculator': TerminalKey.calculator, +// 'ToDoList': TerminalKey.toDoList, +// 'ClearGrab': TerminalKey.clearGrab, + 'Close': TerminalKey.close, + 'Copy': TerminalKey.copy, + 'Cut': TerminalKey.cut, +// 'Display': TerminalKey.display, +// 'DOS': TerminalKey.dOS, +// 'Documents': TerminalKey.documents, +// 'Excel': TerminalKey.excel, +// 'Explorer': TerminalKey.explorer, +// 'Game': TerminalKey.game, +// 'Go': TerminalKey.go, +// 'iTouch': TerminalKey.iTouch, +// 'LogOff': TerminalKey.logOff, +// 'Market': TerminalKey.market, +// 'Meeting': TerminalKey.meeting, +// 'MenuKB': TerminalKey.menuKB, +// 'MenuPB': TerminalKey.menuPB, +// 'MySites': TerminalKey.mySites, +// 'News': TerminalKey.news, +// 'OfficeHome': TerminalKey.officeHome, +// 'Option': TerminalKey.option, +// 'Paste': TerminalKey.paste, +// 'Phone': TerminalKey.phone, +// 'Calendar': TerminalKey.calendar, +// 'Reply': TerminalKey.reply, +// 'Reload': TerminalKey.reload, +// 'RotateWindows': TerminalKey.rotateWindows, +// 'RotationPB': TerminalKey.rotationPB, +// 'RotationKB': TerminalKey.rotationKB, + 'Save': TerminalKey.save, +// 'Send': TerminalKey.send, +// 'Spell': TerminalKey.spell, +// 'SplitScreen': TerminalKey.splitScreen, +// 'Support': TerminalKey.support, +// 'TaskPane': TerminalKey.taskPane, +// 'Terminal': TerminalKey.terminal, +// 'Tools': TerminalKey.tools, +// 'Travel': TerminalKey.travel, +// 'Video': TerminalKey.video, +// 'Word': TerminalKey.word, +// 'Xfer': TerminalKey.xfer, + 'ZoomIn': TerminalKey.zoomIn, + 'ZoomOut': TerminalKey.zoomOut, +// 'Away': TerminalKey.away, +// 'Messenger': TerminalKey.messenger, +// 'WebCam': TerminalKey.webCam, +// 'MailForward': TerminalKey.mailForward, +// 'Pictures': TerminalKey.pictures, +// 'Music': TerminalKey.music, +// 'Battery': TerminalKey.battery, +// 'Bluetooth': TerminalKey.bluetooth, +// 'WLAN': TerminalKey.wLAN, +// 'UWB': TerminalKey.uWB, +// 'AudioForward': TerminalKey.audioForward, +// 'AudioRepeat': TerminalKey.audioRepeat, +// 'AudioRandomPlay': TerminalKey.audioRandomPlay, +// 'Subtitle': TerminalKey.subtitle, +// 'AudioCycleTrack': TerminalKey.audioCycleTrack, +// 'Time': TerminalKey.time, +// 'Hibernate': TerminalKey.hibernate, +// 'View': TerminalKey.view, +// 'TopMenu': TerminalKey.topMenu, +// 'PowerDown': TerminalKey.powerDown, +// 'Suspend': TerminalKey.suspend, +// 'ContrastAdjust': TerminalKey.contrastAdjust, +// 'TouchpadToggle': TerminalKey.touchpadToggle, +// 'TouchpadOn': TerminalKey.touchpadOn, +// 'TouchpadOff': TerminalKey.touchpadOff, +// 'MicMute': TerminalKey.micMute, +// 'Red': TerminalKey.red, +// 'Green': TerminalKey.green, +// 'Yellow': TerminalKey.yellow, +// 'Blue': TerminalKey.blue, + 'ChannelUp': TerminalKey.channelUp, + 'ChannelDown': TerminalKey.channelDown, +// 'Guide': TerminalKey.guide, + 'Info': TerminalKey.info, +// 'Settings': TerminalKey.settings, +// 'MicVolumeUp': TerminalKey.micVolumeUp, +// 'MicVolumeDown': TerminalKey.micVolumeDown, +// 'New': TerminalKey.new, + 'Open': TerminalKey.open, + 'Find': TerminalKey.find, + 'Undo': TerminalKey.undo, + 'Redo': TerminalKey.redo, + 'MediaLast': TerminalKey.mediaLast, +// 'unknown': TerminalKey.unknown, +// 'Call': TerminalKey.call, +// 'Camera': TerminalKey.camera, +// 'CameraFocus': TerminalKey.cameraFocus, +// 'Context1': TerminalKey.context1, +// 'Context2': TerminalKey.context2, +// 'Context3': TerminalKey.context3, +// 'Context4': TerminalKey.context4, +// 'Flip': TerminalKey.flip, +// 'Hangup': TerminalKey.hangup, +// 'No': TerminalKey.no, + 'Select': TerminalKey.select, +// 'Yes': TerminalKey.yes, +// 'ToggleCallHangup': TerminalKey.toggleCallHangup, +// 'VoiceDial': TerminalKey.voiceDial, +// 'LastNumberRedial': TerminalKey.lastNumberRedial, +// 'Execute': TerminalKey.execute, +// 'Printer': TerminalKey.printer, +// 'Play': TerminalKey.play, + 'Sleep': TerminalKey.sleep, +// 'Zoom': TerminalKey.zoom, + 'Exit': TerminalKey.exit, +// 'Cancel': TerminalKey.cancel, +}; diff --git a/app/third_party/xterm/lib/src/core/mouse/button.dart b/app/third_party/xterm/lib/src/core/mouse/button.dart new file mode 100644 index 00000000..53dd08b0 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/mouse/button.dart @@ -0,0 +1,29 @@ +enum TerminalMouseButton { + left(id: 0), + + middle(id: 1), + + right(id: 2), + + wheelUp(id: 64 + 4, isWheel: true), + + wheelDown(id: 64 + 5, isWheel: true), + + wheelLeft(id: 64 + 6, isWheel: true), + + wheelRight(id: 64 + 7, isWheel: true), + ; + + /// The id that is used to report a button press or release to the terminal. + /// + /// Mouse wheel up / down use button IDs 4 = 0100 (binary) and 5 = 0101 (binary). + /// The bits three and four of the button are transposed by 64 and 128 + /// respectively, when reporting the id of the button and have have to be + /// adjusted correspondingly. + final int id; + + /// Whether this button is a mouse wheel button. + final bool isWheel; + + const TerminalMouseButton({required this.id, this.isWheel = false}); +} diff --git a/app/third_party/xterm/lib/src/core/mouse/button_state.dart b/app/third_party/xterm/lib/src/core/mouse/button_state.dart new file mode 100644 index 00000000..9c8dc4c2 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/mouse/button_state.dart @@ -0,0 +1,5 @@ +enum TerminalMouseButtonState { + up, + + down, +} diff --git a/app/third_party/xterm/lib/src/core/mouse/handler.dart b/app/third_party/xterm/lib/src/core/mouse/handler.dart new file mode 100644 index 00000000..bb043886 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/mouse/handler.dart @@ -0,0 +1,114 @@ +import 'package:xterm/src/core/buffer/cell_offset.dart'; +import 'package:xterm/src/core/mouse/button_state.dart'; +import 'package:xterm/src/core/mouse/mode.dart'; +import 'package:xterm/src/core/mouse/button.dart'; +import 'package:xterm/src/core/mouse/reporter.dart'; +import 'package:xterm/src/core/platform.dart'; +import 'package:xterm/src/core/state.dart'; + +class TerminalMouseEvent { + /// The button that is pressed or released. + final TerminalMouseButton button; + + /// The current state of the button. + final TerminalMouseButtonState buttonState; + + /// The position of button state change. + final CellOffset position; + + /// The state of the terminal. + final TerminalState state; + + /// The platform of the terminal. + final TerminalTargetPlatform platform; + + TerminalMouseEvent({ + required this.button, + required this.buttonState, + required this.position, + required this.state, + required this.platform, + }); +} + +const defaultMouseHandler = CascadeMouseHandler([ + ClickMouseHandler(), + UpDownMouseHandler(), +]); + +abstract class TerminalMouseHandler { + const TerminalMouseHandler(); + + String? call(TerminalMouseEvent event); +} + +class CascadeMouseHandler implements TerminalMouseHandler { + final List _handlers; + + const CascadeMouseHandler(this._handlers); + + @override + String? call(TerminalMouseEvent event) { + for (var handler in _handlers) { + final result = handler(event); + if (result != null) { + return result; + } + } + return null; + } +} + +class ClickMouseHandler implements TerminalMouseHandler { + const ClickMouseHandler(); + + @override + String? call(TerminalMouseEvent event) { + switch (event.state.mouseMode) { + case MouseMode.clickOnly: + // Only clicks and only the first 3 buttons are reported. + if (event.buttonState == TerminalMouseButtonState.down && + (event.button.id < 3)) { + return MouseReporter.report( + event.button, + event.buttonState, + event.position, + event.state.mouseReportMode, + ); + } + return null; + case MouseMode.none: + case MouseMode.upDownScroll: + case MouseMode.upDownScrollDrag: + case MouseMode.upDownScrollMove: + return null; + } + } +} + +class UpDownMouseHandler implements TerminalMouseHandler { + const UpDownMouseHandler(); + + @override + String? call(TerminalMouseEvent event) { + switch (event.state.mouseMode) { + case MouseMode.none: + case MouseMode.clickOnly: + return null; + case MouseMode.upDownScroll: + case MouseMode.upDownScrollDrag: + case MouseMode.upDownScrollMove: + // Up events are never reported for mouse wheel buttons. + if (event.button.isWheel && + event.buttonState == TerminalMouseButtonState.up) { + return null; + } + return MouseReporter.report( + event.button, + event.buttonState, + event.position, + event.state.mouseReportMode, + ); + } + } +} diff --git a/app/third_party/xterm/lib/src/core/mouse/mode.dart b/app/third_party/xterm/lib/src/core/mouse/mode.dart new file mode 100644 index 00000000..ecd006b0 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/mouse/mode.dart @@ -0,0 +1,36 @@ +/// https://terminalguide.namepad.de/mouse/ +enum MouseMode { + none, + + clickOnly, + + upDownScroll(reportScroll: true), + + upDownScrollDrag(reportScroll: true), + + upDownScrollMove(reportScroll: true), + ; + + const MouseMode({this.reportScroll = false}); + + final bool reportScroll; +} + +/// https://terminalguide.namepad.de/mouse/ +enum MouseReportMode { + /// The default mouse reporting mode where digits are encoded as bytes with + /// `32 + code`. This mode has a range from 1 to 223. + normal, + + /// When code < 96 this is the same as [normal], otherwise the `code + 32` is + /// encoded as 2 bytes in UTF-8. This mode has a range from 1 to 2015. + utf, + + /// In this mode the code are encoded as 10-based numbers. Tha range is + /// unlimited. + sgr, + + /// Similar to [sgr], the difference is that the button id is encoded as + /// `32 + code`. + urxvt, +} diff --git a/app/third_party/xterm/lib/src/core/mouse/reporter.dart b/app/third_party/xterm/lib/src/core/mouse/reporter.dart new file mode 100644 index 00000000..3417b634 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/mouse/reporter.dart @@ -0,0 +1,48 @@ +import 'package:xterm/src/core/buffer/cell_offset.dart'; +import 'package:xterm/src/core/mouse/mode.dart'; +import 'package:xterm/src/core/mouse/button.dart'; +import 'package:xterm/src/core/mouse/button_state.dart'; + +abstract class MouseReporter { + static String report( + TerminalMouseButton button, + TerminalMouseButtonState state, + CellOffset position, + MouseReportMode reportMode, + ) { + // x and y offsets have to be incremented by 1 as the offset if 0-based, + // The position has to be reported using 1-based coordinates. + final x = position.x + 1; + final y = position.y + 1; + switch (reportMode) { + case MouseReportMode.normal: + case MouseReportMode.utf: + // Button ID 3 is used to signal a button release. + final buttonID = state == TerminalMouseButtonState.up ? 3 : button.id; + // The button ID is reported as shifted by 32 to produce a printable + // character. + final btn = String.fromCharCode(32 + buttonID); + // Normal mode only supports a maximum position of 223, while utf + // supports positions up to 2015. Both modes send a null byte if the + // position exceeds that limit. + final col = (reportMode == MouseReportMode.normal && x > 223) || + (reportMode == MouseReportMode.utf && x > 2015) + ? '\x00' + : String.fromCharCode(32 + x); + final row = (reportMode == MouseReportMode.normal && y > 223) || + (reportMode == MouseReportMode.utf && y > 2015) + ? '\x00' + : String.fromCharCode(32 + y + 1); + return "\x1b[M$btn$col$row"; + case MouseReportMode.sgr: + final buttonID = button.id; + final upDown = state == TerminalMouseButtonState.down ? 'M' : 'm'; + return "\x1b[<$buttonID;$x;$y$upDown"; + case MouseReportMode.urxvt: + // The button ID uses the same id as to report it as in normal mode. + final buttonID = + 32 + (state == TerminalMouseButtonState.up ? 3 : button.id); + return "\x1b[$buttonID;$x;${y}M"; + } + } +} diff --git a/app/third_party/xterm/lib/src/core/platform.dart b/app/third_party/xterm/lib/src/core/platform.dart new file mode 100644 index 00000000..3c955fd8 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/platform.dart @@ -0,0 +1,17 @@ +enum TerminalTargetPlatform { + unknown, + + android, + + ios, + + fuchsia, + + linux, + + macos, + + windows, + + web, +} diff --git a/app/third_party/xterm/lib/src/core/reflow.dart b/app/third_party/xterm/lib/src/core/reflow.dart new file mode 100644 index 00000000..06e326e6 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/reflow.dart @@ -0,0 +1,197 @@ +import 'package:xterm/src/core/buffer/line.dart'; +import 'package:xterm/src/utils/circular_buffer.dart'; + +class _LineBuilder { + _LineBuilder([this._capacity = 80]) { + _result = BufferLine(_capacity); + } + + final int _capacity; + + late BufferLine _result; + + int _length = 0; + + int get length => _length; + + bool get isEmpty => _length == 0; + + bool get isNotEmpty => _length != 0; + + /// Adds a range of cells from [src] to the builder. Anchors within the range + /// will be reparented to the new line returned by [take]. + void add(BufferLine src, int start, int length) { + _result.copyFrom(src, start, _length, length); + _length += length; + } + + /// Reuses the given [line] as the initial buffer for this builder. + void setBuffer(BufferLine line, int length) { + _result = line; + _length = length; + } + + void addAnchor(CellAnchor anchor, int offset) { + anchor.reparent(_result, _length + offset); + } + + BufferLine take({required bool wrapped}) { + final result = _result; + result.isWrapped = wrapped; + // result.resize(_length); + + _result = BufferLine(_capacity); + _length = 0; + + return result; + } +} + +/// Holds a the state of reflow operation of a single logical line. +class _LineReflow { + final int oldWidth; + + final int newWidth; + + _LineReflow(this.oldWidth, this.newWidth); + + final _lines = []; + + late final _builder = _LineBuilder(newWidth); + + /// Adds a line to the reflow operation. This method will try to reuse the + /// given line if possible. + void add(BufferLine line) { + final trimmedLength = line.getTrimmedLength(oldWidth); + + // A fast path for empty lines + if (trimmedLength == 0) { + _lines.add(line); + return; + } + + // We already have some content in the buffer, so we copy the content into + // the builder instead of reusing the line. + if (_lines.isNotEmpty || _builder.isNotEmpty) { + _addPart(line, from: 0, to: trimmedLength); + return; + } + + if (newWidth >= oldWidth) { + // Reuse the line to avoid copying the content and object allocation. + _builder.setBuffer(line, trimmedLength); + } else { + _lines.add(line); + + if (trimmedLength > newWidth) { + if (line.getWidth(newWidth - 1) == 2) { + _addPart(line, from: newWidth - 1, to: trimmedLength); + } else { + _addPart(line, from: newWidth, to: trimmedLength); + } + } + } + + line.resize(newWidth); + + if (line.getWidth(newWidth - 1) == 2) { + line.resetCell(newWidth - 1); + } + } + + /// Adds part of [line] from [from] to [to] to the reflow operation. + /// Anchors within the range will be removed from [line] and reparented to + /// the new line(s) returned by [finish]. + void _addPart(BufferLine line, {required int from, required int to}) { + var cellsLeft = to - from; + + while (cellsLeft > 0) { + final bufferRemainingCells = newWidth - _builder.length; + + // How many cells we should copy in this iteration. + var cellsToCopy = cellsLeft; + + // Whether the buffer is filled up in this iteration. + var lineFilled = false; + + if (cellsToCopy >= bufferRemainingCells) { + cellsToCopy = bufferRemainingCells; + lineFilled = true; + } + + // Leave the last cell to the next iteration if it's a wide char. + if (lineFilled && line.getWidth(from + cellsToCopy - 1) == 2) { + cellsToCopy--; + } + + for (var anchor in line.anchors.toList()) { + if (anchor.x >= from && anchor.x <= from + cellsToCopy) { + _builder.addAnchor(anchor, anchor.x - from); + } + } + + _builder.add(line, from, cellsToCopy); + + from += cellsToCopy; + cellsLeft -= cellsToCopy; + + // Create a new line if the buffer is filled up. + if (lineFilled) { + _lines.add(_builder.take(wrapped: _lines.isNotEmpty)); + } + } + + if (line.anchors.isNotEmpty) { + for (var anchor in line.anchors.toList()) { + if (anchor.x >= to) { + _builder.addAnchor(anchor, anchor.x - to); + } + } + } + } + + /// Finalizes the reflow operation and returns the result. + List finish() { + if (_builder.isNotEmpty) { + _lines.add(_builder.take(wrapped: _lines.isNotEmpty)); + } + + return _lines; + } +} + +List reflow( + IndexAwareCircularBuffer lines, + int oldWidth, + int newWidth, +) { + final result = []; + + for (var i = 0; i < lines.length; i++) { + final line = lines[i]; + + final reflow = _LineReflow(oldWidth, newWidth); + + reflow.add(line); + + for (var offset = i + 1; offset < lines.length; offset++) { + final nextLine = lines[offset]; + + if (!nextLine.isWrapped) { + break; + } + + i++; + + reflow.add(nextLine); + } + + result.addAll(reflow.finish()); + } + + for (var line in result) { + line.resize(newWidth); + } + + return result; +} diff --git a/app/third_party/xterm/lib/src/core/snapshot.dart b/app/third_party/xterm/lib/src/core/snapshot.dart new file mode 100644 index 00000000..319fc4a2 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/snapshot.dart @@ -0,0 +1,3 @@ +abstract class TerminalSnapshot { + void trimScrollback(); +} diff --git a/app/third_party/xterm/lib/src/core/state.dart b/app/third_party/xterm/lib/src/core/state.dart new file mode 100644 index 00000000..85684f86 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/state.dart @@ -0,0 +1,44 @@ +import 'package:xterm/src/core/cursor.dart'; +import 'package:xterm/src/core/mouse/mode.dart'; + +abstract class TerminalState { + int get viewWidth; + + int get viewHeight; + + CursorStyle get cursor; + + bool get reflowEnabled; + + /* Modes */ + + bool get insertMode; + + bool get lineFeedMode; + + /* DEC Private modes */ + + bool get cursorKeysMode; + + bool get reverseDisplayMode; + + bool get originMode; + + bool get autoWrapMode; + + MouseMode get mouseMode; + + MouseReportMode get mouseReportMode; + + bool get cursorBlinkMode; + + bool get cursorVisibleMode; + + bool get appKeypadMode; + + bool get reportFocusMode; + + bool get altBufferMouseScrollMode; + + bool get bracketedPasteMode; +} diff --git a/app/third_party/xterm/lib/src/core/tabs.dart b/app/third_party/xterm/lib/src/core/tabs.dart new file mode 100644 index 00000000..385f9499 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/tabs.dart @@ -0,0 +1,68 @@ +import 'dart:math' show min; + +const _kMaxColumns = 1024; + +/// Manages the tab stop state for a terminal. +class TabStops { + final _stops = List.filled(_kMaxColumns, false); + + TabStops() { + _initialize(); + } + + /// Initializes the tab stops to the default 8 column intervals. + void _initialize() { + const interval = 8; + for (var i = 0; i < _kMaxColumns; i += interval) { + _stops[i] = true; + } + } + + /// Finds the next tab stop index, which satisfies [start] <= index < [end]. + int? find(int start, int end) { + if (start >= end) { + return null; + } + end = min(end, _stops.length); + for (var i = start; i < end; i++) { + if (_stops[i]) { + return i; + } + } + return null; + } + + /// Sets the tab stop at [index]. If there is already a tab stop at [index], + /// this method does nothing. + /// + /// See also: + /// * [clearAt] which does the opposite. + void setAt(int index) { + assert(index >= 0 && index < _kMaxColumns); + _stops[index] = true; + } + + /// Clears the tab stop at [index]. If there is no tab stop at [index], this + /// method does nothing. + void clearAt(int index) { + assert(index >= 0 && index < _kMaxColumns); + _stops[index] = false; + } + + /// Clears all tab stops without resetting them to the default 8 column + /// intervals. + void clearAll() { + _stops.fillRange(0, _kMaxColumns, false); + } + + /// Returns true if there is a tab stop at [index]. + bool isSetAt(int index) { + return _stops[index]; + } + + /// Resets the tab stops to the default 8 column intervals. + void reset() { + clearAll(); + _initialize(); + } +} diff --git a/app/third_party/xterm/lib/src/terminal.dart b/app/third_party/xterm/lib/src/terminal.dart new file mode 100644 index 00000000..461e2084 --- /dev/null +++ b/app/third_party/xterm/lib/src/terminal.dart @@ -0,0 +1,906 @@ +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/cursor.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'; +import 'package:xterm/src/core/input/handler.dart'; +import 'package:xterm/src/core/input/keys.dart'; +import 'package:xterm/src/core/mouse/button.dart'; +import 'package:xterm/src/core/mouse/button_state.dart'; +import 'package:xterm/src/core/mouse/handler.dart'; +import 'package:xterm/src/core/mouse/mode.dart'; +import 'package:xterm/src/core/platform.dart'; +import 'package:xterm/src/core/state.dart'; +import 'package:xterm/src/core/tabs.dart'; +import 'package:xterm/src/utils/ascii.dart'; +import 'package:xterm/src/utils/circular_buffer.dart'; + +/// [Terminal] is an interface to interact with command line applications. It +/// translates escape sequences from the application into updates to the +/// [buffer] and events such as [onTitleChange] or [onBell], as well as +/// translating user input into escape sequences that the application can +/// understand. +class Terminal with Observable implements TerminalState, EscapeHandler { + /// The number of lines that the scrollback buffer can hold. If the buffer + /// exceeds this size, the lines at the top of the buffer will be removed. + final int maxLines; + + /// Function that is called when the program requests the terminal to ring + /// the bell. If not set, the terminal will do nothing. + void Function()? onBell; + + /// Function that is called when the program requests the terminal to change + /// the title of the window to [title]. + void Function(String title)? onTitleChange; + + /// Function that is called when the program requests the terminal to change + /// the icon of the window. [icon] is the name of the icon. + void Function(String icon)? onIconChange; + + /// Function that is called when the terminal emits data to the underlying + /// program. This is typically caused by user inputs from [textInput], + /// [keyInput], [mouseInput], or [paste]. + void Function(String data)? onOutput; + + /// Function that is called when the dimensions of the terminal change. + void Function(int width, int height, int pixelWidth, int pixelHeight)? + onResize; + + /// The [TerminalInputHandler] used by this terminal. [defaultInputHandler] is + /// used when not specified. User of this class can provide their own + /// implementation of [TerminalInputHandler] or extend [defaultInputHandler] + /// with [CascadeInputHandler]. + TerminalInputHandler? inputHandler; + + TerminalMouseHandler? mouseHandler; + + /// The callback that is called when the terminal receives a unrecognized + /// escape sequence. + void Function(String code, List args)? onPrivateOSC; + + /// Flag to toggle os specific behaviors. + final TerminalTargetPlatform platform; + + /// Characters that break selection when double clicking. If not set, the + /// [Buffer.defaultWordSeparators] will be used. + final Set? wordSeparators; + + Terminal({ + this.maxLines = 1000, + this.onBell, + this.onTitleChange, + this.onIconChange, + this.onOutput, + this.onResize, + this.platform = TerminalTargetPlatform.unknown, + this.inputHandler = defaultInputHandler, + this.mouseHandler = defaultMouseHandler, + this.onPrivateOSC, + this.reflowEnabled = true, + this.wordSeparators, + }); + + late final _parser = EscapeParser(this); + + final _emitter = const EscapeEmitter(); + + late var _buffer = _mainBuffer; + + late final _mainBuffer = Buffer( + this, + maxLines: maxLines, + isAltBuffer: false, + wordSeparators: wordSeparators, + ); + + late final _altBuffer = Buffer( + this, + maxLines: maxLines, + isAltBuffer: true, + wordSeparators: wordSeparators, + ); + + final _tabStops = TabStops(); + + /// The last character written to the buffer. Used to implement some escape + /// sequences that repeat the last character. + var _precedingCodepoint = 0; + + /* TerminalState */ + + int _viewWidth = 80; + + int _viewHeight = 24; + + final _cursorStyle = CursorStyle(); + + bool _insertMode = false; + + bool _lineFeedMode = false; + + bool _cursorKeysMode = false; + + bool _reverseDisplayMode = false; + + bool _originMode = false; + + bool _autoWrapMode = true; + + MouseMode _mouseMode = MouseMode.none; + + MouseReportMode _mouseReportMode = MouseReportMode.normal; + + bool _cursorBlinkMode = false; + + bool _cursorVisibleMode = true; + + bool _appKeypadMode = false; + + bool _reportFocusMode = false; + + bool _altBufferMouseScrollMode = false; + + bool _bracketedPasteMode = false; + + /* State getters */ + + /// Number of cells in a terminal row. + @override + int get viewWidth => _viewWidth; + + /// Number of rows in this terminal. + @override + int get viewHeight => _viewHeight; + + @override + CursorStyle get cursor => _cursorStyle; + + @override + bool get insertMode => _insertMode; + + @override + bool get lineFeedMode => _lineFeedMode; + + @override + bool get cursorKeysMode => _cursorKeysMode; + + @override + bool get reverseDisplayMode => _reverseDisplayMode; + + @override + bool get originMode => _originMode; + + @override + bool get autoWrapMode => _autoWrapMode; + + @override + MouseMode get mouseMode => _mouseMode; + + @override + MouseReportMode get mouseReportMode => _mouseReportMode; + + @override + bool get cursorBlinkMode => _cursorBlinkMode; + + @override + bool get cursorVisibleMode => _cursorVisibleMode; + + @override + bool get appKeypadMode => _appKeypadMode; + + @override + bool get reportFocusMode => _reportFocusMode; + + @override + bool get altBufferMouseScrollMode => _altBufferMouseScrollMode; + + @override + bool get bracketedPasteMode => _bracketedPasteMode; + + /// Current active buffer of the terminal. This is initially [mainBuffer] and + /// can be switched back and forth from [altBuffer] to [mainBuffer] when + /// the underlying program requests it. + Buffer get buffer => _buffer; + + Buffer get mainBuffer => _mainBuffer; + + Buffer get altBuffer => _altBuffer; + + bool get isUsingAltBuffer => _buffer == _altBuffer; + + /// Lines of the active buffer. + IndexAwareCircularBuffer get lines => _buffer.lines; + + /// Whether the terminal performs reflow when the viewport size changes or + /// simply truncates lines. true by default. + @override + bool reflowEnabled; + + /// Writes the data from the underlying program to the terminal. Calling this + /// updates the states of the terminal and emits events such as [onBell] or + /// [onTitleChange] when the escape sequences in [data] request it. + void write(String data) { + _parser.write(data); + notifyListeners(); + } + + /// Sends a key event to the underlying program. + /// + /// See also: + /// - [charInput] + /// - [textInput] + /// - [paste] + bool keyInput( + TerminalKey key, { + bool shift = false, + bool alt = false, + bool ctrl = false, + }) { + final output = inputHandler?.call( + TerminalKeyboardEvent( + key: key, + shift: shift, + alt: alt, + ctrl: ctrl, + state: this, + altBuffer: isUsingAltBuffer, + platform: platform, + ), + ); + + if (output != null) { + onOutput?.call(output); + return true; + } + + return false; + } + + /// Similary to [keyInput], but takes a character as input instead of a + /// [TerminalKey]. + /// + /// See also: + /// - [keyInput] + /// - [textInput] + /// - [paste] + bool charInput( + int charCode, { + bool alt = false, + bool ctrl = false, + }) { + if (ctrl) { + // a(97) ~ z(122) + if (charCode >= Ascii.a && charCode <= Ascii.z) { + final output = charCode - Ascii.a + 1; + onOutput?.call(String.fromCharCode(output)); + return true; + } + + // [(91) ~ _(95) + if (charCode >= Ascii.openBracket && charCode <= Ascii.underscore) { + final output = charCode - Ascii.openBracket + 27; + onOutput?.call(String.fromCharCode(output)); + return true; + } + } + + if (alt && platform != TerminalTargetPlatform.macos) { + if (charCode >= Ascii.a && charCode <= Ascii.z) { + final code = charCode - Ascii.a + 65; + final input = [0x1b, code]; + onOutput?.call(String.fromCharCodes(input)); + return true; + } + } + + return false; + } + + /// Sends regular text input to the underlying program. + /// + /// See also: + /// - [keyInput] + /// - [charInput] + /// - [paste] + void textInput(String text) { + onOutput?.call(text); + } + + /// Similar to [textInput], except that when the program tells the terminal + /// that it supports [bracketedPasteMode], the text is wrapped in escape + /// sequences to indicate that it is a paste operation. Prefer this method + /// over [textInput] when pasting text. + /// + /// See also: + /// - [textInput] + void paste(String text) { + if (_bracketedPasteMode) { + onOutput?.call(_emitter.bracketedPaste(text)); + } else { + textInput(text); + } + } + + // Handle a mouse event and return true if it was handled. + bool mouseInput( + TerminalMouseButton button, + TerminalMouseButtonState buttonState, + CellOffset position, + ) { + final output = mouseHandler?.call(TerminalMouseEvent( + button: button, + buttonState: buttonState, + position: position, + state: this, + platform: platform, + )); + if (output != null) { + onOutput?.call(output); + return true; + } + return false; + } + + /// Resize the terminal screen. [newWidth] and [newHeight] should be greater + /// than 0. Text reflow is currently not implemented and will be avaliable in + /// the future. + @override + void resize( + int newWidth, + int newHeight, [ + int? pixelWidth, + int? pixelHeight, + ]) { + newWidth = max(newWidth, 1); + newHeight = max(newHeight, 1); + + onResize?.call(newWidth, newHeight, pixelWidth ?? 0, pixelHeight ?? 0); + + //we need to resize both buffers so that they are ready when we switch between them + _altBuffer.resize(_viewWidth, _viewHeight, newWidth, newHeight); + _mainBuffer.resize(_viewWidth, _viewHeight, newWidth, newHeight); + + _viewWidth = newWidth; + _viewHeight = newHeight; + + if (buffer == _altBuffer) { + buffer.clearScrollback(); + } + + _altBuffer.resetVerticalMargins(); + _mainBuffer.resetVerticalMargins(); + } + + @override + String toString() { + return 'Terminal(#$hashCode, $_viewWidth x $_viewHeight, ${_buffer.height} lines)'; + } + + /* Handlers */ + + @override + void writeChar(int char) { + _precedingCodepoint = char; + _buffer.writeChar(char); + } + + /* SBC */ + + @override + void bell() { + onBell?.call(); + } + + @override + void backspaceReturn() { + _buffer.moveCursorX(-1); + } + + @override + void tab() { + final nextStop = _tabStops.find(_buffer.cursorX + 1, _viewWidth); + + if (nextStop != null) { + _buffer.setCursorX(nextStop); + } else { + _buffer.setCursorX(_viewWidth); + _buffer.cursorGoForward(); // Enter pending-wrap state + } + } + + @override + void lineFeed() { + _buffer.lineFeed(); + } + + @override + void carriageReturn() { + _buffer.setCursorX(0); + } + + @override + void shiftOut() { + _buffer.charset.use(1); + } + + @override + void shiftIn() { + _buffer.charset.use(0); + } + + @override + void unknownSBC(int char) { + // no-op + } + + /* ANSI sequence */ + + @override + void saveCursor() { + _buffer.saveCursor(); + } + + @override + void restoreCursor() { + _buffer.restoreCursor(); + } + + @override + void index() { + _buffer.index(); + } + + @override + void nextLine() { + _buffer.index(); + _buffer.setCursorX(0); + } + + @override + void setTapStop() { + _tabStops.isSetAt(_buffer.cursorX); + } + + @override + void reverseIndex() { + _buffer.reverseIndex(); + } + + @override + void designateCharset(int charset, int name) { + _buffer.charset.designate(charset, name); + } + + @override + void unkownEscape(int char) { + // no-op + } + + /* CSI */ + + @override + void repeatPreviousCharacter(int count) { + if (_precedingCodepoint == 0) { + return; + } + + for (var i = 0; i < count; i++) { + _buffer.writeChar(_precedingCodepoint); + } + } + + @override + void setCursor(int x, int y) { + _buffer.setCursor(x, y); + } + + @override + void setCursorX(int x) { + _buffer.setCursorX(x); + } + + @override + void setCursorY(int y) { + _buffer.setCursorY(y); + } + + @override + void moveCursorX(int offset) { + _buffer.moveCursorX(offset); + } + + @override + void moveCursorY(int n) { + _buffer.moveCursorY(n); + } + + @override + void clearTabStopUnderCursor() { + _tabStops.clearAt(_buffer.cursorX); + } + + @override + void clearAllTabStops() { + _tabStops.clearAll(); + } + + @override + void sendPrimaryDeviceAttributes() { + onOutput?.call(_emitter.primaryDeviceAttributes()); + } + + @override + void sendSecondaryDeviceAttributes() { + onOutput?.call(_emitter.secondaryDeviceAttributes()); + } + + @override + void sendTertiaryDeviceAttributes() { + onOutput?.call(_emitter.tertiaryDeviceAttributes()); + } + + @override + void sendOperatingStatus() { + onOutput?.call(_emitter.operatingStatus()); + } + + @override + void sendCursorPosition() { + onOutput?.call(_emitter.cursorPosition(_buffer.cursorX, _buffer.cursorY)); + } + + @override + void setMargins(int top, [int? bottom]) { + _buffer.setVerticalMargins(top, bottom ?? viewHeight - 1); + } + + @override + void cursorNextLine(int amount) { + _buffer.moveCursorY(amount); + _buffer.setCursorX(0); + } + + @override + void cursorPrecedingLine(int amount) { + _buffer.moveCursorY(-amount); + _buffer.setCursorX(0); + } + + @override + void eraseDisplayBelow() { + _buffer.eraseDisplayFromCursor(); + } + + @override + void eraseDisplayAbove() { + _buffer.eraseDisplayToCursor(); + } + + @override + void eraseDisplay() { + _buffer.eraseDisplay(); + } + + @override + void eraseScrollbackOnly() { + _buffer.clearScrollback(); + } + + @override + void eraseLineRight() { + _buffer.eraseLineFromCursor(); + } + + @override + void eraseLineLeft() { + _buffer.eraseLineToCursor(); + } + + @override + void eraseLine() { + _buffer.eraseLine(); + } + + @override + void insertLines(int amount) { + _buffer.insertLines(amount); + } + + @override + void deleteLines(int amount) { + _buffer.deleteLines(amount); + } + + @override + void deleteChars(int amount) { + _buffer.deleteChars(amount); + } + + @override + void scrollUp(int amount) { + _buffer.scrollUp(amount); + } + + @override + void scrollDown(int amount) { + _buffer.scrollDown(amount); + } + + @override + void eraseChars(int amount) { + _buffer.eraseChars(amount); + } + + @override + void insertBlankChars(int amount) { + _buffer.insertBlankChars(amount); + } + + @override + void sendSize() { + onOutput?.call(_emitter.size(viewHeight, viewWidth)); + } + + @override + void unknownCSI(int finalByte) { + // no-op + } + + /* Modes */ + + @override + void setInsertMode(bool enabled) { + _insertMode = enabled; + } + + @override + void setLineFeedMode(bool enabled) { + _lineFeedMode = enabled; + } + + @override + void setUnknownMode(int mode, bool enabled) { + // no-op + } + + /* DEC Private modes */ + + @override + void setCursorKeysMode(bool enabled) { + _cursorKeysMode = enabled; + } + + @override + void setReverseDisplayMode(bool enabled) { + _reverseDisplayMode = enabled; + } + + @override + void setOriginMode(bool enabled) { + _originMode = enabled; + } + + @override + void setColumnMode(bool enabled) { + // no-op + } + + @override + void setAutoWrapMode(bool enabled) { + _autoWrapMode = enabled; + } + + @override + void setMouseMode(MouseMode mode) { + _mouseMode = mode; + } + + @override + void setCursorBlinkMode(bool enabled) { + _cursorBlinkMode = enabled; + } + + @override + void setCursorVisibleMode(bool enabled) { + _cursorVisibleMode = enabled; + } + + @override + void useAltBuffer() { + _buffer = _altBuffer; + } + + @override + void useMainBuffer() { + _buffer = _mainBuffer; + } + + @override + void clearAltBuffer() { + _altBuffer.clear(); + } + + @override + void setAppKeypadMode(bool enabled) { + _appKeypadMode = enabled; + } + + @override + void setReportFocusMode(bool enabled) { + _reportFocusMode = enabled; + } + + @override + void setMouseReportMode(MouseReportMode mode) { + _mouseReportMode = mode; + } + + @override + void setAltBufferMouseScrollMode(bool enabled) { + _altBufferMouseScrollMode = enabled; + } + + @override + void setBracketedPasteMode(bool enabled) { + _bracketedPasteMode = enabled; + } + + @override + void setUnknownDecMode(int mode, bool enabled) { + // no-op + } + + /* Select Graphic Rendition (SGR) */ + + @override + void resetCursorStyle() { + _cursorStyle.reset(); + } + + @override + void setCursorBold() { + _cursorStyle.setBold(); + } + + @override + void setCursorFaint() { + _cursorStyle.setFaint(); + } + + @override + void setCursorItalic() { + _cursorStyle.setItalic(); + } + + @override + void setCursorUnderline() { + _cursorStyle.setUnderline(); + } + + @override + void setCursorBlink() { + _cursorStyle.setBlink(); + } + + @override + void setCursorInverse() { + _cursorStyle.setInverse(); + } + + @override + void setCursorInvisible() { + _cursorStyle.setInvisible(); + } + + @override + void setCursorStrikethrough() { + _cursorStyle.setStrikethrough(); + } + + @override + void unsetCursorBold() { + _cursorStyle.unsetBold(); + } + + @override + void unsetCursorFaint() { + _cursorStyle.unsetFaint(); + } + + @override + void unsetCursorItalic() { + _cursorStyle.unsetItalic(); + } + + @override + void unsetCursorUnderline() { + _cursorStyle.unsetUnderline(); + } + + @override + void unsetCursorBlink() { + _cursorStyle.unsetBlink(); + } + + @override + void unsetCursorInverse() { + _cursorStyle.unsetInverse(); + } + + @override + void unsetCursorInvisible() { + _cursorStyle.unsetInvisible(); + } + + @override + void unsetCursorStrikethrough() { + _cursorStyle.unsetStrikethrough(); + } + + @override + void setForegroundColor16(int color) { + _cursorStyle.setForegroundColor16(color); + } + + @override + void setForegroundColor256(int index) { + _cursorStyle.setForegroundColor256(index); + } + + @override + void setForegroundColorRgb(int r, int g, int b) { + _cursorStyle.setForegroundColorRgb(r, g, b); + } + + @override + void resetForeground() { + _cursorStyle.resetForegroundColor(); + } + + @override + void setBackgroundColor16(int color) { + _cursorStyle.setBackgroundColor16(color); + } + + @override + void setBackgroundColor256(int index) { + _cursorStyle.setBackgroundColor256(index); + } + + @override + void setBackgroundColorRgb(int r, int g, int b) { + _cursorStyle.setBackgroundColorRgb(r, g, b); + } + + @override + void resetBackground() { + _cursorStyle.resetBackgroundColor(); + } + + @override + void unsupportedStyle(int param) { + // no-op + } + + /* OSC */ + + @override + void setTitle(String name) { + onTitleChange?.call(name); + } + + @override + void setIconName(String name) { + onIconChange?.call(name); + } + + @override + void unknownOSC(String ps, List pt) { + onPrivateOSC?.call(ps, pt); + } +} diff --git a/app/third_party/xterm/lib/src/terminal_view.dart b/app/third_party/xterm/lib/src/terminal_view.dart new file mode 100644 index 00000000..cf2c3c3c --- /dev/null +++ b/app/third_party/xterm/lib/src/terminal_view.dart @@ -0,0 +1,533 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:xterm/src/core/buffer/cell_offset.dart'; + +import 'package:xterm/src/core/input/keys.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/custom_text_edit.dart'; +import 'package:xterm/src/ui/gesture/gesture_handler.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'; +import 'package:xterm/src/ui/render.dart'; +import 'package:xterm/src/ui/scroll_handler.dart'; +import 'package:xterm/src/ui/shortcut/actions.dart'; +import 'package:xterm/src/ui/shortcut/shortcuts.dart'; +import 'package:xterm/src/ui/terminal_text_style.dart'; +import 'package:xterm/src/ui/terminal_theme.dart'; +import 'package:xterm/src/ui/themes.dart'; + +class TerminalView extends StatefulWidget { + const TerminalView( + this.terminal, { + super.key, + this.controller, + this.theme = TerminalThemes.defaultTheme, + this.textStyle = const TerminalStyle(), + this.textScaler, + this.padding, + this.scrollController, + this.autoResize = true, + this.backgroundOpacity = 1, + this.focusNode, + this.autofocus = false, + this.onTapUp, + this.onSecondaryTapDown, + this.onSecondaryTapUp, + this.mouseCursor = SystemMouseCursors.text, + this.keyboardType = TextInputType.emailAddress, + this.keyboardAppearance = Brightness.dark, + this.cursorType = TerminalCursorType.block, + this.alwaysShowCursor = false, + this.deleteDetection = false, + this.shortcuts, + this.onKeyEvent, + this.readOnly = false, + this.hardwareKeyboardOnly = false, + this.simulateScroll = true, + }); + + /// The underlying terminal that this widget renders. + final Terminal terminal; + + final TerminalController? controller; + + /// The theme to use for this terminal. + final TerminalTheme theme; + + /// The style to use for painting characters. + final TerminalStyle textStyle; + + final TextScaler? textScaler; + + /// Padding around the inner [Scrollable] widget. + final EdgeInsets? padding; + + /// Scroll controller for the inner [Scrollable] widget. + final ScrollController? scrollController; + + /// Should this widget automatically notify the underlying terminal when its + /// size changes. [true] by default. + final bool autoResize; + + /// Opacity of the terminal background. Set to 0 to make the terminal + /// background transparent. + final double backgroundOpacity; + + /// An optional focus node to use as the focus node for this widget. + final FocusNode? focusNode; + + /// True if this widget will be selected as the initial focus when no other + /// node in its scope is currently focused. + final bool autofocus; + + /// Callback for when the user taps on the terminal. + final void Function(TapUpDetails, CellOffset)? onTapUp; + + /// Function called when the user taps on the terminal with a secondary + /// button. + final void Function(TapDownDetails, CellOffset)? onSecondaryTapDown; + + /// Function called when the user stops holding down a secondary button. + final void Function(TapUpDetails, CellOffset)? onSecondaryTapUp; + + /// The mouse cursor for mouse pointers that are hovering over the terminal. + /// [SystemMouseCursors.text] by default. + final MouseCursor mouseCursor; + + /// The type of information for which to optimize the text input control. + /// [TextInputType.emailAddress] by default. + final TextInputType keyboardType; + + /// The appearance of the keyboard. [Brightness.dark] by default. + /// + /// This setting is only honored on iOS devices. + final Brightness keyboardAppearance; + + /// The type of cursor to use. [TerminalCursorType.block] by default. + final TerminalCursorType cursorType; + + /// Whether to always show the cursor. This is useful for debugging. + /// [false] by default. + final bool alwaysShowCursor; + + /// Workaround to detect delete key for platforms and IMEs that does not + /// emit hardware delete event. Prefered on mobile platforms. [false] by + /// default. + final bool deleteDetection; + + /// Shortcuts for this terminal. This has higher priority than input handler + /// of the terminal If not provided, [defaultTerminalShortcuts] will be used. + final Map? shortcuts; + + /// Keyboard event handler of the terminal. This has higher priority than + /// [shortcuts] and input handler of the terminal. + final FocusOnKeyEventCallback? onKeyEvent; + + /// True if no input should send to the terminal. + final bool readOnly; + + /// True if only hardware keyboard events should be used as input. This will + /// also prevent any on-screen keyboard to be shown. + final bool hardwareKeyboardOnly; + + /// If true, when the terminal is in alternate buffer (for example running + /// vim, man, etc), if the application does not declare that it can handle + /// scrolling, the terminal will simulate scrolling by sending up/down arrow + /// keys to the application. This is standard behavior for most terminal + /// emulators. True by default. + final bool simulateScroll; + + @override + State createState() => TerminalViewState(); +} + +class TerminalViewState extends State { + late FocusNode _focusNode; + + late final ShortcutManager _shortcutManager; + + final _customTextEditKey = GlobalKey(); + + final _scrollableKey = GlobalKey(); + + final _viewportKey = GlobalKey(); + + String? _composingText; + + late TerminalController _controller; + + late ScrollController _scrollController; + + RenderTerminal get renderTerminal => + _viewportKey.currentContext!.findRenderObject() as RenderTerminal; + + @override + void initState() { + _focusNode = widget.focusNode ?? FocusNode(); + _controller = widget.controller ?? TerminalController(); + _scrollController = widget.scrollController ?? ScrollController(); + _shortcutManager = ShortcutManager( + shortcuts: widget.shortcuts ?? defaultTerminalShortcuts, + ); + super.initState(); + } + + @override + void didUpdateWidget(TerminalView oldWidget) { + if (oldWidget.focusNode != widget.focusNode) { + if (oldWidget.focusNode == null) { + _focusNode.dispose(); + } + _focusNode = widget.focusNode ?? FocusNode(); + } + if (oldWidget.controller != widget.controller) { + if (oldWidget.controller == null) { + _controller.dispose(); + } + _controller = widget.controller ?? TerminalController(); + } + if (oldWidget.scrollController != widget.scrollController) { + if (oldWidget.scrollController == null) { + _scrollController.dispose(); + } + _scrollController = widget.scrollController ?? ScrollController(); + } + _shortcutManager.shortcuts = widget.shortcuts ?? defaultTerminalShortcuts; + super.didUpdateWidget(oldWidget); + } + + @override + void dispose() { + if (widget.focusNode == null) { + _focusNode.dispose(); + } + if (widget.controller == null) { + _controller.dispose(); + } + if (widget.scrollController == null) { + _scrollController.dispose(); + } + _shortcutManager.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + Widget child = Scrollable( + key: _scrollableKey, + controller: _scrollController, + viewportBuilder: (context, offset) { + return _TerminalView( + key: _viewportKey, + terminal: widget.terminal, + controller: _controller, + offset: offset, + padding: MediaQuery.of(context).padding, + autoResize: widget.autoResize, + textStyle: widget.textStyle, + textScaler: widget.textScaler ?? MediaQuery.textScalerOf(context), + theme: widget.theme, + focusNode: _focusNode, + cursorType: widget.cursorType, + alwaysShowCursor: widget.alwaysShowCursor, + onEditableRect: _onEditableRect, + composingText: _composingText, + ); + }, + ); + + child = TerminalScrollGestureHandler( + terminal: widget.terminal, + simulateScroll: widget.simulateScroll, + getCellOffset: (offset) => renderTerminal.getCellOffset(offset), + getLineHeight: () => renderTerminal.lineHeight, + child: child, + ); + + if (!widget.hardwareKeyboardOnly) { + child = CustomTextEdit( + key: _customTextEditKey, + focusNode: _focusNode, + autofocus: widget.autofocus, + inputType: widget.keyboardType, + keyboardAppearance: widget.keyboardAppearance, + deleteDetection: widget.deleteDetection, + onInsert: _onInsert, + onDelete: () { + _scrollToBottom(); + widget.terminal.keyInput(TerminalKey.backspace); + }, + onComposing: _onComposing, + onAction: (action) { + _scrollToBottom(); + if (action == TextInputAction.done) { + widget.terminal.keyInput(TerminalKey.enter); + } + }, + onKeyEvent: _handleKeyEvent, + readOnly: widget.readOnly, + child: child, + ); + } else if (!widget.readOnly) { + // Only listen for key input from a hardware keyboard. + child = CustomKeyboardListener( + child: child, + focusNode: _focusNode, + autofocus: widget.autofocus, + onInsert: _onInsert, + onComposing: _onComposing, + onKeyEvent: _handleKeyEvent, + ); + } + + child = TerminalActions( + terminal: widget.terminal, + controller: _controller, + child: child, + ); + + child = KeyboardVisibilty( + onKeyboardShow: _onKeyboardShow, + child: child, + ); + + child = TerminalGestureHandler( + terminalView: this, + terminalController: _controller, + onTapUp: _onTapUp, + onTapDown: _onTapDown, + onSecondaryTapDown: + widget.onSecondaryTapDown != null ? _onSecondaryTapDown : null, + onSecondaryTapUp: + widget.onSecondaryTapUp != null ? _onSecondaryTapUp : null, + readOnly: widget.readOnly, + child: child, + ); + + child = MouseRegion( + cursor: widget.mouseCursor, + child: child, + ); + + child = Container( + color: widget.theme.background.withOpacity(widget.backgroundOpacity), + padding: widget.padding, + child: child, + ); + + return child; + } + + void requestKeyboard() { + _customTextEditKey.currentState?.requestKeyboard(); + } + + void closeKeyboard() { + _customTextEditKey.currentState?.closeKeyboard(); + } + + Rect get cursorRect { + return renderTerminal.cursorOffset & renderTerminal.cellSize; + } + + Rect get globalCursorRect { + return renderTerminal.localToGlobal(renderTerminal.cursorOffset) & + renderTerminal.cellSize; + } + + void _onTapUp(TapUpDetails details) { + final offset = renderTerminal.getCellOffset(details.localPosition); + widget.onTapUp?.call(details, offset); + } + + void _onTapDown(_) { + if (_controller.selection != null) { + _controller.clearSelection(); + } else { + if (!widget.hardwareKeyboardOnly) { + _customTextEditKey.currentState?.requestKeyboard(); + } else { + _focusNode.requestFocus(); + } + } + } + + void _onSecondaryTapDown(TapDownDetails details) { + final offset = renderTerminal.getCellOffset(details.localPosition); + widget.onSecondaryTapDown?.call(details, offset); + } + + void _onSecondaryTapUp(TapUpDetails details) { + final offset = renderTerminal.getCellOffset(details.localPosition); + widget.onSecondaryTapUp?.call(details, offset); + } + + bool get hasInputConnection { + return _customTextEditKey.currentState?.hasInputConnection == true; + } + + void _onInsert(String text) { + final key = charToTerminalKey(text.trim()); + + // On mobile platforms there is no guarantee that virtual keyboard will + // generate hardware key events. So we need first try to send the key + // as a hardware key event. If it fails, then we send it as a text input. + final consumed = key == null ? false : widget.terminal.keyInput(key); + + if (!consumed) { + widget.terminal.textInput(text); + } + + _scrollToBottom(); + } + + void _onComposing(String? text) { + setState(() => _composingText = text); + } + + KeyEventResult _handleKeyEvent(FocusNode focusNode, KeyEvent event) { + final resultOverride = widget.onKeyEvent?.call(focusNode, event); + if (resultOverride != null && resultOverride != KeyEventResult.ignored) { + return resultOverride; + } + + // ignore: invalid_use_of_protected_member + final shortcutResult = _shortcutManager.handleKeypress( + focusNode.context!, + event, + ); + + if (shortcutResult != KeyEventResult.ignored) { + return shortcutResult; + } + + if (event is KeyUpEvent) { + return KeyEventResult.ignored; + } + + final key = keyToTerminalKey(event.logicalKey); + + if (key == null) { + return KeyEventResult.ignored; + } + + final handled = widget.terminal.keyInput( + key, + ctrl: HardwareKeyboard.instance.isControlPressed, + alt: HardwareKeyboard.instance.isAltPressed, + shift: HardwareKeyboard.instance.isShiftPressed, + ); + + if (handled) { + _scrollToBottom(); + } + + return handled ? KeyEventResult.handled : KeyEventResult.ignored; + } + + void _onKeyboardShow() { + if (_focusNode.hasFocus) { + WidgetsBinding.instance.addPostFrameCallback((_) { + _scrollToBottom(); + }); + } + } + + void _onEditableRect(Rect rect, Rect caretRect) { + _customTextEditKey.currentState?.setEditableRect(rect, caretRect); + } + + void _scrollToBottom() { + final position = _scrollableKey.currentState?.position; + if (position != null) { + position.jumpTo(position.maxScrollExtent); + } + } +} + +class _TerminalView extends LeafRenderObjectWidget { + const _TerminalView({ + super.key, + required this.terminal, + required this.controller, + required this.offset, + required this.padding, + required this.autoResize, + required this.textStyle, + required this.textScaler, + required this.theme, + required this.focusNode, + required this.cursorType, + required this.alwaysShowCursor, + this.onEditableRect, + this.composingText, + }); + + final Terminal terminal; + + final TerminalController controller; + + final ViewportOffset offset; + + final EdgeInsets padding; + + final bool autoResize; + + final TerminalStyle textStyle; + + final TextScaler textScaler; + + final TerminalTheme theme; + + final FocusNode focusNode; + + final TerminalCursorType cursorType; + + final bool alwaysShowCursor; + + final EditableRectCallback? onEditableRect; + + final String? composingText; + + @override + RenderTerminal createRenderObject(BuildContext context) { + return RenderTerminal( + terminal: terminal, + controller: controller, + offset: offset, + padding: padding, + autoResize: autoResize, + textStyle: textStyle, + textScaler: textScaler, + theme: theme, + focusNode: focusNode, + cursorType: cursorType, + alwaysShowCursor: alwaysShowCursor, + onEditableRect: onEditableRect, + composingText: composingText, + ); + } + + @override + void updateRenderObject(BuildContext context, RenderTerminal renderObject) { + renderObject + ..terminal = terminal + ..controller = controller + ..offset = offset + ..padding = padding + ..autoResize = autoResize + ..textStyle = textStyle + ..textScaler = textScaler + ..theme = theme + ..focusNode = focusNode + ..cursorType = cursorType + ..alwaysShowCursor = alwaysShowCursor + ..onEditableRect = onEditableRect + ..composingText = composingText; + } +} diff --git a/app/third_party/xterm/lib/src/ui/char_metrics.dart b/app/third_party/xterm/lib/src/ui/char_metrics.dart new file mode 100644 index 00000000..e35439d4 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/char_metrics.dart @@ -0,0 +1,21 @@ +import 'dart:ui'; + +import 'package:flutter/painting.dart'; +import 'package:xterm/src/ui/terminal_text_style.dart'; + +Size calcCharSize(TerminalStyle style, TextScaler textScaler) { + const test = 'mmmmmmmmmm'; + + final textStyle = style.toTextStyle(); + final builder = ParagraphBuilder(textStyle.getParagraphStyle()); + builder.pushStyle(textStyle.getTextStyle(textScaler: textScaler)); + builder.addText(test); + + final paragraph = builder.build(); + paragraph.layout(ParagraphConstraints(width: double.infinity)); + + return Size( + paragraph.maxIntrinsicWidth / test.length, + paragraph.height, + ); +} diff --git a/app/third_party/xterm/lib/src/ui/controller.dart b/app/third_party/xterm/lib/src/ui/controller.dart new file mode 100644 index 00000000..1e107c2d --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/controller.dart @@ -0,0 +1,174 @@ +import 'package:flutter/material.dart'; +import 'package:meta/meta.dart'; +import 'package:xterm/src/base/disposable.dart'; +import 'package:xterm/src/core/buffer/cell_offset.dart'; +import 'package:xterm/src/core/buffer/line.dart'; +import 'package:xterm/src/core/buffer/range.dart'; +import 'package:xterm/src/core/buffer/range_block.dart'; +import 'package:xterm/src/core/buffer/range_line.dart'; +import 'package:xterm/src/ui/pointer_input.dart'; +import 'package:xterm/src/ui/selection_mode.dart'; + +class TerminalController with ChangeNotifier { + TerminalController({ + SelectionMode selectionMode = SelectionMode.line, + PointerInputs pointerInputs = const PointerInputs({PointerInput.tap}), + bool suspendPointerInput = false, + }) : _selectionMode = selectionMode, + _pointerInputs = pointerInputs, + _suspendPointerInputs = suspendPointerInput; + + CellAnchor? _selectionBase; + CellAnchor? _selectionExtent; + + SelectionMode get selectionMode => _selectionMode; + SelectionMode _selectionMode; + + /// The set of pointer events which will be used as mouse input for the terminal. + PointerInputs get pointerInput => _pointerInputs; + PointerInputs _pointerInputs; + + /// True if sending pointer events to the terminal is suspended. + bool get suspendedPointerInputs => _suspendPointerInputs; + bool _suspendPointerInputs; + + List get highlights => _highlights; + final _highlights = []; + + BufferRange? get selection { + final base = _selectionBase; + final extent = _selectionExtent; + + if (base == null || extent == null) { + return null; + } + + if (!base.attached || !extent.attached) { + return null; + } + + return _createRange(base.offset, extent.offset); + } + + /// Set selection on the terminal from [base] to [extent]. This method takes + /// the ownership of [base] and [extent] and will dispose them when the + /// selection is cleared or changed. + void setSelection(CellAnchor base, CellAnchor extent, {SelectionMode? mode}) { + _selectionBase?.dispose(); + _selectionBase = base; + + _selectionExtent?.dispose(); + _selectionExtent = extent; + + if (mode != null) { + _selectionMode = mode; + } + + notifyListeners(); + } + + BufferRange _createRange(CellOffset begin, CellOffset end) { + switch (selectionMode) { + case SelectionMode.line: + return BufferRangeLine(begin, end); + case SelectionMode.block: + return BufferRangeBlock(begin, end); + } + } + + /// Controls how the terminal behaves when the user selects a range of text. + /// The default is [SelectionMode.line]. Setting this to [SelectionMode.block] + /// enables block selection mode. + void setSelectionMode(SelectionMode newSelectionMode) { + // If the new mode is the same as the old mode, + // nothing has to be changed. + if (_selectionMode == newSelectionMode) { + return; + } + // Set the new mode. + _selectionMode = newSelectionMode; + notifyListeners(); + } + + /// Clears the current selection. + void clearSelection() { + _selectionBase?.dispose(); + _selectionBase = null; + _selectionExtent?.dispose(); + _selectionExtent = null; + notifyListeners(); + } + + // Select which type of pointer events are send to the terminal. + void setPointerInputs(PointerInputs pointerInput) { + _pointerInputs = pointerInput; + notifyListeners(); + } + + // Toggle sending pointer events to the terminal. + void setSuspendPointerInput(bool suspend) { + _suspendPointerInputs = suspend; + notifyListeners(); + } + + // Returns true if this type of PointerInput should be send to the Terminal. + @internal + bool shouldSendPointerInput(PointerInput pointerInput) { + // Always return false if pointer input is suspended. + return _suspendPointerInputs + ? false + : _pointerInputs.inputs.contains(pointerInput); + } + + /// Creates a new highlight on the terminal from [p1] to [p2] with the given + /// [color]. The highlight will be removed when the returned object is + /// disposed. + TerminalHighlight highlight({ + required CellAnchor p1, + required CellAnchor p2, + required Color color, + }) { + final highlight = TerminalHighlight( + this, + p1: p1, + p2: p2, + color: color, + ); + + _highlights.add(highlight); + notifyListeners(); + + highlight.registerCallback(() { + _highlights.remove(highlight); + notifyListeners(); + }); + + return highlight; + } +} + +class TerminalHighlight with Disposable { + final TerminalController owner; + + final CellAnchor p1; + + final CellAnchor p2; + + final Color color; + + TerminalHighlight( + this.owner, { + required this.p1, + required this.p2, + required this.color, + }); + + /// Returns the range of the highlight. May be null if the anchors that + /// define the highlight are not attached to the terminal. + BufferRange? get range { + if (!p1.attached || !p2.attached) { + return null; + } + return BufferRangeLine(p1.offset, p2.offset); + } +} diff --git a/app/third_party/xterm/lib/src/ui/cursor_type.dart b/app/third_party/xterm/lib/src/ui/cursor_type.dart new file mode 100644 index 00000000..0af0a58d --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/cursor_type.dart @@ -0,0 +1,7 @@ +enum TerminalCursorType { + block, + + underline, + + verticalBar, +} diff --git a/app/third_party/xterm/lib/src/ui/custom_text_edit.dart b/app/third_party/xterm/lib/src/ui/custom_text_edit.dart new file mode 100644 index 00000000..1d33c7a2 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/custom_text_edit.dart @@ -0,0 +1,281 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +class CustomTextEdit extends StatefulWidget { + CustomTextEdit({ + super.key, + required this.child, + required this.onInsert, + required this.onDelete, + required this.onComposing, + required this.onAction, + required this.onKeyEvent, + required this.focusNode, + this.autofocus = false, + this.readOnly = false, + // this.initEditingState = TextEditingValue.empty, + this.inputType = TextInputType.text, + this.inputAction = TextInputAction.newline, + this.keyboardAppearance = Brightness.light, + this.deleteDetection = false, + }); + + final Widget child; + + final void Function(String) onInsert; + + final void Function() onDelete; + + final void Function(String?) onComposing; + + final void Function(TextInputAction) onAction; + + final KeyEventResult Function(FocusNode, KeyEvent) onKeyEvent; + + final FocusNode focusNode; + + final bool autofocus; + + final bool readOnly; + + final TextInputType inputType; + + final TextInputAction inputAction; + + final Brightness keyboardAppearance; + + final bool deleteDetection; + + @override + CustomTextEditState createState() => CustomTextEditState(); +} + +class CustomTextEditState extends State with TextInputClient { + TextInputConnection? _connection; + + @override + void initState() { + widget.focusNode.addListener(_onFocusChange); + super.initState(); + } + + @override + void didUpdateWidget(CustomTextEdit oldWidget) { + super.didUpdateWidget(oldWidget); + + if (widget.focusNode != oldWidget.focusNode) { + oldWidget.focusNode.removeListener(_onFocusChange); + widget.focusNode.addListener(_onFocusChange); + } + + if (!_shouldCreateInputConnection) { + _closeInputConnectionIfNeeded(); + } else { + if (oldWidget.readOnly && widget.focusNode.hasFocus) { + _openInputConnection(); + } + } + } + + @override + void dispose() { + widget.focusNode.removeListener(_onFocusChange); + _closeInputConnectionIfNeeded(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Focus( + focusNode: widget.focusNode, + autofocus: widget.autofocus, + onKeyEvent: _onKeyEvent, + child: widget.child, + ); + } + + bool get hasInputConnection => _connection != null && _connection!.attached; + + void requestKeyboard() { + if (widget.focusNode.hasFocus) { + _openInputConnection(); + } else { + widget.focusNode.requestFocus(); + } + } + + void closeKeyboard() { + if (hasInputConnection) { + _connection?.close(); + } + } + + void setEditingState(TextEditingValue value) { + _currentEditingState = value; + _connection?.setEditingState(value); + } + + void setEditableRect(Rect rect, Rect caretRect) { + if (!hasInputConnection) { + return; + } + + _connection?.setEditableSizeAndTransform( + rect.size, + Matrix4.translationValues(0, 0, 0), + ); + + _connection?.setCaretRect(caretRect); + } + + void _onFocusChange() { + _openOrCloseInputConnectionIfNeeded(); + } + + KeyEventResult _onKeyEvent(FocusNode focusNode, KeyEvent event) { + if (_currentEditingState.composing.isCollapsed) { + return widget.onKeyEvent(focusNode, event); + } + + return KeyEventResult.skipRemainingHandlers; + } + + void _openOrCloseInputConnectionIfNeeded() { + if (widget.focusNode.hasFocus && widget.focusNode.consumeKeyboardToken()) { + _openInputConnection(); + } else if (!widget.focusNode.hasFocus) { + _closeInputConnectionIfNeeded(); + } + } + + bool get _shouldCreateInputConnection => kIsWeb || !widget.readOnly; + + void _openInputConnection() { + if (!_shouldCreateInputConnection) { + return; + } + + if (hasInputConnection) { + _connection!.show(); + } else { + final config = TextInputConfiguration( + inputType: widget.inputType, + inputAction: widget.inputAction, + keyboardAppearance: widget.keyboardAppearance, + autocorrect: false, + enableSuggestions: false, + enableIMEPersonalizedLearning: false, + ); + + _connection = TextInput.attach(this, config); + + _connection!.show(); + + // setEditableRect(Rect.zero, Rect.zero); + + _connection!.setEditingState(_initEditingState); + } + } + + void _closeInputConnectionIfNeeded() { + if (_connection != null && _connection!.attached) { + _connection!.close(); + _connection = null; + } + } + + TextEditingValue get _initEditingState => widget.deleteDetection + ? const TextEditingValue( + text: ' ', + selection: TextSelection.collapsed(offset: 2), + ) + : const TextEditingValue( + text: '', + selection: TextSelection.collapsed(offset: 0), + ); + + late var _currentEditingState = _initEditingState.copyWith(); + + @override + TextEditingValue? get currentTextEditingValue { + return _currentEditingState; + } + + @override + AutofillScope? get currentAutofillScope { + return null; + } + + @override + void updateEditingValue(TextEditingValue value) { + _currentEditingState = value; + + // Get input after composing is done + if (!_currentEditingState.composing.isCollapsed) { + final text = _currentEditingState.text; + final composingText = _currentEditingState.composing.textInside(text); + widget.onComposing(composingText); + return; + } + + widget.onComposing(null); + + if (_currentEditingState.text.length < _initEditingState.text.length) { + widget.onDelete(); + } else { + final textDelta = _currentEditingState.text.substring( + _initEditingState.text.length, + ); + + widget.onInsert(textDelta); + } + + // Reset editing state if composing is done + if (_currentEditingState.composing.isCollapsed && + _currentEditingState.text != _initEditingState.text) { + _connection!.setEditingState(_initEditingState); + } + } + + @override + void performAction(TextInputAction action) { + // print('performAction $action'); + widget.onAction(action); + } + + @override + void updateFloatingCursor(RawFloatingCursorPoint point) { + // print('updateFloatingCursor $point'); + } + + @override + void showAutocorrectionPromptRect(int start, int end) { + // print('showAutocorrectionPromptRect'); + } + + @override + void connectionClosed() { + // print('connectionClosed'); + } + + @override + void performPrivateCommand(String action, Map data) { + // print('performPrivateCommand $action'); + } + + @override + void insertTextPlaceholder(Size size) { + // print('insertTextPlaceholder'); + } + + @override + void removeTextPlaceholder() { + // print('removeTextPlaceholder'); + } + + @override + void showToolbar() { + // print('showToolbar'); + } +} diff --git a/app/third_party/xterm/lib/src/ui/gesture/gesture_detector.dart b/app/third_party/xterm/lib/src/ui/gesture/gesture_detector.dart new file mode 100644 index 00000000..c29e50b0 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/gesture/gesture_detector.dart @@ -0,0 +1,162 @@ +import 'dart:async'; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/widgets.dart'; + +class TerminalGestureDetector extends StatefulWidget { + const TerminalGestureDetector({ + super.key, + this.child, + this.onSingleTapUp, + this.onTapUp, + this.onTapDown, + this.onSecondaryTapDown, + this.onSecondaryTapUp, + this.onTertiaryTapDown, + this.onTertiaryTapUp, + this.onLongPressStart, + this.onLongPressMoveUpdate, + this.onLongPressUp, + this.onDragStart, + this.onDragUpdate, + this.onDoubleTapDown, + }); + + final Widget? child; + + final GestureTapUpCallback? onTapUp; + + final GestureTapUpCallback? onSingleTapUp; + + final GestureTapDownCallback? onTapDown; + + final GestureTapDownCallback? onSecondaryTapDown; + + final GestureTapUpCallback? onSecondaryTapUp; + + final GestureTapDownCallback? onDoubleTapDown; + + final GestureTapDownCallback? onTertiaryTapDown; + + final GestureTapUpCallback? onTertiaryTapUp; + + final GestureLongPressStartCallback? onLongPressStart; + + final GestureLongPressMoveUpdateCallback? onLongPressMoveUpdate; + + final GestureLongPressUpCallback? onLongPressUp; + + final GestureDragStartCallback? onDragStart; + + final GestureDragUpdateCallback? onDragUpdate; + + @override + State createState() => + _TerminalGestureDetectorState(); +} + +class _TerminalGestureDetectorState extends State { + Timer? _doubleTapTimer; + + Offset? _lastTapOffset; + + // True if a second tap down of a double tap is detected. Used to discard + // subsequent tap up / tap hold of the same tap. + bool _isDoubleTap = false; + + // The down handler is force-run on success of a single tap and optimistically + // run before a long press success. + void _handleTapDown(TapDownDetails details) { + widget.onTapDown?.call(details); + + if (_doubleTapTimer != null && + _isWithinDoubleTapTolerance(details.globalPosition)) { + // If there was already a previous tap, the second down hold/tap is a + // double tap down. + widget.onDoubleTapDown?.call(details); + + _doubleTapTimer!.cancel(); + _doubleTapTimeout(); + _isDoubleTap = true; + } + } + + void _handleTapUp(TapUpDetails details) { + if (!_isDoubleTap) { + widget.onSingleTapUp?.call(details); + _lastTapOffset = details.globalPosition; + _doubleTapTimer = Timer(kDoubleTapTimeout, _doubleTapTimeout); + } + _isDoubleTap = false; + } + + void _doubleTapTimeout() { + _doubleTapTimer = null; + _lastTapOffset = null; + } + + bool _isWithinDoubleTapTolerance(Offset secondTapOffset) { + if (_lastTapOffset == null) { + return false; + } + + final Offset difference = secondTapOffset - _lastTapOffset!; + return difference.distance <= kDoubleTapSlop; + } + + @override + Widget build(BuildContext context) { + final gestures = {}; + + gestures[TapGestureRecognizer] = + GestureRecognizerFactoryWithHandlers( + () => TapGestureRecognizer(debugOwner: this), + (TapGestureRecognizer instance) { + instance + ..onTapDown = _handleTapDown + ..onTapUp = _handleTapUp + ..onSecondaryTapDown = widget.onSecondaryTapDown + ..onSecondaryTapUp = widget.onSecondaryTapUp + ..onTertiaryTapDown = widget.onTertiaryTapDown + ..onTertiaryTapUp = widget.onTertiaryTapUp; + }, + ); + + gestures[LongPressGestureRecognizer] = + GestureRecognizerFactoryWithHandlers( + () => LongPressGestureRecognizer( + debugOwner: this, + supportedDevices: { + PointerDeviceKind.touch, + // PointerDeviceKind.mouse, // for debugging purposes only + }, + ), + (LongPressGestureRecognizer instance) { + instance + ..onLongPressStart = widget.onLongPressStart + ..onLongPressMoveUpdate = widget.onLongPressMoveUpdate + ..onLongPressUp = widget.onLongPressUp; + }, + ); + + gestures[PanGestureRecognizer] = + GestureRecognizerFactoryWithHandlers( + () => PanGestureRecognizer( + debugOwner: this, + supportedDevices: {PointerDeviceKind.mouse}, + ), + (PanGestureRecognizer instance) { + instance + ..dragStartBehavior = DragStartBehavior.down + ..onStart = widget.onDragStart + ..onUpdate = widget.onDragUpdate; + }, + ); + + return RawGestureDetector( + gestures: gestures, + excludeFromSemantics: true, + child: widget.child, + ); + } +} diff --git a/app/third_party/xterm/lib/src/ui/gesture/gesture_handler.dart b/app/third_party/xterm/lib/src/ui/gesture/gesture_handler.dart new file mode 100644 index 00000000..2f6d7b69 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/gesture/gesture_handler.dart @@ -0,0 +1,191 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/widgets.dart'; +import 'package:xterm/src/core/mouse/button.dart'; +import 'package:xterm/src/core/mouse/button_state.dart'; +import 'package:xterm/src/terminal_view.dart'; +import 'package:xterm/src/ui/controller.dart'; +import 'package:xterm/src/ui/gesture/gesture_detector.dart'; +import 'package:xterm/src/ui/pointer_input.dart'; +import 'package:xterm/src/ui/render.dart'; + +class TerminalGestureHandler extends StatefulWidget { + const TerminalGestureHandler({ + super.key, + required this.terminalView, + required this.terminalController, + this.child, + this.onTapUp, + this.onSingleTapUp, + this.onTapDown, + this.onSecondaryTapDown, + this.onSecondaryTapUp, + this.onTertiaryTapDown, + this.onTertiaryTapUp, + this.readOnly = false, + }); + + final TerminalViewState terminalView; + + final TerminalController terminalController; + + final Widget? child; + + final GestureTapUpCallback? onTapUp; + + final GestureTapUpCallback? onSingleTapUp; + + final GestureTapDownCallback? onTapDown; + + final GestureTapDownCallback? onSecondaryTapDown; + + final GestureTapUpCallback? onSecondaryTapUp; + + final GestureTapDownCallback? onTertiaryTapDown; + + final GestureTapUpCallback? onTertiaryTapUp; + + final bool readOnly; + + @override + State createState() => _TerminalGestureHandlerState(); +} + +class _TerminalGestureHandlerState extends State { + TerminalViewState get terminalView => widget.terminalView; + + RenderTerminal get renderTerminal => terminalView.renderTerminal; + + DragStartDetails? _lastDragStartDetails; + + LongPressStartDetails? _lastLongPressStartDetails; + + @override + Widget build(BuildContext context) { + return TerminalGestureDetector( + child: widget.child, + onTapUp: widget.onTapUp, + onSingleTapUp: onSingleTapUp, + onTapDown: onTapDown, + onSecondaryTapDown: onSecondaryTapDown, + onSecondaryTapUp: onSecondaryTapUp, + onTertiaryTapDown: onSecondaryTapDown, + onTertiaryTapUp: onSecondaryTapUp, + onLongPressStart: onLongPressStart, + onLongPressMoveUpdate: onLongPressMoveUpdate, + // onLongPressUp: onLongPressUp, + onDragStart: onDragStart, + onDragUpdate: onDragUpdate, + onDoubleTapDown: onDoubleTapDown, + ); + } + + bool get _shouldSendTapEvent => + !widget.readOnly && + widget.terminalController.shouldSendPointerInput(PointerInput.tap); + + void _tapDown( + GestureTapDownCallback? callback, + TapDownDetails details, + TerminalMouseButton button, { + bool forceCallback = false, + }) { + // Check if the terminal should and can handle the tap down event. + var handled = false; + if (_shouldSendTapEvent) { + handled = renderTerminal.mouseEvent( + button, + TerminalMouseButtonState.down, + details.localPosition, + ); + } + // If the event was not handled by the terminal, use the supplied callback. + if (!handled || forceCallback) { + callback?.call(details); + } + } + + void _tapUp( + GestureTapUpCallback? callback, + TapUpDetails details, + TerminalMouseButton button, { + bool forceCallback = false, + }) { + // Check if the terminal should and can handle the tap up event. + var handled = false; + if (_shouldSendTapEvent) { + handled = renderTerminal.mouseEvent( + button, + TerminalMouseButtonState.up, + details.localPosition, + ); + } + // If the event was not handled by the terminal, use the supplied callback. + if (!handled || forceCallback) { + callback?.call(details); + } + } + + void onTapDown(TapDownDetails details) { + // onTapDown is special, as it will always call the supplied callback. + // The TerminalView depends on it to bring the terminal into focus. + _tapDown( + widget.onTapDown, + details, + TerminalMouseButton.left, + forceCallback: true, + ); + } + + void onSingleTapUp(TapUpDetails details) { + _tapUp(widget.onSingleTapUp, details, TerminalMouseButton.left); + } + + void onSecondaryTapDown(TapDownDetails details) { + _tapDown(widget.onSecondaryTapDown, details, TerminalMouseButton.right); + } + + void onSecondaryTapUp(TapUpDetails details) { + _tapUp(widget.onSecondaryTapUp, details, TerminalMouseButton.right); + } + + void onTertiaryTapDown(TapDownDetails details) { + _tapDown(widget.onTertiaryTapDown, details, TerminalMouseButton.middle); + } + + void onTertiaryTapUp(TapUpDetails details) { + _tapUp(widget.onTertiaryTapUp, details, TerminalMouseButton.right); + } + + void onDoubleTapDown(TapDownDetails details) { + renderTerminal.selectWord(details.localPosition); + } + + void onLongPressStart(LongPressStartDetails details) { + _lastLongPressStartDetails = details; + renderTerminal.selectWord(details.localPosition); + } + + void onLongPressMoveUpdate(LongPressMoveUpdateDetails details) { + renderTerminal.selectWord( + _lastLongPressStartDetails!.localPosition, + details.localPosition, + ); + } + + // void onLongPressUp() {} + + void onDragStart(DragStartDetails details) { + _lastDragStartDetails = details; + + details.kind == PointerDeviceKind.mouse + ? renderTerminal.selectCharacters(details.localPosition) + : renderTerminal.selectWord(details.localPosition); + } + + void onDragUpdate(DragUpdateDetails details) { + renderTerminal.selectCharacters( + _lastDragStartDetails!.localPosition, + details.localPosition, + ); + } +} diff --git a/app/third_party/xterm/lib/src/ui/infinite_scroll_view.dart b/app/third_party/xterm/lib/src/ui/infinite_scroll_view.dart new file mode 100644 index 00000000..9640a3ca --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/infinite_scroll_view.dart @@ -0,0 +1,115 @@ +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +/// The function called when the user scrolls the [InfiniteScrollView]. [offset] +/// is the current offset of the scroll view, ranging from [double.negativeInfinity] +/// to [double.infinity]. +typedef ScrollCallback = void Function(double offset); + +/// A [Scrollable] that can be scrolled infinitely in both directions. When +/// scroll happens, the [onScroll] callback is called with the new offset. +class InfiniteScrollView extends StatelessWidget { + const InfiniteScrollView({ + super.key, + required this.onScroll, + required this.child, + }); + + final ScrollCallback onScroll; + + final Widget child; + + @override + Widget build(BuildContext context) { + return Scrollable( + viewportBuilder: (context, position) { + return _InfiniteScrollView( + position: position, + onScroll: onScroll, + child: child, + ); + }, + ); + } +} + +class _InfiniteScrollView extends SingleChildRenderObjectWidget { + const _InfiniteScrollView({ + // super.key, + super.child, + required this.position, + required this.onScroll, + }); + + final ViewportOffset position; + + final ScrollCallback onScroll; + + @override + RenderObject createRenderObject(BuildContext context) { + return _RenderInfiniteScrollView( + position: position, + onScroll: onScroll, + ); + } + + @override + void updateRenderObject( + BuildContext context, + _RenderInfiniteScrollView renderObject, + ) { + renderObject + ..position = position + ..onScroll = onScroll; + } +} + +class _RenderInfiniteScrollView extends RenderShiftedBox { + _RenderInfiniteScrollView({ + RenderBox? child, + required ViewportOffset position, + required ScrollCallback onScroll, + }) : _position = position, + _scrollCallback = onScroll, + super(child); + + ViewportOffset _position; + set position(ViewportOffset value) { + if (_position == value) return; + if (attached) _position.removeListener(markNeedsLayout); + _position = value; + if (attached) _position.addListener(markNeedsLayout); + markNeedsLayout(); + } + + ScrollCallback _scrollCallback; + set onScroll(ScrollCallback value) { + if (_scrollCallback == value) return; + _scrollCallback = value; + markNeedsLayout(); + } + + void _onScroll() { + _scrollCallback(_position.pixels); + } + + @override + void attach(covariant PipelineOwner owner) { + super.attach(owner); + _position.addListener(_onScroll); + } + + @override + void detach() { + super.detach(); + _position.removeListener(_onScroll); + } + + @override + void performLayout() { + child?.layout(constraints, parentUsesSize: true); + size = child?.size ?? Size.zero; + _position.applyViewportDimension(size.height); + _position.applyContentDimensions(double.negativeInfinity, double.infinity); + } +} diff --git a/app/third_party/xterm/lib/src/ui/input_map.dart b/app/third_party/xterm/lib/src/ui/input_map.dart new file mode 100644 index 00000000..3f65d1d1 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/input_map.dart @@ -0,0 +1,288 @@ +import 'package:flutter/services.dart'; +import 'package:xterm/src/core/input/keys.dart'; + +final _keyToTerminalKey = { + LogicalKeyboardKey.hyper: TerminalKey.hyper, + LogicalKeyboardKey.superKey: TerminalKey.superKey, + LogicalKeyboardKey.fnLock: TerminalKey.fnLock, + LogicalKeyboardKey.suspend: TerminalKey.suspend, + LogicalKeyboardKey.resume: TerminalKey.resume, + LogicalKeyboardKey.sleep: TerminalKey.sleep, + LogicalKeyboardKey.wakeUp: TerminalKey.wakeUp, + LogicalKeyboardKey.keyA: TerminalKey.keyA, + LogicalKeyboardKey.keyB: TerminalKey.keyB, + LogicalKeyboardKey.keyC: TerminalKey.keyC, + LogicalKeyboardKey.keyD: TerminalKey.keyD, + LogicalKeyboardKey.keyE: TerminalKey.keyE, + LogicalKeyboardKey.keyF: TerminalKey.keyF, + LogicalKeyboardKey.keyG: TerminalKey.keyG, + LogicalKeyboardKey.keyH: TerminalKey.keyH, + LogicalKeyboardKey.keyI: TerminalKey.keyI, + LogicalKeyboardKey.keyJ: TerminalKey.keyJ, + LogicalKeyboardKey.keyK: TerminalKey.keyK, + LogicalKeyboardKey.keyL: TerminalKey.keyL, + LogicalKeyboardKey.keyM: TerminalKey.keyM, + LogicalKeyboardKey.keyN: TerminalKey.keyN, + LogicalKeyboardKey.keyO: TerminalKey.keyO, + LogicalKeyboardKey.keyP: TerminalKey.keyP, + LogicalKeyboardKey.keyQ: TerminalKey.keyQ, + LogicalKeyboardKey.keyR: TerminalKey.keyR, + LogicalKeyboardKey.keyS: TerminalKey.keyS, + LogicalKeyboardKey.keyT: TerminalKey.keyT, + LogicalKeyboardKey.keyU: TerminalKey.keyU, + LogicalKeyboardKey.keyV: TerminalKey.keyV, + LogicalKeyboardKey.keyW: TerminalKey.keyW, + LogicalKeyboardKey.keyX: TerminalKey.keyX, + LogicalKeyboardKey.keyY: TerminalKey.keyY, + LogicalKeyboardKey.keyZ: TerminalKey.keyZ, + LogicalKeyboardKey.digit1: TerminalKey.digit1, + LogicalKeyboardKey.digit2: TerminalKey.digit2, + LogicalKeyboardKey.digit3: TerminalKey.digit3, + LogicalKeyboardKey.digit4: TerminalKey.digit4, + LogicalKeyboardKey.digit5: TerminalKey.digit5, + LogicalKeyboardKey.digit6: TerminalKey.digit6, + LogicalKeyboardKey.digit7: TerminalKey.digit7, + LogicalKeyboardKey.digit8: TerminalKey.digit8, + LogicalKeyboardKey.digit9: TerminalKey.digit9, + LogicalKeyboardKey.digit0: TerminalKey.digit0, + LogicalKeyboardKey.enter: TerminalKey.enter, + LogicalKeyboardKey.escape: TerminalKey.escape, + LogicalKeyboardKey.backspace: TerminalKey.backspace, + LogicalKeyboardKey.tab: TerminalKey.tab, + LogicalKeyboardKey.space: TerminalKey.space, + LogicalKeyboardKey.minus: TerminalKey.minus, + LogicalKeyboardKey.equal: TerminalKey.equal, + LogicalKeyboardKey.bracketLeft: TerminalKey.bracketLeft, + LogicalKeyboardKey.bracketRight: TerminalKey.bracketRight, + LogicalKeyboardKey.backslash: TerminalKey.backslash, + LogicalKeyboardKey.semicolon: TerminalKey.semicolon, + LogicalKeyboardKey.quote: TerminalKey.quote, + LogicalKeyboardKey.backquote: TerminalKey.backquote, + LogicalKeyboardKey.comma: TerminalKey.comma, + LogicalKeyboardKey.period: TerminalKey.period, + LogicalKeyboardKey.slash: TerminalKey.slash, + LogicalKeyboardKey.capsLock: TerminalKey.capsLock, + LogicalKeyboardKey.f1: TerminalKey.f1, + LogicalKeyboardKey.f2: TerminalKey.f2, + LogicalKeyboardKey.f3: TerminalKey.f3, + LogicalKeyboardKey.f4: TerminalKey.f4, + LogicalKeyboardKey.f5: TerminalKey.f5, + LogicalKeyboardKey.f6: TerminalKey.f6, + LogicalKeyboardKey.f7: TerminalKey.f7, + LogicalKeyboardKey.f8: TerminalKey.f8, + LogicalKeyboardKey.f9: TerminalKey.f9, + LogicalKeyboardKey.f10: TerminalKey.f10, + LogicalKeyboardKey.f11: TerminalKey.f11, + LogicalKeyboardKey.f12: TerminalKey.f12, + LogicalKeyboardKey.printScreen: TerminalKey.printScreen, + LogicalKeyboardKey.scrollLock: TerminalKey.scrollLock, + LogicalKeyboardKey.pause: TerminalKey.pause, + LogicalKeyboardKey.insert: TerminalKey.insert, + LogicalKeyboardKey.home: TerminalKey.home, + LogicalKeyboardKey.pageUp: TerminalKey.pageUp, + LogicalKeyboardKey.delete: TerminalKey.delete, + LogicalKeyboardKey.end: TerminalKey.end, + LogicalKeyboardKey.pageDown: TerminalKey.pageDown, + LogicalKeyboardKey.arrowRight: TerminalKey.arrowRight, + LogicalKeyboardKey.arrowLeft: TerminalKey.arrowLeft, + LogicalKeyboardKey.arrowDown: TerminalKey.arrowDown, + LogicalKeyboardKey.arrowUp: TerminalKey.arrowUp, + LogicalKeyboardKey.numLock: TerminalKey.numLock, + LogicalKeyboardKey.numpadDivide: TerminalKey.numpadDivide, + LogicalKeyboardKey.numpadMultiply: TerminalKey.numpadMultiply, + LogicalKeyboardKey.numpadSubtract: TerminalKey.numpadSubtract, + LogicalKeyboardKey.numpadAdd: TerminalKey.numpadAdd, + LogicalKeyboardKey.numpadEnter: TerminalKey.numpadEnter, + LogicalKeyboardKey.numpad1: TerminalKey.numpad1, + LogicalKeyboardKey.numpad2: TerminalKey.numpad2, + LogicalKeyboardKey.numpad3: TerminalKey.numpad3, + LogicalKeyboardKey.numpad4: TerminalKey.numpad4, + LogicalKeyboardKey.numpad5: TerminalKey.numpad5, + LogicalKeyboardKey.numpad6: TerminalKey.numpad6, + LogicalKeyboardKey.numpad7: TerminalKey.numpad7, + LogicalKeyboardKey.numpad8: TerminalKey.numpad8, + LogicalKeyboardKey.numpad9: TerminalKey.numpad9, + LogicalKeyboardKey.numpad0: TerminalKey.numpad0, + LogicalKeyboardKey.numpadDecimal: TerminalKey.numpadDecimal, + LogicalKeyboardKey.intlBackslash: TerminalKey.intlBackslash, + LogicalKeyboardKey.contextMenu: TerminalKey.contextMenu, + LogicalKeyboardKey.power: TerminalKey.power, + LogicalKeyboardKey.numpadEqual: TerminalKey.numpadEqual, + LogicalKeyboardKey.f13: TerminalKey.f13, + LogicalKeyboardKey.f14: TerminalKey.f14, + LogicalKeyboardKey.f15: TerminalKey.f15, + LogicalKeyboardKey.f16: TerminalKey.f16, + LogicalKeyboardKey.f17: TerminalKey.f17, + LogicalKeyboardKey.f18: TerminalKey.f18, + LogicalKeyboardKey.f19: TerminalKey.f19, + LogicalKeyboardKey.f20: TerminalKey.f20, + LogicalKeyboardKey.f21: TerminalKey.f21, + LogicalKeyboardKey.f22: TerminalKey.f22, + LogicalKeyboardKey.f23: TerminalKey.f23, + LogicalKeyboardKey.f24: TerminalKey.f24, + LogicalKeyboardKey.open: TerminalKey.open, + LogicalKeyboardKey.help: TerminalKey.help, + LogicalKeyboardKey.select: TerminalKey.select, + LogicalKeyboardKey.again: TerminalKey.again, + LogicalKeyboardKey.undo: TerminalKey.undo, + LogicalKeyboardKey.cut: TerminalKey.cut, + LogicalKeyboardKey.copy: TerminalKey.copy, + LogicalKeyboardKey.paste: TerminalKey.paste, + LogicalKeyboardKey.find: TerminalKey.find, + LogicalKeyboardKey.audioVolumeMute: TerminalKey.audioVolumeMute, + LogicalKeyboardKey.audioVolumeUp: TerminalKey.audioVolumeUp, + LogicalKeyboardKey.audioVolumeDown: TerminalKey.audioVolumeDown, + LogicalKeyboardKey.numpadComma: TerminalKey.numpadComma, + LogicalKeyboardKey.intlRo: TerminalKey.intlRo, + LogicalKeyboardKey.kanaMode: TerminalKey.kanaMode, + LogicalKeyboardKey.intlYen: TerminalKey.intlYen, + LogicalKeyboardKey.convert: TerminalKey.convert, + LogicalKeyboardKey.nonConvert: TerminalKey.nonConvert, + LogicalKeyboardKey.lang1: TerminalKey.lang1, + LogicalKeyboardKey.lang2: TerminalKey.lang2, + LogicalKeyboardKey.lang3: TerminalKey.lang3, + LogicalKeyboardKey.lang4: TerminalKey.lang4, + LogicalKeyboardKey.lang5: TerminalKey.lang5, + LogicalKeyboardKey.abort: TerminalKey.abort, + LogicalKeyboardKey.props: TerminalKey.props, + LogicalKeyboardKey.numpadParenLeft: TerminalKey.numpadParenLeft, + LogicalKeyboardKey.numpadParenRight: TerminalKey.numpadParenRight, + LogicalKeyboardKey.controlLeft: TerminalKey.controlLeft, + LogicalKeyboardKey.shiftLeft: TerminalKey.shiftLeft, + LogicalKeyboardKey.altLeft: TerminalKey.altLeft, + LogicalKeyboardKey.metaLeft: TerminalKey.metaLeft, + LogicalKeyboardKey.controlRight: TerminalKey.controlRight, + LogicalKeyboardKey.shiftRight: TerminalKey.shiftRight, + LogicalKeyboardKey.altRight: TerminalKey.altRight, + LogicalKeyboardKey.metaRight: TerminalKey.metaRight, + LogicalKeyboardKey.info: TerminalKey.info, + LogicalKeyboardKey.closedCaptionToggle: TerminalKey.closedCaptionToggle, + LogicalKeyboardKey.brightnessUp: TerminalKey.brightnessUp, + LogicalKeyboardKey.brightnessDown: TerminalKey.brightnessDown, + LogicalKeyboardKey.mediaLast: TerminalKey.mediaLast, + LogicalKeyboardKey.launchPhone: TerminalKey.launchPhone, + LogicalKeyboardKey.exit: TerminalKey.exit, + LogicalKeyboardKey.channelUp: TerminalKey.channelUp, + LogicalKeyboardKey.channelDown: TerminalKey.channelDown, + LogicalKeyboardKey.mediaPlay: TerminalKey.mediaPlay, + LogicalKeyboardKey.mediaPause: TerminalKey.mediaPause, + LogicalKeyboardKey.mediaRecord: TerminalKey.mediaRecord, + LogicalKeyboardKey.mediaFastForward: TerminalKey.mediaFastForward, + LogicalKeyboardKey.mediaRewind: TerminalKey.mediaRewind, + LogicalKeyboardKey.mediaTrackNext: TerminalKey.mediaTrackNext, + LogicalKeyboardKey.mediaTrackPrevious: TerminalKey.mediaTrackPrevious, + LogicalKeyboardKey.mediaStop: TerminalKey.mediaStop, + LogicalKeyboardKey.eject: TerminalKey.eject, + LogicalKeyboardKey.mediaPlayPause: TerminalKey.mediaPlayPause, + LogicalKeyboardKey.speechInputToggle: TerminalKey.speechInputToggle, + LogicalKeyboardKey.launchWordProcessor: TerminalKey.launchWordProcessor, + LogicalKeyboardKey.launchSpreadsheet: TerminalKey.launchSpreadsheet, + LogicalKeyboardKey.launchMail: TerminalKey.launchMail, + LogicalKeyboardKey.launchContacts: TerminalKey.launchContacts, + LogicalKeyboardKey.launchCalendar: TerminalKey.launchCalendar, + LogicalKeyboardKey.logOff: TerminalKey.logOff, + LogicalKeyboardKey.launchControlPanel: TerminalKey.launchControlPanel, + LogicalKeyboardKey.spellCheck: TerminalKey.spellCheck, + LogicalKeyboardKey.launchScreenSaver: TerminalKey.launchScreenSaver, + LogicalKeyboardKey.launchAssistant: TerminalKey.launchAssistant, + LogicalKeyboardKey.newKey: TerminalKey.newKey, + LogicalKeyboardKey.close: TerminalKey.close, + LogicalKeyboardKey.save: TerminalKey.save, + LogicalKeyboardKey.print: TerminalKey.print, + LogicalKeyboardKey.browserSearch: TerminalKey.browserSearch, + LogicalKeyboardKey.browserHome: TerminalKey.browserHome, + LogicalKeyboardKey.browserBack: TerminalKey.browserBack, + LogicalKeyboardKey.browserForward: TerminalKey.browserForward, + LogicalKeyboardKey.browserStop: TerminalKey.browserStop, + LogicalKeyboardKey.browserRefresh: TerminalKey.browserRefresh, + LogicalKeyboardKey.browserFavorites: TerminalKey.browserFavorites, + LogicalKeyboardKey.zoomIn: TerminalKey.zoomIn, + LogicalKeyboardKey.zoomOut: TerminalKey.zoomOut, + LogicalKeyboardKey.zoomToggle: TerminalKey.zoomToggle, + LogicalKeyboardKey.redo: TerminalKey.redo, + LogicalKeyboardKey.mailReply: TerminalKey.mailReply, + LogicalKeyboardKey.mailForward: TerminalKey.mailForward, + LogicalKeyboardKey.mailSend: TerminalKey.mailSend, + LogicalKeyboardKey.gameButton1: TerminalKey.gameButton1, + LogicalKeyboardKey.gameButton2: TerminalKey.gameButton2, + LogicalKeyboardKey.gameButton3: TerminalKey.gameButton3, + LogicalKeyboardKey.gameButton4: TerminalKey.gameButton4, + LogicalKeyboardKey.gameButton5: TerminalKey.gameButton5, + LogicalKeyboardKey.gameButton6: TerminalKey.gameButton6, + LogicalKeyboardKey.gameButton7: TerminalKey.gameButton7, + LogicalKeyboardKey.gameButton8: TerminalKey.gameButton8, + LogicalKeyboardKey.gameButton9: TerminalKey.gameButton9, + LogicalKeyboardKey.gameButton10: TerminalKey.gameButton10, + LogicalKeyboardKey.gameButton11: TerminalKey.gameButton11, + LogicalKeyboardKey.gameButton12: TerminalKey.gameButton12, + LogicalKeyboardKey.gameButton13: TerminalKey.gameButton13, + LogicalKeyboardKey.gameButton14: TerminalKey.gameButton14, + LogicalKeyboardKey.gameButton15: TerminalKey.gameButton15, + LogicalKeyboardKey.gameButton16: TerminalKey.gameButton16, + LogicalKeyboardKey.gameButtonA: TerminalKey.gameButtonA, + LogicalKeyboardKey.gameButtonB: TerminalKey.gameButtonB, + LogicalKeyboardKey.gameButtonC: TerminalKey.gameButtonC, + LogicalKeyboardKey.gameButtonLeft1: TerminalKey.gameButtonLeft1, + LogicalKeyboardKey.gameButtonLeft2: TerminalKey.gameButtonLeft2, + LogicalKeyboardKey.gameButtonMode: TerminalKey.gameButtonMode, + LogicalKeyboardKey.gameButtonRight1: TerminalKey.gameButtonRight1, + LogicalKeyboardKey.gameButtonRight2: TerminalKey.gameButtonRight2, + LogicalKeyboardKey.gameButtonSelect: TerminalKey.gameButtonSelect, + LogicalKeyboardKey.gameButtonStart: TerminalKey.gameButtonStart, + LogicalKeyboardKey.gameButtonThumbLeft: TerminalKey.gameButtonThumbLeft, + LogicalKeyboardKey.gameButtonThumbRight: TerminalKey.gameButtonThumbRight, + LogicalKeyboardKey.gameButtonX: TerminalKey.gameButtonX, + LogicalKeyboardKey.gameButtonY: TerminalKey.gameButtonY, + LogicalKeyboardKey.gameButtonZ: TerminalKey.gameButtonZ, + LogicalKeyboardKey.fn: TerminalKey.fn, + LogicalKeyboardKey.shift: TerminalKey.shift, + LogicalKeyboardKey.meta: TerminalKey.meta, + LogicalKeyboardKey.alt: TerminalKey.alt, + LogicalKeyboardKey.control: TerminalKey.control, +}; + +final _keyById = () { + final map = {}; + for (final entry in _keyToTerminalKey.entries) { + map[entry.key.keyId] = entry.value; + } + return map; +}(); + +final _keyByChar = () { + final map = {}; + for (final entry in _keyToTerminalKey.entries) { + final label = entry.key.keyLabel; + + if (label.isEmpty || label.length > 1) { + continue; + } + + map[label] = entry.value; + map[label.toUpperCase()] = entry.value; + map[label.toLowerCase()] = entry.value; + } + return map; +}(); + +/// Converts a [LogicalKeyboardKey] to a [TerminalKey]. Returns `null` if the +/// key does not have a corresponding [TerminalKey]. +/// +/// For example, `LogicalKeyboardKey.keyA` will be converted to +/// `TerminalKey.keyA`. +TerminalKey? keyToTerminalKey(LogicalKeyboardKey key) { + return _keyById[key.keyId]; +} + +/// Converts a character to a [TerminalKey]. Returns `null` if the character +/// does not have a corresponding [TerminalKey]. +/// +/// For example, `charToTerminalKey('a')` or `charToTerminalKey('A')` will both +/// return [TerminalKey.a]. +TerminalKey? charToTerminalKey(String char) { + if (char.length != 1) { + return null; + } + + return _keyByChar[char]; +} diff --git a/app/third_party/xterm/lib/src/ui/keyboard_listener.dart b/app/third_party/xterm/lib/src/ui/keyboard_listener.dart new file mode 100644 index 00000000..bb2f9920 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/keyboard_listener.dart @@ -0,0 +1,49 @@ +import 'package:flutter/widgets.dart'; + +class CustomKeyboardListener extends StatelessWidget { + final Widget child; + + final FocusNode focusNode; + + final bool autofocus; + + final void Function(String) onInsert; + + final void Function(String?) onComposing; + + final KeyEventResult Function(FocusNode, KeyEvent) onKeyEvent; + + const CustomKeyboardListener({ + super.key, + required this.child, + required this.focusNode, + this.autofocus = false, + required this.onInsert, + required this.onComposing, + required this.onKeyEvent, + }); + + KeyEventResult _onKeyEvent(FocusNode focusNode, KeyEvent keyEvent) { + // First try to handle the key event directly. + final handled = onKeyEvent(focusNode, keyEvent); + if (handled == KeyEventResult.ignored) { + // If it was not handled, but the key corresponds to a character, + // insert the character. + if (keyEvent.character != null && keyEvent.character != "") { + onInsert(keyEvent.character!); + return KeyEventResult.handled; + } + } + return handled; + } + + @override + Widget build(BuildContext context) { + return Focus( + focusNode: focusNode, + autofocus: autofocus, + onKeyEvent: _onKeyEvent, + child: child, + ); + } +} diff --git a/app/third_party/xterm/lib/src/ui/keyboard_visibility.dart b/app/third_party/xterm/lib/src/ui/keyboard_visibility.dart new file mode 100644 index 00000000..158c5d11 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/keyboard_visibility.dart @@ -0,0 +1,58 @@ +import 'package:flutter/widgets.dart'; + +class KeyboardVisibilty extends StatefulWidget { + const KeyboardVisibilty({ + super.key, + required this.child, + this.onKeyboardShow, + this.onKeyboardHide, + }); + + final Widget child; + + final VoidCallback? onKeyboardShow; + + final VoidCallback? onKeyboardHide; + + @override + KeyboardVisibiltyState createState() => KeyboardVisibiltyState(); +} + +class KeyboardVisibiltyState extends State + with WidgetsBindingObserver { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + void didChangeMetrics() { + final bottomInset = View.of(context).viewInsets.bottom; + + if (bottomInset != _lastBottomInset) { + if (bottomInset > 0) { + widget.onKeyboardShow?.call(); + } else { + widget.onKeyboardHide?.call(); + } + } + + _lastBottomInset = bottomInset; + + super.didChangeMetrics(); + } + + var _lastBottomInset = 0.0; + + @override + Widget build(BuildContext context) { + return widget.child; + } +} diff --git a/app/third_party/xterm/lib/src/ui/painter.dart b/app/third_party/xterm/lib/src/ui/painter.dart new file mode 100644 index 00000000..64a78e08 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/painter.dart @@ -0,0 +1,279 @@ +import 'dart:ui'; +import 'package:flutter/painting.dart'; + +import 'package:xterm/src/ui/palette_builder.dart'; +import 'package:xterm/src/ui/paragraph_cache.dart'; +import 'package:xterm/xterm.dart'; + +/// Encapsulates the logic for painting various terminal elements. +class TerminalPainter { + TerminalPainter({ + required TerminalTheme theme, + required TerminalStyle textStyle, + required TextScaler textScaler, + }) : _textStyle = textStyle, + _theme = theme, + _textScaler = textScaler; + + /// A lookup table from terminal colors to Flutter colors. + late var _colorPalette = PaletteBuilder(_theme).build(); + + /// Size of each character in the terminal. + late var _cellSize = _measureCharSize(); + + /// The cached for cells in the terminal. Should be cleared when the same + /// cell no longer produces the same visual output. For example, when + /// [_textStyle] is changed, or when the system font changes. + final _paragraphCache = ParagraphCache(10240); + + TerminalStyle get textStyle => _textStyle; + TerminalStyle _textStyle; + set textStyle(TerminalStyle value) { + if (value == _textStyle) return; + _textStyle = value; + _cellSize = _measureCharSize(); + _paragraphCache.clear(); + } + + TextScaler get textScaler => _textScaler; + TextScaler _textScaler = TextScaler.linear(1.0); + set textScaler(TextScaler value) { + if (value == _textScaler) return; + _textScaler = value; + _cellSize = _measureCharSize(); + _paragraphCache.clear(); + } + + TerminalTheme get theme => _theme; + TerminalTheme _theme; + set theme(TerminalTheme value) { + if (value == _theme) return; + _theme = value; + _colorPalette = PaletteBuilder(value).build(); + _paragraphCache.clear(); + } + + Size _measureCharSize() { + const test = 'mmmmmmmmmm'; + + final textStyle = _textStyle.toTextStyle(); + final builder = ParagraphBuilder(textStyle.getParagraphStyle()); + builder.pushStyle( + textStyle.getTextStyle(textScaler: _textScaler), + ); + builder.addText(test); + + final paragraph = builder.build(); + paragraph.layout(ParagraphConstraints(width: double.infinity)); + + final result = Size( + paragraph.maxIntrinsicWidth / test.length, + paragraph.height, + ); + + paragraph.dispose(); + return result; + } + + /// The size of each character in the terminal. + Size get cellSize => _cellSize; + + /// When the set of font available to the system changes, call this method to + /// clear cached state related to font rendering. + void clearFontCache() { + _cellSize = _measureCharSize(); + _paragraphCache.clear(); + } + + /// Paints the cursor based on the current cursor type. + void paintCursor( + Canvas canvas, + Offset offset, { + required TerminalCursorType cursorType, + bool hasFocus = true, + }) { + final paint = Paint() + ..color = _theme.cursor + ..strokeWidth = 1; + + if (!hasFocus) { + paint.style = PaintingStyle.stroke; + canvas.drawRect(offset & _cellSize, paint); + return; + } + + switch (cursorType) { + case TerminalCursorType.block: + paint.style = PaintingStyle.fill; + canvas.drawRect(offset & _cellSize, paint); + return; + case TerminalCursorType.underline: + return canvas.drawLine( + Offset(offset.dx, _cellSize.height - 1), + Offset(offset.dx + _cellSize.width, _cellSize.height - 1), + paint, + ); + case TerminalCursorType.verticalBar: + return canvas.drawLine( + Offset(offset.dx, 0), + Offset(offset.dx, _cellSize.height), + paint, + ); + } + } + + @pragma('vm:prefer-inline') + void paintHighlight(Canvas canvas, Offset offset, int length, Color color) { + final endOffset = + offset.translate(length * _cellSize.width, _cellSize.height); + + final paint = Paint() + ..color = color + ..strokeWidth = 1; + + canvas.drawRect( + Rect.fromPoints(offset, endOffset), + paint, + ); + } + + /// Paints [line] to [canvas] at [offset]. The x offset of [offset] is usually + /// 0, and the y offset is the top of the line. + void paintLine( + Canvas canvas, + Offset offset, + BufferLine line, + ) { + final cellData = CellData.empty(); + final cellWidth = _cellSize.width; + + for (var i = 0; i < line.length; i++) { + line.getCellData(i, cellData); + + final charWidth = cellData.content >> CellContent.widthShift; + final cellOffset = offset.translate(i * cellWidth, 0); + + paintCell(canvas, cellOffset, cellData); + + if (charWidth == 2) { + i++; + } + } + } + + @pragma('vm:prefer-inline') + void paintCell(Canvas canvas, Offset offset, CellData cellData) { + paintCellBackground(canvas, offset, cellData); + paintCellForeground(canvas, offset, cellData); + } + + /// Paints the character in the cell represented by [cellData] to [canvas] at + /// [offset]. + @pragma('vm:prefer-inline') + void paintCellForeground(Canvas canvas, Offset offset, CellData cellData) { + final charCode = cellData.content & CellContent.codepointMask; + if (charCode == 0) return; + + final cacheKey = cellData.getHash() ^ _textScaler.hashCode; + var paragraph = _paragraphCache.getLayoutFromCache(cacheKey); + + if (paragraph == null) { + final cellFlags = cellData.flags; + + var color = cellFlags & CellFlags.inverse == 0 + ? resolveForegroundColor(cellData.foreground) + : resolveBackgroundColor(cellData.background); + + if (cellData.flags & CellFlags.faint != 0) { + color = color.withOpacity(0.5); + } + + final style = _textStyle.toTextStyle( + color: color, + bold: cellFlags & CellFlags.bold != 0, + italic: cellFlags & CellFlags.italic != 0, + underline: cellFlags & CellFlags.underline != 0, + ); + + // Flutter does not draw an underline below a space which is not between + // other regular characters. As only single characters are drawn, this + // will never produce an underline below a space in the terminal. As a + // workaround the regular space CodePoint 0x20 is replaced with + // the CodePoint 0xA0. This is a non breaking space and a underline can be + // drawn below it. + var char = String.fromCharCode(charCode); + if (cellFlags & CellFlags.underline != 0 && charCode == 0x20) { + char = String.fromCharCode(0xA0); + } + + paragraph = _paragraphCache.performAndCacheLayout( + char, + style, + _textScaler, + cacheKey, + ); + } + + canvas.drawParagraph(paragraph, offset); + } + + /// Paints the background of a cell represented by [cellData] to [canvas] at + /// [offset]. + @pragma('vm:prefer-inline') + void paintCellBackground(Canvas canvas, Offset offset, CellData cellData) { + late Color color; + final colorType = cellData.background & CellColor.typeMask; + + if (cellData.flags & CellFlags.inverse != 0) { + color = resolveForegroundColor(cellData.foreground); + } else if (colorType == CellColor.normal) { + return; + } else { + color = resolveBackgroundColor(cellData.background); + } + + final paint = Paint()..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); + } + + /// Get the effective foreground color for a cell from information encoded in + /// [cellColor]. + @pragma('vm:prefer-inline') + Color resolveForegroundColor(int cellColor) { + final colorType = cellColor & CellColor.typeMask; + final colorValue = cellColor & CellColor.valueMask; + + switch (colorType) { + case CellColor.normal: + return _theme.foreground; + case CellColor.named: + case CellColor.palette: + return _colorPalette[colorValue]; + case CellColor.rgb: + default: + return Color(colorValue | 0xFF000000); + } + } + + /// Get the effective background color for a cell from information encoded in + /// [cellColor]. + @pragma('vm:prefer-inline') + Color resolveBackgroundColor(int cellColor) { + final colorType = cellColor & CellColor.typeMask; + final colorValue = cellColor & CellColor.valueMask; + + switch (colorType) { + case CellColor.normal: + return _theme.background; + case CellColor.named: + case CellColor.palette: + return _colorPalette[colorValue]; + case CellColor.rgb: + default: + return Color(colorValue | 0xFF000000); + } + } +} diff --git a/app/third_party/xterm/lib/src/ui/palette_builder.dart b/app/third_party/xterm/lib/src/ui/palette_builder.dart new file mode 100644 index 00000000..0dedff03 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/palette_builder.dart @@ -0,0 +1,118 @@ +import 'package:flutter/widgets.dart'; +import 'package:xterm/src/ui/terminal_theme.dart'; +import 'package:xterm/src/utils/lookup_table.dart'; + +class PaletteBuilder { + final TerminalTheme theme; + + PaletteBuilder(this.theme); + + List build() { + return List.generate( + 256, + paletteColor, + growable: false, + ); + } + + /// https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit + Color paletteColor(int colNum) { + switch (colNum) { + case 0: + return theme.black; + case 1: + return theme.red; + case 2: + return theme.green; + case 3: + return theme.yellow; + case 4: + return theme.blue; + case 5: + return theme.magenta; + case 6: + return theme.cyan; + case 7: + return theme.white; + case 8: + return theme.brightBlack; + case 9: + return theme.brightRed; + case 10: + return theme.brightGreen; + case 11: + return theme.brightYellow; + case 12: + return theme.brightBlue; + case 13: + return theme.brightMagenta; + case 14: + return theme.brightCyan; + case 15: + return theme.white; + } + + if (colNum < 232) { + var r = 0; + var g = 0; + var b = 0; + + final index = colNum - 16; + + for (var i = 0; i < index; i++) { + if (b == 0) { + b = 95; + } else if (b < 255) { + b += 40; + } else { + b = 0; + if (g == 0) { + g = 95; + } else if (g < 255) { + g += 40; + } else { + g = 0; + if (r == 0) { + r = 95; + } else if (r < 255) { + r += 40; + } else { + break; + } + } + } + } + + return Color.fromARGB(0xFF, r, g, b); + } + + return Color(_grayscaleColors[colNum.clamp(232, 255)]!); + } +} + +final _grayscaleColors = FastLookupTable({ + 232: 0xff080808, + 233: 0xff121212, + 234: 0xff1c1c1c, + 235: 0xff262626, + 236: 0xff303030, + 237: 0xff3a3a3a, + 238: 0xff444444, + 239: 0xff4e4e4e, + 240: 0xff585858, + 241: 0xff626262, + 242: 0xff6c6c6c, + 243: 0xff767676, + 244: 0xff808080, + 245: 0xff8a8a8a, + 246: 0xff949494, + 247: 0xff9e9e9e, + 248: 0xffa8a8a8, + 249: 0xffb2b2b2, + 250: 0xffbcbcbc, + 251: 0xffc6c6c6, + 252: 0xffd0d0d0, + 253: 0xffdadada, + 254: 0xffe4e4e4, + 255: 0xffeeeeee, +}); diff --git a/app/third_party/xterm/lib/src/ui/paragraph_cache.dart b/app/third_party/xterm/lib/src/ui/paragraph_cache.dart new file mode 100644 index 00000000..80896a04 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/paragraph_cache.dart @@ -0,0 +1,51 @@ +import 'dart:ui'; + +import 'package:flutter/widgets.dart'; +import 'package:quiver/collection.dart'; + +/// A cache of laid out [Paragraph]s. This is used to avoid laying out the same +/// text multiple times, which is expensive. +class ParagraphCache { + ParagraphCache(int maximumSize) + : _cache = LruMap(maximumSize: maximumSize); + + final LruMap _cache; + + /// Returns a [Paragraph] for the given [key]. [key] is the same as the + /// key argument to [performAndCacheLayout]. + Paragraph? getLayoutFromCache(int key) { + return _cache[key]; + } + + /// Applies [style] and [textScaler] to [text] and lays it out to create + /// a [Paragraph]. The [Paragraph] is cached and can be retrieved with the + /// same [key] by calling [getLayoutFromCache]. + Paragraph performAndCacheLayout( + String text, + TextStyle style, + TextScaler textScaler, + int key, + ) { + final builder = ParagraphBuilder(style.getParagraphStyle()); + builder.pushStyle(style.getTextStyle(textScaler: textScaler)); + builder.addText(text); + + final paragraph = builder.build(); + paragraph.layout(ParagraphConstraints(width: double.infinity)); + + _cache[key] = paragraph; + return paragraph; + } + + /// Clears the cache. This should be called when the same text and style + /// pair no longer produces the same layout. For example, when a font is + /// loaded. + void clear() { + _cache.clear(); + } + + /// Returns the number of [Paragraph]s in the cache. + int get length { + return _cache.length; + } +} diff --git a/app/third_party/xterm/lib/src/ui/pointer_input.dart b/app/third_party/xterm/lib/src/ui/pointer_input.dart new file mode 100644 index 00000000..1f2bd537 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/pointer_input.dart @@ -0,0 +1,29 @@ +enum PointerInput { + /// Taps / buttons presses & releases. + tap, + + /// Scroll / mouse wheels events. + scroll, + + /// Drag events, a pointer is in a down state and dragged across the terminal. + drag, + + /// Move events, a pointer is in an up state and moved across the terminal. + move, +} + +class PointerInputs { + final Set inputs; + + const PointerInputs(this.inputs); + + const PointerInputs.none() : inputs = const {}; + + const PointerInputs.all() + : inputs = const { + PointerInput.tap, + PointerInput.scroll, + PointerInput.drag, + PointerInput.move, + }; +} diff --git a/app/third_party/xterm/lib/src/ui/render.dart b/app/third_party/xterm/lib/src/ui/render.dart new file mode 100644 index 00000000..de2a2f7f --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/render.dart @@ -0,0 +1,552 @@ +import 'dart:math' show max; +import 'dart:ui'; + +import 'package:flutter/rendering.dart'; +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/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/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'; + +typedef EditableRectCallback = void Function(Rect rect, Rect caretRect); + +class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { + RenderTerminal({ + required Terminal terminal, + required TerminalController controller, + required ViewportOffset offset, + required EdgeInsets padding, + required bool autoResize, + required TerminalStyle textStyle, + required TextScaler textScaler, + required TerminalTheme theme, + required FocusNode focusNode, + required TerminalCursorType cursorType, + required bool alwaysShowCursor, + EditableRectCallback? onEditableRect, + String? composingText, + }) : _terminal = terminal, + _controller = controller, + _offset = offset, + _padding = padding, + _autoResize = autoResize, + _focusNode = focusNode, + _cursorType = cursorType, + _alwaysShowCursor = alwaysShowCursor, + _onEditableRect = onEditableRect, + _composingText = composingText, + _painter = TerminalPainter( + theme: theme, + textStyle: textStyle, + textScaler: textScaler, + ); + + Terminal _terminal; + set terminal(Terminal terminal) { + if (_terminal == terminal) return; + if (attached) _terminal.removeListener(_onTerminalChange); + _terminal = terminal; + if (attached) _terminal.addListener(_onTerminalChange); + _resizeTerminalIfNeeded(); + markNeedsLayout(); + } + + TerminalController _controller; + set controller(TerminalController controller) { + if (_controller == controller) return; + if (attached) _controller.removeListener(_onControllerUpdate); + _controller = controller; + if (attached) _controller.addListener(_onControllerUpdate); + markNeedsLayout(); + } + + ViewportOffset _offset; + set offset(ViewportOffset value) { + if (value == _offset) return; + if (attached) _offset.removeListener(_onScroll); + _offset = value; + if (attached) _offset.addListener(_onScroll); + markNeedsLayout(); + } + + EdgeInsets _padding; + set padding(EdgeInsets value) { + if (value == _padding) return; + _padding = value; + markNeedsLayout(); + } + + bool _autoResize; + set autoResize(bool value) { + if (value == _autoResize) return; + _autoResize = value; + markNeedsLayout(); + } + + set textStyle(TerminalStyle value) { + if (value == _painter.textStyle) return; + _painter.textStyle = value; + markNeedsLayout(); + } + + set textScaler(TextScaler value) { + if (value == _painter.textScaler) return; + _painter.textScaler = value; + markNeedsLayout(); + } + + set theme(TerminalTheme value) { + if (value == _painter.theme) return; + _painter.theme = value; + markNeedsPaint(); + } + + FocusNode _focusNode; + set focusNode(FocusNode value) { + if (value == _focusNode) return; + if (attached) _focusNode.removeListener(_onFocusChange); + _focusNode = value; + if (attached) _focusNode.addListener(_onFocusChange); + markNeedsPaint(); + } + + TerminalCursorType _cursorType; + set cursorType(TerminalCursorType value) { + if (value == _cursorType) return; + _cursorType = value; + markNeedsPaint(); + } + + bool _alwaysShowCursor; + set alwaysShowCursor(bool value) { + if (value == _alwaysShowCursor) return; + _alwaysShowCursor = value; + markNeedsPaint(); + } + + EditableRectCallback? _onEditableRect; + set onEditableRect(EditableRectCallback? value) { + if (value == _onEditableRect) return; + _onEditableRect = value; + markNeedsLayout(); + } + + String? _composingText; + set composingText(String? value) { + if (value == _composingText) return; + _composingText = value; + markNeedsPaint(); + } + + TerminalSize? _viewportSize; + + final TerminalPainter _painter; + + var _stickToBottom = true; + + void _onScroll() { + _stickToBottom = _scrollOffset >= _maxScrollExtent; + markNeedsLayout(); + _notifyEditableRect(); + } + + void _onFocusChange() { + markNeedsPaint(); + } + + void _onTerminalChange() { + markNeedsLayout(); + _notifyEditableRect(); + } + + void _onControllerUpdate() { + markNeedsLayout(); + } + + @override + final isRepaintBoundary = true; + + @override + void attach(PipelineOwner owner) { + super.attach(owner); + _offset.addListener(_onScroll); + _terminal.addListener(_onTerminalChange); + _controller.addListener(_onControllerUpdate); + _focusNode.addListener(_onFocusChange); + } + + @override + void detach() { + super.detach(); + _offset.removeListener(_onScroll); + _terminal.removeListener(_onTerminalChange); + _controller.removeListener(_onControllerUpdate); + _focusNode.removeListener(_onFocusChange); + } + + @override + bool hitTestSelf(Offset position) { + return true; + } + + @override + void systemFontsDidChange() { + _painter.clearFontCache(); + super.systemFontsDidChange(); + } + + @override + void performLayout() { + size = constraints.biggest; + + _updateViewportSize(); + + _updateScrollOffset(); + + if (_stickToBottom) { + _offset.correctBy(_maxScrollExtent - _scrollOffset); + } + } + + /// Total height of the terminal in pixels. Includes scrollback buffer. + double get _terminalHeight => + _terminal.buffer.lines.length * _painter.cellSize.height; + + /// The distance from the top of the terminal to the top of the viewport. + // double get _scrollOffset => _offset.pixels; + double get _scrollOffset { + // return _offset.pixels ~/ _painter.cellSize.height * _painter.cellSize.height; + return _offset.pixels; + } + + /// The height of a terminal line in pixels. This includes the line spacing. + /// Height of the entire terminal is expected to be a multiple of this value. + double get lineHeight => _painter.cellSize.height; + + /// Get the top-left corner of the cell at [cellOffset] in pixels. + Offset getOffset(CellOffset cellOffset) { + final row = cellOffset.y; + final col = cellOffset.x; + final x = col * _painter.cellSize.width; + final y = row * _painter.cellSize.height; + return Offset(x + _padding.left, y + _padding.top - _scrollOffset); + } + + /// Get the [CellOffset] of the cell that [offset] is in. + CellOffset getCellOffset(Offset offset) { + final x = offset.dx - _padding.left; + final y = offset.dy - _padding.top + _scrollOffset; + final row = y ~/ _painter.cellSize.height; + final col = x ~/ _painter.cellSize.width; + return CellOffset( + col.clamp(0, _terminal.viewWidth - 1), + row.clamp(0, _terminal.buffer.lines.length - 1), + ); + } + + /// Selects entire words in the terminal that contains [from] and [to]. + void selectWord(Offset from, [Offset? to]) { + final fromOffset = getCellOffset(from); + final fromBoundary = _terminal.buffer.getWordBoundary(fromOffset); + if (fromBoundary == null) return; + if (to == null) { + _controller.setSelection( + _terminal.buffer.createAnchorFromOffset(fromBoundary.begin), + _terminal.buffer.createAnchorFromOffset(fromBoundary.end), + mode: SelectionMode.line, + ); + } else { + final toOffset = getCellOffset(to); + final toBoundary = _terminal.buffer.getWordBoundary(toOffset); + if (toBoundary == null) return; + final range = fromBoundary.merge(toBoundary); + _controller.setSelection( + _terminal.buffer.createAnchorFromOffset(range.begin), + _terminal.buffer.createAnchorFromOffset(range.end), + mode: SelectionMode.line, + ); + } + } + + /// Selects characters in the terminal that starts from [from] to [to]. At + /// least one cell is selected even if [from] and [to] are same. + void selectCharacters(Offset from, [Offset? to]) { + final fromPosition = getCellOffset(from); + if (to == null) { + _controller.setSelection( + _terminal.buffer.createAnchorFromOffset(fromPosition), + _terminal.buffer.createAnchorFromOffset(fromPosition), + ); + } else { + var toPosition = getCellOffset(to); + if (toPosition.x >= fromPosition.x) { + toPosition = CellOffset(toPosition.x + 1, toPosition.y); + } + _controller.setSelection( + _terminal.buffer.createAnchorFromOffset(fromPosition), + _terminal.buffer.createAnchorFromOffset(toPosition), + ); + } + } + + /// Send a mouse event at [offset] with [button] being currently in [buttonState]. + bool mouseEvent( + TerminalMouseButton button, + TerminalMouseButtonState buttonState, + Offset offset, + ) { + final position = getCellOffset(offset); + return _terminal.mouseInput(button, buttonState, position); + } + + void _notifyEditableRect() { + final cursor = localToGlobal(cursorOffset); + + final rect = Rect.fromLTRB( + cursor.dx, + cursor.dy, + size.width, + cursor.dy + _painter.cellSize.height, + ); + + final caretRect = cursor & _painter.cellSize; + + _onEditableRect?.call(rect, caretRect); + } + + /// Update the viewport size in cells based on the current widget size in + /// pixels. + void _updateViewportSize() { + if (size <= _painter.cellSize) { + return; + } + + final viewportSize = TerminalSize( + size.width ~/ _painter.cellSize.width, + _viewportHeight ~/ _painter.cellSize.height, + ); + + if (_viewportSize != viewportSize) { + _viewportSize = viewportSize; + _resizeTerminalIfNeeded(); + } + } + + /// Notify the underlying terminal that the viewport size has changed. + void _resizeTerminalIfNeeded() { + if (_autoResize && _viewportSize != null) { + _terminal.resize( + _viewportSize!.width, + _viewportSize!.height, + _painter.cellSize.width.round(), + _painter.cellSize.height.round(), + ); + } + } + + /// Update the scroll offset based on the current terminal state. This should + /// be called in [performLayout] after the viewport size has been updated. + void _updateScrollOffset() { + _offset.applyViewportDimension(_viewportHeight); + _offset.applyContentDimensions(0, _maxScrollExtent); + } + + bool get _isComposingText { + return _composingText != null && _composingText!.isNotEmpty; + } + + bool get _shouldShowCursor { + return _terminal.cursorVisibleMode || _alwaysShowCursor || _isComposingText; + } + + double get _viewportHeight { + return size.height - _padding.vertical; + } + + double get _maxScrollExtent { + return max(_terminalHeight - _viewportHeight, 0.0); + } + + double get _lineOffset { + return -_scrollOffset + _padding.top; + } + + /// The offset of the cursor from the top left corner of this render object. + Offset get cursorOffset { + return Offset( + _terminal.buffer.cursorX * _painter.cellSize.width, + _terminal.buffer.absoluteCursorY * _painter.cellSize.height + _lineOffset, + ); + } + + Size get cellSize { + return _painter.cellSize; + } + + @override + void paint(PaintingContext context, Offset offset) { + _paint(context, offset); + context.setWillChangeHint(); + } + + void _paint(PaintingContext context, Offset offset) { + final canvas = context.canvas; + + final lines = _terminal.buffer.lines; + final charHeight = _painter.cellSize.height; + + final firstLineOffset = _scrollOffset - _padding.top; + final lastLineOffset = _scrollOffset + size.height + _padding.bottom; + + final firstLine = firstLineOffset ~/ charHeight; + final lastLine = lastLineOffset ~/ charHeight; + + final effectFirstLine = firstLine.clamp(0, lines.length - 1); + final effectLastLine = lastLine.clamp(0, lines.length - 1); + + for (var i = effectFirstLine; i <= effectLastLine; i++) { + _painter.paintLine( + canvas, + offset.translate(0, (i * charHeight + _lineOffset).truncateToDouble()), + lines[i], + ); + } + + if (_terminal.buffer.absoluteCursorY >= effectFirstLine && + _terminal.buffer.absoluteCursorY <= effectLastLine) { + if (_isComposingText) { + _paintComposingText(canvas, offset + cursorOffset); + } + + if (_shouldShowCursor) { + _painter.paintCursor( + canvas, + offset + cursorOffset, + cursorType: _cursorType, + hasFocus: _focusNode.hasFocus, + ); + } + } + + _paintHighlights( + canvas, + _controller.highlights, + effectFirstLine, + effectLastLine, + ); + + if (_controller.selection != null) { + _paintSelection( + canvas, + _controller.selection!, + effectFirstLine, + effectLastLine, + ); + } + } + + /// 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) { + final composingText = _composingText; + if (composingText == null) { + return; + } + + final style = _painter.textStyle.toTextStyle( + color: _painter.resolveForegroundColor(_terminal.cursor.foreground), + backgroundColor: _painter.theme.background, + underline: true, + ); + + final builder = ParagraphBuilder(style.getParagraphStyle()); + builder.addPlaceholder( + offset.dx, + _painter.cellSize.height, + PlaceholderAlignment.middle, + ); + builder.pushStyle( + style.getTextStyle(textScaler: _painter.textScaler), + ); + builder.addText(composingText); + + final paragraph = builder.build(); + paragraph.layout(ParagraphConstraints(width: size.width)); + + canvas.drawParagraph(paragraph, Offset(0, offset.dy)); + } + + void _paintSelection( + Canvas canvas, + BufferRange selection, + int firstLine, + int lastLine, + ) { + for (final segment in selection.toSegments()) { + if (segment.line >= _terminal.buffer.lines.length) { + break; + } + + if (segment.line < firstLine) { + continue; + } + + if (segment.line > lastLine) { + break; + } + + _paintSegment(canvas, segment, _painter.theme.selection); + } + } + + void _paintHighlights( + Canvas canvas, + List highlights, + int firstLine, + int lastLine, + ) { + for (var highlight in _controller.highlights) { + final range = highlight.range?.normalized; + + if (range == null || + range.begin.y > lastLine || + range.end.y < firstLine) { + continue; + } + + for (var segment in range.toSegments()) { + if (segment.line < firstLine) { + continue; + } + + if (segment.line > lastLine) { + break; + } + + _paintSegment(canvas, segment, highlight.color); + } + } + } + + @pragma('vm:prefer-inline') + void _paintSegment(Canvas canvas, BufferSegment segment, Color color) { + final start = segment.start ?? 0; + final end = segment.end ?? _terminal.viewWidth; + + final startOffset = Offset( + start * _painter.cellSize.width, + segment.line * _painter.cellSize.height + _lineOffset, + ); + + _painter.paintHighlight(canvas, startOffset, end - start, color); + } +} diff --git a/app/third_party/xterm/lib/src/ui/scroll_handler.dart b/app/third_party/xterm/lib/src/ui/scroll_handler.dart new file mode 100644 index 00000000..d0ad9a8d --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/scroll_handler.dart @@ -0,0 +1,133 @@ +import 'package:flutter/widgets.dart'; +import 'package:xterm/core.dart'; +import 'package:xterm/src/ui/infinite_scroll_view.dart'; + +/// Handles scrolling gestures in the alternate screen buffer. In alternate +/// screen buffer, the terminal don't have a scrollback buffer, instead, the +/// scroll gestures are converted to escape sequences based on the current +/// report mode declared by the application. +class TerminalScrollGestureHandler extends StatefulWidget { + const TerminalScrollGestureHandler({ + super.key, + required this.terminal, + required this.getCellOffset, + required this.getLineHeight, + this.simulateScroll = true, + required this.child, + }); + + final Terminal terminal; + + /// Returns the cell offset for the pixel offset. + final CellOffset Function(Offset) getCellOffset; + + /// Returns the pixel height of lines in the terminal. + final double Function() getLineHeight; + + /// Whether to simulate scroll events in the terminal when the application + /// doesn't declare it supports mouse wheel events. true by default as it + /// is the default behavior of most terminals. + final bool simulateScroll; + + final Widget child; + + @override + State createState() => + _TerminalScrollGestureHandlerState(); +} + +class _TerminalScrollGestureHandlerState + extends State { + /// Whether the application is in alternate screen buffer. If false, then this + /// widget does nothing. + var isAltBuffer = false; + + /// The variable that tracks the line offset in last scroll event. Used to + /// determine how many the scroll events should be sent to the terminal. + var lastLineOffset = 0; + + /// This variable tracks the last offset where the scroll gesture started. + /// Used to calculate the cell offset of the terminal mouse event. + var lastPointerPosition = Offset.zero; + + @override + void initState() { + widget.terminal.addListener(_onTerminalUpdated); + isAltBuffer = widget.terminal.isUsingAltBuffer; + super.initState(); + } + + @override + void dispose() { + widget.terminal.removeListener(_onTerminalUpdated); + super.dispose(); + } + + @override + void didUpdateWidget(covariant TerminalScrollGestureHandler oldWidget) { + if (oldWidget.terminal != widget.terminal) { + oldWidget.terminal.removeListener(_onTerminalUpdated); + widget.terminal.addListener(_onTerminalUpdated); + isAltBuffer = widget.terminal.isUsingAltBuffer; + } + super.didUpdateWidget(oldWidget); + } + + void _onTerminalUpdated() { + if (isAltBuffer != widget.terminal.isUsingAltBuffer) { + isAltBuffer = widget.terminal.isUsingAltBuffer; + setState(() {}); + } + } + + /// Send a single scroll event to the terminal. If [simulateScroll] is true, + /// then if the application doesn't recognize mouse wheel events, this method + /// will simulate scroll events by sending up/down arrow keys. + void _sendScrollEvent(bool up) { + final position = widget.getCellOffset(lastPointerPosition); + + final handled = widget.terminal.mouseInput( + up ? TerminalMouseButton.wheelUp : TerminalMouseButton.wheelDown, + TerminalMouseButtonState.down, + position, + ); + + if (!handled && widget.simulateScroll) { + widget.terminal.keyInput( + up ? TerminalKey.arrowUp : TerminalKey.arrowDown, + ); + } + } + + void _onScroll(double offset) { + final currentLineOffset = offset ~/ widget.getLineHeight(); + + final delta = currentLineOffset - lastLineOffset; + + for (var i = 0; i < delta.abs(); i++) { + _sendScrollEvent(delta < 0); + } + + lastLineOffset = currentLineOffset; + } + + @override + Widget build(BuildContext context) { + if (!isAltBuffer) { + return widget.child; + } + + return Listener( + onPointerSignal: (event) { + lastPointerPosition = event.position; + }, + onPointerDown: (event) { + lastPointerPosition = event.position; + }, + child: InfiniteScrollView( + onScroll: _onScroll, + child: widget.child, + ), + ); + } +} diff --git a/app/third_party/xterm/lib/src/ui/selection_mode.dart b/app/third_party/xterm/lib/src/ui/selection_mode.dart new file mode 100644 index 00000000..aa3a5044 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/selection_mode.dart @@ -0,0 +1,5 @@ +enum SelectionMode { + line, + + block, +} diff --git a/app/third_party/xterm/lib/src/ui/shortcut/actions.dart b/app/third_party/xterm/lib/src/ui/shortcut/actions.dart new file mode 100644 index 00000000..a06670b7 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/shortcut/actions.dart @@ -0,0 +1,71 @@ +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:xterm/src/terminal.dart'; +import 'package:xterm/src/ui/controller.dart'; +import 'package:xterm/src/ui/selection_mode.dart'; + +class TerminalActions extends StatelessWidget { + const TerminalActions({ + super.key, + required this.terminal, + required this.controller, + required this.child, + }); + + final Terminal terminal; + + final TerminalController controller; + + final Widget child; + + @override + Widget build(BuildContext context) { + return Actions( + actions: { + PasteTextIntent: CallbackAction( + onInvoke: (intent) async { + final data = await Clipboard.getData(Clipboard.kTextPlain); + final text = data?.text; + if (text != null) { + terminal.paste(text); + controller.clearSelection(); + } + return null; + }, + ), + CopySelectionTextIntent: CallbackAction( + onInvoke: (intent) async { + final selection = controller.selection; + + if (selection == null) { + return; + } + + final text = terminal.buffer.getText(selection); + + await Clipboard.setData(ClipboardData(text: text)); + + return null; + }, + ), + SelectAllTextIntent: CallbackAction( + onInvoke: (intent) { + controller.setSelection( + terminal.buffer.createAnchor( + 0, + terminal.buffer.height - terminal.viewHeight, + ), + terminal.buffer.createAnchor( + terminal.viewWidth, + terminal.buffer.height - 1, + ), + mode: SelectionMode.line, + ); + return null; + }, + ), + }, + child: child, + ); + } +} diff --git a/app/third_party/xterm/lib/src/ui/shortcut/shortcuts.dart b/app/third_party/xterm/lib/src/ui/shortcut/shortcuts.dart new file mode 100644 index 00000000..042ee156 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/shortcut/shortcuts.dart @@ -0,0 +1,34 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +Map get defaultTerminalShortcuts { + switch (defaultTargetPlatform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.windows: + return _defaultShortcuts; + case TargetPlatform.iOS: + case TargetPlatform.macOS: + return _defaultAppleShortcuts; + } +} + +final _defaultShortcuts = { + SingleActivator(LogicalKeyboardKey.keyC, control: true, shift: true): + CopySelectionTextIntent.copy, + SingleActivator(LogicalKeyboardKey.keyV, control: true): + const PasteTextIntent(SelectionChangedCause.keyboard), + SingleActivator(LogicalKeyboardKey.keyA, control: true): + const SelectAllTextIntent(SelectionChangedCause.keyboard), +}; + +final _defaultAppleShortcuts = { + SingleActivator(LogicalKeyboardKey.keyC, meta: true): + CopySelectionTextIntent.copy, + SingleActivator(LogicalKeyboardKey.keyV, meta: true): + const PasteTextIntent(SelectionChangedCause.keyboard), + SingleActivator(LogicalKeyboardKey.keyA, meta: true): + const SelectAllTextIntent(SelectionChangedCause.keyboard), +}; diff --git a/app/third_party/xterm/lib/src/ui/terminal_size.dart b/app/third_party/xterm/lib/src/ui/terminal_size.dart new file mode 100644 index 00000000..07258c9a --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/terminal_size.dart @@ -0,0 +1,24 @@ +class TerminalSize { + final int width; + + final int height; + + const TerminalSize(this.width, this.height); + + @override + String toString() => 'TerminalSize($width, $height)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + if (other is! TerminalSize) { + return false; + } + return other.width == width && other.height == height; + } + + @override + int get hashCode => width.hashCode ^ height.hashCode; +} diff --git a/app/third_party/xterm/lib/src/ui/terminal_text_style.dart b/app/third_party/xterm/lib/src/ui/terminal_text_style.dart new file mode 100644 index 00000000..8da3b287 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/terminal_text_style.dart @@ -0,0 +1,87 @@ +import 'package:flutter/widgets.dart'; + +const _kDefaultFontSize = 13.0; + +const _kDefaultHeight = 1.2; + +const _kDefaultFontFamily = 'monospace'; + +const _kDefaultFontFamilyFallback = [ + 'Menlo', + 'Monaco', + 'Consolas', + 'Liberation Mono', + 'Courier New', + 'Noto Sans Mono CJK SC', + 'Noto Sans Mono CJK TC', + 'Noto Sans Mono CJK KR', + 'Noto Sans Mono CJK JP', + 'Noto Sans Mono CJK HK', + 'Noto Color Emoji', + 'Noto Sans Symbols', + 'monospace', + 'sans-serif', +]; + +class TerminalStyle { + const TerminalStyle({ + this.fontSize = _kDefaultFontSize, + this.height = _kDefaultHeight, + this.fontFamily = _kDefaultFontFamily, + this.fontFamilyFallback = _kDefaultFontFamilyFallback, + }); + + factory TerminalStyle.fromTextStyle(TextStyle textStyle) { + return TerminalStyle( + fontSize: textStyle.fontSize ?? _kDefaultFontSize, + height: textStyle.height ?? _kDefaultHeight, + fontFamily: textStyle.fontFamily ?? + textStyle.fontFamilyFallback?.first ?? + _kDefaultFontFamily, + fontFamilyFallback: + textStyle.fontFamilyFallback ?? _kDefaultFontFamilyFallback, + ); + } + + final double fontSize; + + final double height; + + final String fontFamily; + + final List fontFamilyFallback; + + TextStyle toTextStyle({ + Color? color, + Color? backgroundColor, + bool bold = false, + bool italic = false, + bool underline = false, + }) { + return TextStyle( + fontSize: fontSize, + height: height, + fontFamily: fontFamily, + fontFamilyFallback: fontFamilyFallback, + color: color, + backgroundColor: backgroundColor, + fontWeight: bold ? FontWeight.bold : FontWeight.normal, + fontStyle: italic ? FontStyle.italic : FontStyle.normal, + decoration: underline ? TextDecoration.underline : TextDecoration.none, + ); + } + + TerminalStyle copyWith({ + double? fontSize, + double? height, + String? fontFamily, + List? fontFamilyFallback, + }) { + return TerminalStyle( + fontSize: fontSize ?? this.fontSize, + height: height ?? this.height, + fontFamily: fontFamily ?? this.fontFamily, + fontFamilyFallback: fontFamilyFallback ?? this.fontFamilyFallback, + ); + } +} diff --git a/app/third_party/xterm/lib/src/ui/terminal_theme.dart b/app/third_party/xterm/lib/src/ui/terminal_theme.dart new file mode 100644 index 00000000..0b70e422 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/terminal_theme.dart @@ -0,0 +1,57 @@ +import 'package:flutter/widgets.dart'; + +class TerminalTheme { + const TerminalTheme({ + required this.cursor, + required this.selection, + required this.foreground, + required this.background, + required this.black, + required this.white, + required this.red, + required this.green, + required this.yellow, + required this.blue, + required this.magenta, + required this.cyan, + required this.brightBlack, + required this.brightRed, + required this.brightGreen, + required this.brightYellow, + required this.brightBlue, + required this.brightMagenta, + required this.brightCyan, + required this.brightWhite, + required this.searchHitBackground, + required this.searchHitBackgroundCurrent, + required this.searchHitForeground, + }); + + final Color cursor; + final Color selection; + + final Color foreground; + final Color background; + + final Color black; + final Color red; + final Color green; + final Color yellow; + final Color blue; + final Color magenta; + final Color cyan; + final Color white; + + final Color brightBlack; + final Color brightRed; + final Color brightGreen; + final Color brightYellow; + final Color brightBlue; + final Color brightMagenta; + final Color brightCyan; + final Color brightWhite; + + final Color searchHitBackground; + final Color searchHitBackgroundCurrent; + final Color searchHitForeground; +} diff --git a/app/third_party/xterm/lib/src/ui/themes.dart b/app/third_party/xterm/lib/src/ui/themes.dart new file mode 100644 index 00000000..6c5e3e85 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/themes.dart @@ -0,0 +1,56 @@ +import 'package:flutter/widgets.dart'; +import 'package:xterm/src/ui/terminal_theme.dart'; + +class TerminalThemes { + static const defaultTheme = TerminalTheme( + cursor: Color(0XAAAEAFAD), + selection: Color(0XAAAEAFAD), + foreground: Color(0XFFCCCCCC), + background: Color(0XFF1E1E1E), + black: Color(0XFF000000), + red: Color(0XFFCD3131), + green: Color(0XFF0DBC79), + yellow: Color(0XFFE5E510), + blue: Color(0XFF2472C8), + magenta: Color(0XFFBC3FBC), + cyan: Color(0XFF11A8CD), + white: Color(0XFFE5E5E5), + brightBlack: Color(0XFF666666), + brightRed: Color(0XFFF14C4C), + brightGreen: Color(0XFF23D18B), + brightYellow: Color(0XFFF5F543), + brightBlue: Color(0XFF3B8EEA), + brightMagenta: Color(0XFFD670D6), + brightCyan: Color(0XFF29B8DB), + brightWhite: Color(0XFFFFFFFF), + searchHitBackground: Color(0XFFFFFF2B), + searchHitBackgroundCurrent: Color(0XFF31FF26), + searchHitForeground: Color(0XFF000000), + ); + + static const whiteOnBlack = TerminalTheme( + cursor: Color(0XFFAEAFAD), + selection: Color(0XFFAEAFAD), + foreground: Color(0XFFFFFFFF), + background: Color(0XFF000000), + black: Color(0XFF000000), + red: Color(0XFFCD3131), + green: Color(0XFF0DBC79), + yellow: Color(0XFFE5E510), + blue: Color(0XFF2472C8), + magenta: Color(0XFFBC3FBC), + cyan: Color(0XFF11A8CD), + white: Color(0XFFE5E5E5), + brightBlack: Color(0XFF666666), + brightRed: Color(0XFFF14C4C), + brightGreen: Color(0XFF23D18B), + brightYellow: Color(0XFFF5F543), + brightBlue: Color(0XFF3B8EEA), + brightMagenta: Color(0XFFD670D6), + brightCyan: Color(0XFF29B8DB), + brightWhite: Color(0XFFFFFFFF), + searchHitBackground: Color(0XFFFFFF2B), + searchHitBackgroundCurrent: Color(0XFF31FF26), + searchHitForeground: Color(0XFF000000), + ); +} diff --git a/app/third_party/xterm/lib/src/utils/ascii.dart b/app/third_party/xterm/lib/src/utils/ascii.dart new file mode 100644 index 00000000..b5a67ab6 --- /dev/null +++ b/app/third_party/xterm/lib/src/utils/ascii.dart @@ -0,0 +1,403 @@ +// ignore_for_file: constant_identifier_names + +abstract class Ascii { + /* + * Helper functions + */ + + static bool isNonPrintable(int c) { + return c < 32 || c == 127; + } + + /* + * Non-printable ASCII characters + */ + + /// Null character + static const NULL = 00; + + /// Start of Header + static const SOH = 01; + + /// Start of Text + static const STX = 02; + + /// End of Text, hearts card suit + static const ETX = 03; + + /// End of Transmission, diamonds card suit + static const EOT = 04; + + /// Enquiry, clubs card suit + static const ENQ = 05; + + /// Acknowledgement, spade card suit + static const ACK = 06; + + /// Bell + static const BEL = 07; + + /// Backspace + static const BS = 08; + + /// Horizontal Tab + static const HT = 09; + + /// Line feed + static const LF = 10; + + /// Vertical Tab, male symbol, symbol for Mars + static const VT = 11; + + /// Form feed, female symbol, symbol for Venus + static const FF = 12; + + /// Carriage return + static const CR = 13; + + /// Shift Out + static const SO = 14; + + /// Shift In + static const SI = 15; + + /// Data link escape + static const DLE = 16; + + /// Device control 1 + static const DC1 = 17; + + /// Device control 2 + static const DC2 = 18; + + /// Device control 3 + static const DC3 = 19; + + /// Device control 4 + static const DC4 = 20; + + /// NAK Negative-acknowledge + static const NAK = 21; + + /// Synchronous idle + static const SYN = 22; + + /// End of trans. block + static const ETB = 23; + + /// Cancel + static const CAN = 24; + + /// End of medium + static const EM = 25; + + /// Substitute + static const SUB = 26; + + /// Escape + static const ESC = 27; + + /// File separator + static const FS = 28; + + /// Group separator + static const GS = 29; + + /// Record separator + static const RS = 30; + + /// Unit separator + static const US = 31; + + /// Delete + static const DEL = 127; + + /* + * Printable ASCII characters + */ + + /// Space " " + static const space = 32; + + /// Exclamation mark "!" + static const exclamationMark = 33; + + /// Double quotes '"' + static const doubleQuotes = 34; + + /// Number sign '#' + static const numberSign = 35; + + /// Dollar sign '$' + static const dollarSign = 36; + + /// Percent sign '%' + static const percentSign = 37; + + /// Ampersand '&' + static const ampersand = 38; + + /// Single quote "'" + static const singleQuote = 39; + + /// round brackets or parentheses, opening round bracket '(' + static const openParentheses = 40; + + /// parentheses or round brackets, closing parentheses ')' + static const closeParentheses = 41; + + /// Asterisk '*' + static const asterisk = 42; + + /// Plus sign '+' + static const plus = 43; + + /// Comma "," + static const comma = 44; + + /// Hyphen , minus sign '-' + static const minus = 45; + + /// Dot, full stop '.' + static const dot = 46; + + /// Slash , forward slash , fraction bar , division slash '/' + static const slash = 47; + + /// number zero + static const num0 = 48; + + /// number one + static const num1 = 49; + + /// number two + static const num2 = 50; + + /// number three + static const num3 = 51; + + /// number four + static const num4 = 52; + + /// number five + static const num5 = 53; + + /// number six + static const num6 = 54; + + /// number seven + static const num7 = 55; + + /// number eight + static const num8 = 56; + + /// number nine + static const num9 = 57; + + /// Colon ':' + static const colon = 58; + + /// Semicolon ';' + static const semicolon = 59; + + /// Less-than sign '<' + static const lessThan = 60; + + /// Equals sign '=' + static const equal = 61; + + /// Greater-than sign ; Inequality sign '>' + static const greaterThan = 62; + + /// Question mark '?' + static const questionMark = 63; + + /// At sign '@' + static const atSign = 64; + + /// Capital letter A + static const A = 65; + + /// Capital letter B + static const B = 66; + + /// Capital letter C + static const C = 67; + + /// Capital letter D + static const D = 68; + + /// Capital letter E + static const E = 69; + + /// Capital letter F + static const F = 70; + + /// Capital letter G + static const G = 71; + + /// Capital letter H + static const H = 72; + + /// Capital letter I + static const I = 73; + + /// Capital letter J + static const J = 74; + + /// Capital letter K + static const K = 75; + + /// Capital letter L + static const L = 76; + + /// Capital letter M + static const M = 77; + + /// Capital letter N + static const N = 78; + + /// Capital letter O + static const O = 79; + + /// Capital letter P + static const P = 80; + + /// Capital letter Q + static const Q = 81; + + /// Capital letter R + static const R = 82; + + /// Capital letter S + static const S = 83; + + /// Capital letter T + static const T = 84; + + /// Capital letter U + static const U = 85; + + /// Capital letter V + static const V = 86; + + /// Capital letter W + static const W = 87; + + /// Capital letter X + static const X = 88; + + /// Capital letter Y + static const Y = 89; + + /// Capital letter Z + static const Z = 90; + + /// square brackets or box brackets, opening bracket '[' + static const openBracket = 91; + + /// Backslash , reverse slash '\\' + static const backslash = 92; + + /// box brackets or square brackets, closing bracket ']' + static const closeBracket = 93; + + /// Circumflex accent or Caret '^' + static const caret = 94; + + /// underscore , understrike , underbar or low line '_' + static const underscore = 95; + + /// Grave accent '`' + static const graveAccent = 96; + + /// Lowercase letter a , minuscule a + static const a = 97; + + /// Lowercase letter b , minuscule b + static const b = 98; + + /// Lowercase letter c , minuscule c + static const c = 99; + + /// Lowercase letter d , minuscule d + static const d = 100; + + /// Lowercase letter e , minuscule e + static const e = 101; + + /// Lowercase letter f , minuscule f + static const f = 102; + + /// Lowercase letter g , minuscule g + static const g = 103; + + /// Lowercase letter h , minuscule h + static const h = 104; + + /// Lowercase letter i , minuscule i + static const i = 105; + + /// Lowercase letter j , minuscule j + static const j = 106; + + /// Lowercase letter k , minuscule k + static const k = 107; + + /// Lowercase letter l , minuscule l + static const l = 108; + + /// Lowercase letter m , minuscule m + static const m = 109; + + /// Lowercase letter n , minuscule n + static const n = 110; + + /// Lowercase letter o , minuscule o + static const o = 111; + + /// Lowercase letter p , minuscule p + static const p = 112; + + /// Lowercase letter q , minuscule q + static const q = 113; + + /// Lowercase letter r , minuscule r + static const r = 114; + + /// Lowercase letter s , minuscule s + static const s = 115; + + /// Lowercase letter t , minuscule t + static const t = 116; + + /// Lowercase letter u , minuscule u + static const u = 117; + + /// Lowercase letter v , minuscule v + static const v = 118; + + /// Lowercase letter w , minuscule w + static const w = 119; + + /// Lowercase letter x , minuscule x + static const x = 120; + + /// Lowercase letter y , minuscule y + static const y = 121; + + /// Lowercase letter z , minuscule z + static const z = 122; + + /// braces or curly brackets, opening braces '{' + static const openBrace = 123; + + /// vertical-bar, vbar, vertical line or vertical slash '|' + static const verticalBar = 124; + + /// curly brackets or braces, closing curly brackets '}' + static const closeBrace = 125; + + /// Tilde ; swung dash '~' + static const tilde = 126; +} diff --git a/app/third_party/xterm/lib/src/utils/byte_consumer.dart b/app/third_party/xterm/lib/src/utils/byte_consumer.dart new file mode 100644 index 00000000..4a2ad382 --- /dev/null +++ b/app/third_party/xterm/lib/src/utils/byte_consumer.dart @@ -0,0 +1,107 @@ +import 'dart:collection'; + +class ByteConsumer { + final _queue = ListQueue>(); + + final _consumed = ListQueue>(); + + var _currentOffset = 0; + + var _length = 0; + + var _totalConsumed = 0; + + void add(String data) { + if (data.isEmpty) return; + final runes = data.runes.toList(growable: false); + _queue.addLast(runes); + _length += runes.length; + } + + int peek() { + final data = _queue.first; + if (_currentOffset < data.length) { + return data[_currentOffset]; + } else { + final result = consume(); + rollback(); + return result; + } + } + + int consume() { + final data = _queue.first; + + if (_currentOffset >= data.length) { + _consumed.add(_queue.removeFirst()); + _currentOffset -= data.length; + return consume(); + } + + _length--; + _totalConsumed++; + return data[_currentOffset++]; + } + + /// Rolls back the last [n] call. + void rollback([int n = 1]) { + _currentOffset -= n; + _totalConsumed -= n; + _length += n; + while (_currentOffset < 0) { + final rollback = _consumed.removeLast(); + _queue.addFirst(rollback); + _currentOffset += rollback.length; + } + } + + /// Rolls back to the state when this consumer had [length] bytes. + void rollbackTo(int length) { + rollback(length - _length); + } + + int get length => _length; + + int get totalConsumed => _totalConsumed; + + bool get isEmpty => _length == 0; + + bool get isNotEmpty => _length != 0; + + /// Unreferences data blocks that have been consumed. After calling this + /// method, the consumer will not be able to roll back to consumed blocks. + void unrefConsumedBlocks() { + _consumed.clear(); + } + + /// Resets the consumer to its initial state. + void reset() { + _queue.clear(); + _consumed.clear(); + _currentOffset = 0; + _totalConsumed = 0; + _length = 0; + } +} + +// void main() { +// final consumer = ByteConsumer(); +// consumer.add(Uint8List.fromList([1, 2, 3])); +// consumer.add(Uint8List.fromList([4, 5, 6])); + +// while (consumer.isNotEmpty) { +// print(consumer.consume()); +// } + +// consumer.rollback(5); + +// while (consumer.isNotEmpty) { +// print(consumer.consume()); +// } + +// consumer.rollbackTo(3); + +// while (consumer.isNotEmpty) { +// print(consumer.consume()); +// } +// } diff --git a/app/third_party/xterm/lib/src/utils/char_code.dart b/app/third_party/xterm/lib/src/utils/char_code.dart new file mode 100644 index 00000000..9eb79e0a --- /dev/null +++ b/app/third_party/xterm/lib/src/utils/char_code.dart @@ -0,0 +1,5 @@ +extension StringCharCode on String { + int get charCode { + return codeUnitAt(0); + } +} diff --git a/app/third_party/xterm/lib/src/utils/circular_buffer.dart b/app/third_party/xterm/lib/src/utils/circular_buffer.dart new file mode 100644 index 00000000..f74fb436 --- /dev/null +++ b/app/third_party/xterm/lib/src/utils/circular_buffer.dart @@ -0,0 +1,315 @@ +/// A circular buffer in which elements know their index in the buffer. +class IndexAwareCircularBuffer { + /// Creates a new circular list with the specified [maxLength]. + IndexAwareCircularBuffer(int maxLength) + : _array = List.filled(maxLength, null); + + /// The backing array for this list. Length is always equal to [maxLength]. + late List _array; + + /// The number of elements in the list. This is always less than or equal to + /// [maxLength]. + var _length = 0; + + /// The index of the first element in [_array]. + var _startIndex = 0; + + /// The start index of this list, including items that has been dropped in + /// overflow + var _absoluteStartIndex = 0; + + /// Gets the cyclic index for the specified regular index. The cyclic index + /// can then be used on the backing array to get the element associated with + /// the regular index. + @pragma('vm:prefer-inline') + int _getCyclicIndex(int index) { + return (_startIndex + index) % _array.length; + } + + /// Removes the element at [index] from the list. + @pragma('vm:prefer-inline') + void _dropChild(int index) { + final cyclicIndex = _getCyclicIndex(index); + _array[cyclicIndex]?._detach(); + _array[cyclicIndex] = null; + } + + /// Adds the specified [child] to the list at the specified [index]. + @pragma('vm:prefer-inline') + void _adoptChild(int index, T child) { + final cyclicIndex = _getCyclicIndex(index); + _array[cyclicIndex]?._detach(); + _array[cyclicIndex] = child.._attach(this, index); + } + + /// Moves the element at [fromIndex] to [toIndex]. Both indexes should be + /// less than [maxLength]. + @pragma('vm:prefer-inline') + void _moveChild(int fromIndex, int toIndex) { + final fromCyclicIndex = _getCyclicIndex(fromIndex); + final toCyclicIndex = _getCyclicIndex(toIndex); + _array[toCyclicIndex]?._detach(); + _array[toCyclicIndex] = _array[fromCyclicIndex]?.._move(toIndex); + _array[fromCyclicIndex] = null; + } + + /// Gets the element at the specified [index] in the list. + @pragma('vm:prefer-inline') + T? _getChild(int index) { + return _array[_getCyclicIndex(index)]; + } + + /// The number of elements that can be stored in the list. + int get maxLength { + return _array.length; + } + + /// Sets the number of elements that can be stored in the list. This operation + /// is relatively expensive, as it requires the backing array to be + /// reallocated. + set maxLength(int value) { + if (value <= 0) { + throw ArgumentError.value(value, 'value', "maxLength can't be negative!"); + } + + if (value == _array.length) return; + + // Reconstruct array, starting at index 0. Only transfer values from the + // indexes 0 to length. + final newArray = List.generate( + value, + (index) => index < _length ? _getChild(index) : null, + ); + + _startIndex = 0; + _array = newArray; + } + + /// Number of elements in the list. + int get length { + return _length; + } + + /// Iterates over the list and calls [callback] for each element. + void forEach(void Function(T item) callback) { + final length = _length; + for (int i = 0; i < length; i++) { + callback(_getChild(i)!); + } + } + + /// Gets the element at the specified [index] in the list. Throws if the + /// index is out of bounds. + T operator [](int index) { + RangeError.checkValueInInterval(index, 0, length - 1, 'index'); + return _getChild(index)!; + } + + /// Sets the element at the specified [index] in the list. Throws if the + /// index is out of bounds. + operator []=(int index, T value) { + RangeError.checkValueInInterval(index, 0, length - 1, 'index'); + _adoptChild(index, value); + } + + /// Removes all elements from the list. + void clear() { + for (var i = 0; i < _length; i++) { + _dropChild(i); + } + _startIndex = 0; + _length = 0; + } + + /// Adds all elements in [items] to the list. + void pushAll(Iterable items) { + for (var element in items) { + push(element); + } + } + + /// Adds [value] to the end of the list. May cause the first element to be + /// trimmed if the list is full. + void push(T value) { + _adoptChild(_length, value); + + if (_length == _array.length) { + // When the list is full, we trim the first element + _startIndex++; + _absoluteStartIndex++; + if (_startIndex == _array.length) { + _startIndex = 0; + } + } else { + // When the list is not full, we just increase the length + _length++; + } + } + + /// Removes and returns the last value on the list, throws if the list is + /// empty. + T pop() { + assert(_length > 0, 'Cannot pop from an empty list'); + final result = _getChild(_length - 1); + _dropChild(_length - 1); + _length--; + return result!; + } + + /// Deletes [count] elements starting at [index], shifting all elements after + /// [index] to the left. + void remove(int index, [int count = 1]) { + if (count > 0) { + if (index + count >= _length) { + count = _length - index; + } + for (var i = index; i < _length - count; i++) { + _moveChild(i + count, i); + } + for (var i = _length - count; i < _length; i++) { + _dropChild(i); + } + _length -= count; + } + } + + /// Inserts [item] at [index], shifting all elements after [index] to the + /// right. May cause the first element to be trimmed if the list is full. + void insert(int index, T item) { + RangeError.checkValueInInterval(index, 0, _length, 'index'); + + if (index == _length) { + return push(item); + } + + if (index == 0 && _length >= _array.length) { + // when something is inserted at index 0 and the list is full then + // the new value immediately gets removed => nothing changes + return; + } + + for (var i = _length - 1; i >= index; i--) { + _moveChild(i, i + 1); + } + + _adoptChild(index, item); + + if (_length >= _array.length) { + _startIndex += 1; + _absoluteStartIndex += 1; + } else { + _length++; + } + } + + /// Inserts [items] at [index] in order. + void insertAll(int index, List items) { + for (var i = items.length - 1; i >= 0; i--) { + insert(index, items[i]); + // when the list is full then we have to move the index down + // as newly inserted values remove values with a lower index + if (_length >= _array.length) { + index--; + if (index < 0) { + return; + } + } + } + } + + /// Removes [count] elements starting at [index], shifting all elements after + /// [index] to the left. + /// + /// This method is cheap since it does not actually modify the list, but + /// instead just adjusts the start index and length. + void trimStart(int count) { + if (count > _length) count = _length; + _startIndex += count; + _startIndex %= _array.length; + _length -= count; + } + + /// Replaces all elements in the list with [replacement]. + void replaceWith(List replacement) { + for (var i = 0; i < _length; i++) { + _dropChild(i); + } + + var copyStart = 0; + if (replacement.length > maxLength) { + copyStart = replacement.length - maxLength; + } + + for (var i = 0; i < copyStart; i++) { + _dropChild(i); + } + + final copyLength = replacement.length - copyStart; + for (var i = 0; i < copyLength; i++) { + _adoptChild(i, replacement[copyStart + i]); + } + + _startIndex = 0; + _length = copyLength; + } + + /// Replaces the element at [index] with [value] and returns the replaced + /// item. + T swap(int index, T value) { + final result = _getChild(index); + _adoptChild(index, value); + return result!; + } + + /// Whether adding another element would cause the first element to be + /// trimmed. + bool get isFull => length == maxLength; + + /// Returns a list containing all elements in the list. + List toList() { + return List.generate(length, (index) => this[index]); + } + + String debugDump() { + final buffer = StringBuffer(); + buffer.writeln('CircularList:'); + for (var i = 0; i < _length; i++) { + final child = _getChild(i); + buffer.writeln(' $i: $child'); + } + return buffer.toString(); + } +} + +mixin IndexedItem { + IndexAwareCircularBuffer? _owner; + + int? _absoluteIndex; + + /// The index of this item in the buffer. Must only be accessed when + /// [attached] is true. + int get index => _absoluteIndex! - _owner!._absoluteStartIndex; + + /// Whether this item is currently stored in a buffer. + bool get attached => _owner != null; + + /// Sets the owner and index of this item. This is called by the buffer when + /// the item is adopted. + void _attach(IndexAwareCircularBuffer owner, int index) { + _owner = owner; + _absoluteIndex = owner._absoluteStartIndex + index; + } + + /// Marks this item as detached from a buffer. This is called after the item + /// has been removed from the buffer. + void _detach() { + _owner = null; + _absoluteIndex = null; + } + + /// Moves this item to [newIndex] in the buffer. + void _move(int newIndex) { + assert(attached); + _absoluteIndex = _owner!._absoluteStartIndex + newIndex; + } +} diff --git a/app/third_party/xterm/lib/src/utils/debugger.dart b/app/third_party/xterm/lib/src/utils/debugger.dart new file mode 100644 index 00000000..303bbbbe --- /dev/null +++ b/app/third_party/xterm/lib/src/utils/debugger.dart @@ -0,0 +1,595 @@ +import 'package:xterm/src/core/escape/handler.dart'; +import 'package:xterm/src/core/escape/parser.dart'; +import 'package:xterm/src/core/mouse/mode.dart'; +import 'package:xterm/src/base/observable.dart'; + +class TerminalCommand { + TerminalCommand( + this.start, + this.end, + this.chars, + this.escapedChars, + this.explanation, + this.error, + ); + + final int start; + + final int end; + + final String chars; + + final String escapedChars; + + final List explanation; + + final bool error; +} + +class TerminalDebugger with Observable { + late final _parser = EscapeParser(_handler); + + late final _handler = _TerminalDebuggerHandler(recordCommand); + + final recorded = []; + + final commands = []; + + void write(String chunk) { + recorded.addAll(chunk.runes); + _parser.write(chunk); + notifyListeners(); + } + + void recordCommand(String explanation, {bool error = false}) { + final start = _parser.tokenBegin; + final end = _parser.tokenEnd; + + if (commands.isNotEmpty && commands.last.end == end) { + commands.last.explanation.add(explanation); + } else { + final charCodes = recorded.sublist(start, end); + final chars = String.fromCharCodes(charCodes); + final escapedChars = _escape(chars); + commands.add( + TerminalCommand(start, end, chars, escapedChars, [explanation], error), + ); + } + } + + String getRecord(TerminalCommand command) { + final charCodes = recorded.sublist(0, command.end); + return String.fromCharCodes(charCodes); + } + + static String _escape(String chars) { + final escaped = StringBuffer(); + for (final char in chars.runes) { + if (char == 0x1b) { + escaped.write('ESC'); + } else if (char < 32) { + escaped.write('^0x${char.toRadixString(16)}'); + } else if (char == 127) { + escaped.write('^?'); + } else { + escaped.writeCharCode(char); + } + } + return escaped.toString(); + } +} + +class _TerminalDebuggerHandler implements EscapeHandler { + _TerminalDebuggerHandler(this.onCommand); + + final void Function(String explanation, {bool error}) onCommand; + + @override + void writeChar(int char) { + onCommand('writeChar(${String.fromCharCode(char)})'); + } + + /* SBC */ + + @override + void bell() { + onCommand('bell'); + } + + @override + void backspaceReturn() { + onCommand('backspaceReturn'); + } + + @override + void tab() { + onCommand('tab'); + } + + @override + void lineFeed() { + onCommand('lineFeed'); + } + + @override + void carriageReturn() { + onCommand('carriageReturn'); + } + + @override + void shiftOut() { + onCommand('shiftOut'); + } + + @override + void shiftIn() { + onCommand('shiftIn'); + } + + @override + void unknownSBC(int char) { + onCommand('unkownSBC(${String.fromCharCode(char)})', error: true); + } + + /* ANSI sequence */ + + @override + void saveCursor() { + onCommand('saveCursor'); + } + + @override + void restoreCursor() { + onCommand('restoreCursor'); + } + + @override + void index() { + onCommand('index'); + } + + @override + void nextLine() { + onCommand('nextLine'); + } + + @override + void setTapStop() { + onCommand('setTapStop'); + } + + @override + void reverseIndex() { + onCommand('reverseIndex'); + } + + @override + void designateCharset(int charset, int name) { + onCommand('designateCharset($charset, $name)'); + } + + @override + void unkownEscape(int char) { + onCommand('unkownEscape(${String.fromCharCode(char)})', error: true); + } + + /* CSI */ + + @override + void repeatPreviousCharacter(int count) { + onCommand('repeatPreviousCharacter($count)'); + } + + @override + void unknownCSI(int finalByte) { + onCommand('unkownCSI(${String.fromCharCode(finalByte)})', error: true); + } + + @override + void setCursor(int x, int y) { + onCommand('setCursor($x, $y)'); + } + + @override + void setCursorX(int x) { + onCommand('setCursorX($x)'); + } + + @override + void setCursorY(int y) { + onCommand('setCursorY($y)'); + } + + @override + void sendPrimaryDeviceAttributes() { + onCommand('sendPrimaryDeviceAttributes'); + } + + @override + void clearTabStopUnderCursor() { + onCommand('clearTabStopUnderCursor'); + } + + @override + void clearAllTabStops() { + onCommand('clearAllTabStops'); + } + + @override + void moveCursorX(int offset) { + onCommand('moveCursorX($offset)'); + } + + @override + void moveCursorY(int n) { + onCommand('moveCursorY($n)'); + } + + @override + void sendSecondaryDeviceAttributes() { + onCommand('sendSecondaryDeviceAttributes'); + } + + @override + void sendTertiaryDeviceAttributes() { + onCommand('sendTertiaryDeviceAttributes'); + } + + @override + void sendOperatingStatus() { + onCommand('sendOperatingStatus'); + } + + @override + void sendCursorPosition() { + onCommand('sendCursorPosition'); + } + + @override + void setMargins(int i, [int? bottom]) { + onCommand('setMargins($i, $bottom)'); + } + + @override + void cursorNextLine(int amount) { + onCommand('cursorNextLine($amount)'); + } + + @override + void cursorPrecedingLine(int amount) { + onCommand('cursorPrecedingLine($amount)'); + } + + @override + void eraseDisplayBelow() { + onCommand('eraseDisplayBelow'); + } + + @override + void eraseDisplayAbove() { + onCommand('eraseDisplayAbove'); + } + + @override + void eraseDisplay() { + onCommand('eraseDisplay'); + } + + @override + void eraseScrollbackOnly() { + onCommand('eraseScrollbackOnly'); + } + + @override + void eraseLineRight() { + onCommand('eraseLineRight'); + } + + @override + void eraseLineLeft() { + onCommand('eraseLineLeft'); + } + + @override + void eraseLine() { + onCommand('eraseLine'); + } + + @override + void insertLines(int amount) { + onCommand('insertLines($amount)'); + } + + @override + void deleteLines(int amount) { + onCommand('deleteLines($amount)'); + } + + @override + void deleteChars(int amount) { + onCommand('deleteChars($amount)'); + } + + @override + void scrollUp(int amount) { + onCommand('scrollUp($amount)'); + } + + @override + void scrollDown(int amount) { + onCommand('scrollDown($amount)'); + } + + @override + void eraseChars(int amount) { + onCommand('eraseChars($amount)'); + } + + @override + void insertBlankChars(int amount) { + onCommand('insertBlankChars($amount)'); + } + + @override + void resize(int cols, int rows) { + onCommand('resize($cols, $rows)'); + } + + @override + void sendSize() { + onCommand('sendSize'); + } + + /* Modes */ + + @override + void setInsertMode(bool enabled) { + onCommand('setInsertMode($enabled)'); + } + + @override + void setLineFeedMode(bool enabled) { + onCommand('setLineFeedMode($enabled)'); + } + + @override + void setUnknownMode(int mode, bool enabled) { + onCommand('setUnknownMode($mode, $enabled)', error: true); + } + + /* DEC Private modes */ + + @override + void setCursorKeysMode(bool enabled) { + onCommand('setCursorKeysMode($enabled)'); + } + + @override + void setReverseDisplayMode(bool enabled) { + onCommand('setReverseDisplayMode($enabled)'); + } + + @override + void setOriginMode(bool enabled) { + onCommand('setOriginMode($enabled)'); + } + + @override + void setColumnMode(bool enabled) { + onCommand('setColumnMode($enabled)'); + } + + @override + void setAutoWrapMode(bool enabled) { + onCommand('setAutoWrapMode($enabled)'); + } + + @override + void setMouseMode(MouseMode mode) { + onCommand('setMouseMode($mode)'); + } + + @override + void setCursorBlinkMode(bool enabled) { + onCommand('setCursorBlinkMode($enabled)'); + } + + @override + void setCursorVisibleMode(bool enabled) { + onCommand('setCursorVisibleMode($enabled)'); + } + + @override + void useAltBuffer() { + onCommand('useAltBuffer'); + } + + @override + void useMainBuffer() { + onCommand('useMainBuffer'); + } + + @override + void clearAltBuffer() { + onCommand('clearAltBuffer'); + } + + @override + void setAppKeypadMode(bool enabled) { + onCommand('setAppKeypadMode($enabled)'); + } + + @override + void setReportFocusMode(bool enabled) { + onCommand('setReportFocusMode($enabled)'); + } + + @override + void setMouseReportMode(MouseReportMode mode) { + onCommand('setMouseReportMode($mode)'); + } + + @override + void setAltBufferMouseScrollMode(bool enabled) { + onCommand('setAltBufferMouseScrollMode($enabled)'); + } + + @override + void setBracketedPasteMode(bool enabled) { + onCommand('setBracketedPasteMode($enabled)'); + } + + @override + void setUnknownDecMode(int mode, bool enabled) { + onCommand('setUnknownDecMode($mode, $enabled)', error: true); + } + + /* Select Graphic Rendition (SGR) */ + + @override + void resetCursorStyle() { + onCommand('resetCursorStyle'); + } + + @override + void setCursorBold() { + onCommand('setCursorBold'); + } + + @override + void setCursorFaint() { + onCommand('setCursorFaint'); + } + + @override + void setCursorItalic() { + onCommand('setCursorItalic'); + } + + @override + void setCursorUnderline() { + onCommand('setCursorUnderline'); + } + + @override + void setCursorBlink() { + onCommand('setCursorBlink'); + } + + @override + void setCursorInverse() { + onCommand('setCursorInverse'); + } + + @override + void setCursorInvisible() { + onCommand('setCursorInvisible'); + } + + @override + void setCursorStrikethrough() { + onCommand('setCursorStrikethrough'); + } + + @override + void unsetCursorBold() { + onCommand('unsetCursorBold'); + } + + @override + void unsetCursorFaint() { + onCommand('unsetCursorFaint'); + } + + @override + void unsetCursorItalic() { + onCommand('unsetCursorItalic'); + } + + @override + void unsetCursorUnderline() { + onCommand('unsetCursorUnderline'); + } + + @override + void unsetCursorBlink() { + onCommand('unsetCursorBlink'); + } + + @override + void unsetCursorInverse() { + onCommand('unsetCursorInverse'); + } + + @override + void unsetCursorInvisible() { + onCommand('unsetCursorInvisible'); + } + + @override + void unsetCursorStrikethrough() { + onCommand('unsetCursorStrikethrough'); + } + + @override + void setForegroundColor16(int color) { + onCommand('setForegroundColor16($color)'); + } + + @override + void setForegroundColor256(int index) { + onCommand('setForegroundColor256($index)'); + } + + @override + void setForegroundColorRgb(int r, int g, int b) { + onCommand('setForegroundColorRgb($r, $g, $b)'); + } + + @override + void resetForeground() { + onCommand('resetForeground'); + } + + @override + void setBackgroundColor16(int color) { + onCommand('setBackgroundColor16($color)'); + } + + @override + void setBackgroundColor256(int index) { + onCommand('setBackgroundColor256($index)'); + } + + @override + void setBackgroundColorRgb(int r, int g, int b) { + onCommand('setBackgroundColorRgb($r, $g, $b)'); + } + + @override + void resetBackground() { + onCommand('resetBackground'); + } + + @override + void unsupportedStyle(int param) { + onCommand('unsupportedStyle($param)', error: true); + } + + /* OSC */ + + @override + void setTitle(String name) { + onCommand('setTitle($name)'); + } + + @override + void setIconName(String name) { + onCommand('setIconName($name)'); + } + + @override + void unknownOSC(String code, List args) { + onCommand('unknownOSC($code, $args)', error: true); + } +} diff --git a/app/third_party/xterm/lib/src/utils/debugger_view.dart b/app/third_party/xterm/lib/src/utils/debugger_view.dart new file mode 100644 index 00000000..f5ff556a --- /dev/null +++ b/app/third_party/xterm/lib/src/utils/debugger_view.dart @@ -0,0 +1,170 @@ +import 'package:flutter/material.dart'; +import 'package:xterm/src/utils/debugger.dart'; + +class TerminalDebuggerView extends StatefulWidget { + const TerminalDebuggerView( + this.debugger, { + super.key, + this.scrollController, + this.onSeek, + }); + + final TerminalDebugger debugger; + + final ScrollController? scrollController; + + final void Function(int?)? onSeek; + + @override + State createState() => _TerminalDebuggerViewState(); +} + +class _TerminalDebuggerViewState extends State { + int? selectedCommand; + + @override + void initState() { + widget.debugger.addListener(_onDebuggerChanged); + super.initState(); + } + + @override + void didUpdateWidget(covariant TerminalDebuggerView oldWidget) { + if (oldWidget.debugger != widget.debugger) { + oldWidget.debugger.removeListener(_onDebuggerChanged); + widget.debugger.addListener(_onDebuggerChanged); + } + super.didUpdateWidget(oldWidget); + } + + @override + void dispose() { + widget.debugger.removeListener(_onDebuggerChanged); + super.dispose(); + } + + void _onDebuggerChanged() { + setState(() {}); + } + + @override + Widget build(BuildContext context) { + final commands = widget.debugger.commands; + return ListView.builder( + itemExtent: 20, + controller: widget.scrollController, + itemCount: commands.length, + itemBuilder: (context, index) { + final command = commands[index]; + return _CommandItem( + index, + command, + selected: selectedCommand == index, + onTap: () { + if (selectedCommand == index) { + selectedCommand = null; + } else { + setState(() => selectedCommand = index); + } + widget.onSeek?.call(selectedCommand); + }, + ); + }, + ); + } +} + +class _CommandItem extends StatelessWidget { + const _CommandItem( + this.index, + this.command, { + this.onTap, + this.selected = false, + }); + + final int index; + + final TerminalCommand command; + + final bool selected; + + final void Function()? onTap; + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: onTap, + child: MouseRegion( + cursor: SystemMouseCursors.click, + onEnter: (event) { + if (event.down) { + onTap?.call(); + } + }, + child: Container( + decoration: BoxDecoration( + border: Border.all( + color: selected ? Colors.blue : Colors.transparent, + width: 2, + ), + borderRadius: BorderRadius.circular(5), + ), + child: Row( + children: [ + Container( + width: 50, + child: Text( + '${index + 1}', + style: TextStyle( + color: selected ? Colors.blue : Colors.black, + fontSize: 14, + fontFamily: 'monospace', + fontFamilyFallback: [ + 'Menlo', + 'Monaco', + 'Consolas', + 'Liberation Mono', + 'Courier New', + 'Noto Sans Mono CJK SC', + 'Noto Sans Mono CJK TC', + 'Noto Sans Mono CJK KR', + 'Noto Sans Mono CJK JP', + 'Noto Sans Mono CJK HK', + 'Noto Color Emoji', + 'Noto Sans Symbols', + 'monospace', + 'sans-serif', + ], + ), + textAlign: TextAlign.right, + ), + ), + SizedBox(width: 20), + Container( + width: 400, + child: Text( + command.escapedChars, + style: TextStyle( + color: command.error ? Colors.red : null, + fontSize: 14, + ), + ), + ), + Expanded( + child: Container( + child: Text( + command.explanation.join(','), + style: TextStyle( + color: command.error ? Colors.red : null, + fontSize: 14, + ), + ), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/app/third_party/xterm/lib/src/utils/hash_values.dart b/app/third_party/xterm/lib/src/utils/hash_values.dart new file mode 100644 index 00000000..cdc43ed0 --- /dev/null +++ b/app/third_party/xterm/lib/src/utils/hash_values.dart @@ -0,0 +1,111 @@ +class _HashEnd { + const _HashEnd(); +} + +const _HashEnd _hashEnd = _HashEnd(); + +class _Jenkins { + static int combine(int hash, Object? o) { + assert(o is! Iterable); + hash = 0x1fffffff & (hash + o.hashCode); + hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); + return hash ^ (hash >> 6); + } + + static int finish(int hash) { + hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); + hash = hash ^ (hash >> 11); + return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); + } +} + +int hashValues( + Object? arg01, + Object? arg02, [ + Object? arg03 = _hashEnd, + Object? arg04 = _hashEnd, + Object? arg05 = _hashEnd, + Object? arg06 = _hashEnd, + Object? arg07 = _hashEnd, + Object? arg08 = _hashEnd, + Object? arg09 = _hashEnd, + Object? arg10 = _hashEnd, + Object? arg11 = _hashEnd, + Object? arg12 = _hashEnd, + Object? arg13 = _hashEnd, + Object? arg14 = _hashEnd, + Object? arg15 = _hashEnd, + Object? arg16 = _hashEnd, + Object? arg17 = _hashEnd, + Object? arg18 = _hashEnd, + Object? arg19 = _hashEnd, + Object? arg20 = _hashEnd, +]) { + int result = 0; + result = _Jenkins.combine(result, arg01); + result = _Jenkins.combine(result, arg02); + if (!identical(arg03, _hashEnd)) { + result = _Jenkins.combine(result, arg03); + if (!identical(arg04, _hashEnd)) { + result = _Jenkins.combine(result, arg04); + if (!identical(arg05, _hashEnd)) { + result = _Jenkins.combine(result, arg05); + if (!identical(arg06, _hashEnd)) { + result = _Jenkins.combine(result, arg06); + if (!identical(arg07, _hashEnd)) { + result = _Jenkins.combine(result, arg07); + if (!identical(arg08, _hashEnd)) { + result = _Jenkins.combine(result, arg08); + if (!identical(arg09, _hashEnd)) { + result = _Jenkins.combine(result, arg09); + if (!identical(arg10, _hashEnd)) { + result = _Jenkins.combine(result, arg10); + if (!identical(arg11, _hashEnd)) { + result = _Jenkins.combine(result, arg11); + if (!identical(arg12, _hashEnd)) { + result = _Jenkins.combine(result, arg12); + if (!identical(arg13, _hashEnd)) { + result = _Jenkins.combine(result, arg13); + if (!identical(arg14, _hashEnd)) { + result = _Jenkins.combine(result, arg14); + if (!identical(arg15, _hashEnd)) { + result = _Jenkins.combine(result, arg15); + if (!identical(arg16, _hashEnd)) { + result = _Jenkins.combine(result, arg16); + if (!identical(arg17, _hashEnd)) { + result = _Jenkins.combine(result, arg17); + if (!identical(arg18, _hashEnd)) { + result = _Jenkins.combine(result, arg18); + if (!identical(arg19, _hashEnd)) { + result = _Jenkins.combine(result, arg19); + if (!identical(arg20, _hashEnd)) { + result = _Jenkins.combine(result, arg20); + // I can see my house from here! + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + return _Jenkins.finish(result); +} + +int hashList(Iterable arguments) { + int result = 0; + for (Object argument in arguments) { + result = _Jenkins.combine(result, argument); + } + return _Jenkins.finish(result); +} diff --git a/app/third_party/xterm/lib/src/utils/lookup_table.dart b/app/third_party/xterm/lib/src/utils/lookup_table.dart new file mode 100644 index 00000000..377294bb --- /dev/null +++ b/app/third_party/xterm/lib/src/utils/lookup_table.dart @@ -0,0 +1,34 @@ +/// Fixed-size list based lookup table, optimized for small positive integer +/// keys. +class FastLookupTable { + FastLookupTable(Map data) { + var maxIndex = data.keys.first; + + for (var key in data.keys) { + if (key > maxIndex) { + maxIndex = key; + } + } + + _maxIndex = maxIndex; + + _table = List.filled(maxIndex + 1, null); + + for (var entry in data.entries) { + _table[entry.key] = entry.value; + } + } + + late final List _table; + late final int _maxIndex; + + T? operator [](int index) { + if (index > _maxIndex) { + return null; + } + + return _table[index]; + } + + int get maxIndex => _maxIndex; +} diff --git a/app/third_party/xterm/lib/src/utils/unicode_v11.dart b/app/third_party/xterm/lib/src/utils/unicode_v11.dart new file mode 100644 index 00000000..fd95ba0b --- /dev/null +++ b/app/third_party/xterm/lib/src/utils/unicode_v11.dart @@ -0,0 +1,512 @@ +// ignore_for_file: constant_identifier_names + +import 'dart:typed_data'; + +const BMP_COMBINING = [ + [0x0300, 0x036F], + [0x0483, 0x0489], + [0x0591, 0x05BD], + [0x05BF, 0x05BF], + [0x05C1, 0x05C2], + [0x05C4, 0x05C5], + [0x05C7, 0x05C7], + [0x0600, 0x0605], + [0x0610, 0x061A], + [0x061C, 0x061C], + [0x064B, 0x065F], + [0x0670, 0x0670], + [0x06D6, 0x06DD], + [0x06DF, 0x06E4], + [0x06E7, 0x06E8], + [0x06EA, 0x06ED], + [0x070F, 0x070F], + [0x0711, 0x0711], + [0x0730, 0x074A], + [0x07A6, 0x07B0], + [0x07EB, 0x07F3], + [0x07FD, 0x07FD], + [0x0816, 0x0819], + [0x081B, 0x0823], + [0x0825, 0x0827], + [0x0829, 0x082D], + [0x0859, 0x085B], + [0x08D3, 0x0902], + [0x093A, 0x093A], + [0x093C, 0x093C], + [0x0941, 0x0948], + [0x094D, 0x094D], + [0x0951, 0x0957], + [0x0962, 0x0963], + [0x0981, 0x0981], + [0x09BC, 0x09BC], + [0x09C1, 0x09C4], + [0x09CD, 0x09CD], + [0x09E2, 0x09E3], + [0x09FE, 0x09FE], + [0x0A01, 0x0A02], + [0x0A3C, 0x0A3C], + [0x0A41, 0x0A42], + [0x0A47, 0x0A48], + [0x0A4B, 0x0A4D], + [0x0A51, 0x0A51], + [0x0A70, 0x0A71], + [0x0A75, 0x0A75], + [0x0A81, 0x0A82], + [0x0ABC, 0x0ABC], + [0x0AC1, 0x0AC5], + [0x0AC7, 0x0AC8], + [0x0ACD, 0x0ACD], + [0x0AE2, 0x0AE3], + [0x0AFA, 0x0AFF], + [0x0B01, 0x0B01], + [0x0B3C, 0x0B3C], + [0x0B3F, 0x0B3F], + [0x0B41, 0x0B44], + [0x0B4D, 0x0B4D], + [0x0B56, 0x0B56], + [0x0B62, 0x0B63], + [0x0B82, 0x0B82], + [0x0BC0, 0x0BC0], + [0x0BCD, 0x0BCD], + [0x0C00, 0x0C00], + [0x0C04, 0x0C04], + [0x0C3E, 0x0C40], + [0x0C46, 0x0C48], + [0x0C4A, 0x0C4D], + [0x0C55, 0x0C56], + [0x0C62, 0x0C63], + [0x0C81, 0x0C81], + [0x0CBC, 0x0CBC], + [0x0CBF, 0x0CBF], + [0x0CC6, 0x0CC6], + [0x0CCC, 0x0CCD], + [0x0CE2, 0x0CE3], + [0x0D00, 0x0D01], + [0x0D3B, 0x0D3C], + [0x0D41, 0x0D44], + [0x0D4D, 0x0D4D], + [0x0D62, 0x0D63], + [0x0DCA, 0x0DCA], + [0x0DD2, 0x0DD4], + [0x0DD6, 0x0DD6], + [0x0E31, 0x0E31], + [0x0E34, 0x0E3A], + [0x0E47, 0x0E4E], + [0x0EB1, 0x0EB1], + [0x0EB4, 0x0EBC], + [0x0EC8, 0x0ECD], + [0x0F18, 0x0F19], + [0x0F35, 0x0F35], + [0x0F37, 0x0F37], + [0x0F39, 0x0F39], + [0x0F71, 0x0F7E], + [0x0F80, 0x0F84], + [0x0F86, 0x0F87], + [0x0F8D, 0x0F97], + [0x0F99, 0x0FBC], + [0x0FC6, 0x0FC6], + [0x102D, 0x1030], + [0x1032, 0x1037], + [0x1039, 0x103A], + [0x103D, 0x103E], + [0x1058, 0x1059], + [0x105E, 0x1060], + [0x1071, 0x1074], + [0x1082, 0x1082], + [0x1085, 0x1086], + [0x108D, 0x108D], + [0x109D, 0x109D], + [0x1160, 0x11FF], + [0x135D, 0x135F], + [0x1712, 0x1714], + [0x1732, 0x1734], + [0x1752, 0x1753], + [0x1772, 0x1773], + [0x17B4, 0x17B5], + [0x17B7, 0x17BD], + [0x17C6, 0x17C6], + [0x17C9, 0x17D3], + [0x17DD, 0x17DD], + [0x180B, 0x180E], + [0x1885, 0x1886], + [0x18A9, 0x18A9], + [0x1920, 0x1922], + [0x1927, 0x1928], + [0x1932, 0x1932], + [0x1939, 0x193B], + [0x1A17, 0x1A18], + [0x1A1B, 0x1A1B], + [0x1A56, 0x1A56], + [0x1A58, 0x1A5E], + [0x1A60, 0x1A60], + [0x1A62, 0x1A62], + [0x1A65, 0x1A6C], + [0x1A73, 0x1A7C], + [0x1A7F, 0x1A7F], + [0x1AB0, 0x1ABE], + [0x1B00, 0x1B03], + [0x1B34, 0x1B34], + [0x1B36, 0x1B3A], + [0x1B3C, 0x1B3C], + [0x1B42, 0x1B42], + [0x1B6B, 0x1B73], + [0x1B80, 0x1B81], + [0x1BA2, 0x1BA5], + [0x1BA8, 0x1BA9], + [0x1BAB, 0x1BAD], + [0x1BE6, 0x1BE6], + [0x1BE8, 0x1BE9], + [0x1BED, 0x1BED], + [0x1BEF, 0x1BF1], + [0x1C2C, 0x1C33], + [0x1C36, 0x1C37], + [0x1CD0, 0x1CD2], + [0x1CD4, 0x1CE0], + [0x1CE2, 0x1CE8], + [0x1CED, 0x1CED], + [0x1CF4, 0x1CF4], + [0x1CF8, 0x1CF9], + [0x1DC0, 0x1DF9], + [0x1DFB, 0x1DFF], + [0x200B, 0x200F], + [0x202A, 0x202E], + [0x2060, 0x2064], + [0x2066, 0x206F], + [0x20D0, 0x20F0], + [0x2CEF, 0x2CF1], + [0x2D7F, 0x2D7F], + [0x2DE0, 0x2DFF], + [0x302A, 0x302D], + [0x3099, 0x309A], + [0xA66F, 0xA672], + [0xA674, 0xA67D], + [0xA69E, 0xA69F], + [0xA6F0, 0xA6F1], + [0xA802, 0xA802], + [0xA806, 0xA806], + [0xA80B, 0xA80B], + [0xA825, 0xA826], + [0xA8C4, 0xA8C5], + [0xA8E0, 0xA8F1], + [0xA8FF, 0xA8FF], + [0xA926, 0xA92D], + [0xA947, 0xA951], + [0xA980, 0xA982], + [0xA9B3, 0xA9B3], + [0xA9B6, 0xA9B9], + [0xA9BC, 0xA9BD], + [0xA9E5, 0xA9E5], + [0xAA29, 0xAA2E], + [0xAA31, 0xAA32], + [0xAA35, 0xAA36], + [0xAA43, 0xAA43], + [0xAA4C, 0xAA4C], + [0xAA7C, 0xAA7C], + [0xAAB0, 0xAAB0], + [0xAAB2, 0xAAB4], + [0xAAB7, 0xAAB8], + [0xAABE, 0xAABF], + [0xAAC1, 0xAAC1], + [0xAAEC, 0xAAED], + [0xAAF6, 0xAAF6], + [0xABE5, 0xABE5], + [0xABE8, 0xABE8], + [0xABED, 0xABED], + [0xFB1E, 0xFB1E], + [0xFE00, 0xFE0F], + [0xFE20, 0xFE2F], + [0xFEFF, 0xFEFF], + [0xFFF9, 0xFFFB], +]; + +const HIGH_COMBINING = [ + [0x101FD, 0x101FD], + [0x102E0, 0x102E0], + [0x10376, 0x1037A], + [0x10A01, 0x10A03], + [0x10A05, 0x10A06], + [0x10A0C, 0x10A0F], + [0x10A38, 0x10A3A], + [0x10A3F, 0x10A3F], + [0x10AE5, 0x10AE6], + [0x10D24, 0x10D27], + [0x10F46, 0x10F50], + [0x11001, 0x11001], + [0x11038, 0x11046], + [0x1107F, 0x11081], + [0x110B3, 0x110B6], + [0x110B9, 0x110BA], + [0x110BD, 0x110BD], + [0x110CD, 0x110CD], + [0x11100, 0x11102], + [0x11127, 0x1112B], + [0x1112D, 0x11134], + [0x11173, 0x11173], + [0x11180, 0x11181], + [0x111B6, 0x111BE], + [0x111C9, 0x111CC], + [0x1122F, 0x11231], + [0x11234, 0x11234], + [0x11236, 0x11237], + [0x1123E, 0x1123E], + [0x112DF, 0x112DF], + [0x112E3, 0x112EA], + [0x11300, 0x11301], + [0x1133B, 0x1133C], + [0x11340, 0x11340], + [0x11366, 0x1136C], + [0x11370, 0x11374], + [0x11438, 0x1143F], + [0x11442, 0x11444], + [0x11446, 0x11446], + [0x1145E, 0x1145E], + [0x114B3, 0x114B8], + [0x114BA, 0x114BA], + [0x114BF, 0x114C0], + [0x114C2, 0x114C3], + [0x115B2, 0x115B5], + [0x115BC, 0x115BD], + [0x115BF, 0x115C0], + [0x115DC, 0x115DD], + [0x11633, 0x1163A], + [0x1163D, 0x1163D], + [0x1163F, 0x11640], + [0x116AB, 0x116AB], + [0x116AD, 0x116AD], + [0x116B0, 0x116B5], + [0x116B7, 0x116B7], + [0x1171D, 0x1171F], + [0x11722, 0x11725], + [0x11727, 0x1172B], + [0x1182F, 0x11837], + [0x11839, 0x1183A], + [0x119D4, 0x119D7], + [0x119DA, 0x119DB], + [0x119E0, 0x119E0], + [0x11A01, 0x11A0A], + [0x11A33, 0x11A38], + [0x11A3B, 0x11A3E], + [0x11A47, 0x11A47], + [0x11A51, 0x11A56], + [0x11A59, 0x11A5B], + [0x11A8A, 0x11A96], + [0x11A98, 0x11A99], + [0x11C30, 0x11C36], + [0x11C38, 0x11C3D], + [0x11C3F, 0x11C3F], + [0x11C92, 0x11CA7], + [0x11CAA, 0x11CB0], + [0x11CB2, 0x11CB3], + [0x11CB5, 0x11CB6], + [0x11D31, 0x11D36], + [0x11D3A, 0x11D3A], + [0x11D3C, 0x11D3D], + [0x11D3F, 0x11D45], + [0x11D47, 0x11D47], + [0x11D90, 0x11D91], + [0x11D95, 0x11D95], + [0x11D97, 0x11D97], + [0x11EF3, 0x11EF4], + [0x13430, 0x13438], + [0x16AF0, 0x16AF4], + [0x16B30, 0x16B36], + [0x16F4F, 0x16F4F], + [0x16F8F, 0x16F92], + [0x1BC9D, 0x1BC9E], + [0x1BCA0, 0x1BCA3], + [0x1D167, 0x1D169], + [0x1D173, 0x1D182], + [0x1D185, 0x1D18B], + [0x1D1AA, 0x1D1AD], + [0x1D242, 0x1D244], + [0x1DA00, 0x1DA36], + [0x1DA3B, 0x1DA6C], + [0x1DA75, 0x1DA75], + [0x1DA84, 0x1DA84], + [0x1DA9B, 0x1DA9F], + [0x1DAA1, 0x1DAAF], + [0x1E000, 0x1E006], + [0x1E008, 0x1E018], + [0x1E01B, 0x1E021], + [0x1E023, 0x1E024], + [0x1E026, 0x1E02A], + [0x1E130, 0x1E136], + [0x1E2EC, 0x1E2EF], + [0x1E8D0, 0x1E8D6], + [0x1E944, 0x1E94A], + [0xE0001, 0xE0001], + [0xE0020, 0xE007F], + [0xE0100, 0xE01EF], +]; + +const BMP_WIDE = [ + [0x1100, 0x115F], + [0x231A, 0x231B], + [0x2329, 0x232A], + [0x23E9, 0x23EC], + [0x23F0, 0x23F0], + [0x23F3, 0x23F3], + [0x25FD, 0x25FE], + [0x2614, 0x2615], + [0x2648, 0x2653], + [0x267F, 0x267F], + [0x2693, 0x2693], + [0x26A1, 0x26A1], + [0x26AA, 0x26AB], + [0x26BD, 0x26BE], + [0x26C4, 0x26C5], + [0x26CE, 0x26CE], + [0x26D4, 0x26D4], + [0x26EA, 0x26EA], + [0x26F2, 0x26F3], + [0x26F5, 0x26F5], + [0x26FA, 0x26FA], + [0x26FD, 0x26FD], + [0x2705, 0x2705], + [0x270A, 0x270B], + [0x2728, 0x2728], + [0x274C, 0x274C], + [0x274E, 0x274E], + [0x2753, 0x2755], + [0x2757, 0x2757], + [0x2795, 0x2797], + [0x27B0, 0x27B0], + [0x27BF, 0x27BF], + [0x2B1B, 0x2B1C], + [0x2B50, 0x2B50], + [0x2B55, 0x2B55], + [0x2E80, 0x2E99], + [0x2E9B, 0x2EF3], + [0x2F00, 0x2FD5], + [0x2FF0, 0x2FFB], + [0x3000, 0x3029], + [0x302E, 0x303E], + [0x3041, 0x3096], + [0x309B, 0x30FF], + [0x3105, 0x312F], + [0x3131, 0x318E], + [0x3190, 0x31BA], + [0x31C0, 0x31E3], + [0x31F0, 0x321E], + [0x3220, 0x3247], + [0x3250, 0x4DBF], + [0x4E00, 0xA48C], + [0xA490, 0xA4C6], + [0xA960, 0xA97C], + [0xAC00, 0xD7A3], + [0xF900, 0xFAFF], + [0xFE10, 0xFE19], + [0xFE30, 0xFE52], + [0xFE54, 0xFE66], + [0xFE68, 0xFE6B], + [0xFF01, 0xFF60], + [0xFFE0, 0xFFE6], +]; + +const HIGH_WIDE = [ + [0x16FE0, 0x16FE3], + [0x17000, 0x187F7], + [0x18800, 0x18AF2], + [0x1B000, 0x1B11E], + [0x1B150, 0x1B152], + [0x1B164, 0x1B167], + [0x1B170, 0x1B2FB], + [0x1F004, 0x1F004], + [0x1F0CF, 0x1F0CF], + [0x1F18E, 0x1F18E], + [0x1F191, 0x1F19A], + [0x1F200, 0x1F202], + [0x1F210, 0x1F23B], + [0x1F240, 0x1F248], + [0x1F250, 0x1F251], + [0x1F260, 0x1F265], + [0x1F300, 0x1F320], + [0x1F32D, 0x1F335], + [0x1F337, 0x1F37C], + [0x1F37E, 0x1F393], + [0x1F3A0, 0x1F3CA], + [0x1F3CF, 0x1F3D3], + [0x1F3E0, 0x1F3F0], + [0x1F3F4, 0x1F3F4], + [0x1F3F8, 0x1F43E], + [0x1F440, 0x1F440], + [0x1F442, 0x1F4FC], + [0x1F4FF, 0x1F53D], + [0x1F54B, 0x1F54E], + [0x1F550, 0x1F567], + [0x1F57A, 0x1F57A], + [0x1F595, 0x1F596], + [0x1F5A4, 0x1F5A4], + [0x1F5FB, 0x1F64F], + [0x1F680, 0x1F6C5], + [0x1F6CC, 0x1F6CC], + [0x1F6D0, 0x1F6D2], + [0x1F6D5, 0x1F6D5], + [0x1F6EB, 0x1F6EC], + [0x1F6F4, 0x1F6FA], + [0x1F7E0, 0x1F7EB], + [0x1F90D, 0x1F971], + [0x1F973, 0x1F976], + [0x1F97A, 0x1F9A2], + [0x1F9A5, 0x1F9AA], + [0x1F9AE, 0x1F9CA], + [0x1F9CD, 0x1F9FF], + [0x1FA70, 0x1FA73], + [0x1FA78, 0x1FA7A], + [0x1FA80, 0x1FA82], + [0x1FA90, 0x1FA95], + [0x20000, 0x2FFFD], + [0x30000, 0x3FFFD], +]; + +final table = buildTable(); + +Uint8List buildTable() { + final table = Uint8List(65536); + table.fillRange(0, table.length, 1); + table[0] = 0; + table.fillRange(1, 32, 0); + table.fillRange(0x7f, 0xa0, 0); + for (var r = 0; r < BMP_COMBINING.length; ++r) { + table.fillRange(BMP_COMBINING[r][0], BMP_COMBINING[r][1] + 1, 0); + } + for (var r = 0; r < BMP_WIDE.length; ++r) { + table.fillRange(BMP_WIDE[r][0], BMP_WIDE[r][1] + 1, 2); + } + return table; +} + +bool bisearch(int ucs, List> data) { + var min = 0; + var max = data.length - 1; + int mid; + if (ucs < data[0][0] || ucs > data[max][1]) { + return false; + } + while (max >= min) { + mid = (min + max) >> 1; + if (ucs > data[mid][1]) { + min = mid + 1; + } else if (ucs < data[mid][0]) { + max = mid - 1; + } else { + return true; + } + } + return false; +} + +class UnicodeV11 { + final version = '11'; + + int wcwidth(int codePoint) { + if (codePoint < 32) return 0; + if (codePoint < 127) return 1; + if (codePoint < 65536) return table[codePoint]; + if (bisearch(codePoint, HIGH_COMBINING)) return 0; + if (bisearch(codePoint, HIGH_WIDE)) return 2; + return 1; + } +} + +final unicodeV11 = UnicodeV11(); diff --git a/app/third_party/xterm/lib/suggestion.dart b/app/third_party/xterm/lib/suggestion.dart new file mode 100644 index 00000000..4ca4f8dd --- /dev/null +++ b/app/third_party/xterm/lib/suggestion.dart @@ -0,0 +1,199 @@ +import 'dart:math'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +/// Controls the location of the suggestion popup of [SuggestionPortal]. +class SuggestionPortalController extends OverlayPortalController { + final _cursorRect = ValueNotifier(Rect.zero); + + /// Updates the location of the suggestion popup to [rect]. If the popup is + /// not showing, it will be shown after this call. + void update(Rect rect) { + _cursorRect.value = rect; + if (!isShowing) show(); + } +} + +/// A convenience widget to place a suggestion popup around the cursor specified +/// by [SuggestionPortalController]. +class SuggestionPortal extends StatefulWidget { + const SuggestionPortal({ + super.key, + required this.controller, + required this.overlayBuilder, + required this.child, + this.padding = const EdgeInsets.all(8), + this.cursorMargin = const EdgeInsets.all(4), + }); + + final SuggestionPortalController controller; + + final WidgetBuilder overlayBuilder; + + /// The minimum space between [child] and the screen edge. + final EdgeInsets padding; + + /// The minimum space between [child] and the cursor. Currently, only top and + /// bottom are used. + final EdgeInsets cursorMargin; + + final Widget child; + + @override + State createState() => _SuggestionPortalState(); +} + +class _SuggestionPortalState extends State { + @override + Widget build(BuildContext context) { + return OverlayPortal.targetsRootOverlay( + controller: widget.controller, + overlayChildBuilder: (context) { + return SuggestionLayout( + cursorRect: widget.controller._cursorRect, + padding: widget.padding, + cursorMargin: widget.cursorMargin, + child: widget.overlayBuilder(context), + ); + }, + child: widget.child, + ); + } +} + +/// A widget that places [child] around [cursorRect]. +class SuggestionLayout extends SingleChildRenderObjectWidget { + SuggestionLayout({ + super.child, + required this.cursorRect, + required this.padding, + required this.cursorMargin, + }); + + /// The location of the cursor relative to the top left corner of this widget. + final ValueListenable cursorRect; + + /// The minimum space between [child] and the edge of this widget. + final EdgeInsets padding; + + /// The minimum space between [child] and the cursor. Currently, only top and + /// bottom are used. + final EdgeInsets cursorMargin; + + @override + RenderObject createRenderObject(BuildContext context) { + return RenderCompletionLayout( + null, + cursorRect: cursorRect, + padding: padding, + cursorMargin: cursorMargin, + ); + } + + @override + void updateRenderObject( + BuildContext context, + covariant RenderCompletionLayout renderObject, + ) { + renderObject.cursorRect = cursorRect; + renderObject.padding = padding; + renderObject.cursorMargin = cursorMargin; + } +} + +class RenderCompletionLayout extends RenderShiftedBox { + RenderCompletionLayout( + super.child, { + required ValueListenable cursorRect, + required EdgeInsets padding, + required EdgeInsets cursorMargin, + }) : _cursorRect = cursorRect, + _padding = padding, + _cursorPadding = cursorMargin; + + ValueListenable _cursorRect; + ValueListenable get cursorRect => _cursorRect; + set cursorRect(ValueListenable value) { + if (_cursorRect == value) return; + _cursorRect.removeListener(markNeedsLayout); + _cursorRect = value; + _cursorRect.addListener(markNeedsLayout); + markNeedsLayout(); + } + + EdgeInsets _padding; + EdgeInsets get padding => _padding; + set padding(EdgeInsets value) { + if (_padding == value) return; + _padding = value; + markNeedsLayout(); + } + + EdgeInsets _cursorPadding; + EdgeInsets get cursorMargin => _cursorPadding; + set cursorMargin(EdgeInsets value) { + if (_cursorPadding == value) return; + _cursorPadding = value; + markNeedsLayout(); + } + + @override + void attach(covariant PipelineOwner owner) { + cursorRect.addListener(markNeedsLayout); + super.attach(owner); + } + + @override + void detach() { + cursorRect.removeListener(markNeedsLayout); + super.detach(); + } + + @override + void performLayout() { + final child = this.child; + + if (child == null) { + size = constraints.smallest; + return; + } + + size = constraints.biggest; + + // space available for the completion overlay above the cursor + final spaceAbove = cursorRect.value.top - padding.top - cursorMargin.top; + + // space available for the completion overlay below the cursor + final spaceBelow = size.height - + cursorRect.value.bottom - + padding.bottom - + cursorMargin.bottom; + + final childConstraints = BoxConstraints( + minWidth: 0, + maxWidth: size.width - padding.horizontal, + minHeight: 0, + maxHeight: max(spaceAbove, spaceBelow), + ); + + child.layout(childConstraints, parentUsesSize: true); + + // Whether the completion overlay can be placed above the cursor. + final fitsBelow = spaceBelow >= child.size.height; + + final childParentData = child.parentData as BoxParentData; + childParentData.offset = Offset( + min( + size.width - padding.right - child.size.width, + cursorRect.value.left, + ), + // Showing the completion overlay below the cursor is preferred, unless + // there's insufficient space for it. + fitsBelow + ? cursorRect.value.bottom + cursorMargin.bottom + : cursorRect.value.top - cursorMargin.top - child.size.height, + ); + } +} diff --git a/app/third_party/xterm/lib/ui.dart b/app/third_party/xterm/lib/ui.dart new file mode 100644 index 00000000..bc2c8a94 --- /dev/null +++ b/app/third_party/xterm/lib/ui.dart @@ -0,0 +1,10 @@ +export 'src/terminal_view.dart'; +export 'src/ui/controller.dart'; +export 'src/ui/cursor_type.dart'; +export 'src/ui/keyboard_visibility.dart'; +export 'src/ui/pointer_input.dart'; +export 'src/ui/selection_mode.dart'; +export 'src/ui/shortcut/shortcuts.dart'; +export 'src/ui/terminal_text_style.dart'; +export 'src/ui/terminal_theme.dart'; +export 'src/ui/themes.dart'; diff --git a/app/third_party/xterm/lib/utils.dart b/app/third_party/xterm/lib/utils.dart new file mode 100644 index 00000000..74c0abac --- /dev/null +++ b/app/third_party/xterm/lib/utils.dart @@ -0,0 +1,2 @@ +export 'src/utils/debugger.dart'; +export 'src/utils/debugger_view.dart'; diff --git a/app/third_party/xterm/lib/xterm.dart b/app/third_party/xterm/lib/xterm.dart new file mode 100644 index 00000000..60e7299d --- /dev/null +++ b/app/third_party/xterm/lib/xterm.dart @@ -0,0 +1,3 @@ +export 'core.dart'; +export 'ui.dart'; +export 'zmodem.dart'; diff --git a/app/third_party/xterm/lib/zmodem.dart b/app/third_party/xterm/lib/zmodem.dart new file mode 100644 index 00000000..6498e6d5 --- /dev/null +++ b/app/third_party/xterm/lib/zmodem.dart @@ -0,0 +1,312 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:zmodem/zmodem.dart'; + +export 'package:zmodem/zmodem.dart' show ZModemFileInfo; + +typedef ZModemInputHandler = void Function(String output); + +typedef ZModemOfferHandler = void Function(ZModemOffer offer); + +typedef ZModemRequestHandler = Future> Function(); + +abstract class ZModemOffer { + ZModemFileInfo get info; + + Stream accept(int offset); + + void skip(); +} + +class ZModemCallbackOffer implements ZModemOffer { + @override + final ZModemFileInfo info; + + final Stream Function(int offset) onAccept; + + final void Function()? onSkip; + + ZModemCallbackOffer(this.info, {required this.onAccept, this.onSkip}); + + @override + Stream accept(int offset) { + return onAccept(offset); + } + + @override + void skip() { + onSkip?.call(); + } +} + +final _zmodemSenderInit = '**\x18B0000000'.codeUnits; + +final _zmodemReceiverInit = '**\x18B0100000'.codeUnits; + +class ZModemMux { + /// Data from the underlying data channel. + final Stream stdout; + + /// The sink to write data to the underlying data channel. + final StreamSink> stdin; + + /// The callback to receive data that should be written to the terminal. + ZModemInputHandler? onTerminalInput; + + /// The callback to handle file receiving. If not set, all offers will be + /// skipped. + ZModemOfferHandler? onFileOffer; + + /// The callback to handle file sending. If not set, all requests will be + /// ignored. + ZModemRequestHandler? onFileRequest; + + ZModemMux({required this.stdin, required this.stdout}) { + _stdoutSubscription = stdout.listen(_handleStdout); + } + + /// Subscriptions to [stdout]. Used to pause/resume the stream when no more + /// space is available in local buffers. + late final StreamSubscription _stdoutSubscription; + + late final _terminalSink = StreamController>( + // onPause: _stdoutSubscription.pause, + // onResume: _stdoutSubscription.resume, + ) + ..stream + .transform(Utf8Decoder(allowMalformed: true)) + .listen(onTerminalInput); + + /// Current ZModem session. If null, no session is active. + ZModemCore? _session; + + /// The sink to write data when receiving a file. If null, no file is being + /// received. + StreamController? _receiveSink; + + /// Offers to send to the remote peer. If null, no offers are being sent. + Iterator? _fileOffers; + + /// Writes terminal output to the underlying connection. [input] may be + /// buffered if a ZModem session is active. + void terminalWrite(String input) { + if (_session == null) { + stdin.add(utf8.encode(input)); + } + } + + /// This is the entry point of multiplexing, dispatching data to ZModem or + /// terminal depending on the current state. + void _handleStdout(Uint8List chunk) { + if (_session != null) { + _handleZModem(chunk); + return; + } + + if (_detectZModem(chunk)) { + return; + } + + _terminalSink.add(chunk); + } + + /// Detects a ZModem session in [chunk] and starts it if found. Returns true + /// if a session was started. + bool _detectZModem(Uint8List chunk) { + final index = chunk.listIndexOf(_zmodemSenderInit) ?? + chunk.listIndexOf(_zmodemReceiverInit); + + if (index != null) { + _terminalSink.add(Uint8List.sublistView(chunk, 0, index)); + + _session = ZModemCore( + onPlainText: (text) { + _terminalSink.add([text]); + }, + ); + + _handleZModem(Uint8List.sublistView(chunk, index)); + return true; + } + + return false; + } + + void _handleZModem(Uint8List chunk) async { + for (final event in _session!.receive(chunk)) { + /// remote is sz + if (event is ZFileOfferedEvent) { + _handleZFileOfferedEvent(event); + } else if (event is ZFileDataEvent) { + _handleZFileDataEvent(event); + } else if (event is ZFileEndEvent) { + await _handleZFileEndEvent(event); + } else if (event is ZSessionFinishedEvent) { + await _handleZSessionFinishedEvent(event); + } + + /// remote is rz + else if (event is ZReadyToSendEvent) { + await _handleFileRequestEvent(event); + } else if (event is ZFileAcceptedEvent) { + await _handleFileAcceptedEvent(event); + } else if (event is ZFileSkippedEvent) { + _handleFileSkippedEvent(event); + } + + _flush(); + } + + _flush(); + } + + void _handleZFileOfferedEvent(ZFileOfferedEvent event) { + final onFileOffer = this.onFileOffer; + + if (onFileOffer == null) { + _session!.skipFile(); + return; + } + + onFileOffer(_createRemoteOffer(event.fileInfo)); + } + + void _handleZFileDataEvent(ZFileDataEvent event) { + _receiveSink!.add(event.data as Uint8List); + } + + Future _handleZFileEndEvent(ZFileEndEvent event) async { + await _closeReceiveSink(); + } + + Future _handleZSessionFinishedEvent(ZSessionFinishedEvent event) async { + _flush(); + await _reset(); + } + + Future _handleFileRequestEvent(ZReadyToSendEvent event) async { + _fileOffers ??= (await onFileRequest?.call())?.iterator; + + _moveToNextOffer(); + } + + Future _handleFileAcceptedEvent(ZFileAcceptedEvent event) async { + final data = _fileOffers!.current.accept(event.offset); + var bytesSent = 0; + + await stdin.addStream( + data.transform( + StreamTransformer.fromHandlers( + handleData: (chunk, sink) { + bytesSent += chunk.length; + _session!.sendFileData(chunk); + sink.add(_session!.dataToSend()); + }, + ), + ), + ); + + _session!.finishSending(event.offset + bytesSent); + } + + void _handleFileSkippedEvent(ZFileSkippedEvent event) { + _fileOffers!.current.skip(); + _moveToNextOffer(); + } + + /// Sends next file offer if available, or closes the session if not. + void _moveToNextOffer() { + if (_fileOffers?.moveNext() != true) { + _closeSession(); + return; + } + + _session!.offerFile(_fileOffers!.current.info); + } + + /// Creates a [ZModemOffer] ƒrom the info from remote peer that can be used + /// by local client to accept or skip the file. + ZModemOffer _createRemoteOffer(ZModemFileInfo fileInfo) { + return ZModemCallbackOffer( + fileInfo, + onAccept: (offset) { + _session!.acceptFile(offset); + _flush(); + + _createReceiveSink(); + return _receiveSink!.stream; + }, + onSkip: () { + _session!.skipFile(); + _flush(); + }, + ); + } + + void _createReceiveSink() { + _receiveSink = StreamController( + onPause: () { + // _stdoutSubscription.pause(); + }, + onResume: () { + // _stdoutSubscription.resume(); + }, + ); + } + + Future _closeReceiveSink() async { + _stdoutSubscription.resume(); + await _receiveSink?.close(); + _receiveSink = null; + } + + /// Requests remote to close the session. + void _closeSession() { + _session!.finishSession(); + } + + /// Clears all ZModem state. + Future _reset() async { + await _closeReceiveSink(); + _fileOffers = null; + _session = null; + } + + /// Sends all pending data packets to the remote. No data is automatically + /// sent to the remote without calling this method. + void _flush() { + final dataToSend = _session?.dataToSend(); + if (dataToSend != null && dataToSend.isNotEmpty) { + stdin.add(dataToSend); + } + } +} + +extension ListExtension on List { + String dump() { + return map((e) => e.toRadixString(16).padLeft(2, '0')).join(' '); + } + + int? listIndexOf(List other, [int start = 0]) { + if (other.length + start > length) { + return null; + } + for (var i = start; i < length - other.length; i++) { + if (this[i] == other[0]) { + var found = true; + for (var j = 1; j < other.length; j++) { + if (this[i + j] != other[j]) { + found = false; + break; + } + } + if (found) { + return i; + } + } + } + return null; + } +} diff --git a/app/third_party/xterm/pubspec.yaml b/app/third_party/xterm/pubspec.yaml new file mode 100644 index 00000000..945265ef --- /dev/null +++ b/app/third_party/xterm/pubspec.yaml @@ -0,0 +1,61 @@ +name: xterm +description: xterm.dart is a fast and fully-featured terminal emulator for Flutter applications, with support for mobile and desktop platforms. +version: 4.0.0 +homepage: https://github.com/TerminalStudio/xterm.dart + +environment: + sdk: ">=3.0.0 <4.0.0" + flutter: ">=3.19.0" + +dependencies: + convert: ^3.0.0 + meta: ^1.3.0 + quiver: ^3.0.0 + equatable: ^2.0.3 + flutter: + sdk: flutter + zmodem: ^0.0.6 + +dev_dependencies: + flutter_test: + sdk: flutter + test: ^1.6.5 + lints: ^3.0.0 + dart_code_metrics: ^5.0.0 + mockito: ^5.3.1 + build_runner: ^2.1.1 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter. +flutter: + # To add assets to your package, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + # + # For details regarding assets in packages, see + # https://flutter.dev/assets-and-images/#from-packages + # + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware. + # To add custom fonts to your package, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts in packages, see + # https://flutter.dev/custom-fonts/#from-packages From 5b47db180f1b537632618451d8a85f7091658935 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:20:08 +0000 Subject: [PATCH 02/17] Depend on the vendored xterm through a path dependency The app now builds against app/third_party/xterm instead of the pub.dev 4.0.0 release. The vendored package is excluded from the app's lints; its README records the upstream version and that we patch it. Co-Authored-By: Claude Opus 5.5 --- app/analysis_options.yaml | 5 +++++ app/pubspec.lock | 7 +++---- app/pubspec.yaml | 4 +++- app/third_party/xterm/README.md | 26 ++++++++++++++++++++++++++ 4 files changed, 37 insertions(+), 5 deletions(-) create mode 100644 app/third_party/xterm/README.md diff --git a/app/analysis_options.yaml b/app/analysis_options.yaml index 0d290213..53960603 100644 --- a/app/analysis_options.yaml +++ b/app/analysis_options.yaml @@ -9,6 +9,11 @@ # packages, and plugins designed to encourage good coding practices. include: package:flutter_lints/flutter.yaml +analyzer: + exclude: + # Vendored upstream package (path dependency) with its own style. + - third_party/** + linter: # The lint rules applied to this project can be customized in the # section below to disable rules from the `package:flutter_lints/flutter.yaml` diff --git a/app/pubspec.lock b/app/pubspec.lock index 2778d579..12a704f8 100644 --- a/app/pubspec.lock +++ b/app/pubspec.lock @@ -983,10 +983,9 @@ packages: xterm: dependency: "direct main" description: - name: xterm - sha256: "168dfedca77cba33fdb6f52e2cd001e9fde216e398e89335c19b524bb22da3a2" - url: "https://pub.dev" - source: hosted + path: "third_party/xterm" + relative: true + source: path version: "4.0.0" yaml: dependency: transitive diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 66c0294a..ee4340c9 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -47,7 +47,9 @@ dependencies: file_picker: ^13.3.0 url_launcher: ^6.3.3 bonsoir: ^7.1.5 - xterm: ^4.0.0 + # Vendored, patched xterm.dart 4.0.0; see third_party/xterm/README.md. + xterm: + path: third_party/xterm flutter_tts: ^4.2.3 dev_dependencies: diff --git a/app/third_party/xterm/README.md b/app/third_party/xterm/README.md new file mode 100644 index 00000000..fb792648 --- /dev/null +++ b/app/third_party/xterm/README.md @@ -0,0 +1,26 @@ +# xterm (vendored) + +This is our maintained copy of [xterm.dart](https://github.com/TerminalStudio/xterm.dart), +vendored from the pub.dev release **4.0.0** (MIT, see `LICENSE`; the upstream +README is kept as `UPSTREAM_README.md`). Upstream is unmaintained, so the app +depends on this directory through a path dependency and we patch it here. + +The commit that added this directory is the pristine upstream copy; every later +change is a local patch. Review them with `git log -p -- app/third_party/xterm`. + +Tests for the patches live in the app tree, `app/test/third_party_xterm/`, so they +run under the memory watchdog with the rest of the app tests. The app's +`analysis_options.yaml` excludes this directory from its strict lints; the code +still compiles as part of every app build. + +Local patches (keep this list current): + +- colon-form SGR subparameters (`4:3`, `38:2::r:g:b`, `58`/`59`) +- DCS/APC/PM/SOS strings consumed rather than printed +- full RIS (`ESC c`) reset +- DECSCUSR cursor shapes, SCOSC/SCORC, CHT, CBT, HPA, HPR, VPR +- OSC 10/11/12 colour queries, OSC 8/52/7 callbacks +- alternate screen 1049 cursor restore, separate DECCKM mode +- mouse wheel, drag/motion and middle-button reporting; Shift selection override +- cursor and attribute rendering (inverse block cursor, strikethrough, conceal) +- focus reporting (`?1004`) From e94f4856e39221a409749bab72f8346246779330 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:23:47 +0000 Subject: [PATCH 03/17] xterm: parse colon subparameters, intermediates and empty CSI params CSI parameters now record colon subparameters (ITU T.416), so SGR 4:3 is a curly underline instead of 4 and 3 = 43 (yellow background), and 38:2::r:g:b, 38:2:r:g:b and 38:5:n set colours. Underline styles 4:0-4:5 and 21 (double) are stored on the cell; 58/59 underline colours are consumed and ignored; 53/55 toggle overline; 22 clears bold and faint; truncated 38;5 no longer throws. Intermediate bytes and private prefixes are kept, so CSI > 4;2 m (modifyOtherKeys) is no longer applied as SGR. An empty parameter reads as 0 (default), so CSI ;5H and CSI 3H position the cursor. Co-Authored-By: Claude Opus 5.5 --- app/test/third_party_xterm/sgr_test.dart | 98 ++++ app/test/third_party_xterm/xterm_fixture.dart | 41 ++ app/third_party/xterm/lib/src/core/cell.dart | 7 + .../xterm/lib/src/core/cursor.dart | 26 +- .../xterm/lib/src/core/escape/handler.dart | 7 + .../xterm/lib/src/core/escape/parser.dart | 460 +++++------------- .../xterm/lib/src/core/escape/sgr.dart | 152 ++++++ app/third_party/xterm/lib/src/terminal.dart | 15 + .../xterm/lib/src/utils/debugger.dart | 15 + 9 files changed, 476 insertions(+), 345 deletions(-) create mode 100644 app/test/third_party_xterm/sgr_test.dart create mode 100644 app/test/third_party_xterm/xterm_fixture.dart create mode 100644 app/third_party/xterm/lib/src/core/escape/sgr.dart diff --git a/app/test/third_party_xterm/sgr_test.dart b/app/test/third_party_xterm/sgr_test.dart new file mode 100644 index 00000000..b3e90905 --- /dev/null +++ b/app/test/third_party_xterm/sgr_test.dart @@ -0,0 +1,98 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:xterm/xterm.dart'; + +import 'xterm_fixture.dart'; + +void main() { + CellData styled(String sgr) { + final t = FixtureTerminal()..feed('\x1b[${sgr}mX'); + return t.cell(0, 0); + } + + int underlineStyle(CellData cell) => cell.flags & CellAttr.underline == 0 + ? 0 + : (cell.flags & CellAttr.underlineStyleMask) >> + CellAttr.underlineStyleShift; + + test('4:3 is a curly underline, not a yellow background', () { + final cell = styled('4:3'); + expect(underlineStyle(cell), 3); + expect(cell.background, 0); + expect(cell.flags & CellAttr.italic, 0); + }); + + test('underline styles 4:0 to 4:5 and plain 4 / 24 / 21', () { + expect(underlineStyle(styled('4')), 1); + expect(underlineStyle(styled('4:0')), 0); + expect(underlineStyle(styled('4:1')), 1); + expect(underlineStyle(styled('4:2')), 2); + expect(underlineStyle(styled('4:4')), 4); + expect(underlineStyle(styled('4:5')), 5); + expect(underlineStyle(styled('4:3;24')), 0); + expect(underlineStyle(styled('4:3;4:0')), 0); + expect(underlineStyle(styled('21')), 2); + expect(styled('21').flags & CellAttr.bold, 0); + }); + + test('colon direct colours with and without a colour space id', () { + expect(styled('38:2::10:20:30').foreground, rgb(10, 20, 30)); + expect(styled('38:2:1:10:20:30').foreground, rgb(10, 20, 30)); + expect(styled('38:2:10:20:30').foreground, rgb(10, 20, 30)); + expect(styled('48:2::1:2:3').background, rgb(1, 2, 3)); + }); + + test('colon and semicolon indexed colours', () { + expect(styled('38:5:196').foreground, palette(196)); + expect(styled('48:5:21').background, palette(21)); + expect(styled('38;5;196').foreground, palette(196)); + expect(styled('38;2;1;2;3;1').foreground, rgb(1, 2, 3)); + expect(styled('38;2;1;2;3;1').flags & CellAttr.bold, isNot(0)); + }); + + test('colon groups end at the next semicolon', () { + final cell = styled('38:5:2;41;1'); + expect(cell.foreground, palette(2)); + expect(cell.background, named(NamedColor.red)); + expect(cell.flags & CellAttr.bold, isNot(0)); + }); + + test('underline colour 58 / 59 is consumed, not applied elsewhere', () { + var cell = styled('58:2::255:0:0;4:3'); + expect(cell.foreground, 0); + expect(cell.background, 0); + expect(underlineStyle(cell), 3); + cell = styled('58;5;9;1'); + expect(cell.foreground, 0); + expect(cell.flags & CellAttr.bold, isNot(0)); + cell = styled('58;2;1;2;3;59;7'); + expect(cell.flags & CellAttr.inverse, isNot(0)); + expect(cell.background, 0); + }); + + test('truncated extended colours do not throw or misapply', () { + expect(styled('38;5').foreground, 0); + expect(styled('38;2;1;2').foreground, 0); + expect(styled('48').background, 0); + }); + + test('22 clears bold and faint; 53/55 toggle overline', () { + expect(styled('1;2;22').flags & (CellAttr.bold | CellAttr.faint), 0); + expect(styled('53').flags & CellAttr.overline, isNot(0)); + expect(styled('53;55').flags & CellAttr.overline, 0); + }); + + test('a private-prefixed m (modifyOtherKeys) is not SGR', () { + final t = FixtureTerminal()..feed('\x1b[>4;2mX'); + expect(t.cell(0, 0).flags, 0); + expect(t.row(0), 'X'); + }); + + test('empty parameters default: CSI ; 5 H and CSI 3 H', () { + final t = FixtureTerminal()..feed('\x1b[;5H'); + expect(t.buffer.cursorX, 4); + expect(t.buffer.cursorY, 0); + t.feed('\x1b[3H'); + expect(t.buffer.cursorX, 0); + expect(t.buffer.cursorY, 2); + }); +} diff --git a/app/test/third_party_xterm/xterm_fixture.dart b/app/test/third_party_xterm/xterm_fixture.dart new file mode 100644 index 00000000..6dbce0e8 --- /dev/null +++ b/app/test/third_party_xterm/xterm_fixture.dart @@ -0,0 +1,41 @@ +import 'package:xterm/xterm.dart'; + +/// A terminal fed raw bytes in byte-fixture tests, with every reply it sends +/// to the program collected in [replies]. +class FixtureTerminal { + FixtureTerminal({int width = 20, int height = 5}) { + terminal.onOutput = replies.add; + terminal.resize(width, height); + } + + final terminal = Terminal(maxLines: 100); + final replies = []; + + Buffer get buffer => terminal.buffer; + + void feed(String bytes) => terminal.write(bytes); + + /// The text of screen row [y], trailing blanks trimmed. + String row(int y) => + buffer.lines[buffer.scrollBack + y].getText().trimRight(); + + /// The cell at column [x] of screen row [y]. + CellData cell(int x, int y) { + final data = CellData.empty(); + buffer.lines[buffer.scrollBack + y].getCellData(x, data); + return data; + } + + /// The replies sent so far, joined, and then forgotten. + String takeReplies() { + final all = replies.join(); + replies.clear(); + return all; + } +} + +int rgb(int r, int g, int b) => CellColor.rgb | (r << 16) | (g << 8) | b; + +int palette(int index) => CellColor.palette | index; + +int named(int index) => CellColor.named | index; diff --git a/app/third_party/xterm/lib/src/core/cell.dart b/app/third_party/xterm/lib/src/core/cell.dart index c52039ff..0ef0afd7 100644 --- a/app/third_party/xterm/lib/src/core/cell.dart +++ b/app/third_party/xterm/lib/src/core/cell.dart @@ -44,6 +44,13 @@ abstract class CellAttr { static const inverse = 1 << 5; static const invisible = 1 << 6; static const strikethrough = 1 << 7; + + /// The underline style while [underline] is set: 1 single (also 0), 2 + /// double, 3 curly, 4 dotted, 5 dashed. + static const underlineStyleShift = 8; + static const underlineStyleMask = 7 << underlineStyleShift; + + static const overline = 1 << 11; } 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 ce08610d..0bb3c17e 100644 --- a/app/third_party/xterm/lib/src/core/cursor.dart +++ b/app/third_party/xterm/lib/src/core/cursor.dart @@ -23,8 +23,19 @@ class CursorStyle { attrs |= CellAttr.italic; } - void setUnderline() { - attrs |= CellAttr.underline; + /// Turns underline on in [style] (see [CellAttr.underlineStyleMask]). + void setUnderline([int style = 1]) { + attrs = (attrs & ~CellAttr.underlineStyleMask) | + CellAttr.underline | + ((style & 7) << CellAttr.underlineStyleShift); + } + + void setOverline() { + attrs |= CellAttr.overline; + } + + void unsetOverline() { + attrs &= ~CellAttr.overline; } void setBlink() { @@ -56,7 +67,7 @@ class CursorStyle { } void unsetUnderline() { - attrs &= ~CellAttr.underline; + attrs &= ~(CellAttr.underline | CellAttr.underlineStyleMask); } void unsetBlink() { @@ -89,6 +100,15 @@ class CursorStyle { bool get isInvisible => (attrs & CellAttr.invisible) != 0; + bool get isStrikethrough => (attrs & CellAttr.strikethrough) != 0; + + bool get isOverline => (attrs & CellAttr.overline) != 0; + + /// The underline style (1-5), or 0 without underline. + int get underlineStyle => isUnderline + ? (attrs & CellAttr.underlineStyleMask) >> CellAttr.underlineStyleShift + : 0; + void setForegroundColor16(int color) { foreground = color | CellColor.named; } 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 166fb485..677cb2cb 100644 --- a/app/third_party/xterm/lib/src/core/escape/handler.dart +++ b/app/third_party/xterm/lib/src/core/escape/handler.dart @@ -163,6 +163,13 @@ abstract class EscapeHandler { void setCursorUnderline(); + /// Underline in [style]: 1 single, 2 double, 3 curly, 4 dotted, 5 dashed. + void setCursorUnderlineStyle(int style); + + void setCursorOverline(); + + void unsetCursorOverline(); + void setCursorBlink(); void setCursorInverse(); 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 0c7e74a9..ccb73d34 100644 --- a/app/third_party/xterm/lib/src/core/escape/parser.dart +++ b/app/third_party/xterm/lib/src/core/escape/parser.dart @@ -1,6 +1,6 @@ -import 'package:xterm/src/core/color.dart'; import 'package:xterm/src/core/mouse/mode.dart'; import 'package:xterm/src/core/escape/handler.dart'; +import 'package:xterm/src/core/escape/sgr.dart'; import 'package:xterm/src/utils/ascii.dart'; import 'package:xterm/src/utils/byte_consumer.dart'; import 'package:xterm/src/utils/char_code.dart'; @@ -193,10 +193,26 @@ class EscapeParser { final consumed = _consumeCsi(); if (!consumed) return false; - final csiHandler = _csiHandlers[_csi.finalByte]; + final finalByte = _csi.finalByte; + + // Sequences with intermediate bytes (`CSI Ps SP q`, `CSI ! p`, + // `CSI ? Ps $ p`) are functions distinct from the plain final byte. + if (_csi.intermediates != 0) { + _csiHandleWithIntermediates(); + return true; + } + + // A private prefix (`CSI > 4 ; 2 m`, `CSI ? u`) selects a different + // function too; only the handlers that read the prefix accept one. + if (_csi.prefix != null && !_prefixedFinalBytes.contains(finalByte)) { + handler.unknownCSI(finalByte); + return true; + } + + final csiHandler = _csiHandlers[finalByte]; if (csiHandler == null) { - handler.unknownCSI(_csi.finalByte); + handler.unknownCSI(finalByte); } else { csiHandler(); } @@ -204,30 +220,48 @@ class EscapeParser { return true; } + /// Final bytes whose handlers interpret a private prefix themselves. + static final _prefixedFinalBytes = { + 'c'.codeUnitAt(0), + 'h'.codeUnitAt(0), + 'l'.codeUnitAt(0), + 'n'.codeUnitAt(0), + 'J'.codeUnitAt(0), + 'K'.codeUnitAt(0), + }; + + /// Dispatches a CSI that carries intermediate bytes. + void _csiHandleWithIntermediates() { + handler.unknownCSI(_csi.finalByte); + } + /// The last parsed [_Csi]. This is a mutable singletion by design to reduce /// object allocations. - final _csi = _Csi(finalByte: 0, params: []); + final _csi = _Csi(); /// Parse a CSI from the head of the queue. Return false if the CSI isn't /// complete. After a CSI is successfully parsed, [_csi] is updated. + /// + /// Parameters are separated by `;`; a `:` introduces a subparameter of the + /// preceding parameter (ITU T.416, used by `4:3` and `38:2::r:g:b`). An + /// empty parameter reads as 0, so `CSI ; 5 H` has the parameters 0 and 5. bool _consumeCsi() { if (_queue.isEmpty) { return false; } - _csi.params.clear(); + _csi.reset(); // test whether the csi is a `CSI ? Ps ...` or `CSI Ps ...` final prefix = _queue.peek(); - if (prefix >= Ascii.colon && prefix <= Ascii.questionMark) { + if (prefix >= Ascii.lessThan && prefix <= Ascii.questionMark) { _csi.prefix = prefix; _queue.consume(); - } else { - _csi.prefix = null; } var param = 0; var hasParam = false; + var nextIsSub = false; while (true) { // The sequence isn't completed, just ignore it. if (_queue.isEmpty) { @@ -236,37 +270,42 @@ class EscapeParser { final char = _queue.consume(); - if (char == Ascii.semicolon) { - if (hasParam) { - _csi.params.add(param); - } - param = 0; - continue; - } - if (char >= Ascii.num0 && char <= Ascii.num9) { hasParam = true; - param *= 10; - param += char - Ascii.num0; + if (param < _maxParamValue) { + param = param * 10 + char - Ascii.num0; + } continue; } - if (char > Ascii.NULL && char < Ascii.num0) { - // intermediates.add(char); + if (char == Ascii.semicolon || char == Ascii.colon) { + _csi.add(param, nextIsSub); + nextIsSub = char == Ascii.colon; + param = 0; + hasParam = true; + continue; + } + + if (char >= Ascii.space && char < Ascii.num0) { + _csi.intermediates = (_csi.intermediates << 8 | char) & 0xFFFFFF; continue; } if (char >= Ascii.atSign && char <= Ascii.tilde) { if (hasParam) { - _csi.params.add(param); + _csi.add(param, nextIsSub); } _csi.finalByte = char; return true; } + + // Other bytes (C0 controls, stray private markers) are ignored. } } + static const _maxParamValue = 100000000; + late final _csiHandlers = FastLookupTable<_CsiHandler>({ // 'a'.codeUnitAt(0): _csiHandleCursorHorizontalRelative, 'b'.codeUnitAt(0): _csiHandleRepeatPreviousCharacter, @@ -314,12 +353,7 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_sb/ void _csiHandleRepeatPreviousCharacter() { - var amount = 1; - - if (_csi.params.isNotEmpty) { - amount = _csi.params[0]; - if (amount == 0) amount = 1; - } + final amount = _param(0); handler.repeatPreviousCharacter(amount); } @@ -342,28 +376,23 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_sd/ void _csiHandleLinePositionAbsolute() { - var y = 1; - - if (_csi.params.isNotEmpty) { - y = _csi.params[0]; - } - - handler.setCursorY(y - 1); + handler.setCursorY(_param(0) - 1); } /// `ESC [ Ps ; Ps f` Alias: Set Cursor Position /// /// https://terminalguide.namepad.de/seq/csi_sf/ void _csiHandleCursorPosition() { - var row = 1; - var col = 1; + handler.setCursor(_param(1) - 1, _param(0) - 1); + } - if (_csi.params.length == 2) { - row = _csi.params[0]; - col = _csi.params[1]; - } - - handler.setCursor(col - 1, row - 1); + /// The parameter at [index], or [fallback] when it is missing or 0 (an + /// empty parameter reads as 0, which means "default" for counts and + /// positions). + int _param(int index, [int fallback = 1]) { + final params = _csi.params; + if (index >= params.length || params[index] == 0) return fallback; + return params[index]; } /// `ESC [ Ps g` Tab Clear (TBC) @@ -408,215 +437,7 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_sm/ void _csiHandleSgr() { - final params = _csi.params; - - if (params.isEmpty) { - return handler.resetCursorStyle(); - } - - // This is a workaround for a bug in the analyzer. - // ignore: dead_code - for (var i = 0; i < _csi.params.length; i++) { - final param = params[i]; - switch (param) { - case 0: - handler.resetCursorStyle(); - continue; - case 1: - handler.setCursorBold(); - continue; - case 2: - handler.setCursorFaint(); - continue; - case 3: - handler.setCursorItalic(); - continue; - case 4: - handler.setCursorUnderline(); - continue; - case 5: - handler.setCursorBlink(); - continue; - case 7: - handler.setCursorInverse(); - continue; - case 8: - handler.setCursorInvisible(); - continue; - case 9: - handler.setCursorStrikethrough(); - continue; - - case 21: - handler.unsetCursorBold(); - continue; - case 22: - handler.unsetCursorFaint(); - continue; - case 23: - handler.unsetCursorItalic(); - continue; - case 24: - handler.unsetCursorUnderline(); - continue; - case 25: - handler.unsetCursorBlink(); - continue; - case 27: - handler.unsetCursorInverse(); - continue; - case 28: - handler.unsetCursorInvisible(); - continue; - case 29: - handler.unsetCursorStrikethrough(); - continue; - - case 30: - handler.setForegroundColor16(NamedColor.black); - continue; - case 31: - handler.setForegroundColor16(NamedColor.red); - continue; - case 32: - handler.setForegroundColor16(NamedColor.green); - continue; - case 33: - handler.setForegroundColor16(NamedColor.yellow); - continue; - case 34: - handler.setForegroundColor16(NamedColor.blue); - continue; - case 35: - handler.setForegroundColor16(NamedColor.magenta); - continue; - case 36: - handler.setForegroundColor16(NamedColor.cyan); - continue; - case 37: - handler.setForegroundColor16(NamedColor.white); - continue; - case 38: - final mode = params[i + 1]; - switch (mode) { - case 2: - final r = params[i + 2]; - final g = params[i + 3]; - final b = params[i + 4]; - handler.setForegroundColorRgb(r, g, b); - i += 4; - break; - case 5: - final index = params[i + 2]; - handler.setForegroundColor256(index); - i += 2; - break; - } - continue; - case 39: - handler.resetForeground(); - continue; - - case 40: - handler.setBackgroundColor16(NamedColor.black); - continue; - case 41: - handler.setBackgroundColor16(NamedColor.red); - continue; - case 42: - handler.setBackgroundColor16(NamedColor.green); - continue; - case 43: - handler.setBackgroundColor16(NamedColor.yellow); - continue; - case 44: - handler.setBackgroundColor16(NamedColor.blue); - continue; - case 45: - handler.setBackgroundColor16(NamedColor.magenta); - continue; - case 46: - handler.setBackgroundColor16(NamedColor.cyan); - continue; - case 47: - handler.setBackgroundColor16(NamedColor.white); - continue; - case 48: - final mode = params[i + 1]; - switch (mode) { - case 2: - final r = params[i + 2]; - final g = params[i + 3]; - final b = params[i + 4]; - handler.setBackgroundColorRgb(r, g, b); - i += 4; - break; - case 5: - final index = params[i + 2]; - handler.setBackgroundColor256(index); - i += 2; - break; - } - continue; - case 49: - handler.resetBackground(); - continue; - - case 90: - handler.setForegroundColor16(NamedColor.brightBlack); - continue; - case 91: - handler.setForegroundColor16(NamedColor.brightRed); - continue; - case 92: - handler.setForegroundColor16(NamedColor.brightGreen); - continue; - case 93: - handler.setForegroundColor16(NamedColor.brightYellow); - continue; - case 94: - handler.setForegroundColor16(NamedColor.brightBlue); - continue; - case 95: - handler.setForegroundColor16(NamedColor.brightMagenta); - continue; - case 96: - handler.setForegroundColor16(NamedColor.brightCyan); - continue; - case 97: - handler.setForegroundColor16(NamedColor.brightWhite); - continue; - - case 100: - handler.setBackgroundColor16(NamedColor.brightBlack); - continue; - case 101: - handler.setBackgroundColor16(NamedColor.brightRed); - continue; - case 102: - handler.setBackgroundColor16(NamedColor.brightGreen); - continue; - case 103: - handler.setBackgroundColor16(NamedColor.brightYellow); - continue; - case 104: - handler.setBackgroundColor16(NamedColor.brightBlue); - continue; - case 105: - handler.setBackgroundColor16(NamedColor.brightMagenta); - continue; - case 106: - handler.setBackgroundColor16(NamedColor.brightCyan); - continue; - case 107: - handler.setBackgroundColor16(NamedColor.brightWhite); - continue; - - default: - handler.unsupportedStyle(param); - continue; - } - } + applySgr(handler, _csi.rawParams, _csi.rawIsSub); } /// `ESC [ Ps n` Device Status Report [Dispatch] (DSR) @@ -637,20 +458,10 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_sr/ void _csiHandleSetMargins() { - var top = 1; - int? bottom; - if (_csi.params.length > 2) return; - if (_csi.params.isNotEmpty) { - top = _csi.params[0]; - - if (_csi.params.length == 2) { - bottom = _csi.params[1] - 1; - } - } - - handler.setMargins(top - 1, bottom); + final bottom = _param(1, 0); + handler.setMargins(_param(0) - 1, bottom == 0 ? null : bottom - 1); } /// `ESC [ Ps t` Window operations [DISPATCH] @@ -713,12 +524,7 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_ca/ void _csiHandleCursorUp() { - var amount = 1; - - if (_csi.params.isNotEmpty) { - amount = _csi.params[0]; - if (amount == 0) amount = 1; - } + final amount = _param(0); handler.moveCursorY(-amount); } @@ -727,12 +533,7 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_cb/ void _csiHandleCursorDown() { - var amount = 1; - - if (_csi.params.isNotEmpty) { - amount = _csi.params[0]; - if (amount == 0) amount = 1; - } + final amount = _param(0); handler.moveCursorY(amount); } @@ -741,12 +542,7 @@ class EscapeParser { /// /// Cursor Right (CUF) void _csiHandleCursorForward() { - var amount = 1; - - if (_csi.params.isNotEmpty) { - amount = _csi.params[0]; - if (amount == 0) amount = 1; - } + final amount = _param(0); handler.moveCursorX(amount); } @@ -755,12 +551,7 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_cd/ void _csiHandleCursorBackward() { - var amount = 1; - - if (_csi.params.isNotEmpty) { - amount = _csi.params[0]; - if (amount == 0) amount = 1; - } + final amount = _param(0); handler.moveCursorX(-amount); } @@ -769,12 +560,7 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_ce/ void _csiHandleCursorNextLine() { - var amount = 1; - - if (_csi.params.isNotEmpty) { - amount = _csi.params[0]; - if (amount == 0) amount = 1; - } + final amount = _param(0); handler.cursorNextLine(amount); } @@ -783,12 +569,7 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_cf/ void _csiHandleCursorPrecedingLine() { - var amount = 1; - - if (_csi.params.isNotEmpty) { - amount = _csi.params[0]; - if (amount == 0) amount = 1; - } + final amount = _param(0); handler.cursorPrecedingLine(amount); } @@ -850,11 +631,7 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_cl/ void _csiHandleInsertLines() { - var amount = 1; - - if (_csi.params.isNotEmpty) { - amount = _csi.params[0]; - } + final amount = _param(0); handler.insertLines(amount); } @@ -863,11 +640,7 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_cm/ void _csiHandleDeleteLines() { - var amount = 1; - - if (_csi.params.isNotEmpty) { - amount = _csi.params[0]; - } + final amount = _param(0); handler.deleteLines(amount); } @@ -876,11 +649,7 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_cp/ void _csiHandleDelete() { - var amount = 1; - - if (_csi.params.isNotEmpty) { - amount = _csi.params[0]; - } + final amount = _param(0); handler.deleteChars(amount); } @@ -889,11 +658,7 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_cs/ void _csiHandleScrollUp() { - var amount = 1; - - if (_csi.params.isNotEmpty) { - amount = _csi.params[0]; - } + final amount = _param(0); handler.scrollUp(amount); } @@ -902,11 +667,7 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_ct_1param/ void _csiHandleScrollDown() { - var amount = 1; - - if (_csi.params.isNotEmpty) { - amount = _csi.params[0]; - } + final amount = _param(0); handler.scrollDown(amount); } @@ -915,11 +676,7 @@ class EscapeParser { /// /// https://terminalguide.namepad.de/seq/csi_cx/ void _csiHandleEraseCharacters() { - var amount = 1; - - if (_csi.params.isNotEmpty) { - amount = _csi.params[0]; - } + final amount = _param(0); handler.eraseChars(amount); } @@ -932,11 +689,7 @@ class EscapeParser { /// contents to the right. The contents of the amount right-most columns in /// the scroll region are lost. The cursor position is not changed. void _csiHandleInsertBlankCharacters() { - var amount = 1; - - if (_csi.params.isNotEmpty) { - amount = _csi.params[0]; - } + final amount = _param(0); handler.insertBlankChars(amount); } @@ -1126,18 +879,41 @@ class EscapeParser { } class _Csi { - _Csi({ - required this.params, - required this.finalByte, - // required this.intermediates, - }); + /// At most this many parameters are kept; further ones are dropped. + static const maxParams = 32; int? prefix; - List params; + /// Intermediate bytes (0x20-0x2F), packed one per byte, last one lowest. + int intermediates = 0; - int finalByte; - // final List intermediates; + /// The parameters, not counting colon subparameters. + final List params = []; + + /// Every parameter including subparameters, in order. + final List rawParams = []; + + /// Whether the parameter at the same index of [rawParams] was introduced + /// by a colon. + final List rawIsSub = []; + + int finalByte = 0; + + void reset() { + prefix = null; + intermediates = 0; + params.clear(); + rawParams.clear(); + rawIsSub.clear(); + finalByte = 0; + } + + void add(int value, bool isSub) { + if (rawParams.length >= maxParams) return; + rawParams.add(value); + rawIsSub.add(isSub); + if (!isSub) params.add(value); + } @override String toString() { diff --git a/app/third_party/xterm/lib/src/core/escape/sgr.dart b/app/third_party/xterm/lib/src/core/escape/sgr.dart new file mode 100644 index 00000000..69e2b4e0 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/escape/sgr.dart @@ -0,0 +1,152 @@ +import 'package:xterm/src/core/color.dart'; +import 'package:xterm/src/core/escape/handler.dart'; + +/// Applies the parameters of `CSI Pm m` (SGR) to [handler]. +/// +/// [params] holds every parameter in order and [isSub] marks the ones that +/// were introduced by a colon, so a parameter followed by colon +/// subparameters forms one group: `4:3` is curly underline, not underline +/// followed by `3` (italic), and `38:2::r:g:b` is one direct colour. +/// +/// The legacy semicolon forms `38;5;n` and `38;2;r;g;b` consume the +/// parameters that follow. A truncated sequence stops processing instead of +/// reading past the end. +/// +/// https://terminalguide.namepad.de/seq/csi_sm/ +void applySgr(EscapeHandler handler, List params, List isSub) { + if (params.isEmpty) { + handler.resetCursorStyle(); + return; + } + + var i = 0; + while (i < params.length) { + final code = params[i++]; + + final subStart = i; + while (i < params.length && isSub[i]) { + i++; + } + final subCount = i - subStart; + + switch (code) { + case 0: + handler.resetCursorStyle(); + case 1: + handler.setCursorBold(); + case 2: + handler.setCursorFaint(); + case 3: + handler.setCursorItalic(); + case 4: + final style = subCount > 0 ? params[subStart] : 1; + if (style == 0) { + handler.unsetCursorUnderline(); + } else { + handler.setCursorUnderlineStyle(style > 5 ? 1 : style); + } + case 5: + case 6: + handler.setCursorBlink(); + case 7: + handler.setCursorInverse(); + case 8: + handler.setCursorInvisible(); + case 9: + handler.setCursorStrikethrough(); + case 21: + // ECMA-48 and xterm: doubly underlined (not "bold off"). + handler.setCursorUnderlineStyle(2); + case 22: + handler.unsetCursorBold(); + handler.unsetCursorFaint(); + case 23: + handler.unsetCursorItalic(); + case 24: + handler.unsetCursorUnderline(); + case 25: + handler.unsetCursorBlink(); + case 27: + handler.unsetCursorInverse(); + case 28: + handler.unsetCursorInvisible(); + case 29: + handler.unsetCursorStrikethrough(); + case >= 30 && <= 37: + handler.setForegroundColor16(NamedColor.black + code - 30); + case 38: + case 48: + case 58: + if (subCount > 0) { + _extendedColor(handler, code, params, subStart, subCount); + } else { + final used = _semicolonColorLength(params, isSub, i); + if (used < 0) return; // truncated: nothing sensible follows + _extendedColor(handler, code, params, i, used); + i += used; + } + case 39: + handler.resetForeground(); + case >= 40 && <= 47: + handler.setBackgroundColor16(NamedColor.black + code - 40); + case 49: + handler.resetBackground(); + case 53: + handler.setCursorOverline(); + case 55: + handler.unsetCursorOverline(); + case 59: + // Default underline colour; underline colours are not rendered. + break; + case >= 90 && <= 97: + handler.setForegroundColor16(NamedColor.brightBlack + code - 90); + case >= 100 && <= 107: + handler.setBackgroundColor16(NamedColor.brightBlack + code - 100); + default: + handler.unsupportedStyle(code); + } + } +} + +/// How many parameters after [at] the semicolon form of an extended colour +/// takes (`5;n` or `2;r;g;b`), or -1 when the sequence ends too early. +int _semicolonColorLength(List params, List isSub, int at) { + if (at >= params.length) return -1; + final needed = switch (params[at]) { + 5 => 2, + 2 => 4, + _ => 1, + }; + if (at + needed > params.length) return -1; + return needed; +} + +/// Applies an extended colour whose mode is `params[at]` and whose values +/// follow it, [count] parameters in all. [target] is 38 (foreground), 48 +/// (background) or 58 (underline colour, accepted and ignored). +void _extendedColor( + EscapeHandler handler, + int target, + List params, + int at, + int count, +) { + final mode = params[at]; + if (mode == 5 && count >= 2) { + final index = params[at + 1]; + if (index > 255) return; + if (target == 38) handler.setForegroundColor256(index); + if (target == 48) handler.setBackgroundColor256(index); + return; + } + if (mode == 2 && count >= 4) { + // `2:Pi:r:g:b` carries a colour space id first; `2:r:g:b` and the + // semicolon form `2;r;g;b` do not. + final rgbAt = count >= 5 ? at + 2 : at + 1; + final r = params[rgbAt].clamp(0, 255); + final g = params[rgbAt + 1].clamp(0, 255); + final b = params[rgbAt + 2].clamp(0, 255); + if (target == 38) handler.setForegroundColorRgb(r, g, b); + if (target == 48) handler.setBackgroundColorRgb(r, g, b); + } +} diff --git a/app/third_party/xterm/lib/src/terminal.dart b/app/third_party/xterm/lib/src/terminal.dart index 461e2084..95ca09e4 100644 --- a/app/third_party/xterm/lib/src/terminal.dart +++ b/app/third_party/xterm/lib/src/terminal.dart @@ -782,6 +782,21 @@ class Terminal with Observable implements TerminalState, EscapeHandler { _cursorStyle.setUnderline(); } + @override + void setCursorUnderlineStyle(int style) { + _cursorStyle.setUnderline(style); + } + + @override + void setCursorOverline() { + _cursorStyle.setOverline(); + } + + @override + void unsetCursorOverline() { + _cursorStyle.unsetOverline(); + } + @override void setCursorBlink() { _cursorStyle.setBlink(); diff --git a/app/third_party/xterm/lib/src/utils/debugger.dart b/app/third_party/xterm/lib/src/utils/debugger.dart index 303bbbbe..c7c2d54a 100644 --- a/app/third_party/xterm/lib/src/utils/debugger.dart +++ b/app/third_party/xterm/lib/src/utils/debugger.dart @@ -471,6 +471,21 @@ class _TerminalDebuggerHandler implements EscapeHandler { onCommand('setCursorUnderline'); } + @override + void setCursorUnderlineStyle(int style) { + onCommand('setCursorUnderlineStyle $style'); + } + + @override + void setCursorOverline() { + onCommand('setCursorOverline'); + } + + @override + void unsetCursorOverline() { + onCommand('unsetCursorOverline'); + } + @override void setCursorBlink() { onCommand('setCursorBlink'); From 7592aa1a82081347a3b85a1ce5e29ab71c6ad081 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:25:14 +0000 Subject: [PATCH 04/17] xterm: consume DCS, SOS, PM and APC strings; answer DECRQSS ESC P, ESC X, ESC ^ and ESC _ now open a control string whose body is swallowed up to ST (ESC \), across writes; CAN/SUB or a non-ST ESC abort it. Previously the bodies were printed (nvim's DECRQSS ESC P $qm ESC \ showed as "$qm"). DECRQSS m and r are answered with DCS 1 $ r ... ST, other requests with DCS 0 $ r ST. ESC ESC restarts the escape. Co-Authored-By: Claude Opus 5.5 --- .../control_string_test.dart | 61 +++++++++++++ .../xterm/lib/src/core/escape/handler.dart | 6 ++ .../xterm/lib/src/core/escape/parser.dart | 85 ++++++++++++++++++- .../lib/src/core/escape/status_report.dart | 40 +++++++++ app/third_party/xterm/lib/src/terminal.dart | 17 ++++ .../xterm/lib/src/utils/debugger.dart | 5 ++ 6 files changed, 213 insertions(+), 1 deletion(-) create mode 100644 app/test/third_party_xterm/control_string_test.dart create mode 100644 app/third_party/xterm/lib/src/core/escape/status_report.dart diff --git a/app/test/third_party_xterm/control_string_test.dart b/app/test/third_party_xterm/control_string_test.dart new file mode 100644 index 00000000..cd5084ea --- /dev/null +++ b/app/test/third_party_xterm/control_string_test.dart @@ -0,0 +1,61 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'xterm_fixture.dart'; + +void main() { + test('DCS, APC, PM and SOS bodies are swallowed, not printed', () { + final t = FixtureTerminal() + ..feed('a\x1bP+q544e\x1b\\b') + ..feed('\x1b_Gf=24;AAAA\x1b\\c') + ..feed('\x1b^private\x1b\\d') + ..feed('\x1bXstring\x1b\\e'); + expect(t.row(0), 'abcde'); + }); + + test('a control string split across writes is still swallowed', () { + final t = FixtureTerminal() + ..feed('x\x1bPtmux;') + ..feed('\x1b') + ..feed('\x1b[31mhidden') + ..feed('\x1b') + ..feed('\\y'); + // An ESC that is not ST aborts the string, as on a VT; the next ESC + // starts a CSI, so the output after it is ordinary text again. + expect(t.row(0), 'xhiddeny'); + expect(t.cell(1, 0).foreground, named(1)); + }); + + test('ST split between writes ends the string', () { + final t = FixtureTerminal() + ..feed('1\x1bPq#0;2;0;0;0#0~~@@') + ..feed('\x1b') + ..feed('\\2'); + expect(t.row(0), '12'); + }); + + test('CAN aborts a control string', () { + final t = FixtureTerminal()..feed('\x1bPjunk\x18ok'); + expect(t.row(0), 'ok'); + }); + + test('DECRQSS m reports the current SGR', () { + final t = FixtureTerminal()..feed('\x1b[1;4:3;38;5;196;48;2;1;2;3m'); + t.takeReplies(); + t.feed('\x1bP\$qm\x1b\\'); + expect(t.takeReplies(), '\x1bP1\$r0;1;4:3;38;5;196;48;2;1;2;3m\x1b\\'); + expect(t.row(0), ''); + }); + + test('DECRQSS r reports margins; unknown requests are refused', () { + final t = FixtureTerminal()..feed('\x1b[2;4r'); + t.feed('\x1bP\$qr\x1b\\'); + expect(t.takeReplies(), '\x1bP1\$r2;4r\x1b\\'); + t.feed('\x1bP\$qbogus\x1b\\'); + expect(t.takeReplies(), '\x1bP0\$r\x1b\\'); + }); + + test('a DCS other than DECRQSS sends nothing', () { + final t = FixtureTerminal()..feed('\x1bP+q544e\x1b\\'); + expect(t.takeReplies(), ''); + }); +} 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 677cb2cb..a38a55eb 100644 --- a/app/third_party/xterm/lib/src/core/escape/handler.dart +++ b/app/third_party/xterm/lib/src/core/escape/handler.dart @@ -39,6 +39,12 @@ abstract class EscapeHandler { void unkownEscape(int char); + /* DCS */ + + /// `DCS $ q Pt ST` (DECRQSS): report the setting named by [setting], such + /// as `m` (SGR), `r` (margins) or ` q` (cursor style). + void requestStatusString(String setting); + /* CSI */ void repeatPreviousCharacter(int n); 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 ccb73d34..cd096543 100644 --- a/app/third_party/xterm/lib/src/core/escape/parser.dart +++ b/app/third_party/xterm/lib/src/core/escape/parser.dart @@ -11,7 +11,8 @@ import 'package:xterm/src/utils/lookup_table.dart'; /// /// Design goals: /// * Zero object allocation during processing. -/// * No internal state. Same input will always produce same output. +/// * Little internal state: only an open control string (DCS, SOS, PM, +/// APC) is remembered between writes, so its body is never re-scanned. class EscapeParser { final EscapeHandler handler; @@ -33,6 +34,11 @@ class EscapeParser { void _process() { while (_queue.isNotEmpty) { + if (_stringKind != 0) { + if (!_consumeControlString()) return; + continue; + } + tokenBegin = _queue.totalConsumed; final char = _queue.consume(); @@ -69,6 +75,14 @@ class EscapeParser { if (_queue.isEmpty) return false; final escapeChar = _queue.consume(); + + // `ESC ESC`: the first escape is abandoned and the second one starts + // the sequence. + if (escapeChar == Ascii.ESC) { + _queue.rollback(1); + return true; + } + final escapeHandler = _escHandlers[escapeChar]; if (escapeHandler == null) { @@ -109,8 +123,77 @@ class EscapeParser { // '+'.charCode: _voidHandler(1), // TODO: G3 (vt220) '>'.charCode: _escHandleResetAppKeypadMode, // TODO: Normal Keypad '='.charCode: _escHandleSetAppKeypadMode, // TODO: Application Keypad + 'P'.charCode: () => _beginControlString(Ascii.P), // DCS + 'X'.charCode: () => _beginControlString(Ascii.X), // SOS + '^'.charCode: () => _beginControlString(Ascii.caret), // PM + '_'.charCode: () => _beginControlString(Ascii.underscore), // APC }); + /// The introducer (`P`, `X`, `^` or `_`) of the control string being + /// consumed, or 0 outside one. A control string spans writes, so this is + /// the parser's one piece of state: a long body (sixel, tmux passthrough) + /// is consumed as it arrives instead of being re-scanned. + var _stringKind = 0; + + /// The start of a DCS body, kept to answer requests such as DECRQSS. + final _stringBody = StringBuffer(); + + static const _maxStringBody = 256; + + bool _beginControlString(int kind) { + _stringKind = kind; + _stringBody.clear(); + return true; + } + + /// Consumes control string bytes up to the String Terminator `ESC \`. + /// The body is never printed. CAN or SUB abort the string; an ESC that + /// does not start ST aborts it and starts a new escape sequence. Returns + /// false when more input is needed. + bool _consumeControlString() { + while (_queue.isNotEmpty) { + final char = _queue.consume(); + + if (char == Ascii.ESC) { + if (_queue.isEmpty) { + _queue.rollback(1); + return false; + } + if (_queue.peek() == Ascii.backslash) { + _queue.consume(); + _finishControlString(dispatch: true); + } else { + _queue.rollback(1); + _finishControlString(dispatch: false); + } + return true; + } + + if (char == Ascii.CAN || char == Ascii.SUB) { + _finishControlString(dispatch: false); + return true; + } + + if (_stringKind == Ascii.P && _stringBody.length < _maxStringBody) { + _stringBody.writeCharCode(char); + } + } + return true; + } + + void _finishControlString({required bool dispatch}) { + final kind = _stringKind; + _stringKind = 0; + if (!dispatch || kind != Ascii.P) return; + + final body = _stringBody.toString(); + _stringBody.clear(); + // DECRQSS: `DCS $ q Pt ST` requests the setting named by Pt. + if (body.startsWith(r'$q')) { + handler.requestStatusString(body.substring(2)); + } + } + /// `ESC 7` Save Cursor (DECSC) /// /// https://terminalguide.namepad.de/seq/a_esc_a7/ diff --git a/app/third_party/xterm/lib/src/core/escape/status_report.dart b/app/third_party/xterm/lib/src/core/escape/status_report.dart new file mode 100644 index 00000000..b6816e09 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/escape/status_report.dart @@ -0,0 +1,40 @@ +import 'package:xterm/src/core/cell.dart'; +import 'package:xterm/src/core/cursor.dart'; + +/// The SGR parameters that recreate [style], for a DECRQSS `m` reply: +/// `0;1;38;5;196` and so on, always starting with a reset. +String sgrReport(CursorStyle style) { + final params = ['0']; + if (style.isBold) params.add('1'); + if (style.isFaint) params.add('2'); + if (style.isItalis) params.add('3'); + switch (style.underlineStyle) { + case 0: + break; + case 1: + params.add('4'); + default: + params.add('4:${style.underlineStyle}'); + } + if (style.isBlink) params.add('5'); + if (style.isInverse) params.add('7'); + if (style.isInvisible) params.add('8'); + if (style.isStrikethrough) params.add('9'); + if (style.isOverline) params.add('53'); + _color(params, style.foreground, 30, 90, 38); + _color(params, style.background, 40, 100, 48); + return params.join(';'); +} + +void _color(List params, int color, int base, int bright, int ext) { + final value = color & CellColor.valueMask; + switch (color & CellColor.typeMask) { + case CellColor.named: + params.add('${value < 8 ? base + value : bright + value - 8}'); + case CellColor.palette: + params.add('$ext;5;$value'); + case CellColor.rgb: + params + .add('$ext;2;${value >> 16};${(value >> 8) & 0xFF};${value & 0xFF}'); + } +} diff --git a/app/third_party/xterm/lib/src/terminal.dart b/app/third_party/xterm/lib/src/terminal.dart index 95ca09e4..613413b2 100644 --- a/app/third_party/xterm/lib/src/terminal.dart +++ b/app/third_party/xterm/lib/src/terminal.dart @@ -8,6 +8,7 @@ import 'package:xterm/src/core/cursor.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'; +import 'package:xterm/src/core/escape/status_report.dart'; import 'package:xterm/src/core/input/handler.dart'; import 'package:xterm/src/core/input/keys.dart'; import 'package:xterm/src/core/mouse/button.dart'; @@ -481,6 +482,22 @@ class Terminal with Observable implements TerminalState, EscapeHandler { // no-op } + /* DCS */ + + @override + void requestStatusString(String setting) { + final value = switch (setting) { + 'm' => '${sgrReport(_cursorStyle)}m', + 'r' => '${_buffer.marginTop + 1};${_buffer.marginBottom + 1}r', + _ => null, + }; + // `DCS 1 $ r Pt ST` reports a valid setting, `DCS 0 $ r ST` an + // unrecognised request. + onOutput?.call( + value == null ? '\x1bP0\$r\x1b\\' : '\x1bP1\$r$value\x1b\\', + ); + } + /* CSI */ @override diff --git a/app/third_party/xterm/lib/src/utils/debugger.dart b/app/third_party/xterm/lib/src/utils/debugger.dart index c7c2d54a..7f0319d8 100644 --- a/app/third_party/xterm/lib/src/utils/debugger.dart +++ b/app/third_party/xterm/lib/src/utils/debugger.dart @@ -471,6 +471,11 @@ class _TerminalDebuggerHandler implements EscapeHandler { onCommand('setCursorUnderline'); } + @override + void requestStatusString(String setting) { + onCommand('requestStatusString $setting'); + } + @override void setCursorUnderlineStyle(int style) { onCommand('setCursorUnderlineStyle $style'); From 326e7710d4ee57fcff00389271de3b51186fc33b Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:26:18 +0000 Subject: [PATCH 05/17] xterm: add SCOSC/SCORC, CHT, CBT, HPA, HPR and VPR; fix HTS CSI s / CSI u save and restore the cursor (without parameters; prefixed forms such as the kitty keyboard query CSI ? u are left alone). CSI I and CSI Z move by tab stops, CSI ` sets the column, CSI a and CSI e move relative. ESC H (HTS) set no tab stop because it called isSetAt. Co-Authored-By: Claude Opus 5.5 --- .../cursor_movement_test.dart | 60 +++++++++++++++++++ app/test/third_party_xterm/xterm_fixture.dart | 6 ++ .../xterm/lib/src/core/escape/handler.dart | 7 +++ .../xterm/lib/src/core/escape/parser.dart | 54 ++++++++++++++--- app/third_party/xterm/lib/src/core/tabs.dart | 10 ++++ app/third_party/xterm/lib/src/terminal.dart | 26 +++++++- .../xterm/lib/src/utils/debugger.dart | 10 ++++ 7 files changed, 164 insertions(+), 9 deletions(-) create mode 100644 app/test/third_party_xterm/cursor_movement_test.dart diff --git a/app/test/third_party_xterm/cursor_movement_test.dart b/app/test/third_party_xterm/cursor_movement_test.dart new file mode 100644 index 00000000..c932c482 --- /dev/null +++ b/app/test/third_party_xterm/cursor_movement_test.dart @@ -0,0 +1,60 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'xterm_fixture.dart'; + +void main() { + test('CSI s / CSI u save and restore the cursor (SCOSC / SCORC)', () { + final t = FixtureTerminal()..feed('\x1b[2;3H\x1b[s\x1b[5;9Hx\x1b[uy'); + expect(t.charAt(2, 1), 'y'); + expect(t.charAt(8, 4), 'x'); + expect(t.buffer.cursorX, 3); + expect(t.buffer.cursorY, 1); + }); + + test('CSI ? u (kitty keyboard query) does not restore the cursor', () { + final t = FixtureTerminal()..feed('\x1b[s\x1b[3;3H\x1b[?u'); + expect(t.buffer.cursorX, 2); + expect(t.buffer.cursorY, 2); + expect(t.takeReplies(), ''); + }); + + test('CHT moves forward by tab stops and stops at the last column', () { + final t = FixtureTerminal()..feed('\x1b[I'); + expect(t.buffer.cursorX, 8); + t.feed('\x1b[2I'); + expect(t.buffer.cursorX, 19); + }); + + test('CBT moves back by tab stops and stops at column 0', () { + final t = FixtureTerminal()..feed('\x1b[1;19H\x1b[Z'); + expect(t.buffer.cursorX, 16); + t.feed('\x1b[5Z'); + expect(t.buffer.cursorX, 0); + }); + + test('HTS sets a tab stop that HT and CBT use', () { + final t = FixtureTerminal()..feed('\x1b[1;4H\x1bH\r\t'); + expect(t.buffer.cursorX, 3); + t.feed('\x1b[1;7H\x1b[Z'); + expect(t.buffer.cursorX, 3); + }); + + test('HPA, HPR and VPR', () { + final t = FixtureTerminal()..feed('\x1b[7`'); + expect(t.buffer.cursorX, 6); + t.feed('\x1b[3a'); + expect(t.buffer.cursorX, 9); + t.feed('\x1b[a'); + expect(t.buffer.cursorX, 10); + t.feed('\x1b[2e'); + expect(t.buffer.cursorY, 2); + t.feed('\x1b[e'); + expect(t.buffer.cursorY, 3); + }); + + test('zero counts mean one', () { + final t = FixtureTerminal()..feed('\x1b[0C\x1b[0B'); + expect(t.buffer.cursorX, 1); + expect(t.buffer.cursorY, 1); + }); +} diff --git a/app/test/third_party_xterm/xterm_fixture.dart b/app/test/third_party_xterm/xterm_fixture.dart index 6dbce0e8..5975838e 100644 --- a/app/test/third_party_xterm/xterm_fixture.dart +++ b/app/test/third_party_xterm/xterm_fixture.dart @@ -26,6 +26,12 @@ class FixtureTerminal { return data; } + /// The character at column [x] of screen row [y], '' for an empty cell. + String charAt(int x, int y) { + final code = cell(x, y).content & CellContent.codepointMask; + return code == 0 ? '' : String.fromCharCode(code); + } + /// The replies sent so far, joined, and then forgotten. String takeReplies() { final all = replies.join(); 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 a38a55eb..c13a4b85 100644 --- a/app/third_party/xterm/lib/src/core/escape/handler.dart +++ b/app/third_party/xterm/lib/src/core/escape/handler.dart @@ -79,6 +79,13 @@ abstract class EscapeHandler { void cursorPrecedingLine(int amount); + /// Moves the cursor forward [amount] tab stops (CHT), stopping at the last + /// column. + void cursorForwardTab(int amount); + + /// Moves the cursor back [amount] tab stops (CBT), stopping at column 0. + void cursorBackwardTab(int amount); + void eraseDisplayBelow(); void eraseDisplayAbove(); 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 cd096543..81ba6abc 100644 --- a/app/third_party/xterm/lib/src/core/escape/parser.dart +++ b/app/third_party/xterm/lib/src/core/escape/parser.dart @@ -390,7 +390,13 @@ class EscapeParser { static const _maxParamValue = 100000000; late final _csiHandlers = FastLookupTable<_CsiHandler>({ - // 'a'.codeUnitAt(0): _csiHandleCursorHorizontalRelative, + 'a'.codeUnitAt(0): _csiHandleCursorHorizontalRelative, + '`'.codeUnitAt(0): _csiHandleCursorHorizontalAbsolute, + 'e'.codeUnitAt(0): _csiHandleCursorVerticalRelative, + 'I'.codeUnitAt(0): _csiHandleCursorForwardTab, + 'Z'.codeUnitAt(0): _csiHandleCursorBackwardTab, + 's'.codeUnitAt(0): _csiHandleSaveCursor, + 'u'.codeUnitAt(0): _csiHandleRestoreCursor, 'b'.codeUnitAt(0): _csiHandleRepeatPreviousCharacter, 'c'.codeUnitAt(0): _csiHandleSendDeviceAttributes, 'd'.codeUnitAt(0): _csiHandleLinePositionAbsolute, @@ -424,13 +430,45 @@ class EscapeParser { /// `ESC [ Ps a` Cursor Horizontal Position Relative (HPR) /// /// https://terminalguide.namepad.de/seq/csi_sa/ - // void _csiHandleCursorHorizontalRelative() { - // if (_csi.params.isEmpty) { - // handler.cursorHorizontal(1); - // } else { - // handler.cursorHorizontal(_csi.params[0]); - // } - // } + void _csiHandleCursorHorizontalRelative() { + handler.moveCursorX(_param(0)); + } + + /// `ESC [ Ps e` Cursor Vertical Position Relative (VPR) + /// + /// https://terminalguide.namepad.de/seq/csi_se/ + void _csiHandleCursorVerticalRelative() { + handler.moveCursorY(_param(0)); + } + + /// `ESC [ Ps I` Cursor Horizontal Forward Tabulation (CHT) + /// + /// https://terminalguide.namepad.de/seq/csi_ci/ + void _csiHandleCursorForwardTab() { + handler.cursorForwardTab(_param(0)); + } + + /// `ESC [ Ps Z` Cursor Backward Tabulation (CBT) + /// + /// https://terminalguide.namepad.de/seq/csi_cz/ + void _csiHandleCursorBackwardTab() { + handler.cursorBackwardTab(_param(0)); + } + + /// `ESC [ s` Save Cursor (SCOSC). With parameters this would be DECSLRM + /// (left and right margins), which is not supported. + /// + /// https://terminalguide.namepad.de/seq/csi_ss/ + void _csiHandleSaveCursor() { + if (_csi.params.isEmpty) handler.saveCursor(); + } + + /// `ESC [ u` Restore Cursor (SCORC) + /// + /// https://terminalguide.namepad.de/seq/csi_su/ + void _csiHandleRestoreCursor() { + if (_csi.params.isEmpty) handler.restoreCursor(); + } /// `ESC [ Ps b` Repeat Previous Character (REP) /// diff --git a/app/third_party/xterm/lib/src/core/tabs.dart b/app/third_party/xterm/lib/src/core/tabs.dart index 385f9499..6ac2c052 100644 --- a/app/third_party/xterm/lib/src/core/tabs.dart +++ b/app/third_party/xterm/lib/src/core/tabs.dart @@ -32,6 +32,16 @@ class TabStops { return null; } + /// Finds the closest tab stop index below [start], or null without one. + int? findPrevious(int start) { + for (var i = min(start, _stops.length) - 1; i >= 0; i--) { + if (_stops[i]) { + return i; + } + } + return null; + } + /// Sets the tab stop at [index]. If there is already a tab stop at [index], /// this method does nothing. /// diff --git a/app/third_party/xterm/lib/src/terminal.dart b/app/third_party/xterm/lib/src/terminal.dart index 613413b2..523776e4 100644 --- a/app/third_party/xterm/lib/src/terminal.dart +++ b/app/third_party/xterm/lib/src/terminal.dart @@ -464,7 +464,7 @@ class Terminal with Observable implements TerminalState, EscapeHandler { @override void setTapStop() { - _tabStops.isSetAt(_buffer.cursorX); + _tabStops.setAt(_buffer.cursorX); } @override @@ -588,6 +588,30 @@ class Terminal with Observable implements TerminalState, EscapeHandler { _buffer.setCursorX(0); } + @override + void cursorForwardTab(int amount) { + for (var i = 0; i < amount; i++) { + final next = _tabStops.find(_buffer.cursorX + 1, _viewWidth); + if (next == null) { + _buffer.setCursorX(_viewWidth - 1); + return; + } + _buffer.setCursorX(next); + } + } + + @override + void cursorBackwardTab(int amount) { + for (var i = 0; i < amount; i++) { + final previous = _tabStops.findPrevious(_buffer.cursorX); + if (previous == null) { + _buffer.setCursorX(0); + return; + } + _buffer.setCursorX(previous); + } + } + @override void eraseDisplayBelow() { _buffer.eraseDisplayFromCursor(); diff --git a/app/third_party/xterm/lib/src/utils/debugger.dart b/app/third_party/xterm/lib/src/utils/debugger.dart index 7f0319d8..04323e6e 100644 --- a/app/third_party/xterm/lib/src/utils/debugger.dart +++ b/app/third_party/xterm/lib/src/utils/debugger.dart @@ -471,6 +471,16 @@ class _TerminalDebuggerHandler implements EscapeHandler { onCommand('setCursorUnderline'); } + @override + void cursorForwardTab(int amount) { + onCommand('cursorForwardTab $amount'); + } + + @override + void cursorBackwardTab(int amount) { + onCommand('cursorBackwardTab $amount'); + } + @override void requestStatusString(String setting) { onCommand('requestStatusString $setting'); From 30b32921fe528ac5e5752be19a2c00bc62b6ff06 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:26:47 +0000 Subject: [PATCH 06/17] xterm: restore the cursor leaving 1049; arrow keys follow DECCKM Resetting mode 1049 switched back to the main screen without restoring the cursor saved when it was set. The keytab input handler read application cursor keys from the keypad mode (DECKPAM) instead of DECCKM (CSI ?1 h/l); Terminal.cursorKeysMode is the mode to read. Co-Authored-By: Claude Opus 5.5 --- app/test/third_party_xterm/modes_test.dart | 45 +++++++++++++++++++ .../xterm/lib/src/core/escape/parser.dart | 2 + .../xterm/lib/src/core/input/handler.dart | 2 +- 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 app/test/third_party_xterm/modes_test.dart diff --git a/app/test/third_party_xterm/modes_test.dart b/app/test/third_party_xterm/modes_test.dart new file mode 100644 index 00000000..09ec8b96 --- /dev/null +++ b/app/test/third_party_xterm/modes_test.dart @@ -0,0 +1,45 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:xterm/xterm.dart'; + +import 'xterm_fixture.dart'; + +void main() { + test('leaving the 1049 alternate screen restores the saved cursor', () { + final t = FixtureTerminal()..feed('main\x1b[3;5H\x1b[31m'); + t.feed('\x1b[?1049h'); + expect(t.terminal.isUsingAltBuffer, isTrue); + t.feed('\x1b[1;1H\x1b[0malt screen'); + t.feed('\x1b[?1049l'); + expect(t.terminal.isUsingAltBuffer, isFalse); + expect(t.buffer.cursorX, 4); + expect(t.buffer.cursorY, 2); + expect(t.row(0), 'main'); + t.feed('z'); + expect(t.cell(4, 2).foreground, named(NamedColor.red)); + }); + + test('DECCKM (CSI ? 1 h/l) is its own mode, not the keypad mode', () { + final t = FixtureTerminal(); + expect(t.terminal.cursorKeysMode, isFalse); + t.feed('\x1b[?1h'); + expect(t.terminal.cursorKeysMode, isTrue); + expect(t.terminal.appKeypadMode, isFalse); + t.feed('\x1b[?1l\x1b='); + expect(t.terminal.cursorKeysMode, isFalse); + expect(t.terminal.appKeypadMode, isTrue); + }); + + test('arrow keys follow DECCKM, not DECKPAM', () { + final t = FixtureTerminal(); + t.terminal.keyInput(TerminalKey.arrowUp); + expect(t.takeReplies(), '\x1b[A'); + + t.feed('\x1b='); + t.terminal.keyInput(TerminalKey.arrowUp); + expect(t.takeReplies(), '\x1b[A'); + + t.feed('\x1b>\x1b[?1h'); + t.terminal.keyInput(TerminalKey.arrowUp); + expect(t.takeReplies(), '\x1bOA'); + }); +} 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 81ba6abc..15d09ef8 100644 --- a/app/third_party/xterm/lib/src/core/escape/parser.dart +++ b/app/third_party/xterm/lib/src/core/escape/parser.dart @@ -908,7 +908,9 @@ class EscapeParser { handler.clearAltBuffer(); handler.useAltBuffer(); } else { + // The cursor was saved on the main screen when 1049 was set. handler.useMainBuffer(); + handler.restoreCursor(); } return; case 2004: diff --git a/app/third_party/xterm/lib/src/core/input/handler.dart b/app/third_party/xterm/lib/src/core/input/handler.dart index 6a8ed70b..943ba67d 100644 --- a/app/third_party/xterm/lib/src/core/input/handler.dart +++ b/app/third_party/xterm/lib/src/core/input/handler.dart @@ -116,7 +116,7 @@ class KeytabInputHandler implements TerminalInputHandler { alt: event.alt, shift: event.shift, newLineMode: event.state.lineFeedMode, - appCursorKeys: event.state.appKeypadMode, + appCursorKeys: event.state.cursorKeysMode, appKeyPad: event.state.appKeypadMode, appScreen: event.altBuffer, macos: event.platform == TerminalTargetPlatform.macos, From 31d00e057c8a9ccceff013883dd21efed98b7e3f Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:27:50 +0000 Subject: [PATCH 07/17] xterm: implement RIS (ESC c) and DECSTR (CSI ! p) ESC c was ignored, so `reset` could not recover a terminal left in the alternate screen with a hidden cursor, a scroll region or mouse modes. RIS now resets every mode, the attributes, character sets, tab stops, margins and saved cursors, returns to the main screen and clears it (scrollback is kept, as in xterm). DECSTR resets modes, attributes and margins without touching the text. Co-Authored-By: Claude Opus 5.5 --- app/test/third_party_xterm/reset_test.dart | 75 +++++++++++++++++++ .../xterm/lib/src/core/buffer/buffer.dart | 13 ++++ .../xterm/lib/src/core/charset.dart | 9 +++ .../xterm/lib/src/core/escape/handler.dart | 7 ++ .../xterm/lib/src/core/escape/parser.dart | 22 +++++- app/third_party/xterm/lib/src/terminal.dart | 39 ++++++++++ .../xterm/lib/src/utils/debugger.dart | 10 +++ 7 files changed, 174 insertions(+), 1 deletion(-) create mode 100644 app/test/third_party_xterm/reset_test.dart diff --git a/app/test/third_party_xterm/reset_test.dart b/app/test/third_party_xterm/reset_test.dart new file mode 100644 index 00000000..d6839067 --- /dev/null +++ b/app/test/third_party_xterm/reset_test.dart @@ -0,0 +1,75 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:xterm/xterm.dart'; + +import 'xterm_fixture.dart'; + +void main() { + /// Puts the terminal in the state a crashed full-screen program leaves. + FixtureTerminal messedUp() { + return FixtureTerminal()..feed( + 'shell\r\n' + '\x1b[?1049h' // alternate screen + '\x1b[2;4r' // scroll region + '\x1b[?25l' // cursor hidden + '\x1b[?1h\x1b=' // application cursor keys and keypad + '\x1b[?7l\x1b[4h\x1b[?6h' // no autowrap, insert, origin + '\x1b[?1002h\x1b[?1006h\x1b[?2004h\x1b[?1004h' // mouse, paste, focus + '\x1b(0' // DEC graphics in G0 + '\x1b[1;7;38;5;9m' // attributes + '\x1b[3;3Hjunk', + ); + } + + test('RIS (ESC c) recovers every mode, the screen and the cursor', () { + final t = messedUp()..feed('\x1bc'); + final term = t.terminal; + + expect(term.isUsingAltBuffer, isFalse); + expect(term.cursorVisibleMode, isTrue); + expect(term.cursorKeysMode, isFalse); + expect(term.appKeypadMode, isFalse); + expect(term.autoWrapMode, isTrue); + expect(term.insertMode, isFalse); + expect(term.originMode, isFalse); + expect(term.mouseMode, MouseMode.none); + expect(term.mouseReportMode, MouseReportMode.normal); + expect(term.bracketedPasteMode, isFalse); + expect(term.reportFocusMode, isFalse); + expect(t.buffer.marginTop, 0); + expect(t.buffer.marginBottom, 4); + expect(t.buffer.cursorX, 0); + expect(t.buffer.cursorY, 0); + for (var y = 0; y < 5; y++) { + expect(t.row(y), '', reason: 'row $y is cleared'); + } + + // Plain ASCII and plain attributes again. + t.feed('q'); + expect(t.charAt(0, 0), 'q'); + expect(t.cell(0, 0).flags, 0); + expect(t.cell(0, 0).foreground, 0); + }); + + test('RIS keeps the main screen scrollback', () { + final t = FixtureTerminal(); + for (var i = 0; i < 8; i++) { + t.feed('line $i\r\n'); + } + final scrollBack = t.buffer.scrollBack; + t.feed('\x1bc'); + expect(t.buffer.scrollBack, scrollBack); + expect(t.buffer.lines[0].getText().trimRight(), 'line 0'); + }); + + test('DECSTR (CSI ! p) resets modes and attributes but keeps the text', () { + final t = FixtureTerminal() + ..feed('keep\x1b[?25l\x1b[?1h\x1b[2;4r\x1b[4h\x1b[1m\x1b[!p'); + expect(t.row(0), 'keep'); + expect(t.terminal.cursorVisibleMode, isTrue); + expect(t.terminal.cursorKeysMode, isFalse); + expect(t.terminal.insertMode, isFalse); + expect(t.terminal.cursor.attrs, 0); + expect(t.buffer.marginTop, 0); + expect(t.buffer.marginBottom, 4); + }); +} 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 10789382..44e7df0b 100644 --- a/app/third_party/xterm/lib/src/core/buffer/buffer.dart +++ b/app/third_party/xterm/lib/src/core/buffer/buffer.dart @@ -338,6 +338,19 @@ class Buffer { charset.restore(); } + /// Resets the cursor, the saved cursor, the character sets and the + /// margins to their power-on state (for RIS and DECSTR). The contents are + /// left alone. + void resetState() { + _cursorX = 0; + _cursorY = 0; + _savedCursorX = 0; + _savedCursorY = 0; + _savedCursorStyle.reset(); + charset.reset(); + resetVerticalMargins(); + } + /// Sets the vertical scrolling margin to [top] and [bottom]. /// Both values must be between 0 and [viewHeight] - 1. void setVerticalMargins(int top, int bottom) { diff --git a/app/third_party/xterm/lib/src/core/charset.dart b/app/third_party/xterm/lib/src/core/charset.dart index 3659810a..d062368c 100644 --- a/app/third_party/xterm/lib/src/core/charset.dart +++ b/app/third_party/xterm/lib/src/core/charset.dart @@ -40,6 +40,15 @@ class Charset { _savedIndex = _currentIndex; } + /// Back to G0 selected and no designations (ASCII), as after power-on. + void reset() { + _charsetMap = {}; + _currentIndex = 0; + _savedCharsetMap = {}; + _savedIndex = 0; + _updateCache(); + } + void restore() { _charsetMap = _savedCharsetMap; _currentIndex = _savedIndex; 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 c13a4b85..50d1f82b 100644 --- a/app/third_party/xterm/lib/src/core/escape/handler.dart +++ b/app/third_party/xterm/lib/src/core/escape/handler.dart @@ -39,6 +39,13 @@ abstract class EscapeHandler { void unkownEscape(int char); + /// `ESC c` (RIS): everything back to the power-on state, screen cleared. + void resetTerminal(); + + /// `CSI ! p` (DECSTR): modes, attributes and margins reset; the screen + /// contents stay. + void softResetTerminal(); + /* DCS */ /// `DCS $ q Pt ST` (DECRQSS): report the setting named by [setting], such 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 15d09ef8..2b82bf3e 100644 --- a/app/third_party/xterm/lib/src/core/escape/parser.dart +++ b/app/third_party/xterm/lib/src/core/escape/parser.dart @@ -123,6 +123,7 @@ class EscapeParser { // '+'.charCode: _voidHandler(1), // TODO: G3 (vt220) '>'.charCode: _escHandleResetAppKeypadMode, // TODO: Normal Keypad '='.charCode: _escHandleSetAppKeypadMode, // TODO: Application Keypad + 'c'.charCode: _escHandleReset, 'P'.charCode: () => _beginControlString(Ascii.P), // DCS 'X'.charCode: () => _beginControlString(Ascii.X), // SOS '^'.charCode: () => _beginControlString(Ascii.caret), // PM @@ -194,6 +195,14 @@ class EscapeParser { } } + /// `ESC c` Reset to Initial State (RIS) + /// + /// https://terminalguide.namepad.de/seq/a_esc_sc/ + bool _escHandleReset() { + handler.resetTerminal(); + return true; + } + /// `ESC 7` Save Cursor (DECSC) /// /// https://terminalguide.namepad.de/seq/a_esc_a7/ @@ -315,7 +324,18 @@ class EscapeParser { /// Dispatches a CSI that carries intermediate bytes. void _csiHandleWithIntermediates() { - handler.unknownCSI(_csi.finalByte); + final finalByte = _csi.finalByte; + final intermediates = _csi.intermediates; + + // `CSI ! p` Soft Terminal Reset (DECSTR) + if (intermediates == Ascii.exclamationMark && + finalByte == Ascii.p && + _csi.prefix == null) { + handler.softResetTerminal(); + return; + } + + handler.unknownCSI(finalByte); } /// The last parsed [_Csi]. This is a mutable singletion by design to reduce diff --git a/app/third_party/xterm/lib/src/terminal.dart b/app/third_party/xterm/lib/src/terminal.dart index 523776e4..b3d2426e 100644 --- a/app/third_party/xterm/lib/src/terminal.dart +++ b/app/third_party/xterm/lib/src/terminal.dart @@ -482,6 +482,45 @@ class Terminal with Observable implements TerminalState, EscapeHandler { // no-op } + @override + void resetTerminal() { + _resetModes(); + _mouseMode = MouseMode.none; + _mouseReportMode = MouseReportMode.normal; + _cursorBlinkMode = false; + _lineFeedMode = false; + _reverseDisplayMode = false; + _reportFocusMode = false; + _altBufferMouseScrollMode = false; + _bracketedPasteMode = false; + _precedingCodepoint = 0; + _tabStops.reset(); + + _buffer = _mainBuffer; + _altBuffer.clear(); + _altBuffer.resetState(); + _mainBuffer.resetState(); + // The screen is cleared; scrollback above it is kept, as in xterm. + _mainBuffer.eraseDisplay(); + } + + @override + void softResetTerminal() { + _resetModes(); + _buffer.resetState(); + } + + /// The state shared by RIS and DECSTR. + void _resetModes() { + _cursorStyle.reset(); + _insertMode = false; + _originMode = false; + _autoWrapMode = true; + _cursorKeysMode = false; + _appKeypadMode = false; + _cursorVisibleMode = true; + } + /* DCS */ @override diff --git a/app/third_party/xterm/lib/src/utils/debugger.dart b/app/third_party/xterm/lib/src/utils/debugger.dart index 04323e6e..4a15f905 100644 --- a/app/third_party/xterm/lib/src/utils/debugger.dart +++ b/app/third_party/xterm/lib/src/utils/debugger.dart @@ -471,6 +471,16 @@ class _TerminalDebuggerHandler implements EscapeHandler { onCommand('setCursorUnderline'); } + @override + void resetTerminal() { + onCommand('resetTerminal'); + } + + @override + void softResetTerminal() { + onCommand('softResetTerminal'); + } + @override void cursorForwardTab(int amount) { onCommand('cursorForwardTab $amount'); From bbb2d112ed2558ed98cfdc2d6b13142e26c8d19c Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:30:10 +0000 Subject: [PATCH 08/17] xterm: DECSCUSR cursor shapes; block cursor shows the character CSI Ps SP q is stored as Terminal.cursorShape / cursorShapeBlinks (Ps 0 returns to the view's configured cursorType; RIS clears it) and reported by DECRQSS " q". The painter draws the requested shape. A focused block cursor now redraws the character under it in the background colour instead of hiding it, spans both columns of a wide character, and the underline and bar cursors are drawn in the cursor's cell (they were drawn at the top of the terminal). Blinking is stored but not animated. Co-Authored-By: Claude Opus 5.5 --- .../third_party_xterm/cursor_shape_test.dart | 97 ++++++++++++++++++ app/test/third_party_xterm/paint_fixture.dart | 98 +++++++++++++++++++ .../xterm/lib/src/core/escape/handler.dart | 4 + .../xterm/lib/src/core/escape/parser.dart | 8 ++ app/third_party/xterm/lib/src/terminal.dart | 24 +++++ app/third_party/xterm/lib/src/ui/painter.dart | 58 ++++++++--- app/third_party/xterm/lib/src/ui/render.dart | 8 +- .../xterm/lib/src/utils/debugger.dart | 5 + 8 files changed, 288 insertions(+), 14 deletions(-) create mode 100644 app/test/third_party_xterm/cursor_shape_test.dart create mode 100644 app/test/third_party_xterm/paint_fixture.dart diff --git a/app/test/third_party_xterm/cursor_shape_test.dart b/app/test/third_party_xterm/cursor_shape_test.dart new file mode 100644 index 00000000..81844e65 --- /dev/null +++ b/app/test/third_party_xterm/cursor_shape_test.dart @@ -0,0 +1,97 @@ +import 'package:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:xterm/xterm.dart'; + +import 'paint_fixture.dart'; +import 'xterm_fixture.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('DECSCUSR', () { + test('stores the requested shape and blinking', () { + final t = FixtureTerminal(); + expect(t.terminal.cursorShape, isNull); + const expected = { + 1: (TerminalCursorType.block, true), + 2: (TerminalCursorType.block, false), + 3: (TerminalCursorType.underline, true), + 4: (TerminalCursorType.underline, false), + 5: (TerminalCursorType.verticalBar, true), + 6: (TerminalCursorType.verticalBar, false), + }; + for (final MapEntry(key: ps, value: (shape, blinks)) + in expected.entries) { + t.feed('\x1b[$ps q'); + expect(t.terminal.cursorShape, shape, reason: 'Ps $ps'); + expect(t.terminal.cursorShapeBlinks, blinks, reason: 'Ps $ps'); + } + t.feed('\x1b[0 q'); + expect(t.terminal.cursorShape, isNull); + t.feed('\x1b[6 q\x1bc'); + expect(t.terminal.cursorShape, isNull); + }); + + test('does not print and is reported by DECRQSS', () { + final t = FixtureTerminal()..feed('\x1b[5 qa'); + expect(t.row(0), 'a'); + t.feed('\x1bP\$q q\x1b\\'); + expect(t.takeReplies(), '\x1bP1\$r5 q\x1b\\'); + }); + }); + + group('cursor painting', () { + final cell = fixturePainter().cellSize; + final w = cell.width.ceil(); + final h = cell.height.ceil(); + final area = Rect.fromLTWH(0, 0, cell.width, cell.height); + + Future cursor(TerminalCursorType type, {CellData? under}) => + Pixels.paint( + w * 2, + h, + (canvas) => fixturePainter().paintCursor( + canvas, + Offset.zero, + cursorType: type, + cell: under, + ), + ); + + test('a block cursor draws the character under it inverted', () async { + final empty = await cursor(TerminalCursorType.block); + expect(empty.count(backgroundColor, area), 0); + expect(empty.count(cursorColor, area), greaterThan(0)); + + final withChar = await cursor( + TerminalCursorType.block, + under: cellOf('M'), + ); + // The test font's glyphs fill the whole cell; before the fix the + // block hid them and every pixel was the cursor colour. + expect( + withChar.count(backgroundColor, area), + greaterThan(0), + reason: 'the glyph is drawn in the background colour', + ); + }); + + test('a block cursor over a wide character spans two cells', () async { + final pixels = await cursor( + TerminalCursorType.block, + under: cellOf('中', width: 2), + ); + expect(pixels.at(w + w ~/ 2, 0), cursorColor); + }); + + test('underline and bar cursors sit in the cell, not at the top', () async { + final underline = await cursor(TerminalCursorType.underline); + expect(underline.at(w ~/ 2, h - 1), cursorColor); + expect(underline.at(w ~/ 2, 0), isNot(cursorColor)); + + final bar = await cursor(TerminalCursorType.verticalBar); + expect(bar.at(0, h ~/ 2), cursorColor); + expect(bar.at(w - 1, h ~/ 2), isNot(cursorColor)); + }); + }); +} diff --git a/app/test/third_party_xterm/paint_fixture.dart b/app/test/third_party_xterm/paint_fixture.dart new file mode 100644 index 00000000..134f5036 --- /dev/null +++ b/app/test/third_party_xterm/paint_fixture.dart @@ -0,0 +1,98 @@ +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:flutter/painting.dart'; +import 'package:xterm/src/ui/painter.dart'; +import 'package:xterm/xterm.dart'; + +const cursorColor = Color(0xFFFF0000); +const backgroundColor = Color(0xFF0000FF); +const foregroundColor = Color(0xFF00FF00); + +/// A theme whose cursor, background and foreground are pure red, blue and +/// green, so painted pixels say which of them they are. +const fixtureTheme = TerminalTheme( + cursor: cursorColor, + selection: Color(0x80FFFFFF), + foreground: foregroundColor, + background: backgroundColor, + black: Color(0xFF000000), + red: Color(0xFF800000), + green: Color(0xFF008000), + yellow: Color(0xFF808000), + blue: Color(0xFF000080), + magenta: Color(0xFF800080), + cyan: Color(0xFF008080), + white: Color(0xFFC0C0C0), + brightBlack: Color(0xFF808080), + brightRed: Color(0xFFFF8080), + brightGreen: Color(0xFF80FF80), + brightYellow: Color(0xFFFFFF80), + brightBlue: Color(0xFF8080FF), + brightMagenta: Color(0xFFFF80FF), + brightCyan: Color(0xFF80FFFF), + brightWhite: Color(0xFFFFFFFF), + searchHitBackground: Color(0xFFFFFF00), + searchHitBackgroundCurrent: Color(0xFFFF8000), + searchHitForeground: Color(0xFF000000), +); + +TerminalPainter fixturePainter() => TerminalPainter( + theme: fixtureTheme, + textStyle: const TerminalStyle(fontSize: 20, height: 1), + textScaler: TextScaler.noScaling, +); + +/// The pixels [paint] draws on a transparent canvas of [width] x [height]. +class Pixels { + Pixels._(this.width, this.height, this._rgba); + + final int width; + final int height; + final ByteData _rgba; + + static Future paint( + int width, + int height, + void Function(Canvas canvas) paint, + ) async { + final recorder = ui.PictureRecorder(); + paint(Canvas(recorder)); + final image = await recorder.endRecording().toImage(width, height); + final data = await image.toByteData(format: ui.ImageByteFormat.rawRgba); + image.dispose(); + return Pixels._(width, height, data!); + } + + /// The colour at ([x], [y]), opaque or transparent. + Color at(int x, int y) { + final i = (y * width + x) * 4; + return Color.fromARGB( + _rgba.getUint8(i + 3), + _rgba.getUint8(i), + _rgba.getUint8(i + 1), + _rgba.getUint8(i + 2), + ); + } + + /// How many pixels in [rect] are exactly [color]. + int count(Color color, [Rect? rect]) { + final area = + rect ?? Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()); + var n = 0; + for (var y = area.top.floor(); y < area.bottom.ceil(); y++) { + for (var x = area.left.floor(); x < area.right.ceil(); x++) { + if (at(x, y) == color) n++; + } + } + return n; + } +} + +/// A cell holding [char] with [flags] and default colours. +CellData cellOf(String char, {int flags = 0, int width = 1}) => CellData( + foreground: 0, + background: 0, + flags: flags, + content: char.codeUnitAt(0) | (width << CellContent.widthShift), +); 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 50d1f82b..c6658a1e 100644 --- a/app/third_party/xterm/lib/src/core/escape/handler.dart +++ b/app/third_party/xterm/lib/src/core/escape/handler.dart @@ -123,6 +123,10 @@ abstract class EscapeHandler { void unknownCSI(int finalByte); + /// `CSI Ps SP q` (DECSCUSR): 0 default, 1/2 blinking/steady block, 3/4 + /// underline, 5/6 bar. + void setCursorShape(int shape); + /* Modes */ void setInsertMode(bool enabled); 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 2b82bf3e..30a5744b 100644 --- a/app/third_party/xterm/lib/src/core/escape/parser.dart +++ b/app/third_party/xterm/lib/src/core/escape/parser.dart @@ -335,6 +335,14 @@ class EscapeParser { return; } + // `CSI Ps SP q` Set Cursor Style (DECSCUSR) + if (intermediates == Ascii.space && + finalByte == Ascii.q && + _csi.prefix == null) { + handler.setCursorShape(_param(0, 0)); + return; + } + handler.unknownCSI(finalByte); } diff --git a/app/third_party/xterm/lib/src/terminal.dart b/app/third_party/xterm/lib/src/terminal.dart index b3d2426e..ed15f168 100644 --- a/app/third_party/xterm/lib/src/terminal.dart +++ b/app/third_party/xterm/lib/src/terminal.dart @@ -18,6 +18,7 @@ import 'package:xterm/src/core/mouse/mode.dart'; import 'package:xterm/src/core/platform.dart'; import 'package:xterm/src/core/state.dart'; import 'package:xterm/src/core/tabs.dart'; +import 'package:xterm/src/ui/cursor_type.dart'; import 'package:xterm/src/utils/ascii.dart'; import 'package:xterm/src/utils/circular_buffer.dart'; @@ -148,8 +149,24 @@ class Terminal with Observable implements TerminalState, EscapeHandler { bool _bracketedPasteMode = false; + int _cursorShapeParam = 0; + /* State getters */ + /// The cursor shape the program asked for with DECSCUSR (`CSI Ps SP q`), + /// or null when it has not asked (or asked for the default, Ps 0): the + /// view then draws its own configured cursor type. + TerminalCursorType? get cursorShape => switch (_cursorShapeParam) { + 1 || 2 => TerminalCursorType.block, + 3 || 4 => TerminalCursorType.underline, + 5 || 6 => TerminalCursorType.verticalBar, + _ => null, + }; + + /// Whether the DECSCUSR shape blinks (odd Ps). Null with no request. + bool? get cursorShapeBlinks => + cursorShape == null ? null : _cursorShapeParam.isOdd; + /// Number of cells in a terminal row. @override int get viewWidth => _viewWidth; @@ -494,6 +511,7 @@ class Terminal with Observable implements TerminalState, EscapeHandler { _altBufferMouseScrollMode = false; _bracketedPasteMode = false; _precedingCodepoint = 0; + _cursorShapeParam = 0; _tabStops.reset(); _buffer = _mainBuffer; @@ -528,6 +546,7 @@ class Terminal with Observable implements TerminalState, EscapeHandler { final value = switch (setting) { 'm' => '${sgrReport(_cursorStyle)}m', 'r' => '${_buffer.marginTop + 1};${_buffer.marginBottom + 1}r', + ' q' => '${_cursorShapeParam == 0 ? 2 : _cursorShapeParam} q', _ => null, }; // `DCS 1 $ r Pt ST` reports a valid setting, `DCS 0 $ r ST` an @@ -731,6 +750,11 @@ class Terminal with Observable implements TerminalState, EscapeHandler { // no-op } + @override + void setCursorShape(int shape) { + _cursorShapeParam = shape <= 6 ? shape : 0; + } + /* Modes */ @override diff --git a/app/third_party/xterm/lib/src/ui/painter.dart b/app/third_party/xterm/lib/src/ui/painter.dart index 64a78e08..4d70426b 100644 --- a/app/third_party/xterm/lib/src/ui/painter.dart +++ b/app/third_party/xterm/lib/src/ui/painter.dart @@ -86,42 +86,74 @@ class TerminalPainter { } /// Paints the cursor based on the current cursor type. + /// + /// [cell] is the cell under the cursor: a focused block cursor draws its + /// character again in the background colour, so the character stays + /// readable, and a cursor over a wide character spans both columns. void paintCursor( Canvas canvas, Offset offset, { required TerminalCursorType cursorType, bool hasFocus = true, + CellData? cell, }) { - final paint = Paint() - ..color = _theme.cursor - ..strokeWidth = 1; + final wide = cell != null && cell.content >> CellContent.widthShift == 2; + final size = wide ? Size(_cellSize.width * 2, _cellSize.height) : _cellSize; + final thickness = cursorThickness; + final paint = Paint()..color = _theme.cursor; if (!hasFocus) { - paint.style = PaintingStyle.stroke; - canvas.drawRect(offset & _cellSize, paint); + paint + ..style = PaintingStyle.stroke + ..strokeWidth = 1; + canvas.drawRect((offset & size).deflate(0.5), paint); return; } switch (cursorType) { case TerminalCursorType.block: - paint.style = PaintingStyle.fill; - canvas.drawRect(offset & _cellSize, paint); + canvas.drawRect(offset & size, paint); + if (cell != null) { + paintCellForeground(canvas, offset, _underCursor(cell)); + } return; case TerminalCursorType.underline: - return canvas.drawLine( - Offset(offset.dx, _cellSize.height - 1), - Offset(offset.dx + _cellSize.width, _cellSize.height - 1), + canvas.drawRect( + Rect.fromLTWH( + offset.dx, + offset.dy + size.height - thickness, + size.width, + thickness, + ), paint, ); + return; case TerminalCursorType.verticalBar: - return canvas.drawLine( - Offset(offset.dx, 0), - Offset(offset.dx, _cellSize.height), + canvas.drawRect( + Rect.fromLTWH(offset.dx, offset.dy, thickness, size.height), paint, ); + return; } } + /// The width of an underline or bar cursor: a tenth of the line height, + /// at least one pixel. + double get cursorThickness => + (_cellSize.height / 10).roundToDouble().clamp(1.0, double.infinity); + + /// [cell] as drawn on top of a block cursor: in the background colour, + /// without inverse. + CellData _underCursor(CellData cell) { + final background = _theme.background.toARGB32() & CellColor.valueMask; + return CellData( + foreground: CellColor.rgb | background, + background: 0, + flags: cell.flags & ~CellFlags.inverse, + content: cell.content, + ); + } + @pragma('vm:prefer-inline') void paintHighlight(Canvas canvas, Offset offset, int length, Color color) { final endOffset = diff --git a/app/third_party/xterm/lib/src/ui/render.dart b/app/third_party/xterm/lib/src/ui/render.dart index de2a2f7f..547d76f1 100644 --- a/app/third_party/xterm/lib/src/ui/render.dart +++ b/app/third_party/xterm/lib/src/ui/render.dart @@ -6,6 +6,7 @@ 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'; @@ -428,11 +429,16 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { } if (_shouldShowCursor) { + final buffer = _terminal.buffer; + final cell = CellData.empty(); + buffer.lines[buffer.absoluteCursorY].getCellData(buffer.cursorX, cell); _painter.paintCursor( canvas, offset + cursorOffset, - cursorType: _cursorType, + // The program's DECSCUSR request wins over the configured type. + cursorType: _terminal.cursorShape ?? _cursorType, hasFocus: _focusNode.hasFocus, + cell: _isComposingText ? null : cell, ); } } diff --git a/app/third_party/xterm/lib/src/utils/debugger.dart b/app/third_party/xterm/lib/src/utils/debugger.dart index 4a15f905..ca9125aa 100644 --- a/app/third_party/xterm/lib/src/utils/debugger.dart +++ b/app/third_party/xterm/lib/src/utils/debugger.dart @@ -471,6 +471,11 @@ class _TerminalDebuggerHandler implements EscapeHandler { onCommand('setCursorUnderline'); } + @override + void setCursorShape(int shape) { + onCommand('setCursorShape $shape'); + } + @override void resetTerminal() { onCommand('resetTerminal'); From 8f758bc721eba9806c626f02897f37d380df8460 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:32:21 +0000 Subject: [PATCH 09/17] 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'); From 7d1ffe8ad36ff459b13fccb55afee9154fd00a3b Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:32:29 +0000 Subject: [PATCH 10/17] Terminal: xterm key encoding, no live reflow on resize, Alt+T/Ctrl+T reach the shell - Live terminals no longer reflow (xterm.dart 4.0.0 left the cursor on the wrong row); narrowing cuts and erases cells past the width, rows scroll into scrollback keeping the cursor row; finished output still reflows. - App-side key encoding before xterm.dart's defaults: Alt as Meta (ESC + the typed character), Ctrl symbol table, xterm modifier parameter for arrows/Home/End/PgUp/PgDn/Ins/Del/F-keys, DECCKM and DECKPAM, Alt+BS. - Settings > Appearance > Terminal: Use Option as Meta key (Macs, on). - Inside a focused terminal only Cmd+T and Ctrl+` toggle it. Co-Authored-By: Claude Opus 5.5 --- .../chat/shell/chat_shell_terminal_input.dart | 163 +++++++++ .../shell/chat_shell_terminal_key_input.dart | 127 +++++++ .../shell/chat_shell_terminal_keymap.dart | 139 ++++++++ .../shell/chat_shell_terminal_session.dart | 54 ++- .../chat/shell/chat_shell_terminal_view.dart | 37 ++- .../settings/keyboard_shortcuts_registry.dart | 8 +- .../settings/settings_terminal_section.dart | 15 + .../features/terminal/terminal_layout.dart | 8 + .../features/terminal/terminal_shortcuts.dart | 24 +- .../features/terminal/terminal_surface.dart | 21 +- app/notes/chat-interactive-terminal.md | 39 ++- app/notes/terminal-panel.md | 48 ++- .../shell/chat_shell_terminal_input_test.dart | 309 ++++++++++++++++++ .../chat_shell_terminal_resize_test.dart | 165 ++++++++++ .../chat_shell_terminal_session_test.dart | 22 +- .../chat/shell/chat_shell_terminal_test.dart | 103 ++++++ app/test/features/terminal/terminal_app.dart | 14 +- .../terminal_chat_bar_action_test.dart | 4 +- .../terminal/terminal_chat_tab_test.dart | 2 +- .../terminal/terminal_motion_test.dart | 16 +- .../terminal/terminal_shortcuts_test.dart | 118 ++++++- .../terminal/terminal_surface_test.dart | 33 ++ 22 files changed, 1408 insertions(+), 61 deletions(-) create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_input.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_key_input.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_keymap.dart create mode 100644 app/test/features/chat/shell/chat_shell_terminal_input_test.dart create mode 100644 app/test/features/chat/shell/chat_shell_terminal_resize_test.dart diff --git a/app/lib/features/chat/shell/chat_shell_terminal_input.dart b/app/lib/features/chat/shell/chat_shell_terminal_input.dart new file mode 100644 index 00000000..4979775e --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_input.dart @@ -0,0 +1,163 @@ +import 'package:flutter/foundation.dart'; +import 'package:xterm/core.dart'; + +/// The bytes xterm sends for keys, where xterm.dart 4.0.0's own handlers +/// differ (Alt+letter upper-cased, no Ctrl symbols, the wrong modifier codes, +/// application cursor keys read from the keypad mode). +/// +/// Modified special keys use xterm's parameter: 1 + Shift(1) + Alt(2) + +/// Ctrl(4), so Shift+Up is `CSI 1;2A`, Alt+Left `CSI 1;3D`, Ctrl+Right +/// `CSI 1;5C`, Ctrl+Shift+Home `CSI 1;6H`, Shift+PgUp `CSI 5;2~`. + +const String _esc = '\x1b'; + +/// Whether Alt is Meta here: always outside Apple platforms; on them the +/// Option key is Meta only while [optionAsMeta] (else it types its symbol). +bool chatShellAltIsMeta({required bool optionAsMeta}) { + final apple = + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS; + return !apple || optionAsMeta; +} + +int _modifier({required bool shift, required bool alt, required bool ctrl}) => + 1 + (shift ? 1 : 0) + (alt ? 2 : 0) + (ctrl ? 4 : 0); + +/// Cursor keys and Home/End: their final letter. DECCKM (application cursor +/// keys) sends them unmodified as SS3. +const Map _cursorKeys = { + TerminalKey.arrowUp: 'A', + TerminalKey.arrowDown: 'B', + TerminalKey.arrowRight: 'C', + TerminalKey.arrowLeft: 'D', + TerminalKey.home: 'H', + TerminalKey.end: 'F', +}; + +/// F1–F4: SS3 unmodified, `CSI 1;m P` modified. +const Map _pfKeys = { + TerminalKey.f1: 'P', + TerminalKey.f2: 'Q', + TerminalKey.f3: 'R', + TerminalKey.f4: 'S', +}; + +/// Keys sent as `CSI n ~` (`CSI n;m ~` modified). +const Map _tildeKeys = { + TerminalKey.insert: 2, + TerminalKey.delete: 3, + TerminalKey.pageUp: 5, + TerminalKey.pageDown: 6, + TerminalKey.f5: 15, + TerminalKey.f6: 17, + TerminalKey.f7: 18, + TerminalKey.f8: 19, + TerminalKey.f9: 20, + TerminalKey.f10: 21, + TerminalKey.f11: 23, + TerminalKey.f12: 24, +}; + +/// Keypad keys in application keypad mode (DECKPAM). The digits and the +/// decimal point keep typing their characters, as xterm does while NumLock +/// is on (a keypad digit only arrives with NumLock on). +const Map _keypadKeys = { + TerminalKey.numpadEnter: 'M', + TerminalKey.numpadMultiply: 'j', + TerminalKey.numpadAdd: 'k', + TerminalKey.numpadSubtract: 'm', + TerminalKey.numpadDivide: 'o', + TerminalKey.numpadEqual: 'X', +}; + +/// The bytes for a non-printing key, or null for a key that types a +/// character (letters, digits, symbols, Space, the keypad outside its +/// application mode). [alt] counts in the modifier parameter; [meta] (Alt +/// as Meta) prefixes ESC to the keys that have no parameter. +String? chatShellSpecialKeyBytes( + TerminalKey key, { + required bool shift, + required bool alt, + required bool meta, + required bool ctrl, + required TerminalState state, +}) { + final m = _modifier(shift: shift, alt: alt, ctrl: ctrl); + final prefix = meta ? _esc : ''; + final cursor = _cursorKeys[key]; + if (cursor != null) { + if (m > 1) return '$_esc[1;$m$cursor'; + return state.cursorKeysMode ? '${_esc}O$cursor' : '$_esc[$cursor'; + } + final pf = _pfKeys[key]; + if (pf != null) return m > 1 ? '$_esc[1;$m$pf' : '${_esc}O$pf'; + final tilde = _tildeKeys[key]; + if (tilde != null) return m > 1 ? '$_esc[$tilde;$m~' : '$_esc[$tilde~'; + if (state.appKeypadMode) { + final keypad = _keypadKeys[key]; + if (keypad != null) return '${_esc}O$keypad'; + } + switch (key) { + case TerminalKey.enter || TerminalKey.numpadEnter || TerminalKey.returnKey: + return '$prefix${state.lineFeedMode ? '\r\n' : '\r'}'; + case TerminalKey.tab: + return shift ? '$prefix$_esc[Z' : '$prefix\t'; + case TerminalKey.backtab: + return '$prefix$_esc[Z'; + case TerminalKey.escape: + return '$prefix$_esc'; + case TerminalKey.backspace: + return '$prefix${ctrl ? '\b' : '\x7f'}'; + case TerminalKey.space: + if (ctrl) return '$prefix\x00'; + return meta ? '$_esc ' : null; + default: + return null; + } +} + +/// Ctrl with a character: the C0 code xterm sends for it. +const Map _ctrlSymbols = { + ' ': 0x00, + '@': 0x00, + '2': 0x00, + '[': 0x1b, + '3': 0x1b, + '\\': 0x1c, + '4': 0x1c, + ']': 0x1d, + '5': 0x1d, + '^': 0x1e, + '6': 0x1e, + '_': 0x1f, + '/': 0x1f, + '-': 0x1f, + '7': 0x1f, + '?': 0x7f, + '8': 0x7f, +}; + +/// The control code Ctrl+[char] sends, or null if it has none. +int? chatShellCtrlCode(String char) { + if (char.length != 1) return null; + final code = char.toLowerCase().codeUnitAt(0); + if (code >= 0x61 && code <= 0x7a) return code - 0x60; + return _ctrlSymbols[char]; +} + +/// The bytes for [char] (as typed, Shift applied) with Ctrl and/or Meta +/// ([alt]): Ctrl maps it to its control code, Meta prefixes ESC. Null with +/// neither modifier, or Ctrl with a character that has no control code. +String? chatShellCharBytes( + String char, { + required bool alt, + required bool ctrl, +}) { + if (!alt && !ctrl) return null; + if (ctrl) { + final code = chatShellCtrlCode(char); + if (code == null) return null; + return '${alt ? _esc : ''}${String.fromCharCode(code)}'; + } + return '$_esc$char'; +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_key_input.dart b/app/lib/features/chat/shell/chat_shell_terminal_key_input.dart new file mode 100644 index 00000000..7d4029d0 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_key_input.dart @@ -0,0 +1,127 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:xterm/core.dart'; + +import 'chat_shell_terminal_input.dart'; +import 'chat_shell_terminal_keymap.dart'; + +/// The terminal's input handler, chained before xterm.dart's defaults: it +/// encodes every key [Terminal.keyInput] receives (the key toolbar, the soft +/// keyboard's keys, hardware keys the view did not encode itself) as xterm +/// does. A printing key's character comes from the US layout here; the view +/// encodes hardware keys with their real character first +/// ([chatShellKeyEventBytes]). +class ChatShellInputHandler implements TerminalInputHandler { + const ChatShellInputHandler({required this.optionAsMeta}); + + /// Whether Option is Meta on Apple platforms (read at each key). + final bool Function() optionAsMeta; + + @override + String? call(TerminalKeyboardEvent event) { + final alt = event.alt && chatShellAltIsMeta(optionAsMeta: optionAsMeta()); + final special = chatShellSpecialKeyBytes( + event.key, + shift: event.shift, + alt: event.alt, + meta: alt, + ctrl: event.ctrl, + state: event.state, + ); + if (special != null) return special; + final char = chatShellTerminalKeyChar(event.key); + if (char == null) return null; + return chatShellCharBytes( + event.shift ? chatShellUsShifted(char) : char, + alt: alt, + ctrl: event.ctrl, + ); + } +} + +bool _printable(String? text) { + if (text == null || text.runes.length != 1) return false; + final code = text.runes.single; + return code >= 0x20 && code != 0x7f; +} + +bool _ascii(String text) { + final code = text.codeUnitAt(0); + return code >= 0x20 && code < 0x7f; +} + +/// The character a key types with Shift but without Ctrl or Alt: the event's +/// own character where it is plain ASCII (so the layout counts), else the +/// logical key's, else the physical key's on a US layout. On Apple platforms +/// Option's own symbol (Option+B types ∫) is never the character. +String? _baseChar(KeyEvent event, {required bool shift, required bool option}) { + final character = event.character; + if (_printable(character) && _ascii(character!) && !option) { + return character; + } + final id = event.logicalKey.keyId; + if (id >= 0x20 && id < 0x7f) { + final char = String.fromCharCode(id); + return shift ? chatShellUsShifted(char) : char; + } + final physical = chatShellPhysicalChar(event.physicalKey); + if (physical == null) return null; + return shift ? chatShellUsShifted(physical) : physical; +} + +/// The bytes a hardware key event sends, or null to leave it to the +/// emulator's own handling (plain typing, Cmd chords, IME text). +/// +/// Non-printing keys are encoded as xterm does, honouring application cursor +/// keys and keypad mode in [state]. Ctrl with a character sends its control +/// code; Alt (Meta, see [chatShellAltIsMeta]) sends ESC and the character it +/// types with Shift and the layout. AltGr (Ctrl+Alt typing a symbol outside +/// Apple platforms) types the symbol. +String? chatShellKeyEventBytes( + KeyEvent event, + HardwareKeyboard keyboard, + TerminalState state, { + required bool optionAsMeta, +}) { + if (event is KeyUpEvent || keyboard.isMetaPressed) return null; + final apple = + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS; + final shift = keyboard.isShiftPressed; + final ctrl = keyboard.isControlPressed; + final alt = + keyboard.isAltPressed && chatShellAltIsMeta(optionAsMeta: optionAsMeta); + final special = chatShellSpecialKeys[event.logicalKey]; + if (special != null) { + final bytes = chatShellSpecialKeyBytes( + special, + shift: shift, + alt: keyboard.isAltPressed, + meta: alt, + ctrl: ctrl, + state: state, + ); + if (bytes != null) return bytes; + } + if (!alt && !ctrl) return null; + final base = _baseChar( + event, + shift: shift, + option: apple && keyboard.isAltPressed, + ); + if (base == null) return null; + if (!apple && ctrl && keyboard.isAltPressed) { + // AltGr arrives as Ctrl+Alt: a symbol the layout composes is typed. + final character = event.character; + final id = event.logicalKey.keyId; + final plain = id >= 0x20 && id < 0x7f + ? String.fromCharCode(id) + : chatShellPhysicalChar(event.physicalKey); + if (_printable(character) && + character!.toLowerCase() != plain && + chatShellUsShifted(plain ?? '') != character) { + return null; + } + } + return chatShellCharBytes(base, alt: alt, ctrl: ctrl); +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_keymap.dart b/app/lib/features/chat/shell/chat_shell_terminal_keymap.dart new file mode 100644 index 00000000..cad2b881 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_keymap.dart @@ -0,0 +1,139 @@ +import 'package:flutter/services.dart'; +import 'package:xterm/core.dart'; + +/// Key tables for terminal input: the non-printing keys by their Flutter +/// logical key, and the US layout's characters, used when a key event +/// carries no usable character (Option's symbol on a Mac, a control code). + +/// The non-printing keys the terminal encodes itself. +final Map chatShellSpecialKeys = { + LogicalKeyboardKey.arrowUp: TerminalKey.arrowUp, + LogicalKeyboardKey.arrowDown: TerminalKey.arrowDown, + LogicalKeyboardKey.arrowLeft: TerminalKey.arrowLeft, + LogicalKeyboardKey.arrowRight: TerminalKey.arrowRight, + LogicalKeyboardKey.home: TerminalKey.home, + LogicalKeyboardKey.end: TerminalKey.end, + LogicalKeyboardKey.insert: TerminalKey.insert, + LogicalKeyboardKey.delete: TerminalKey.delete, + LogicalKeyboardKey.pageUp: TerminalKey.pageUp, + LogicalKeyboardKey.pageDown: TerminalKey.pageDown, + LogicalKeyboardKey.f1: TerminalKey.f1, + LogicalKeyboardKey.f2: TerminalKey.f2, + LogicalKeyboardKey.f3: TerminalKey.f3, + LogicalKeyboardKey.f4: TerminalKey.f4, + LogicalKeyboardKey.f5: TerminalKey.f5, + LogicalKeyboardKey.f6: TerminalKey.f6, + LogicalKeyboardKey.f7: TerminalKey.f7, + LogicalKeyboardKey.f8: TerminalKey.f8, + LogicalKeyboardKey.f9: TerminalKey.f9, + LogicalKeyboardKey.f10: TerminalKey.f10, + LogicalKeyboardKey.f11: TerminalKey.f11, + LogicalKeyboardKey.f12: TerminalKey.f12, + LogicalKeyboardKey.enter: TerminalKey.enter, + LogicalKeyboardKey.numpadEnter: TerminalKey.numpadEnter, + LogicalKeyboardKey.tab: TerminalKey.tab, + LogicalKeyboardKey.escape: TerminalKey.escape, + LogicalKeyboardKey.backspace: TerminalKey.backspace, + LogicalKeyboardKey.space: TerminalKey.space, + LogicalKeyboardKey.numpadMultiply: TerminalKey.numpadMultiply, + LogicalKeyboardKey.numpadAdd: TerminalKey.numpadAdd, + LogicalKeyboardKey.numpadSubtract: TerminalKey.numpadSubtract, + LogicalKeyboardKey.numpadDivide: TerminalKey.numpadDivide, + LogicalKeyboardKey.numpadEqual: TerminalKey.numpadEqual, +}; + +/// US layout: each unshifted symbol and its shifted one. +const Map _usShifted = { + '1': '!', + '2': '@', + '3': '#', + '4': r'$', + '5': '%', + '6': '^', + '7': '&', + '8': '*', + '9': '(', + '0': ')', + '-': '_', + '=': '+', + '[': '{', + ']': '}', + '\\': '|', + ';': ':', + "'": '"', + '`': '~', + ',': '<', + '.': '>', + '/': '?', +}; + +/// [char] as Shift types it on a US layout. +String chatShellUsShifted(String char) => + _usShifted[char] ?? char.toUpperCase(); + +/// The unshifted character of a printing [TerminalKey] on a US layout. +String? chatShellTerminalKeyChar(TerminalKey key) { + final index = key.index; + if (index >= TerminalKey.keyA.index && index <= TerminalKey.keyZ.index) { + return String.fromCharCode(0x61 + index - TerminalKey.keyA.index); + } + if (index >= TerminalKey.digit1.index && index <= TerminalKey.digit9.index) { + return String.fromCharCode(0x31 + index - TerminalKey.digit1.index); + } + if (index >= TerminalKey.numpad1.index && + index <= TerminalKey.numpad9.index) { + return String.fromCharCode(0x31 + index - TerminalKey.numpad1.index); + } + return _terminalKeySymbols[key]; +} + +const Map _terminalKeySymbols = { + TerminalKey.digit0: '0', + TerminalKey.numpad0: '0', + TerminalKey.minus: '-', + TerminalKey.equal: '=', + TerminalKey.bracketLeft: '[', + TerminalKey.bracketRight: ']', + TerminalKey.backslash: '\\', + TerminalKey.semicolon: ';', + TerminalKey.quote: "'", + TerminalKey.backquote: '`', + TerminalKey.comma: ',', + TerminalKey.period: '.', + TerminalKey.slash: '/', + TerminalKey.numpadDecimal: '.', + TerminalKey.numpadDivide: '/', + TerminalKey.numpadMultiply: '*', + TerminalKey.numpadSubtract: '-', + TerminalKey.numpadAdd: '+', + TerminalKey.numpadEqual: '=', +}; + +/// The unshifted character a physical key types on a US layout. +String? chatShellPhysicalChar(PhysicalKeyboardKey key) { + final usb = key.usbHidUsage; + // USB HID: keyA (0x70004) … keyZ, digit1 … digit9, digit0. + if (usb >= 0x70004 && usb <= 0x7001d) { + return String.fromCharCode(0x61 + usb - 0x70004); + } + if (usb >= 0x7001e && usb <= 0x70026) { + return String.fromCharCode(0x31 + usb - 0x7001e); + } + return _physicalSymbols[key]; +} + +final Map _physicalSymbols = { + PhysicalKeyboardKey.digit0: '0', + PhysicalKeyboardKey.minus: '-', + PhysicalKeyboardKey.equal: '=', + PhysicalKeyboardKey.bracketLeft: '[', + PhysicalKeyboardKey.bracketRight: ']', + PhysicalKeyboardKey.backslash: '\\', + PhysicalKeyboardKey.semicolon: ';', + PhysicalKeyboardKey.quote: "'", + PhysicalKeyboardKey.backquote: '`', + PhysicalKeyboardKey.comma: ',', + PhysicalKeyboardKey.period: '.', + PhysicalKeyboardKey.slash: '/', + PhysicalKeyboardKey.space: ' ', +}; diff --git a/app/lib/features/chat/shell/chat_shell_terminal_session.dart b/app/lib/features/chat/shell/chat_shell_terminal_session.dart index 01b5103e..b8cf5901 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_session.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_session.dart @@ -1,6 +1,9 @@ +import 'package:flutter/foundation.dart'; import 'package:xterm/core.dart'; +import '../../terminal/terminal_layout.dart'; import 'chat_shell_run.dart'; +import 'chat_shell_terminal_key_input.dart'; /// Lines of scrollback one card's terminal keeps. const int chatShellTerminalScrollback = 5000; @@ -16,7 +19,14 @@ class ChatShellTerminalSession { ChatShellRun run, { required this.onInput, required this.onResize, - }) : terminal = _ChatShellTerminal() { + bool Function()? optionAsMeta, + }) : optionAsMeta = + optionAsMeta ?? (() => TerminalLayout.instance.optionAsMeta), + terminal = _ChatShellTerminal() { + terminal.inputHandler = CascadeInputHandler([ + ChatShellInputHandler(optionAsMeta: this.optionAsMeta), + defaultInputHandler, + ]); // Drawn at the process's own size until a view lays it out at its own. if (run.cols > 0 && run.rows > 0) terminal.resize(run.cols, run.rows); terminal.onOutput = _output; @@ -26,6 +36,9 @@ class ChatShellTerminalSession { final Terminal terminal; + /// Whether a Mac's Option key is Meta (Settings → Appearance → Terminal). + final bool Function() optionAsMeta; + /// Receives input for the process; only called while the run is live. final void Function(String data) onInput; @@ -47,6 +60,7 @@ class ChatShellTerminalSession { /// queries in that output are not sent: the process asked them long ago. void replay(ChatShellRun run) { _live = run.running && run.terminal; + terminal.reflowEnabled = !_live; _replaying = true; try { terminal.useMainBuffer(); @@ -86,6 +100,7 @@ class ChatShellTerminalSession { void finish(ChatShellRun run) { if (!_live) return; _live = false; + terminal.reflowEnabled = true; terminal.setCursorVisibleMode(false); } @@ -125,21 +140,48 @@ class ChatShellTerminalSession { /// The emulator with the scrollback the cards keep. It answers a cursor /// position query (DSR 6) with the one-based row and column the protocol /// specifies; xterm.dart 4.0.0 itself answers zero-based. +/// +/// A live terminal does not reflow on resize: xterm.dart 4.0.0's reflow +/// leaves the cursor on a row other than its line's, so the shell's redraw +/// lands on old output. Without it a resize behaves as xterm's: narrowing +/// cuts rows at the new width, fewer rows scroll the top into scrollback +/// (keeping the cursor's row at the bottom), more rows bring it back. +/// Finished output, which nothing writes to any more, reflows to fit. class _ChatShellTerminal extends Terminal { - _ChatShellTerminal() : super(maxLines: chatShellTerminalScrollback); + _ChatShellTerminal() + : super(maxLines: chatShellTerminalScrollback, platform: _platform()); + + /// The package's own Alt handler (a fallback after the app's) leaves + /// Option alone only when it knows it is on a Mac. + static TerminalTargetPlatform _platform() => + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS + ? TerminalTargetPlatform.macos + : TerminalTargetPlatform.unknown; @override void sendCursorPosition() { onOutput?.call('\x1b[${buffer.cursorY + 1};${buffer.cursorX + 1}R'); } - /// Narrowing rewraps long lines, and xterm.dart 4.0.0 keeps every blank - /// row below the cursor while doing so: the extra rows push the top of - /// the output into scrollback. Blank rows below the cursor are dropped - /// instead, keeping the cursor on its line. @override void resize(int width, int height, [int? pixelWidth, int? pixelHeight]) { + final oldWidth = viewWidth; + if (!reflowEnabled && width >= 1 && width < oldWidth) { + // A cut row keeps its cells past the new width, which a later widening + // would show again beside what was written since: they are erased. + for (final buffer in [mainBuffer, altBuffer]) { + buffer.lines.forEach((line) { + if (line.length > width) { + line.eraseRange(width, line.length, CursorStyle.empty); + } + }); + } + } super.resize(width, height, pixelWidth, pixelHeight); + if (!reflowEnabled) return; + // Rewrapping keeps every blank row below the cursor, and the extra rows + // push the top of finished output into scrollback: they are dropped. final lines = buffer.lines; while (buffer.height > viewHeight && buffer.height - 1 > buffer.absoluteCursorY && diff --git a/app/lib/features/chat/shell/chat_shell_terminal_view.dart b/app/lib/features/chat/shell/chat_shell_terminal_view.dart index 5497d57b..dad810eb 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_view.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_view.dart @@ -6,6 +6,7 @@ import 'package:xterm/xterm.dart'; import '../conversation/chat_composer_paste_focus.dart'; import '../ui/transcript/chat_link_launcher.dart'; import 'chat_shell_metrics.dart'; +import 'chat_shell_terminal_key_input.dart'; import 'chat_shell_terminal_links.dart'; import 'chat_shell_terminal_session.dart'; import 'chat_shell_terminal_theme.dart'; @@ -94,6 +95,9 @@ class _ChatShellTerminalViewState extends State { final TerminalController _controller = TerminalController(); final FocusNode _focus = FocusNode(debugLabel: 'chat-shell-terminal'); final FocusNode _outputFocus = FocusNode(debugLabel: 'chat-shell-output'); + final ScrollController _scroll = ScrollController(); + final Map _shortcuts = + chatShellTerminalShortcuts(); @override void initState() { @@ -109,6 +113,7 @@ class _ChatShellTerminalViewState extends State { _controller.dispose(); _focus.dispose(); _outputFocus.dispose(); + _scroll.dispose(); super.dispose(); } @@ -123,11 +128,30 @@ class _ChatShellTerminalViewState extends State { return true; } - /// Ctrl-C with a selection copies; anything else is the terminal's. - KeyEventResult _key(FocusNode node, KeyEvent event) => - chatShellCopyKey(event, HardwareKeyboard.instance) && _copySelection() - ? KeyEventResult.handled - : KeyEventResult.ignored; + /// Ctrl-C with a selection copies; the terminal's own shortcuts (copy, + /// paste) are left to it; any other key xterm encodes differently from + /// xterm.dart (Alt as Meta, Ctrl symbols, modified special keys) is sent + /// here with its real character. The rest is the emulator's. + KeyEventResult _key(FocusNode node, KeyEvent event) { + final keyboard = HardwareKeyboard.instance; + if (chatShellCopyKey(event, keyboard) && _copySelection()) { + return KeyEventResult.handled; + } + if (_shortcuts.keys.any((key) => key.accepts(event, keyboard))) { + return KeyEventResult.ignored; + } + final session = widget.session; + final bytes = chatShellKeyEventBytes( + event, + keyboard, + session.terminal, + optionAsMeta: session.optionAsMeta(), + ); + if (bytes == null) return KeyEventResult.ignored; + session.terminal.textInput(bytes); + if (_scroll.hasClients) _scroll.jumpTo(_scroll.position.maxScrollExtent); + return KeyEventResult.handled; + } /// A finished run's output takes no keys of its own, so the copy keys are /// answered here while it has the keyboard. @@ -163,6 +187,7 @@ class _ChatShellTerminalViewState extends State { child: TerminalView( session.terminal, controller: _controller, + scrollController: _scroll, focusNode: _focus, autofocus: widget.autofocus && live, autoResize: widget.autoResize, @@ -177,7 +202,7 @@ class _ChatShellTerminalViewState extends State { hardwareKeyboardOnly: !chatShellTouchFirst(), // No autocorrect or suggestions rewriting what is sent to a shell. keyboardType: TextInputType.visiblePassword, - shortcuts: chatShellTerminalShortcuts(), + shortcuts: _shortcuts, cursorType: TerminalCursorType.block, onTapUp: _tapped, onKeyEvent: _key, diff --git a/app/lib/features/settings/keyboard_shortcuts_registry.dart b/app/lib/features/settings/keyboard_shortcuts_registry.dart index 6dc477c8..4cf60f8f 100644 --- a/app/lib/features/settings/keyboard_shortcuts_registry.dart +++ b/app/lib/features/settings/keyboard_shortcuts_registry.dart @@ -208,9 +208,11 @@ class KeyboardShortcutRegistry { web: web, platform: platform, ).toggle.join(', '), - caveat: web - ? 'Browser tab shortcuts such as Cmd+T are not available to the app.' - : null, + caveat: [ + TerminalShortcutLabels(web: web, platform: platform).inTerminalNote, + if (web) + 'Browser tab shortcuts such as Cmd+T are not available to the app.', + ].join(' '), ), if (!web) const KeyboardShortcutEntry( diff --git a/app/lib/features/settings/settings_terminal_section.dart b/app/lib/features/settings/settings_terminal_section.dart index 0e83a0af..400a30a8 100644 --- a/app/lib/features/settings/settings_terminal_section.dart +++ b/app/lib/features/settings/settings_terminal_section.dart @@ -1,3 +1,4 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import '../terminal/terminal_layout.dart'; @@ -63,6 +64,20 @@ class SettingsTerminalSection extends StatelessWidget { ), ), ), + // Alt is always Meta elsewhere; only a Mac's Option types symbols. + if (defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS) + SwitchListTile( + key: const ValueKey('settings-terminal-option-as-meta'), + title: const Text('Use Option as Meta key'), + subtitle: const Text( + 'Option+B, Option+F and Option+D move and delete by word in ' + 'the shell (ESC b, ESC f, ESC d). Off, Option types its ' + 'symbol (∫, ƒ, ∂).', + ), + value: layout.optionAsMeta, + onChanged: layout.setOptionAsMeta, + ), ], ); }, diff --git a/app/lib/features/terminal/terminal_layout.dart b/app/lib/features/terminal/terminal_layout.dart index 136ca981..227fab51 100644 --- a/app/lib/features/terminal/terminal_layout.dart +++ b/app/lib/features/terminal/terminal_layout.dart @@ -75,6 +75,11 @@ class TerminalLayout extends ChangeNotifier { Rect floatRect = terminalFloatDefaultRect; bool maximized = false; + /// Whether a Mac's Option key is Meta in the terminal (Option+B sends + /// ESC b, readline's word back) rather than typing its symbol (∫). Other + /// platforms' Alt is always Meta. + bool optionAsMeta = true; + /// Whether the last change could not be saved. bool saveFailed = false; @@ -100,6 +105,7 @@ class TerminalLayout extends ChangeNotifier { } } maximized = json['maximized'] == true; + optionAsMeta = json['option_as_meta'] != false; } catch (_) { return; } @@ -107,6 +113,7 @@ class TerminalLayout extends ChangeNotifier { } void setMode(TerminalMode value) => _change(() => mode = value); + void setOptionAsMeta(bool value) => _change(() => optionAsMeta = value); void toggle() => _change(() => visible = !visible); void show() => _change(() => visible = true); void hide() => _change(() => visible = false); @@ -128,6 +135,7 @@ class TerminalLayout extends ChangeNotifier { floatRect.height, ], 'maximized': maximized, + 'option_as_meta': optionAsMeta, }), ); if (revision != _revision || saved != saveFailed) return; diff --git a/app/lib/features/terminal/terminal_shortcuts.dart b/app/lib/features/terminal/terminal_shortcuts.dart index fc72200c..677ee3bf 100644 --- a/app/lib/features/terminal/terminal_shortcuts.dart +++ b/app/lib/features/terminal/terminal_shortcuts.dart @@ -3,13 +3,18 @@ import 'package:flutter/services.dart'; /// Whether [event] shows or hides the terminal: Alt+T, Ctrl+T, Cmd+T /// (Meta+T) or Ctrl+` (Shift allowed only with Ctrl+`). They are global key -/// handlers, so inside the terminal they toggle rather than reaching the -/// shell (whose Ctrl+T, transpose-chars, is then not available) and inside -/// text fields they toggle rather than type. +/// handlers, so inside text fields they toggle rather than type. While a +/// terminal has the keyboard ([inTerminal]) only Cmd+T and Ctrl+` toggle: +/// Ctrl+T (transpose-chars) and Alt+T (ESC t, transpose-words) reach the +/// shell. /// /// A held chord's repeats match too (and are swallowed); only its first /// press toggles. -bool terminalToggleShortcut(KeyEvent event, HardwareKeyboard keyboard) { +bool terminalToggleShortcut( + KeyEvent event, + HardwareKeyboard keyboard, { + bool inTerminal = false, +}) { if (event is KeyUpEvent) return false; final control = keyboard.isControlPressed; final meta = keyboard.isMetaPressed; @@ -24,6 +29,7 @@ bool terminalToggleShortcut(KeyEvent event, HardwareKeyboard keyboard) { event.logicalKey == LogicalKeyboardKey.keyT || alt && event.physicalKey == PhysicalKeyboardKey.keyT; if (!t || keyboard.isShiftPressed) return false; + if (inTerminal) return meta && !control && !alt; return [control, meta, alt].where((pressed) => pressed).length == 1; } @@ -66,6 +72,15 @@ class TerminalShortcutLabels { 'Ctrl+`', ]; + /// The keys that still hide the terminal while it has the keyboard: its + /// Ctrl+T and Alt+T are the shell's. + List get toggleInTerminal => [if (!web && _apple) 'Cmd+T', 'Ctrl+`']; + + /// How the in-terminal exception reads in the menu and the cheatsheet. + String get inTerminalNote => + 'Inside the terminal, ${_apple ? 'Option+T' : 'Alt+T'} and Ctrl+T ' + 'reach the shell; ${toggleInTerminal.join(' or ')} hides it.'; + /// The keys that move between tabs, or none where the browser keeps them. List get tabs => web ? const [] : const ['Ctrl+Tab', 'Ctrl+Shift+Tab']; @@ -76,6 +91,7 @@ class TerminalShortcutLabels { /// Every shortcut, one per line, for the terminal's menu. String get summary => [ 'Show or hide: ${toggle.join(', ')}', + inTerminalNote, if (tabs.isNotEmpty) 'Next or previous tab: ${tabs.join(' / ')}', 'Copy selected text: $copy', ].join('\n'); diff --git a/app/lib/features/terminal/terminal_surface.dart b/app/lib/features/terminal/terminal_surface.dart index 404d391a..db648268 100644 --- a/app/lib/features/terminal/terminal_surface.dart +++ b/app/lib/features/terminal/terminal_surface.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../core/api_gateway.dart'; +import '../../ui/input/keyboard_owner.dart'; import '../../ui/motion/motion.dart'; import 'terminal_focus.dart'; import 'terminal_hub.dart'; @@ -81,6 +82,9 @@ class _TerminalSurfaceState extends State bool _panelShown = false; String? _selected; + /// The key of the toggle chord held down, if any. + PhysicalKeyboardKey? _toggleKey; + @override void initState() { super.initState(); @@ -150,8 +154,21 @@ class _TerminalSurfaceState extends State KeyEventResult _key(KeyEvent event) { if (!mounted) return KeyEventResult.ignored; final keyboard = HardwareKeyboard.instance; - if (terminalToggleShortcut(event, keyboard)) { - if (event is KeyDownEvent) toggle(); + // A held toggle chord's repeats stay swallowed after the terminal it + // showed takes the keyboard (where Alt+T and Ctrl+T are the shell's). + if (event.physicalKey == _toggleKey) { + if (event is KeyUpEvent) _toggleKey = null; + if (event is KeyRepeatEvent) return KeyEventResult.handled; + } + if (terminalToggleShortcut( + event, + keyboard, + inTerminal: primaryFocusIsTypingSurface(), + )) { + if (event is KeyDownEvent) { + _toggleKey = event.physicalKey; + toggle(); + } return KeyEventResult.handled; } final step = terminalTabShortcut(event, keyboard); diff --git a/app/notes/chat-interactive-terminal.md b/app/notes/chat-interactive-terminal.md index fbb5a417..53a31290 100644 --- a/app/notes/chat-interactive-terminal.md +++ b/app/notes/chat-interactive-terminal.md @@ -28,7 +28,30 @@ emulator. Auth flows that print a link, wait for a pasted token and continue Android/iOS the toolbar also has a text field ("Type input, then Enter") for the soft keyboard, with a Hide typing toggle; it is emptied when sent. - The terminal is resized to its layout (debounced 150 ms); the process gets - SIGWINCH. New runs start at the last laid-out size. + SIGWINCH. New runs start at the last laid-out size. A live terminal does + not reflow (xterm.dart's reflow left the cursor on another line's row, so + prompts landed on old output and rows merged): narrowing cuts rows at the + new width (the cut cells are erased, so widening never brings stale text + back), fewer rows drop blank rows below the cursor and then scroll the top + into scrollback with the cursor's row at the bottom, more rows bring + scrollback back above it. Finished output still reflows to its card. + - **Keys** (`chat_shell_terminal_{input,key_input,keymap}.dart`): the view + encodes hardware keys before xterm.dart does, with the event's real + character, and a `TerminalInputHandler` chained before the package's + defaults encodes `keyInput` calls (key toolbar, soft keyboard) the same + way. Alt is Meta (ESC + the character, Shift and layout included; Macs: + the Option as Meta setting, the key's own character instead of Option's + symbol). Ctrl maps letters and `@ 2 Space`→NUL, `[ 3`→ESC, `\ 4`→0x1c, + `] 5`→0x1d, `^ 6`→0x1e, `_ / - 7`→0x1f, `? 8`→DEL. Arrows, Home/End, + Insert/Delete, PgUp/PgDn and F1–F12 carry xterm's modifier parameter + (1 + Shift 1 + Alt 2 + Ctrl 4: Shift+Up `CSI 1;2A`, Alt+Left `CSI 1;3D`, + Ctrl+Shift+Right `CSI 1;6C`, Ctrl+PgDn `CSI 6;5~`, Shift+F1 `CSI 1;2P`); + unmodified arrows and Home/End are SS3 under DECCKM. With DECKPAM the + keypad's Enter and operators send SS3 (`ESC O M`, `k`, `m`, `j`, `o`); + keypad digits keep typing (NumLock on). Alt+Backspace is `ESC DEL`, + Ctrl+Backspace `^H`, Shift+Tab `CSI Z`, Alt+Enter `ESC CR`. Ctrl+Alt + typing a composed symbol outside Apple platforms (AltGr) types it. + Cmd (Meta key) chords and plain typing are left to the emulator. - Printed `http(s)` links open in the browser on tap (wrapped links are joined). Other schemes are ignored. - Finished runs are drawn read-only, shrunk to the rows their output takes @@ -92,8 +115,16 @@ emulator. Auth flows that print a link, wait for a pasted token and continue position) for a live run, so two open clients send two answers. xterm.dart 4.0.0 answers DSR 6 zero-based; the app overrides it to the correct one-based answer. -- xterm.dart 4.0.0 keeps blank rows when it rewraps; the app drops blank rows - below the cursor after a resize so the top of the output stays in view. +- xterm.dart 4.0.0 keeps blank rows when it rewraps; for finished output + (the only output that reflows) the app drops blank rows below the cursor + after a resize so the top of the output stays in view. +- A live terminal's long lines are cut, not rewrapped, when it narrows, and + stay cut when it widens again (as xterm without reflow). +- Key encoding gaps: no modifyOtherKeys / CSI u (Ctrl+Shift+letter sends the + plain control code, Ctrl+1/9/0 type the digit); Alt as Meta on Linux + assumes AltGr arrives as Ctrl+Alt or its own key; a Mac's Option as Meta + takes the character from the logical key, else the US position of the + physical key, so a non-US Mac layout's Option+key may send the US letter. - Desktop typing uses key events (no IME composition for CJK input). Touch platforms use the field. - A descendant that keeps the PTY open after the command exits is read for @@ -110,7 +141,7 @@ emulator. Auth flows that print a link, wait for a pasted token and continue `chat_shell_plain.go`, `chat_shell_runner.go`, `chat_shell_supervise.go`, `chat_shell_run_handlers.go`, `chat_shell_share.go`, `chat.go`, `websocket.go`; `internal/pipeline/chat_shell_runs.go`; `go.mod`, `go.sum`. -- App: `lib/features/chat/shell/chat_shell_terminal_{session,view,keys,theme,links,page}.dart`, +- App: `lib/features/chat/shell/chat_shell_terminal_{session,view,keys,theme,links,page,input,key_input,keymap}.dart`, `chat_shell_terminals.dart`, `chat_shell_output_view.dart`, `chat_shell_run{,_card}.dart`, `chat_shell_card_actions.dart`, `chat_shell_runs_{controller,repository}.dart`, `chat_shell_metrics.dart`; diff --git a/app/notes/terminal-panel.md b/app/notes/terminal-panel.md index 44683a39..f61e21b0 100644 --- a/app/notes/terminal-panel.md +++ b/app/notes/terminal-panel.md @@ -25,14 +25,20 @@ tmux inside it for work that must survive that). own login and asks for the password again. - **Shortcuts** (`terminal_shortcuts.dart`, handled by the surface as a `FocusManager` early key handler, so they work wherever focus is, including - inside the terminal and in the chat composer, and neither receives the key): + in the chat composer, which does not receive the key): - **Alt+T** (Option+T), **Ctrl+T**, **Cmd+T** (Meta+T) and **Ctrl+`** show or hide the terminal in the selected mode; on a narrow window they open and close the full-screen page. Only the one modifier counts (Ctrl+Shift+T, Ctrl+Alt+T pass through); Option+T, which types † on a Mac, is also matched by key position. Cmd+` stays the macOS window - switcher. **The shell's own Ctrl+T (transpose-chars) no longer reaches - it** while this binding is on. + switcher. + - **Inside a focused terminal** (any `TypingSurface`, i.e. a terminal + view) only **Cmd+T** and **Ctrl+`** toggle: **Ctrl+T** reaches the shell + as `^T` (transpose-chars) and **Alt+T** as `ESC t` (transpose-words). + A held chord that opened the terminal from outside keeps its repeats + swallowed after the terminal takes the keyboard, so nothing is typed. + The ⋮ menu and the shortcut cheatsheet say so + (`TerminalShortcutLabels.inTerminalNote`). - **Ctrl+Tab / Ctrl+Shift+Tab**, while the terminal is shown (panel, window or narrow page), select the next / previous terminal tab, wrapping, and focus it. This deliberately overrides the chat's Ctrl+Tab pane @@ -89,9 +95,16 @@ tmux inside it for work that must survive that). from its retained output. A dropped connection resumes after the last byte held. A restarted server lists the terminals as ended, with why. - **Keyboard:** a focused terminal gets every key (Ctrl-C, Esc, Tab, arrows, - Ctrl-letters) except the shortcuts above (Ctrl+T, Alt+T, Cmd+T, Ctrl+`, - and Ctrl+Tab while shown); paste is Cmd-V (Apple) or Ctrl-V/Ctrl-Shift-V. Clicking - elsewhere moves focus away normally. + Ctrl-letters, Ctrl+T, Alt+T) except Cmd+T, Ctrl+` and Ctrl+Tab while + shown; paste is Cmd-V (Apple) or Ctrl-V/Ctrl-Shift-V. Clicking elsewhere + moves focus away normally. Keys are encoded as xterm does; see + `chat-interactive-terminal.md` (Keys). **Option as Meta** (Settings → + Appearance → Terminal, Macs only, saved with the layout, default on): a + Mac's Option sends `ESC` + the key's character (Option+B = `ESC b`) + instead of typing its symbol (∫). On by default because the shell's + Meta bindings (word motion, transpose, yank-last-arg) are used far more + in a terminal than Option's symbols; turn it off to type them. Other + platforms' Alt is always Meta. - No terminal request is sent until the terminal is first shown (or a terminal is opened): each connection sends one request at a time, so the first screen's read is never queued behind `terminal_list`. @@ -391,3 +404,26 @@ The tmux results above (restart survival, client replacement, the service outlived it and was killed by hand. - Not verified: logging in for real (needs the operator's password), Linux su, and the app against a live server in a browser (widget tests only). + +### Terminal input and resize fixes, round 1 (2026-11-25) + +- Resize: live terminals run with `reflowEnabled: false`; the old + blank-row-trimming `resize` override now applies only to finished + (reflowing) output, and narrowing erases cells past the new width. + Tests: `test/features/chat/shell/chat_shell_terminal_resize_test.dart` + (long lines shrink/grow with the prompt on the cursor row, shell redraw + and command output after shrinking, no stale text after widening, cleared + screen and scrollback stay cleared, a view whose box shrinks and grows). +- Keys: xterm encoding for Alt/Meta, Ctrl symbols, modified special keys, + DECCKM and DECKPAM (`chat-interactive-terminal.md`, Keys); Option as Meta + setting. Tests: `chat_shell_terminal_input_test.dart` (key event to + bytes, Linux and macOS variants, setting on and off, toolbar `keyInput`), + `chat_shell_terminal_test.dart` (keys through the real view, Ctrl-V paste + intact), `terminal_surface_test.dart` (setting saved and restored, hidden + off Apple platforms). +- Shortcuts: inside a terminal Alt+T and Ctrl+T reach the shell; Cmd+T + and Ctrl+` still toggle (`terminal_shortcuts_test.dart`). +- Not verified: bytes against a real PTY in a browser or native build after + the change (widget tests only), real macOS Option events (native and + browser logical-key shapes are assumed as the tests model them), AltGr on + a real non-US Linux/Windows layout. diff --git a/app/test/features/chat/shell/chat_shell_terminal_input_test.dart b/app/test/features/chat/shell/chat_shell_terminal_input_test.dart new file mode 100644 index 00000000..888489d6 --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_terminal_input_test.dart @@ -0,0 +1,309 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_run.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_key_input.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_session.dart'; +import 'package:xterm/core.dart'; + +/// Modifiers held, as [chatShellKeyEventBytes] reads them. +class _Held extends HardwareKeyboard { + _Held(String mods) + : shift = mods.contains('S'), + alt = mods.contains('A'), + ctrl = mods.contains('C'), + meta = mods.contains('M'); + final bool shift, alt, ctrl, meta; + @override + bool get isShiftPressed => shift; + @override + bool get isAltPressed => alt; + @override + bool get isControlPressed => ctrl; + @override + bool get isMetaPressed => meta; +} + +KeyDownEvent _down( + LogicalKeyboardKey logical, { + PhysicalKeyboardKey? physical, + String? character, +}) => KeyDownEvent( + physicalKey: physical ?? PhysicalKeyboardKey.keyA, + logicalKey: logical, + character: character, + timeStamp: Duration.zero, +); + +/// The bytes a key sends with [mods] (S Shift, A Alt, C Ctrl, M Meta). +String? _bytes( + LogicalKeyboardKey logical, { + String mods = '', + String? character, + PhysicalKeyboardKey? physical, + Terminal? terminal, + bool optionAsMeta = true, +}) => chatShellKeyEventBytes( + _down(logical, physical: physical, character: character), + _Held(mods), + terminal ?? Terminal(), + optionAsMeta: optionAsMeta, +); + +const _l = LogicalKeyboardKey.new; + +void main() { + final linux = TargetPlatformVariant.only(TargetPlatform.linux); + final mac = TargetPlatformVariant.only(TargetPlatform.macOS); + + testWidgets('Alt is Meta: ESC and the character typed, Shift and layout ' + 'included', (tester) async { + expect(_bytes(LogicalKeyboardKey.keyB, mods: 'A', character: 'b'), '\x1bb'); + expect(_bytes(LogicalKeyboardKey.keyF, mods: 'A', character: 'f'), '\x1bf'); + expect(_bytes(LogicalKeyboardKey.keyD, mods: 'A', character: 'd'), '\x1bd'); + expect( + _bytes(LogicalKeyboardKey.keyB, mods: 'AS', character: 'B'), + '\x1bB', + ); + expect( + _bytes(LogicalKeyboardKey.period, mods: 'A', character: '.'), + '\x1b.', + ); + expect( + _bytes(LogicalKeyboardKey.digit1, mods: 'A', character: '1'), + '\x1b1', + ); + // Without a character (some platforms send none with Alt): the key's. + expect(_bytes(LogicalKeyboardKey.keyT, mods: 'A'), '\x1bt'); + expect(_bytes(LogicalKeyboardKey.period, mods: 'AS'), '\x1b>'); + // A non-US layout's own character (AZERTY's A key types "q"). + expect(_bytes(LogicalKeyboardKey.keyQ, mods: 'A', character: 'q'), '\x1bq'); + expect(_bytes(LogicalKeyboardKey.backspace, mods: 'A'), '\x1b\x7f'); + expect(_bytes(LogicalKeyboardKey.enter, mods: 'A'), '\x1b\r'); + expect( + _bytes(LogicalKeyboardKey.space, mods: 'A', character: ' '), + '\x1b ', + ); + }, variant: linux); + + testWidgets('Ctrl sends the control code of letters and symbols', ( + tester, + ) async { + final table = <(LogicalKeyboardKey, String, String), String>{ + (LogicalKeyboardKey.keyA, '', 'a'): '\x01', + (LogicalKeyboardKey.keyT, '', 't'): '\x14', + (LogicalKeyboardKey.keyT, 'S', 'T'): '\x14', + (LogicalKeyboardKey.slash, '', '/'): '\x1f', + (LogicalKeyboardKey.bracketRight, '', ']'): '\x1d', + (LogicalKeyboardKey.backslash, '', '\\'): '\x1c', + (LogicalKeyboardKey.bracketLeft, '', '['): '\x1b', + (LogicalKeyboardKey.minus, 'S', '_'): '\x1f', + (LogicalKeyboardKey.digit2, '', '2'): '\x00', + (LogicalKeyboardKey.digit2, 'S', '@'): '\x00', + (LogicalKeyboardKey.digit6, 'S', '^'): '\x1e', + (LogicalKeyboardKey.digit8, '', '8'): '\x7f', + (LogicalKeyboardKey.space, '', ' '): '\x00', + (LogicalKeyboardKey.keyB, 'A', 'b'): '\x1b\x02', + }; + for (final MapEntry(key: (key, mods, character), value: bytes) + in table.entries) { + expect( + _bytes(key, mods: 'C$mods', character: character), + bytes, + reason: 'Ctrl+$mods $character', + ); + } + // A control character as the event's character still maps by key. + expect( + _bytes(LogicalKeyboardKey.slash, mods: 'C', character: '\x1f'), + '\x1f', + ); + expect(_bytes(LogicalKeyboardKey.backspace, mods: 'C'), '\b'); + // Ctrl+1 has no control code: the emulator types it. + expect( + _bytes(LogicalKeyboardKey.digit1, mods: 'C', character: '1'), + isNull, + ); + }, variant: linux); + + testWidgets('modified special keys use the xterm modifier parameter', ( + tester, + ) async { + const up = LogicalKeyboardKey.arrowUp; + expect(_bytes(up), '\x1b[A'); + expect(_bytes(up, mods: 'S'), '\x1b[1;2A'); + expect(_bytes(LogicalKeyboardKey.arrowLeft, mods: 'A'), '\x1b[1;3D'); + expect(_bytes(LogicalKeyboardKey.arrowDown, mods: 'AS'), '\x1b[1;4B'); + expect(_bytes(LogicalKeyboardKey.arrowRight, mods: 'C'), '\x1b[1;5C'); + expect(_bytes(up, mods: 'CS'), '\x1b[1;6A'); + expect(_bytes(up, mods: 'CA'), '\x1b[1;7A'); + expect(_bytes(up, mods: 'CAS'), '\x1b[1;8A'); + expect(_bytes(LogicalKeyboardKey.home), '\x1b[H'); + expect(_bytes(LogicalKeyboardKey.end, mods: 'S'), '\x1b[1;2F'); + expect(_bytes(LogicalKeyboardKey.home, mods: 'C'), '\x1b[1;5H'); + expect(_bytes(LogicalKeyboardKey.pageUp), '\x1b[5~'); + expect(_bytes(LogicalKeyboardKey.pageUp, mods: 'S'), '\x1b[5;2~'); + expect(_bytes(LogicalKeyboardKey.pageDown, mods: 'C'), '\x1b[6;5~'); + expect(_bytes(LogicalKeyboardKey.insert), '\x1b[2~'); + expect(_bytes(LogicalKeyboardKey.delete), '\x1b[3~'); + expect(_bytes(LogicalKeyboardKey.delete, mods: 'A'), '\x1b[3;3~'); + expect(_bytes(LogicalKeyboardKey.f1), '\x1bOP'); + expect(_bytes(LogicalKeyboardKey.f1, mods: 'S'), '\x1b[1;2P'); + expect(_bytes(LogicalKeyboardKey.f4, mods: 'C'), '\x1b[1;5S'); + expect(_bytes(LogicalKeyboardKey.f5), '\x1b[15~'); + expect(_bytes(LogicalKeyboardKey.f12, mods: 'C'), '\x1b[24;5~'); + expect(_bytes(LogicalKeyboardKey.tab, mods: 'S'), '\x1b[Z'); + expect(_bytes(LogicalKeyboardKey.tab), '\t'); + expect(_bytes(LogicalKeyboardKey.enter), '\r'); + expect(_bytes(LogicalKeyboardKey.escape), '\x1b'); + expect(_bytes(LogicalKeyboardKey.backspace), '\x7f'); + }, variant: linux); + + testWidgets('application cursor keys and keypad mode', (tester) async { + final terminal = Terminal()..write('\x1b[?1h'); + String? bytes(LogicalKeyboardKey key, [String mods = '']) => + _bytes(key, mods: mods, terminal: terminal); + expect(bytes(LogicalKeyboardKey.arrowUp), '\x1bOA'); + expect(bytes(LogicalKeyboardKey.arrowLeft), '\x1bOD'); + expect(bytes(LogicalKeyboardKey.home), '\x1bOH'); + expect(bytes(LogicalKeyboardKey.end), '\x1bOF'); + // Modified keys are the same in either mode. + expect(bytes(LogicalKeyboardKey.arrowUp, 'C'), '\x1b[1;5A'); + // The keypad's operators and Enter follow DECKPAM; digits keep typing. + expect(bytes(LogicalKeyboardKey.numpadAdd), isNull); + expect(bytes(LogicalKeyboardKey.numpadEnter), '\r'); + terminal.write('\x1b='); + expect(bytes(LogicalKeyboardKey.numpadAdd), '\x1bOk'); + expect(bytes(LogicalKeyboardKey.numpadEnter), '\x1bOM'); + expect(bytes(LogicalKeyboardKey.numpadDivide), '\x1bOo'); + expect(bytes(LogicalKeyboardKey.numpad1), isNull); + terminal.write('\x1b>\x1b[?1l'); + expect(bytes(LogicalKeyboardKey.arrowUp), '\x1b[A'); + expect(bytes(LogicalKeyboardKey.numpadAdd), isNull); + // Enter in line feed mode (LNM). + terminal.write('\x1b[20h'); + expect(bytes(LogicalKeyboardKey.enter), '\r\n'); + }, variant: linux); + + testWidgets('plain typing, Cmd chords and AltGr are left to the emulator', ( + tester, + ) async { + expect(_bytes(LogicalKeyboardKey.keyA, character: 'a'), isNull); + expect(_bytes(LogicalKeyboardKey.keyA, mods: 'S', character: 'A'), isNull); + expect(_bytes(LogicalKeyboardKey.space, character: ' '), isNull); + expect(_bytes(LogicalKeyboardKey.keyK, mods: 'M', character: 'k'), isNull); + // German AltGr+Q types @. + expect( + _bytes( + LogicalKeyboardKey.keyQ, + mods: 'CA', + character: '@', + physical: PhysicalKeyboardKey.keyQ, + ), + isNull, + ); + }, variant: linux); + + testWidgets('a Mac\'s Option is Meta while the setting is on', ( + tester, + ) async { + // Option+B types ∫; its logical key is B (natively) or ∫ (browsers). + expect(_bytes(LogicalKeyboardKey.keyB, mods: 'A', character: '∫'), '\x1bb'); + expect( + _bytes( + _l(0x222b), + mods: 'A', + character: '∫', + physical: PhysicalKeyboardKey.keyB, + ), + '\x1bb', + ); + expect( + _bytes( + _l(0x0131), + mods: 'AS', + character: 'ı', + physical: PhysicalKeyboardKey.keyB, + ), + '\x1bB', + ); + expect( + _bytes( + _l(0x2265), + mods: 'A', + character: '≥', + physical: PhysicalKeyboardKey.period, + ), + '\x1b.', + ); + expect(_bytes(LogicalKeyboardKey.backspace, mods: 'A'), '\x1b\x7f'); + expect(_bytes(LogicalKeyboardKey.slash, mods: 'C', character: '/'), '\x1f'); + // Off, Option types its symbol; special keys keep the Alt parameter. + expect( + _bytes( + LogicalKeyboardKey.keyB, + mods: 'A', + character: '∫', + optionAsMeta: false, + ), + isNull, + ); + expect( + _bytes(LogicalKeyboardKey.backspace, mods: 'A', optionAsMeta: false), + '\x7f', + ); + expect( + _bytes(LogicalKeyboardKey.arrowLeft, mods: 'A', optionAsMeta: false), + '\x1b[1;3D', + ); + expect( + _bytes(LogicalKeyboardKey.arrowLeft, mods: 'A', optionAsMeta: true), + '\x1b[1;3D', + ); + }, variant: mac); + + ChatShellTerminalSession session(List sent, bool Function() meta) => + ChatShellTerminalSession( + ChatShellRun.fromJson({ + 'id': 'run_1', + 'command': 'sh', + 'directory': '/w', + 'status': 'running', + 'started_at': 1, + 'output': '', + 'output_bytes': 0, + 'terminal': true, + 'cols': 40, + 'rows': 10, + })!, + onInput: sent.add, + onResize: (_, _) {}, + optionAsMeta: meta, + ); + + testWidgets('the toolbar and soft keyboard keys go through the same ' + 'encoding', (tester) async { + final sent = []; + final terminal = session(sent, () => true).terminal; + terminal.keyInput(TerminalKey.arrowUp); + terminal.write('\x1b[?1h'); + terminal.keyInput(TerminalKey.arrowUp); + terminal.keyInput(TerminalKey.keyB, alt: true); + terminal.keyInput(TerminalKey.keyB, alt: true, shift: true); + terminal.keyInput(TerminalKey.slash, ctrl: true); + terminal.keyInput(TerminalKey.arrowLeft, alt: true); + // A plain letter is typed as its text instead. + expect(terminal.keyInput(TerminalKey.keyB), isFalse); + expect(sent, ['\x1b[A', '\x1bOA', '\x1bb', '\x1bB', '\x1f', '\x1b[1;3D']); + }, variant: linux); + + testWidgets('on a Mac with Option as Meta off, the package does not ' + 'send its own Alt sequence', (tester) async { + final sent = []; + var meta = false; + final terminal = session(sent, () => meta).terminal; + expect(terminal.keyInput(TerminalKey.keyB, alt: true), isFalse); + meta = true; + expect(terminal.keyInput(TerminalKey.keyB, alt: true), isTrue); + expect(sent, ['\x1bb']); + }, variant: mac); +} diff --git a/app/test/features/chat/shell/chat_shell_terminal_resize_test.dart b/app/test/features/chat/shell/chat_shell_terminal_resize_test.dart new file mode 100644 index 00000000..c2814b23 --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_terminal_resize_test.dart @@ -0,0 +1,165 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_run.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_session.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_view.dart'; +import 'package:xterm/core.dart'; + +ChatShellTerminalSession _session({int cols = 40, int rows = 10}) => + ChatShellTerminalSession( + ChatShellRun.fromJson({ + 'id': 'run_1', + 'command': 'sh', + 'directory': '/w', + 'status': 'running', + 'started_at': 1, + 'output': '', + 'output_bytes': 0, + 'terminal': true, + 'cols': cols, + 'rows': rows, + })!, + onInput: (_) {}, + onResize: (_, _) {}, + ); + +/// The rows on screen, trimmed. +List _screen(Terminal terminal) { + final buffer = terminal.buffer; + final top = buffer.height - terminal.viewHeight; + return [ + for (var y = 0; y < terminal.viewHeight; y++) + buffer.lines[top + y].getText().trimRight(), + ]; +} + +String _cursorRow(Terminal terminal) => terminal + .buffer + .lines[terminal.buffer.absoluteCursorY] + .getText() + .trimRight(); + +/// Twelve output lines of 58 characters (two rows each at 40 columns), then +/// a prompt. +String _longLines() => [ + for (var i = 0; i < 12; i++) + 'line ${i.toString().padLeft(2, '0')} ${'x' * 50}', + r'$ ', +].join('\r\n'); + +void main() { + test('shrinking keeps the prompt on the cursor row at the bottom, and ' + 'growing brings the rows above back in order', () { + final terminal = _session().terminal..write(_longLines()); + expect(terminal.buffer.cursorY, 9); + expect(_cursorRow(terminal), r'$'); + + terminal.resize(20, 5); + expect(terminal.buffer.cursorY, 4); + expect(_cursorRow(terminal), r'$'); + // Line 11's second row (cut at 20 columns), then the prompt. + expect(_screen(terminal), [ + 'line 10 ${'x' * 12}', + 'x' * 18, + 'line 11 ${'x' * 12}', + 'x' * 18, + r'$', + ]); + + // The shell redraws its prompt and runs a command: nothing lands on + // old rows and no rows merge. + terminal.write('\r\x1b[K\$ ls\r\nout\r\n\$ '); + expect(_screen(terminal).sublist(2), [r'$ ls', 'out', r'$']); + + terminal.resize(40, 10); + expect(terminal.buffer.cursorY, 9); + expect(_cursorRow(terminal), r'$'); + final screen = _screen(terminal); + expect(screen.sublist(7), [r'$ ls', 'out', r'$']); + // Rows cut while narrow stay cut: no stale text past column 20. + for (final row in screen) { + expect(row.length, lessThanOrEqualTo(20), reason: row); + } + }); + + test('a prompt redrawn while narrow does not grow stale text when the ' + 'terminal widens again', () { + final terminal = _session().terminal..write('\$ ${'abcdefghij' * 3}'); + terminal.resize(10, 10); + terminal.write('\r\x1b[K\$ '); + terminal.resize(40, 10); + expect(_cursorRow(terminal), r'$'); + expect(terminal.buffer.cursorX, 2); + }); + + test('a cleared screen and scrollback stay cleared across resizes', () { + final terminal = _session().terminal..write(_longLines()); + terminal.write('\x1b[H\x1b[2J\x1b[3J\$ '); + terminal.resize(20, 5); + terminal.resize(40, 12); + expect(_screen(terminal), [r'$', for (var i = 0; i < 11; i++) '']); + expect(terminal.buffer.height, 12); + expect(terminal.buffer.absoluteCursorY, 0); + }); + + test('fewer rows than the output drop blank rows below the cursor first', () { + final terminal = _session().terminal..write('a\r\nb\r\n\$ '); + terminal.resize(40, 4); + expect(_screen(terminal), ['a', 'b', r'$', '']); + expect(terminal.buffer.absoluteCursorY, 2); + terminal.resize(40, 10); + expect(_screen(terminal).take(3), ['a', 'b', r'$']); + expect(terminal.buffer.absoluteCursorY, 2); + }); + + testWidgets('the view resizes the live terminal as its box changes, ' + 'keeping the prompt on the cursor row', (tester) async { + final session = _session(cols: 80, rows: 24); + final sizes = <(int, int)>[]; + session.terminal.onResize = (cols, rows, _, _) => sizes.add((cols, rows)); + session.terminal.write(_longLines()); + var size = const Size(600, 300); + late StateSetter setSize; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: StatefulBuilder( + builder: (context, setState) { + setSize = setState; + return SizedBox.fromSize( + size: size, + child: ChatShellTerminalView(session: session, fill: true), + ); + }, + ), + ), + ), + ), + ); + await tester.pump(); + final wide = session.terminal.viewWidth; + // The prompt is the 13th line; the screen has room below it. + final row = session.terminal.buffer.cursorY; + expect(row, 12); + expect(_cursorRow(session.terminal), r'$'); + + setSize(() => size = const Size(250, 120)); + await tester.pump(); + final terminal = session.terminal; + expect(terminal.viewWidth, lessThan(wide)); + expect(terminal.buffer.cursorY, terminal.viewHeight - 1); + expect(_cursorRow(terminal), r'$'); + + setSize(() => size = const Size(600, 300)); + await tester.pump(); + expect(terminal.viewWidth, wide); + // The rows that scrolled off come back above the prompt. + expect(terminal.buffer.cursorY, row); + expect(_cursorRow(terminal), r'$'); + expect(_screen(terminal)[row - 1], startsWith('line 11')); + expect(_screen(terminal)[0], startsWith('line 00')); + expect(sizes.length, greaterThanOrEqualTo(3)); + }); +} diff --git a/app/test/features/chat/shell/chat_shell_terminal_session_test.dart b/app/test/features/chat/shell/chat_shell_terminal_session_test.dart index 7394fed9..55a1a335 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_session_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_session_test.dart @@ -85,7 +85,8 @@ void main() { ); }); - test('narrowing rewraps without pushing the first line out of view', () { + test('narrowing a live terminal cuts rows instead of rewrapping, keeping ' + 'the first line and the cursor on its own', () { final session = ChatShellTerminalSession( _run('first\r\n${'u' * 30}\r\nprompt: '), onInput: (_) {}, @@ -95,11 +96,26 @@ void main() { final buffer = session.terminal.buffer; expect(buffer.height, 6); expect(buffer.lines[0].getText().trim(), 'first'); - expect(buffer.lines[3].getText().trim(), 'prompt:'); - expect(buffer.absoluteCursorY, 3); + expect(buffer.lines[1].getText().trim(), 'u' * 20); + expect(buffer.lines[2].getText().trim(), 'prompt:'); + expect(buffer.absoluteCursorY, 2); expect(buffer.cursorX, 8); }); + test('finished output still rewraps to the width it is shown at', () { + final session = ChatShellTerminalSession( + _run('first\r\n${'u' * 30}\r\nend', status: 'exited'), + onInput: (_) {}, + onResize: (_, _) {}, + ); + session.terminal.resize(20, 6); + final buffer = session.terminal.buffer; + expect(buffer.lines[0].getText().trim(), 'first'); + expect(buffer.lines[1].getText().trim(), 'u' * 20); + expect(buffer.lines[2].getText().trim(), 'u' * 10); + expect(buffer.lines[3].getText().trim(), 'end'); + }); + test('a finished run counts the rows its output takes at a width', () { final session = ChatShellTerminalSession( _run('a\r\n${'x' * 50}\r\nend\r\n', status: 'exited'), diff --git a/app/test/features/chat/shell/chat_shell_terminal_test.dart b/app/test/features/chat/shell/chat_shell_terminal_test.dart index b6cf9af7..db5a9644 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_test.dart @@ -110,6 +110,109 @@ void main() { ); } + Future press( + WidgetTester tester, + LogicalKeyboardKey key, { + List modifiers = const [], + String? character, + PhysicalKeyboardKey? physical, + }) async { + for (final modifier in modifiers) { + await tester.sendKeyDownEvent(modifier); + } + await tester.sendKeyDownEvent( + key, + character: character, + physicalKey: physical, + ); + await tester.sendKeyUpEvent(key, physicalKey: physical); + for (final modifier in modifiers.reversed) { + await tester.sendKeyUpEvent(modifier); + } + await tester.pump(); + } + + testWidgets('the focused terminal sends xterm bytes for Alt, Ctrl and ' + 'modified keys, and the copy and paste keys still work', (tester) async { + await openRunning(tester, output: r'$ '); + await tester.tap(find.byType(TerminalView)); + await tester.pump(); + const alt = [LogicalKeyboardKey.altLeft]; + const ctrl = [LogicalKeyboardKey.controlLeft]; + const shift = [LogicalKeyboardKey.shiftLeft]; + await press(tester, LogicalKeyboardKey.keyB, modifiers: alt); + await press(tester, LogicalKeyboardKey.keyF, modifiers: alt); + await press(tester, LogicalKeyboardKey.period, modifiers: alt); + await press( + tester, + LogicalKeyboardKey.keyB, + modifiers: [...alt, ...shift], + character: 'B', + ); + await press(tester, LogicalKeyboardKey.backspace, modifiers: alt); + await press(tester, LogicalKeyboardKey.slash, modifiers: ctrl); + await press(tester, LogicalKeyboardKey.bracketRight, modifiers: ctrl); + await press(tester, LogicalKeyboardKey.arrowUp, modifiers: shift); + await press(tester, LogicalKeyboardKey.arrowLeft, modifiers: alt); + await press(tester, LogicalKeyboardKey.arrowRight, modifiers: ctrl); + await press(tester, LogicalKeyboardKey.keyT, modifiers: ctrl); + await press(tester, LogicalKeyboardKey.keyX); + expect( + typed(), + '\x1bb\x1bf\x1b.\x1bB\x1b\x7f\x1f\x1d' + '\x1b[1;2A\x1b[1;3D\x1b[1;5C\x14x', + ); + // Application cursor keys from the process's own mode switch. + gateway.emitOutput('run_t', '\x1b[?1h', 2); + await tester.pump(); + gateway.calls.clear(); + await press(tester, LogicalKeyboardKey.arrowUp); + expect(typed(), '\x1bOA'); + // Ctrl-V is still paste, not ^V. + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async => + call.method == 'Clipboard.getData' ? {'text': 'tok'} : null, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + await press(tester, LogicalKeyboardKey.keyV, modifiers: ctrl); + for (var i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 20)); + } + expect(typed(), '\x1bOAtok'); + await tester.pump(const Duration(milliseconds: 400)); + }, variant: TargetPlatformVariant.only(TargetPlatform.linux)); + + testWidgets( + 'on a Mac, Option is Meta in the terminal', + (tester) async { + await openRunning(tester, output: r'$ '); + await tester.tap(find.byType(TerminalView)); + await tester.pump(); + await press( + tester, + LogicalKeyboardKey.keyB, + modifiers: [LogicalKeyboardKey.altLeft], + character: '∫', + ); + await press( + tester, + const LogicalKeyboardKey(0x2202), + modifiers: [LogicalKeyboardKey.altLeft], + character: '∂', + physical: PhysicalKeyboardKey.keyD, + ); + expect(typed(), '\x1bb\x1bd'); + await tester.pump(const Duration(milliseconds: 400)); + }, + variant: TargetPlatformVariant.only(TargetPlatform.macOS), + ); + testWidgets('on Linux, Ctrl-C copies a selection and interrupts without one; ' 'Ctrl-Insert copies too', (tester) async { await openRunning(tester, output: 'Paste your token: '); diff --git a/app/test/features/terminal/terminal_app.dart b/app/test/features/terminal/terminal_app.dart index cd6e0124..2d2f4024 100644 --- a/app/test/features/terminal/terminal_app.dart +++ b/app/test/features/terminal/terminal_app.dart @@ -90,9 +90,7 @@ class TerminalTestAppState extends State { child: Scaffold( appBar: AppBar( title: const Text('App'), - actions: [ - TerminalToggleButton(layout: widget.layout), - ], + actions: [TerminalToggleButton(layout: widget.layout)], ), body: const TextField(key: appField), ), @@ -125,6 +123,8 @@ Future chord( } } +/// Alt+T: shows or hides the terminal from outside it (inside, it is the +/// shell's ESC t). Future altT(WidgetTester tester, {bool settle = true}) => chord( tester, LogicalKeyboardKey.keyT, @@ -132,6 +132,14 @@ Future altT(WidgetTester tester, {bool settle = true}) => chord( settle: settle, ); +/// Ctrl+`: shows or hides the terminal wherever the keyboard is. +Future toggleTerminal(WidgetTester tester, {bool settle = true}) => chord( + tester, + LogicalKeyboardKey.backquote, + [LogicalKeyboardKey.controlLeft], + settle: settle, +); + Future ctrlTab(WidgetTester tester, {bool reverse = false}) => chord( tester, LogicalKeyboardKey.tab, diff --git a/app/test/features/terminal/terminal_chat_bar_action_test.dart b/app/test/features/terminal/terminal_chat_bar_action_test.dart index ac55adf1..ea65d070 100644 --- a/app/test/features/terminal/terminal_chat_bar_action_test.dart +++ b/app/test/features/terminal/terminal_chat_bar_action_test.dart @@ -57,9 +57,7 @@ Future _pumpBar( await tester.pumpWidget( MaterialApp( theme: theme, - home: actions == null - ? bar - : TerminalScope(actions: actions, child: bar), + home: actions == null ? bar : TerminalScope(actions: actions, child: bar), ), ); await tester.pump(); diff --git a/app/test/features/terminal/terminal_chat_tab_test.dart b/app/test/features/terminal/terminal_chat_tab_test.dart index 2cdc4043..fbd52709 100644 --- a/app/test/features/terminal/terminal_chat_tab_test.dart +++ b/app/test/features/terminal/terminal_chat_tab_test.dart @@ -106,7 +106,7 @@ void main() { // Hidden again: the composer that had the keyboard gets it back, and // Ctrl+Tab is the chat's once more. - await altT(tester); + await toggleTerminal(tester); expect(_composer(tester, 'a').focusNode.hasPrimaryFocus, isTrue); await ctrlTab(tester); expect(workspace.activePane?.sessionId, 'b'); diff --git a/app/test/features/terminal/terminal_motion_test.dart b/app/test/features/terminal/terminal_motion_test.dart index 381c4648..a5aefaea 100644 --- a/app/test/features/terminal/terminal_motion_test.dart +++ b/app/test/features/terminal/terminal_motion_test.dart @@ -48,7 +48,7 @@ void main() { await pumpTerminalApp(tester, hub: hub, layout: layout); await tester.tap(find.byKey(appField)); await tester.pump(); - await altT(tester, settle: false); + await toggleTerminal(tester, settle: false); await tester.pump(const Duration(milliseconds: 100)); expect(panelFinder, findsOneWidget); // Midway: the app has given up part of the panel's height, and the @@ -61,7 +61,7 @@ void main() { expect(appBottom(tester), shown); expect(panelOpacity(tester), 1); - await altT(tester, settle: false); + await toggleTerminal(tester, settle: false); // The keyboard is back in the field at once; the panel leaves after. expect(appFieldFocused(tester), isTrue); await tester.pump(const Duration(milliseconds: 100)); @@ -77,7 +77,7 @@ void main() { 'shrinks away', (tester) async { layout.setMode(TerminalMode.float); await pumpTerminalApp(tester, hub: hub, layout: layout); - await altT(tester, settle: false); + await toggleTerminal(tester, settle: false); // The window is built, then its motion starts. await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); @@ -87,7 +87,7 @@ void main() { expect(appBottom(tester), 800); await tester.pumpAndSettle(); expect(floatScale(tester).scale.value, 1); - await altT(tester, settle: false); + await toggleTerminal(tester, settle: false); await tester.pump(const Duration(milliseconds: 100)); // Hiding: no longer shown, still painted while it shrinks away. expect(floatFinder, findsNothing); @@ -100,7 +100,7 @@ void main() { // AnimationSpeedController plays animations at half speed this way. timeDilation = 2; await pumpTerminalApp(tester, hub: hub, layout: layout); - await altT(tester, settle: false); + await toggleTerminal(tester, settle: false); await tester.pump(const Duration(milliseconds: 300)); expect(appBottom(tester), inExclusiveRange(shown, 800)); await tester.pumpAndSettle(); @@ -112,16 +112,16 @@ void main() { tester, ) async { await pumpTerminalApp(tester, hub: hub, layout: layout, reduceMotion: true); - await altT(tester, settle: false); + await toggleTerminal(tester, settle: false); await tester.pump(); expect(appBottom(tester), shown); expect(panelOpacity(tester), 1); - await altT(tester, settle: false); + await toggleTerminal(tester, settle: false); await tester.pump(); expect(panelFinder, findsNothing); expect(appBottom(tester), 800); layout.setMode(TerminalMode.float); - await altT(tester, settle: false); + await toggleTerminal(tester, settle: false); await tester.pump(); expect(floatScale(tester).scale.value, 1); // The emulator's size reaches the server after its debounce. diff --git a/app/test/features/terminal/terminal_shortcuts_test.dart b/app/test/features/terminal/terminal_shortcuts_test.dart index cf0ac39a..f7eaf1b0 100644 --- a/app/test/features/terminal/terminal_shortcuts_test.dart +++ b/app/test/features/terminal/terminal_shortcuts_test.dart @@ -31,16 +31,48 @@ void main() { String key(String id) => terminalKey('mac', id); + /// Each toggle chord, and what it sends to the shell from inside the + /// terminal (null: it hides the terminal there too). const toggles = { - 'Alt+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.altLeft), - 'Ctrl+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.controlLeft), - 'Cmd+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.metaLeft), - 'Ctrl+`': (LogicalKeyboardKey.backquote, LogicalKeyboardKey.controlLeft), + 'Alt+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.altLeft, '\x1bt'), + 'Ctrl+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.controlLeft, '\x14'), + 'Cmd+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.metaLeft, null), + 'Ctrl+`': ( + LogicalKeyboardKey.backquote, + LogicalKeyboardKey.controlLeft, + null, + ), }; for (final mode in TerminalMode.values) { - for (final MapEntry(key: name, value: (letter, modifier)) + for (final MapEntry(key: name, value: (letter, modifier, sent)) in toggles.entries) { + if (sent != null) { + desktopTestWidgets( + '$name shows the ${mode.label.toLowerCase()} from a text field; ' + 'inside the terminal it reaches the shell', + (tester) async { + layout.setMode(mode); + await pumpTerminalApp(tester, hub: hub, layout: layout); + await tester.tap(find.byKey(appField)); + await tester.pump(); + await chord(tester, letter, [modifier]); + expect(layout.visible, isTrue); + expect(find.text('t'), findsNothing); + expect(terminalFocused(key('term_a')), isTrue); + await chord(tester, letter, [modifier]); + expect(layout.visible, isTrue); + expect(mac.bodies('terminal_input').last['data'], sent); + // Cmd+T and Ctrl+` still hide it from inside. + await chord(tester, LogicalKeyboardKey.backquote, [ + LogicalKeyboardKey.controlLeft, + ]); + expect(layout.visible, isFalse); + await tester.pump(const Duration(milliseconds: 300)); + }, + ); + continue; + } desktopTestWidgets( '$name toggles the ${mode.label.toLowerCase()} from a text ' 'field and from inside the terminal', @@ -58,8 +90,7 @@ void main() { // The shortcut never types into the field it was pressed in. expect(find.text('t'), findsNothing); expect(terminalFocused(key('term_a')), isTrue); - // Inside the terminal the same keys hide it instead of reaching the - // shell (Ctrl+T would be transpose-chars there). + // Inside the terminal the same keys hide it. final typed = mac.bodies('terminal_input').length; await chord(tester, letter, [modifier]); expect(surface, findsNothing); @@ -79,6 +110,54 @@ void main() { timeStamp: Duration.zero, ); expect(terminalToggleShortcut(event, _AltHeld()), isTrue); + // Inside the terminal Option+T is the shell's (ESC t, or † when Option + // is not Meta). + expect( + terminalToggleShortcut(event, _AltHeld(), inTerminal: true), + isFalse, + ); + }); + + test('inside the terminal only Cmd+T and Ctrl+` toggle', () { + KeyDownEvent down(LogicalKeyboardKey key, PhysicalKeyboardKey physical) => + KeyDownEvent( + physicalKey: physical, + logicalKey: key, + timeStamp: Duration.zero, + ); + final t = down(LogicalKeyboardKey.keyT, PhysicalKeyboardKey.keyT); + final tick = down( + LogicalKeyboardKey.backquote, + PhysicalKeyboardKey.backquote, + ); + bool inside(KeyDownEvent event, HardwareKeyboard keyboard) => + terminalToggleShortcut(event, keyboard, inTerminal: true); + expect(inside(t, _AltHeld()), isFalse); + expect(inside(t, _Held(control: true)), isFalse); + expect(inside(t, _Held(meta: true)), isTrue); + expect(inside(tick, _Held(control: true)), isTrue); + expect(terminalToggleShortcut(t, _Held(control: true)), isTrue); + }); + + test('the menu and cheatsheet say which keys reach the shell', () { + expect( + const TerminalShortcutLabels( + web: false, + platform: TargetPlatform.macOS, + ).inTerminalNote, + 'Inside the terminal, Option+T and Ctrl+T reach the shell; Cmd+T or ' + 'Ctrl+` hides it.', + ); + const linuxWeb = TerminalShortcutLabels( + web: true, + platform: TargetPlatform.linux, + ); + expect( + linuxWeb.inTerminalNote, + 'Inside the terminal, Alt+T and Ctrl+T reach the shell; Ctrl+` hides ' + 'it.', + ); + expect(linuxWeb.summary, contains(linuxWeb.inTerminalNote)); }); desktopTestWidgets('holding the chord toggles once and types nothing', ( @@ -127,7 +206,7 @@ void main() { await tester.sendKeyEvent(LogicalKeyboardKey.keyX); await tester.pump(); expect(mac.bodies('terminal_input').last['data'], 'x'); - await altT(tester); + await toggleTerminal(tester); expect(appFieldFocused(tester), isTrue); // The bar button focuses it as well. await tester.tap(find.byIcon(Icons.terminal)); @@ -170,7 +249,7 @@ void main() { await ctrlTab(tester); expect(hub.selected!.info.id, 'term_a'); expect(terminalFocused(key('term_a')), isTrue); - await altT(tester); + await toggleTerminal(tester); await ctrlTab(tester); expect(hub.selected!.info.id, 'term_a'); }); @@ -195,8 +274,8 @@ void main() { expect(empty.bodies('terminal_open'), hasLength(1)); expect(bare.tabs, hasLength(1)); expect(terminalFocused(bare.tabs.single.key), isTrue); - await altT(tester); - await altT(tester); + await toggleTerminal(tester); + await toggleTerminal(tester); expect(empty.bodies('terminal_open'), hasLength(1)); }); @@ -220,7 +299,7 @@ void main() { await ctrlTab(tester, reverse: true); expect(hub.selected!.info.id, 'term_c'); expect(terminalFocused(key('term_c')), isTrue); - await chord(tester, LogicalKeyboardKey.keyT, [ + await chord(tester, LogicalKeyboardKey.backquote, [ LogicalKeyboardKey.controlLeft, ]); expect(find.widgetWithText(AppBar, 'Terminal'), findsNothing); @@ -284,6 +363,21 @@ void main() { }); } +/// A keyboard with the given modifiers held. +class _Held extends HardwareKeyboard { + _Held({this.control = false, this.meta = false}); + final bool control; + final bool meta; + @override + bool get isAltPressed => false; + @override + bool get isControlPressed => control; + @override + bool get isMetaPressed => meta; + @override + bool get isShiftPressed => false; +} + /// A keyboard on which only Alt (Option) is held. class _AltHeld extends HardwareKeyboard { @override diff --git a/app/test/features/terminal/terminal_surface_test.dart b/app/test/features/terminal/terminal_surface_test.dart index f029887d..5638cadd 100644 --- a/app/test/features/terminal/terminal_surface_test.dart +++ b/app/test/features/terminal/terminal_surface_test.dart @@ -265,6 +265,39 @@ void main() { expect(layout.mode, TerminalMode.panel); }); + Future pumpSettings(WidgetTester tester) => tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: SettingsTerminalSection(layout: layout), + ), + ), + ), + ); + const optionAsMeta = ValueKey('settings-terminal-option-as-meta'); + + desktopTestWidgets('on a Mac, Settings chooses whether Option is Meta, ' + 'saved with the layout', (tester) async { + await pumpSettings(tester); + expect(layout.optionAsMeta, isTrue); + await tester.tap(find.byKey(optionAsMeta)); + await tester.pumpAndSettle(); + expect(layout.optionAsMeta, isFalse); + expect(saved()['option_as_meta'], isFalse); + final restored = TerminalLayout(store: store); + await restored.restore(); + expect(restored.optionAsMeta, isFalse); + }); + + testWidgets( + 'elsewhere Alt is always Meta and there is no Option switch', + (tester) async { + await pumpSettings(tester); + expect(find.byKey(optionAsMeta), findsNothing); + }, + variant: TargetPlatformVariant.only(TargetPlatform.linux), + ); + desktopTestWidgets( 'a narrow window opens the terminal full screen with the key ' 'toolbar', From 9b90806093a4579902fe581606d44e18df4c705b Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:36:32 +0000 Subject: [PATCH 11/17] xterm: fix mouse wheel, drag, motion and middle-button reporting - Wheel buttons were encoded as 68/69 (64 + 4/5, i.e. Shift + wheel down/ wheel right); they are 64 up and 65 down. - Wheel, click and drag positions use the view's own screen cell: the wheel used the window position, and clicks used the buffer row (counting scrollback) instead of the screen row. Default encoding sent the row one too high. - A new TerminalMouseListener reports mouse presses, releases, drags (1002) and motion (1003, also without a button) from pointer events, with Ctrl/Alt modifiers. Before, a drag became a text selection and motion was never sent. Holding Shift at the press leaves the pointer to selection while the program owns the mouse. - The middle button's press and release were reported as the right button. SGR releases name the released button. - With mouse tracking on, the wheel is reported on the main screen too. - TerminalController reports every pointer input kind by default; the program's mouse mode decides what is sent. Co-Authored-By: Claude Opus 5.5 --- .../third_party_xterm/mouse_report_test.dart | 105 ++++++++++++ .../third_party_xterm/mouse_view_test.dart | 159 ++++++++++++++++++ .../xterm/lib/src/core/mouse/button.dart | 20 ++- .../xterm/lib/src/core/mouse/handler.dart | 44 ++++- .../xterm/lib/src/core/mouse/reporter.dart | 63 ++++--- app/third_party/xterm/lib/src/terminal.dart | 17 +- .../xterm/lib/src/terminal_view.dart | 18 +- .../xterm/lib/src/ui/controller.dart | 4 +- .../lib/src/ui/gesture/gesture_handler.dart | 37 +++- .../xterm/lib/src/ui/mouse_listener.dart | 152 +++++++++++++++++ app/third_party/xterm/lib/src/ui/render.dart | 27 ++- .../xterm/lib/src/ui/scroll_handler.dart | 39 +++-- 12 files changed, 613 insertions(+), 72 deletions(-) create mode 100644 app/test/third_party_xterm/mouse_report_test.dart create mode 100644 app/test/third_party_xterm/mouse_view_test.dart create mode 100644 app/third_party/xterm/lib/src/ui/mouse_listener.dart diff --git a/app/test/third_party_xterm/mouse_report_test.dart b/app/test/third_party_xterm/mouse_report_test.dart new file mode 100644 index 00000000..64cf40f1 --- /dev/null +++ b/app/test/third_party_xterm/mouse_report_test.dart @@ -0,0 +1,105 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:xterm/xterm.dart'; + +import 'xterm_fixture.dart'; + +void main() { + const down = TerminalMouseButtonState.down; + const up = TerminalMouseButtonState.up; + const at = CellOffset(4, 2); // column 5, row 3 one-based + + String report( + String modes, + TerminalMouseButton button, + TerminalMouseButtonState state, { + bool motion = false, + bool ctrl = false, + }) { + final t = FixtureTerminal()..feed(modes); + t.terminal.mouseInput(button, state, at, motion: motion, ctrl: ctrl); + return t.takeReplies(); + } + + test('SGR wheel is 64 up and 65 down', () { + const sgr = '\x1b[?1000h\x1b[?1006h'; + expect(report(sgr, TerminalMouseButton.wheelUp, down), '\x1b[<64;5;3M'); + expect(report(sgr, TerminalMouseButton.wheelDown, down), '\x1b[<65;5;3M'); + expect(report(sgr, TerminalMouseButton.wheelUp, up), ''); + }); + + test('default encoding: 32 + code, 32 + column, 32 + row', () { + const normal = '\x1b[?1000h'; + expect( + report(normal, TerminalMouseButton.left, down), + '\x1b[M\x20\x25\x23', + ); + expect(report(normal, TerminalMouseButton.left, up), '\x1b[M\x23\x25\x23'); + expect( + report(normal, TerminalMouseButton.wheelDown, down), + '\x1b[M\x61\x25\x23', + ); + }); + + test('SGR reports which button was released', () { + const sgr = '\x1b[?1000h\x1b[?1006h'; + expect(report(sgr, TerminalMouseButton.middle, down), '\x1b[<1;5;3M'); + expect(report(sgr, TerminalMouseButton.middle, up), '\x1b[<1;5;3m'); + expect(report(sgr, TerminalMouseButton.right, up), '\x1b[<2;5;3m'); + }); + + test('modifiers add 4/8/16', () { + const sgr = '\x1b[?1000h\x1b[?1006h'; + expect( + report(sgr, TerminalMouseButton.left, down, ctrl: true), + '\x1b[<16;5;3M', + ); + }); + + group('motion', () { + test('1000 reports no motion', () { + expect( + report( + '\x1b[?1000h\x1b[?1006h', + TerminalMouseButton.left, + down, + motion: true, + ), + '', + ); + }); + + test('1002 reports drags with the button held, plus 32', () { + const drag = '\x1b[?1002h\x1b[?1006h'; + expect( + report(drag, TerminalMouseButton.left, down, motion: true), + '\x1b[<32;5;3M', + ); + expect(report(drag, TerminalMouseButton.none, down, motion: true), ''); + }); + + test('1003 reports motion without a button as 35', () { + expect( + report( + '\x1b[?1003h\x1b[?1006h', + TerminalMouseButton.none, + down, + motion: true, + ), + '\x1b[<35;5;3M', + ); + expect( + report('\x1b[?1003h', TerminalMouseButton.none, down, motion: true), + '\x1b[M\x43\x25\x23', + ); + }); + }); + + test('X10 mode (9) reports presses only', () { + expect( + report('\x1b[?9h', TerminalMouseButton.left, down), + '\x1b[M\x20\x25\x23', + ); + expect(report('\x1b[?9h', TerminalMouseButton.left, up), ''); + expect(report('\x1b[?9h', TerminalMouseButton.wheelUp, down), ''); + }); +} diff --git a/app/test/third_party_xterm/mouse_view_test.dart b/app/test/third_party_xterm/mouse_view_test.dart new file mode 100644 index 00000000..f671d268 --- /dev/null +++ b/app/test/third_party_xterm/mouse_view_test.dart @@ -0,0 +1,159 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:xterm/xterm.dart'; + +/// A TerminalView placed away from the window's origin, so a report that +/// used window coordinates instead of the view's own would be wrong. +class _Harness { + _Harness(this.tester); + + final WidgetTester tester; + final terminal = Terminal(); + final controller = TerminalController(); + final replies = []; + + Future pump() async { + terminal.onOutput = replies.add; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Padding( + padding: const EdgeInsets.only(left: 100, top: 60), + child: SizedBox( + width: 400, + height: 200, + child: TerminalView( + terminal, + controller: controller, + hardwareKeyboardOnly: true, + ), + ), + ), + ), + ), + ); + } + + TerminalViewState get _view => + tester.state(find.byType(TerminalView)); + + /// The global centre of zero-based screen cell ([x], [y]). + Offset cell(int x, int y) { + final render = _view.renderTerminal; + final size = render.cellSize; + return render.localToGlobal( + Offset((x + 0.5) * size.width, (y + 0.5) * size.height), + ); + } + + double get lineHeight => _view.renderTerminal.lineHeight; + + String take() { + final all = replies.join(); + replies.clear(); + return all; + } +} + +void main() { + testWidgets('a left drag with 1002 is reported, not selected', ( + tester, + ) async { + final h = _Harness(tester); + await h.pump(); + h.terminal.write('\x1b[?1002h\x1b[?1006h'); + await tester.pump(); + + final gesture = await tester.startGesture( + h.cell(1, 1), + kind: PointerDeviceKind.mouse, + ); + await gesture.moveTo(h.cell(4, 1)); + await gesture.moveTo(h.cell(6, 2)); + await gesture.up(); + await tester.pumpAndSettle(); + + expect(h.take(), '\x1b[<0;2;2M\x1b[<32;5;2M\x1b[<32;7;3M\x1b[<0;7;3m'); + expect(h.controller.selection, isNull); + }); + + testWidgets('1003 reports plain motion; 1000 does not', (tester) async { + final h = _Harness(tester); + await h.pump(); + h.terminal.write('\x1b[?1003h\x1b[?1006h'); + final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + await gesture.addPointer(location: h.cell(0, 0)); + await gesture.moveTo(h.cell(3, 2)); + expect(h.take(), '\x1b[<35;4;3M'); + + h.terminal.write('\x1b[?1003l\x1b[?1000h'); + await gesture.moveTo(h.cell(5, 2)); + expect(h.take(), ''); + await gesture.removePointer(); + }); + + testWidgets('a middle click is reported as middle press and release', ( + tester, + ) async { + final h = _Harness(tester); + await h.pump(); + h.terminal.write('\x1b[?1000h\x1b[?1006h'); + final gesture = await tester.startGesture( + h.cell(2, 0), + kind: PointerDeviceKind.mouse, + buttons: kMiddleMouseButton, + ); + await gesture.up(); + await tester.pumpAndSettle(); + expect(h.take(), '\x1b[<1;3;1M\x1b[<1;3;1m'); + }); + + testWidgets('Shift+drag selects text even while the program has the mouse', ( + tester, + ) async { + final h = _Harness(tester); + await h.pump(); + h.terminal.write('hello world\x1b[?1002h\x1b[?1006h'); + await tester.pump(); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + final gesture = await tester.startGesture( + h.cell(0, 0), + kind: PointerDeviceKind.mouse, + ); + await gesture.moveTo(h.cell(2, 0)); + await gesture.moveTo(h.cell(4, 0)); + await gesture.up(); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.pumpAndSettle(); + + expect(h.take(), ''); + final selection = h.controller.selection; + expect(selection, isNotNull); + expect(h.terminal.buffer.getText(selection), startsWith('hell')); + }); + + testWidgets('the wheel reports 65 down / 64 up at the view cell', ( + tester, + ) async { + final h = _Harness(tester); + await h.pump(); + h.terminal.write('\x1b[?1049h\x1b[?1000h\x1b[?1006h'); + await tester.pump(); + + final pointer = TestPointer(1, PointerDeviceKind.mouse); + final at = h.cell(3, 1); + await tester.sendEventToBinding(pointer.hover(at)); + await tester.sendEventToBinding( + pointer.scroll(Offset(0, h.lineHeight * 2)), + ); + await tester.pump(); + expect(h.take(), '\x1b[<65;4;2M\x1b[<65;4;2M'); + + await tester.sendEventToBinding(pointer.scroll(Offset(0, -h.lineHeight))); + await tester.pump(); + expect(h.take(), '\x1b[<64;4;2M'); + }); +} diff --git a/app/third_party/xterm/lib/src/core/mouse/button.dart b/app/third_party/xterm/lib/src/core/mouse/button.dart index 53dd08b0..b463514d 100644 --- a/app/third_party/xterm/lib/src/core/mouse/button.dart +++ b/app/third_party/xterm/lib/src/core/mouse/button.dart @@ -5,21 +5,23 @@ enum TerminalMouseButton { right(id: 2), - wheelUp(id: 64 + 4, isWheel: true), + /// No button: the pointer moved with no button held (mode 1003 motion). + none(id: 3), - wheelDown(id: 64 + 5, isWheel: true), + wheelUp(id: 64 + 0, isWheel: true), - wheelLeft(id: 64 + 6, isWheel: true), + wheelDown(id: 64 + 1, isWheel: true), - wheelRight(id: 64 + 7, isWheel: true), + wheelLeft(id: 64 + 2, isWheel: true), + + wheelRight(id: 64 + 3, isWheel: true), ; - /// The id that is used to report a button press or release to the terminal. + /// The button code reported to the program, before modifiers and the + /// motion flag are added. /// - /// Mouse wheel up / down use button IDs 4 = 0100 (binary) and 5 = 0101 (binary). - /// The bits three and four of the button are transposed by 64 and 128 - /// respectively, when reporting the id of the button and have have to be - /// adjusted correspondingly. + /// The wheel is reported as buttons 4-7, which the protocol encodes by + /// setting bit 6 (64) on codes 0-3: wheel up is 64, wheel down 65. final int id; /// Whether this button is a mouse wheel button. diff --git a/app/third_party/xterm/lib/src/core/mouse/handler.dart b/app/third_party/xterm/lib/src/core/mouse/handler.dart index bb043886..356543d4 100644 --- a/app/third_party/xterm/lib/src/core/mouse/handler.dart +++ b/app/third_party/xterm/lib/src/core/mouse/handler.dart @@ -13,7 +13,7 @@ class TerminalMouseEvent { /// The current state of the button. final TerminalMouseButtonState buttonState; - /// The position of button state change. + /// The zero-based screen cell of the event. final CellOffset position; /// The state of the terminal. @@ -22,13 +22,33 @@ class TerminalMouseEvent { /// The platform of the terminal. final TerminalTargetPlatform platform; + /// Whether the pointer moved (with [button] held, or [TerminalMouseButton.none]) + /// rather than a button changing state. + final bool motion; + + final bool shift; + + final bool alt; + + final bool ctrl; + TerminalMouseEvent({ required this.button, required this.buttonState, required this.position, required this.state, required this.platform, + this.motion = false, + this.shift = false, + this.alt = false, + this.ctrl = false, }); + + /// The modifier bits of the report. + int get modifiers => + (shift ? MouseReporter.shiftBit : 0) | + (alt ? MouseReporter.altBit : 0) | + (ctrl ? MouseReporter.ctrlBit : 0); } const defaultMouseHandler = CascadeMouseHandler([ @@ -59,6 +79,8 @@ class CascadeMouseHandler implements TerminalMouseHandler { } } +/// X10 compatibility mode (`CSI ? 9 h`): button presses only, no +/// modifiers, no wheel. class ClickMouseHandler implements TerminalMouseHandler { const ClickMouseHandler(); @@ -66,9 +88,9 @@ class ClickMouseHandler implements TerminalMouseHandler { String? call(TerminalMouseEvent event) { switch (event.state.mouseMode) { case MouseMode.clickOnly: - // Only clicks and only the first 3 buttons are reported. if (event.buttonState == TerminalMouseButtonState.down && - (event.button.id < 3)) { + !event.motion && + event.button.id < 3) { return MouseReporter.report( event.button, event.buttonState, @@ -86,18 +108,30 @@ class ClickMouseHandler implements TerminalMouseHandler { } } +/// Normal (1000), button-event (1002) and any-event (1003) tracking: +/// presses, releases and the wheel; 1002 adds motion with a button held, +/// 1003 all motion. class UpDownMouseHandler implements TerminalMouseHandler { const UpDownMouseHandler(); @override String? call(TerminalMouseEvent event) { - switch (event.state.mouseMode) { + final mode = event.state.mouseMode; + switch (mode) { case MouseMode.none: case MouseMode.clickOnly: return null; case MouseMode.upDownScroll: case MouseMode.upDownScrollDrag: case MouseMode.upDownScrollMove: + if (event.motion) { + final reported = mode == MouseMode.upDownScrollMove || + mode == MouseMode.upDownScrollDrag && + event.button != TerminalMouseButton.none; + if (!reported) return null; + } else if (event.button == TerminalMouseButton.none) { + return null; + } // Up events are never reported for mouse wheel buttons. if (event.button.isWheel && event.buttonState == TerminalMouseButtonState.up) { @@ -108,6 +142,8 @@ class UpDownMouseHandler implements TerminalMouseHandler { event.buttonState, event.position, event.state.mouseReportMode, + motion: event.motion, + modifiers: event.modifiers, ); } } diff --git a/app/third_party/xterm/lib/src/core/mouse/reporter.dart b/app/third_party/xterm/lib/src/core/mouse/reporter.dart index 3417b634..24d65f39 100644 --- a/app/third_party/xterm/lib/src/core/mouse/reporter.dart +++ b/app/third_party/xterm/lib/src/core/mouse/reporter.dart @@ -4,45 +4,56 @@ import 'package:xterm/src/core/mouse/button.dart'; import 'package:xterm/src/core/mouse/button_state.dart'; abstract class MouseReporter { + /// Modifier bits added to the button code. + static const shiftBit = 4; + static const altBit = 8; + static const ctrlBit = 16; + + /// Added to the button code for a motion event (modes 1002 and 1003). + static const motionBit = 32; + + /// Encodes a mouse event at the zero-based screen cell [position]. + /// + /// [modifiers] is a combination of [shiftBit], [altBit] and [ctrlBit]; + /// [motion] marks a move rather than a press or release. static String report( TerminalMouseButton button, TerminalMouseButtonState state, CellOffset position, - MouseReportMode reportMode, - ) { + MouseReportMode reportMode, { + bool motion = false, + int modifiers = 0, + }) { // x and y offsets have to be incremented by 1 as the offset if 0-based, // The position has to be reported using 1-based coordinates. final x = position.x + 1; final y = position.y + 1; + final extra = modifiers | (motion ? motionBit : 0); switch (reportMode) { case MouseReportMode.normal: case MouseReportMode.utf: - // Button ID 3 is used to signal a button release. - final buttonID = state == TerminalMouseButtonState.up ? 3 : button.id; - // The button ID is reported as shifted by 32 to produce a printable - // character. - final btn = String.fromCharCode(32 + buttonID); - // Normal mode only supports a maximum position of 223, while utf - // supports positions up to 2015. Both modes send a null byte if the - // position exceeds that limit. - final col = (reportMode == MouseReportMode.normal && x > 223) || - (reportMode == MouseReportMode.utf && x > 2015) - ? '\x00' - : String.fromCharCode(32 + x); - final row = (reportMode == MouseReportMode.normal && y > 223) || - (reportMode == MouseReportMode.utf && y > 2015) - ? '\x00' - : String.fromCharCode(32 + y + 1); - return "\x1b[M$btn$col$row"; + // Button code 3 signals a release; these encodings cannot say which + // button was released. + final code = + (state == TerminalMouseButtonState.up && !motion ? 3 : button.id) | + extra; + // The code and coordinates are sent as 32 + value. Normal mode only + // reaches 223, utf mode 2015; beyond that a null byte is sent. + final limit = reportMode == MouseReportMode.normal ? 223 : 2015; + String encode(int value) => + value > limit ? '\x00' : String.fromCharCode(32 + value); + return '\x1b[M${String.fromCharCode(32 + code)}${encode(x)}${encode(y)}'; case MouseReportMode.sgr: - final buttonID = button.id; - final upDown = state == TerminalMouseButtonState.down ? 'M' : 'm'; - return "\x1b[<$buttonID;$x;$y$upDown"; + // SGR reports the released button and marks a release with `m`. + final code = button.id | extra; + final upDown = + state == TerminalMouseButtonState.up && !motion ? 'm' : 'M'; + return '\x1b[<$code;$x;$y$upDown'; case MouseReportMode.urxvt: - // The button ID uses the same id as to report it as in normal mode. - final buttonID = - 32 + (state == TerminalMouseButtonState.up ? 3 : button.id); - return "\x1b[$buttonID;$x;${y}M"; + final code = + (state == TerminalMouseButtonState.up && !motion ? 3 : button.id) | + extra; + return '\x1b[${32 + code};$x;${y}M'; } } } diff --git a/app/third_party/xterm/lib/src/terminal.dart b/app/third_party/xterm/lib/src/terminal.dart index 12206578..1480b047 100644 --- a/app/third_party/xterm/lib/src/terminal.dart +++ b/app/third_party/xterm/lib/src/terminal.dart @@ -376,18 +376,29 @@ class Terminal with Observable implements TerminalState, EscapeHandler { } } - // Handle a mouse event and return true if it was handled. + /// Reports a mouse event at the zero-based screen cell [position] to the + /// program, as its mouse mode asks; returns true if it was reported. + /// [motion] marks a pointer move (with [button] held, or + /// [TerminalMouseButton.none] in mode 1003). bool mouseInput( TerminalMouseButton button, TerminalMouseButtonState buttonState, - CellOffset position, - ) { + CellOffset position, { + bool motion = false, + bool shift = false, + bool alt = false, + bool ctrl = false, + }) { final output = mouseHandler?.call(TerminalMouseEvent( button: button, buttonState: buttonState, position: position, state: this, platform: platform, + motion: motion, + shift: shift, + alt: alt, + ctrl: ctrl, )); if (output != null) { onOutput?.call(output); diff --git a/app/third_party/xterm/lib/src/terminal_view.dart b/app/third_party/xterm/lib/src/terminal_view.dart index cf2c3c3c..d770e2d7 100644 --- a/app/third_party/xterm/lib/src/terminal_view.dart +++ b/app/third_party/xterm/lib/src/terminal_view.dart @@ -13,6 +13,7 @@ import 'package:xterm/src/ui/gesture/gesture_handler.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'; +import 'package:xterm/src/ui/mouse_listener.dart'; import 'package:xterm/src/ui/render.dart'; import 'package:xterm/src/ui/scroll_handler.dart'; import 'package:xterm/src/ui/shortcut/actions.dart'; @@ -166,6 +167,10 @@ class TerminalViewState extends State { RenderTerminal get renderTerminal => _viewportKey.currentContext!.findRenderObject() as RenderTerminal; + /// Whether the latest mouse press was reported to the program (mouse + /// tracking on, Shift not held), so the gestures it starts do not select. + bool mousePressReported = false; + @override void initState() { _focusNode = widget.focusNode ?? FocusNode(); @@ -244,7 +249,9 @@ class TerminalViewState extends State { child = TerminalScrollGestureHandler( terminal: widget.terminal, simulateScroll: widget.simulateScroll, - getCellOffset: (offset) => renderTerminal.getCellOffset(offset), + getCellOffset: (globalPosition) => renderTerminal.getScreenCellOffset( + renderTerminal.globalToLocal(globalPosition), + ), getLineHeight: () => renderTerminal.lineHeight, child: child, ); @@ -296,6 +303,15 @@ class TerminalViewState extends State { child: child, ); + child = TerminalMouseListener( + terminal: widget.terminal, + controller: _controller, + renderTerminal: () => renderTerminal, + readOnly: widget.readOnly, + onPressReported: (reported) => mousePressReported = reported, + child: child, + ); + child = TerminalGestureHandler( terminalView: this, terminalController: _controller, diff --git a/app/third_party/xterm/lib/src/ui/controller.dart b/app/third_party/xterm/lib/src/ui/controller.dart index 1e107c2d..29864973 100644 --- a/app/third_party/xterm/lib/src/ui/controller.dart +++ b/app/third_party/xterm/lib/src/ui/controller.dart @@ -12,7 +12,9 @@ import 'package:xterm/src/ui/selection_mode.dart'; class TerminalController with ChangeNotifier { TerminalController({ SelectionMode selectionMode = SelectionMode.line, - PointerInputs pointerInputs = const PointerInputs({PointerInput.tap}), + // Every kind by default: the program opts into each with its mouse + // mode, so drags (1002) and motion (1003) are reported when asked for. + PointerInputs pointerInputs = const PointerInputs.all(), bool suspendPointerInput = false, }) : _selectionMode = selectionMode, _pointerInputs = pointerInputs, diff --git a/app/third_party/xterm/lib/src/ui/gesture/gesture_handler.dart b/app/third_party/xterm/lib/src/ui/gesture/gesture_handler.dart index 2f6d7b69..50e4e4e0 100644 --- a/app/third_party/xterm/lib/src/ui/gesture/gesture_handler.dart +++ b/app/third_party/xterm/lib/src/ui/gesture/gesture_handler.dart @@ -68,8 +68,8 @@ class _TerminalGestureHandlerState extends State { onTapDown: onTapDown, onSecondaryTapDown: onSecondaryTapDown, onSecondaryTapUp: onSecondaryTapUp, - onTertiaryTapDown: onSecondaryTapDown, - onTertiaryTapUp: onSecondaryTapUp, + onTertiaryTapDown: onTertiaryTapDown, + onTertiaryTapUp: onTertiaryTapUp, onLongPressStart: onLongPressStart, onLongPressMoveUpdate: onLongPressMoveUpdate, // onLongPressUp: onLongPressUp, @@ -89,9 +89,10 @@ class _TerminalGestureHandlerState extends State { TerminalMouseButton button, { bool forceCallback = false, }) { - // Check if the terminal should and can handle the tap down event. - var handled = false; - if (_shouldSendTapEvent) { + // Check if the terminal should and can handle the tap down event. A + // mouse press was already reported by the TerminalMouseListener. + var handled = _isReportedMouse(details.kind); + if (!_isMouse(details.kind) && _shouldSendTapEvent) { handled = renderTerminal.mouseEvent( button, TerminalMouseButtonState.down, @@ -111,8 +112,8 @@ class _TerminalGestureHandlerState extends State { bool forceCallback = false, }) { // Check if the terminal should and can handle the tap up event. - var handled = false; - if (_shouldSendTapEvent) { + var handled = _isReportedMouse(details.kind); + if (!_isMouse(details.kind) && _shouldSendTapEvent) { handled = renderTerminal.mouseEvent( button, TerminalMouseButtonState.up, @@ -153,10 +154,21 @@ class _TerminalGestureHandlerState extends State { } void onTertiaryTapUp(TapUpDetails details) { - _tapUp(widget.onTertiaryTapUp, details, TerminalMouseButton.right); + _tapUp(widget.onTertiaryTapUp, details, TerminalMouseButton.middle); } + /// Whether [kind] is a mouse, whose presses the TerminalMouseListener + /// reports instead of this handler. + static bool _isMouse(PointerDeviceKind? kind) => + kind == PointerDeviceKind.mouse; + + /// Whether the current press is a mouse press reported to the program, + /// which therefore must not select text. + bool _isReportedMouse(PointerDeviceKind? kind) => + _isMouse(kind) && terminalView.mousePressReported; + void onDoubleTapDown(TapDownDetails details) { + if (_isReportedMouse(details.kind)) return; renderTerminal.selectWord(details.localPosition); } @@ -175,6 +187,11 @@ class _TerminalGestureHandlerState extends State { // void onLongPressUp() {} void onDragStart(DragStartDetails details) { + if (_isReportedMouse(details.kind)) { + // The program follows the drag (mode 1002/1003), not the selection. + _lastDragStartDetails = null; + return; + } _lastDragStartDetails = details; details.kind == PointerDeviceKind.mouse @@ -183,8 +200,10 @@ class _TerminalGestureHandlerState extends State { } void onDragUpdate(DragUpdateDetails details) { + final start = _lastDragStartDetails; + if (start == null) return; renderTerminal.selectCharacters( - _lastDragStartDetails!.localPosition, + start.localPosition, details.localPosition, ); } diff --git a/app/third_party/xterm/lib/src/ui/mouse_listener.dart b/app/third_party/xterm/lib/src/ui/mouse_listener.dart new file mode 100644 index 00000000..7a270014 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/mouse_listener.dart @@ -0,0 +1,152 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:xterm/src/core/buffer/cell_offset.dart'; +import 'package:xterm/src/core/mouse/button.dart'; +import 'package:xterm/src/core/mouse/button_state.dart'; +import 'package:xterm/src/core/mouse/mode.dart'; +import 'package:xterm/src/terminal.dart'; +import 'package:xterm/src/ui/controller.dart'; +import 'package:xterm/src/ui/pointer_input.dart'; +import 'package:xterm/src/ui/render.dart'; + +/// Reports mouse buttons, drags and motion to the program while it has +/// enabled mouse tracking (`CSI ? 1000/1002/1003 h`), straight from pointer +/// events so presses, drags and releases keep their buttons and order. +/// +/// Holding Shift at the press leaves the pointer to text selection, as in +/// other terminals. Touch input is not handled here: taps on a touch screen +/// are reported by the gesture handler. +class TerminalMouseListener extends StatefulWidget { + const TerminalMouseListener({ + super.key, + required this.terminal, + required this.controller, + required this.renderTerminal, + required this.readOnly, + required this.onPressReported, + required this.child, + }); + + final Terminal terminal; + + final TerminalController controller; + + final RenderTerminal Function() renderTerminal; + + final bool readOnly; + + /// Called at each mouse press with whether the press goes to the program + /// (and so must not start a selection). + final void Function(bool reported) onPressReported; + + final Widget child; + + @override + State createState() => _TerminalMouseListenerState(); +} + +class _TerminalMouseListenerState extends State { + /// The pointer whose press was reported, and its button. + int? _pointer; + TerminalMouseButton _button = TerminalMouseButton.left; + + /// The last cell a motion was reported for, so a move within one cell is + /// not reported again. + CellOffset? _lastCell; + + bool _wants(PointerInput input) => + !widget.readOnly && + widget.terminal.mouseMode != MouseMode.none && + widget.controller.shouldSendPointerInput(input); + + static bool get _shift => HardwareKeyboard.instance.isShiftPressed; + + bool _report( + TerminalMouseButton button, + TerminalMouseButtonState state, + Offset globalPosition, { + bool motion = false, + }) { + final keyboard = HardwareKeyboard.instance; + final cell = _cellOf(globalPosition); + _lastCell = cell; + return widget.terminal.mouseInput( + button, + state, + cell, + motion: motion, + alt: keyboard.isAltPressed, + ctrl: keyboard.isControlPressed, + ); + } + + static TerminalMouseButton? _buttonOf(int buttons) { + if (buttons & kPrimaryMouseButton != 0) return TerminalMouseButton.left; + if (buttons & kMiddleMouseButton != 0) return TerminalMouseButton.middle; + if (buttons & kSecondaryMouseButton != 0) return TerminalMouseButton.right; + return null; + } + + void _down(PointerDownEvent event) { + if (event.kind != PointerDeviceKind.mouse || _pointer != null) return; + final button = _buttonOf(event.buttons); + final take = button != null && !_shift && _wants(PointerInput.tap); + widget.onPressReported(take); + if (!take) return; + _pointer = event.pointer; + _button = button; + _report(button, TerminalMouseButtonState.down, event.position); + } + + void _move(PointerMoveEvent event) { + if (event.pointer != _pointer || !_wants(PointerInput.drag)) return; + if (_cellOf(event.position) == _lastCell) return; + _report( + _button, + TerminalMouseButtonState.down, + event.position, + motion: true, + ); + } + + void _up(PointerEvent event) { + if (event.pointer != _pointer) return; + _pointer = null; + if (widget.terminal.mouseMode == MouseMode.none) return; + _report(_button, TerminalMouseButtonState.up, event.position); + } + + void _hover(PointerHoverEvent event) { + if (event.kind != PointerDeviceKind.mouse || + widget.terminal.mouseMode != MouseMode.upDownScrollMove || + _shift || + !_wants(PointerInput.move)) { + return; + } + if (_cellOf(event.position) == _lastCell) return; + _report( + TerminalMouseButton.none, + TerminalMouseButtonState.down, + event.position, + motion: true, + ); + } + + CellOffset _cellOf(Offset globalPosition) { + final render = widget.renderTerminal(); + return render.getScreenCellOffset(render.globalToLocal(globalPosition)); + } + + @override + Widget build(BuildContext context) { + return Listener( + onPointerDown: _down, + onPointerMove: _move, + onPointerUp: _up, + onPointerCancel: _up, + onPointerHover: _hover, + child: widget.child, + ); + } +} diff --git a/app/third_party/xterm/lib/src/ui/render.dart b/app/third_party/xterm/lib/src/ui/render.dart index 7154b8a4..8314de75 100644 --- a/app/third_party/xterm/lib/src/ui/render.dart +++ b/app/third_party/xterm/lib/src/ui/render.dart @@ -316,10 +316,29 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { bool mouseEvent( TerminalMouseButton button, TerminalMouseButtonState buttonState, - Offset offset, - ) { - final position = getCellOffset(offset); - return _terminal.mouseInput(button, buttonState, position); + Offset offset, { + bool motion = false, + bool shift = false, + bool alt = false, + bool ctrl = false, + }) { + return _terminal.mouseInput( + button, + buttonState, + getScreenCellOffset(offset), + motion: motion, + shift: shift, + alt: alt, + ctrl: ctrl, + ); + } + + /// The screen cell (row 0 is the top of the screen, not of the + /// scrollback) that the local [offset] is in, as mouse reports use. + CellOffset getScreenCellOffset(Offset offset) { + final cell = getCellOffset(offset); + final row = cell.y - _terminal.buffer.scrollBack; + return CellOffset(cell.x, row.clamp(0, _terminal.viewHeight - 1)); } void _notifyEditableRect() { diff --git a/app/third_party/xterm/lib/src/ui/scroll_handler.dart b/app/third_party/xterm/lib/src/ui/scroll_handler.dart index d0ad9a8d..8ef578f8 100644 --- a/app/third_party/xterm/lib/src/ui/scroll_handler.dart +++ b/app/third_party/xterm/lib/src/ui/scroll_handler.dart @@ -2,10 +2,10 @@ import 'package:flutter/widgets.dart'; import 'package:xterm/core.dart'; import 'package:xterm/src/ui/infinite_scroll_view.dart'; -/// Handles scrolling gestures in the alternate screen buffer. In alternate -/// screen buffer, the terminal don't have a scrollback buffer, instead, the -/// scroll gestures are converted to escape sequences based on the current -/// report mode declared by the application. +/// Handles scrolling gestures in the alternate screen buffer, and on either +/// screen while the program tracks the mouse. There the scroll gestures are +/// reported as wheel events in the program's mouse report mode, or (in the +/// alternate screen without mouse tracking) simulated with arrow keys. class TerminalScrollGestureHandler extends StatefulWidget { const TerminalScrollGestureHandler({ super.key, @@ -18,8 +18,8 @@ class TerminalScrollGestureHandler extends StatefulWidget { final Terminal terminal; - /// Returns the cell offset for the pixel offset. - final CellOffset Function(Offset) getCellOffset; + /// Returns the zero-based screen cell under a global pixel position. + final CellOffset Function(Offset globalPosition) getCellOffset; /// Returns the pixel height of lines in the terminal. final double Function() getLineHeight; @@ -38,22 +38,26 @@ class TerminalScrollGestureHandler extends StatefulWidget { class _TerminalScrollGestureHandlerState extends State { - /// Whether the application is in alternate screen buffer. If false, then this - /// widget does nothing. + /// Whether the application is in alternate screen buffer. var isAltBuffer = false; + /// Whether the program asked for wheel events. With neither this nor + /// [isAltBuffer] this widget does nothing and the scrollback scrolls. + var reportsScroll = false; + /// The variable that tracks the line offset in last scroll event. Used to /// determine how many the scroll events should be sent to the terminal. var lastLineOffset = 0; - /// This variable tracks the last offset where the scroll gesture started. - /// Used to calculate the cell offset of the terminal mouse event. + /// The global position where the scroll gesture started. Used to + /// calculate the cell offset of the terminal mouse event. var lastPointerPosition = Offset.zero; @override void initState() { widget.terminal.addListener(_onTerminalUpdated); isAltBuffer = widget.terminal.isUsingAltBuffer; + reportsScroll = widget.terminal.mouseMode.reportScroll; super.initState(); } @@ -69,14 +73,19 @@ class _TerminalScrollGestureHandlerState oldWidget.terminal.removeListener(_onTerminalUpdated); widget.terminal.addListener(_onTerminalUpdated); isAltBuffer = widget.terminal.isUsingAltBuffer; + reportsScroll = widget.terminal.mouseMode.reportScroll; } super.didUpdateWidget(oldWidget); } void _onTerminalUpdated() { - if (isAltBuffer != widget.terminal.isUsingAltBuffer) { - isAltBuffer = widget.terminal.isUsingAltBuffer; - setState(() {}); + final terminal = widget.terminal; + if (isAltBuffer != terminal.isUsingAltBuffer || + reportsScroll != terminal.mouseMode.reportScroll) { + setState(() { + isAltBuffer = terminal.isUsingAltBuffer; + reportsScroll = terminal.mouseMode.reportScroll; + }); } } @@ -92,7 +101,7 @@ class _TerminalScrollGestureHandlerState position, ); - if (!handled && widget.simulateScroll) { + if (!handled && widget.simulateScroll && isAltBuffer) { widget.terminal.keyInput( up ? TerminalKey.arrowUp : TerminalKey.arrowDown, ); @@ -113,7 +122,7 @@ class _TerminalScrollGestureHandlerState @override Widget build(BuildContext context) { - if (!isAltBuffer) { + if (!isAltBuffer && !reportsScroll) { return widget.child; } From 822d77b1df1d03a223266aba1ce342d14c4a80cf Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:37:09 +0000 Subject: [PATCH 12/17] xterm: report focus changes (?1004) Terminal.focusInput sends CSI I / CSI O while the program has enabled focus reporting, and TerminalView calls it when its focus node gains or loses focus (not for read-only views). The mode was parsed but never acted on. Co-Authored-By: Claude Opus 5.5 --- .../third_party_xterm/focus_report_test.dart | 46 +++++++++++++++++++ app/third_party/xterm/lib/src/terminal.dart | 10 ++++ .../xterm/lib/src/terminal_view.dart | 16 +++++++ 3 files changed, 72 insertions(+) create mode 100644 app/test/third_party_xterm/focus_report_test.dart diff --git a/app/test/third_party_xterm/focus_report_test.dart b/app/test/third_party_xterm/focus_report_test.dart new file mode 100644 index 00000000..40d6c717 --- /dev/null +++ b/app/test/third_party_xterm/focus_report_test.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:xterm/xterm.dart'; + +import 'xterm_fixture.dart'; + +void main() { + test('focusInput sends CSI I / CSI O only with ?1004 set', () { + final t = FixtureTerminal(); + expect(t.terminal.focusInput(true), isFalse); + expect(t.takeReplies(), ''); + t.feed('\x1b[?1004h'); + expect(t.terminal.focusInput(true), isTrue); + t.terminal.focusInput(false); + expect(t.takeReplies(), '\x1b[I\x1b[O'); + t.feed('\x1b[?1004l'); + t.terminal.focusInput(true); + expect(t.takeReplies(), ''); + }); + + testWidgets('TerminalView reports its focus changes', (tester) async { + final terminal = Terminal(); + final replies = []; + terminal.onOutput = replies.add; + final focus = FocusNode(); + addTearDown(focus.dispose); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: TerminalView( + terminal, + focusNode: focus, + hardwareKeyboardOnly: true, + ), + ), + ), + ); + terminal.write('\x1b[?1004h'); + + focus.requestFocus(); + await tester.pump(); + focus.unfocus(); + await tester.pump(); + expect(replies.join(), '\x1b[I\x1b[O'); + }); +} diff --git a/app/third_party/xterm/lib/src/terminal.dart b/app/third_party/xterm/lib/src/terminal.dart index 1480b047..07aea210 100644 --- a/app/third_party/xterm/lib/src/terminal.dart +++ b/app/third_party/xterm/lib/src/terminal.dart @@ -407,6 +407,16 @@ class Terminal with Observable implements TerminalState, EscapeHandler { return false; } + /// Tells the program the terminal gained or lost focus (`CSI I` / + /// `CSI O`) when it enabled focus reporting with `CSI ? 1004 h`; returns + /// whether anything was sent. [TerminalView] calls this when its focus + /// changes. + bool focusInput(bool focused) { + if (!_reportFocusMode) return false; + onOutput?.call(focused ? '\x1b[I' : '\x1b[O'); + return true; + } + /// Resize the terminal screen. [newWidth] and [newHeight] should be greater /// than 0. Text reflow is currently not implemented and will be avaliable in /// the future. diff --git a/app/third_party/xterm/lib/src/terminal_view.dart b/app/third_party/xterm/lib/src/terminal_view.dart index d770e2d7..2fc16a90 100644 --- a/app/third_party/xterm/lib/src/terminal_view.dart +++ b/app/third_party/xterm/lib/src/terminal_view.dart @@ -174,6 +174,8 @@ class TerminalViewState extends State { @override void initState() { _focusNode = widget.focusNode ?? FocusNode(); + _focusNode.addListener(_onFocusChange); + _hadFocus = _focusNode.hasFocus; _controller = widget.controller ?? TerminalController(); _scrollController = widget.scrollController ?? ScrollController(); _shortcutManager = ShortcutManager( @@ -182,13 +184,26 @@ class TerminalViewState extends State { super.initState(); } + bool _hadFocus = false; + + /// Reports focus changes to a program that asked for them (`CSI ? 1004 h`). + void _onFocusChange() { + final hasFocus = _focusNode.hasFocus; + if (hasFocus == _hadFocus) return; + _hadFocus = hasFocus; + if (!widget.readOnly) widget.terminal.focusInput(hasFocus); + } + @override void didUpdateWidget(TerminalView oldWidget) { if (oldWidget.focusNode != widget.focusNode) { + _focusNode.removeListener(_onFocusChange); if (oldWidget.focusNode == null) { _focusNode.dispose(); } _focusNode = widget.focusNode ?? FocusNode(); + _focusNode.addListener(_onFocusChange); + _hadFocus = _focusNode.hasFocus; } if (oldWidget.controller != widget.controller) { if (oldWidget.controller == null) { @@ -208,6 +223,7 @@ class TerminalViewState extends State { @override void dispose() { + _focusNode.removeListener(_onFocusChange); if (widget.focusNode == null) { _focusNode.dispose(); } From c3458d8a7f0fb9b31785199cdda814c6d5496e5a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:37:16 +0000 Subject: [PATCH 13/17] Terminals: one active client per terminal; keystrokes skip the request queue Several clients drawing one terminal (machine terminal or chat terminal command) no longer interfere. The server tracks, per terminal, the connections drawing it, most recently active first: the active client (the opener, then whoever last typed or focused it) owns the PTY size and is the only one whose emulator's automatic query answers reach the process; other clients' answers are acknowledged and dropped, and their sizes recorded but not applied. When the active connection closes the next most recent client's size is applied. Protocol (backwards compatible; all new fields optional): - terminal_input / chat_shell_input: reply (emulator answer), cols/rows (the typist's size, applied before the input). - terminal_resize / chat_shell_resize: activate (the client focused it). Latency: PipelinesClient sends terminal_input, terminal_resize, chat_shell_input and chat_shell_resize at once rather than behind the previous request's reply. The server reads those onto a per-connection terminal lane handled in order beside the ordinary request loop, and terminal_open (up to 5 s waiting for su) now runs off the read loop. Client: ChatShellTerminalSession routes what the emulator emits while drawing output to onReply and reports focus through activate(); ChatShellInputPipe keeps answers and typing in separate requests. Co-Authored-By: Claude Opus 5.5 --- app/lib/core/transport/pipelines_client.dart | 39 +++- .../shell/chat_shell_runs_repository.dart | 52 ++++- .../shell/chat_shell_terminal_session.dart | 51 ++++- .../chat/shell/chat_shell_terminal_view.dart | 11 + .../chat/shell/chat_shell_terminals.dart | 54 ++++- app/lib/features/terminal/terminal_tab.dart | 77 ++++--- app/notes/terminal-panel.md | 24 ++- .../core/transport/pipelines_client_test.dart | 70 +++++++ .../chat_shell_terminal_session_test.dart | 29 +++ .../chat/shell/chat_shell_terminal_test.dart | 41 ++++ .../terminal/terminal_active_client_test.dart | 101 ++++++++++ docs/cli.md | 14 +- internal/protocol/chat_shell_run.go | 8 +- internal/protocol/chat_shell_terminal.go | 20 +- internal/protocol/terminal.go | 14 +- internal/server/chat_shell_run_handlers.go | 5 +- internal/server/chat_shell_runner.go | 2 + .../server/chat_shell_terminal_ws_test.go | 4 +- internal/server/terminal_active.go | 160 +++++++++++++++ internal/server/terminal_active_test.go | 189 ++++++++++++++++++ internal/server/terminal_handlers.go | 5 +- internal/server/terminal_lane.go | 75 +++++++ internal/server/terminal_manager.go | 16 +- internal/server/terminal_process.go | 2 + internal/server/terminal_viewers.go | 155 ++++++++++++++ internal/server/terminal_viewers_test.go | 60 ++++++ internal/server/terminal_ws_test.go | 6 +- internal/server/websocket.go | 32 ++- 28 files changed, 1229 insertions(+), 87 deletions(-) create mode 100644 app/test/features/terminal/terminal_active_client_test.dart create mode 100644 internal/server/terminal_active.go create mode 100644 internal/server/terminal_active_test.go create mode 100644 internal/server/terminal_lane.go create mode 100644 internal/server/terminal_viewers.go create mode 100644 internal/server/terminal_viewers_test.go diff --git a/app/lib/core/transport/pipelines_client.dart b/app/lib/core/transport/pipelines_client.dart index 8585f162..576b81d1 100644 --- a/app/lib/core/transport/pipelines_client.dart +++ b/app/lib/core/transport/pipelines_client.dart @@ -127,11 +127,28 @@ class PipelinesClient implements ApiGateway { if (!_states.isClosed) _states.add(value); } + /// Requests sent at once rather than after the previous request's reply: + /// a terminal's keystrokes and sizes. They are written to the socket in + /// call order, and the server handles them in arrival order on a lane of + /// their own, so they never wait behind a slow request (a terminal_open + /// waiting for its login prompt, a chat backend call) and stay in order + /// among themselves. An older server handles them in order with the rest. + static const pipelined = { + 'terminal_input', + 'terminal_resize', + 'chat_shell_input', + 'chat_shell_resize', + }; + @override Future call(String type, [JsonMap fields = const {}]) { final completer = Completer(); final generation = _generation; final snapshot = Map.of(fields); + if (pipelined.contains(type)) { + _send(type, snapshot, completer, generation); + return completer.future; + } final run = _queue.then( (_) => _sendCall(type, snapshot, completer, generation), ); @@ -145,6 +162,22 @@ class PipelinesClient implements ApiGateway { Completer result, int generation, ) async { + _send(type, fields, result, generation); + // Match the existing client's serialized request semantics, even on errors. + try { + await result.future; + } catch (_) { + /* The caller receives the error. */ + } + } + + /// Writes one request now; [result] completes with its reply. + void _send( + String type, + JsonMap fields, + Completer result, + int generation, + ) { if (generation != _generation) { result.completeError(StateError('Connection replaced')); return; @@ -175,12 +208,6 @@ class PipelinesClient implements ApiGateway { timer.cancel(); if (_pending.remove(id) != null) result.completeError(error); } - // Match the existing client's serialized request semantics, even on errors. - try { - await result.future; - } catch (_) { - /* The caller receives the error. */ - } } String sendOnly(String type, [JsonMap fields = const {}]) { diff --git a/app/lib/features/chat/shell/chat_shell_runs_repository.dart b/app/lib/features/chat/shell/chat_shell_runs_repository.dart index 5297c9be..c246ab88 100644 --- a/app/lib/features/chat/shell/chat_shell_runs_repository.dart +++ b/app/lib/features/chat/shell/chat_shell_runs_repository.dart @@ -15,6 +15,8 @@ class ChatShellRunsRepository { String? data, int? after, List? runIds, + bool reply = false, + bool activate = false, }) => { 'chat_shell_run_request': { 'session_id': sessionId, @@ -25,6 +27,8 @@ class ChatShellRunsRepository { 'data': ?data, 'after': ?after, 'run_ids': ?runIds, + if (reply) 'reply': true, + if (activate) 'activate': true, }, }; @@ -43,16 +47,46 @@ class ChatShellRunsRepository { ); /// Writes typed text (control characters and escape sequences included) - /// to a running command's terminal. - Future input(String sessionId, String runId, String data) => gateway - .call('chat_shell_input', _body(sessionId, runId: runId, data: data)); + /// to a running command's terminal. [reply] marks the emulator's automatic + /// answer to a query, which the server passes on only from the terminal's + /// active client; typing carries the [size] this client draws it at. + Future input( + String sessionId, + String runId, + String data, { + bool reply = false, + (int, int)? size, + }) => gateway.call( + 'chat_shell_input', + _body( + sessionId, + runId: runId, + data: data, + reply: reply, + cols: size?.$1, + rows: size?.$2, + ), + ); - /// Sets a running command's terminal size. - Future resize(String sessionId, String runId, int cols, int rows) => - gateway.call( - 'chat_shell_resize', - _body(sessionId, runId: runId, cols: cols, rows: rows), - ); + /// Reports the size this client draws a running command's terminal at; + /// [activate] makes it the active client (it focused the terminal), whose + /// size the process takes. + Future resize( + String sessionId, + String runId, + int cols, + int rows, { + bool activate = false, + }) => gateway.call( + 'chat_shell_resize', + _body( + sessionId, + runId: runId, + cols: cols, + rows: rows, + activate: activate, + ), + ); Future stop(String sessionId, String runId) => gateway.call('chat_shell_stop', _body(sessionId, runId: runId)); diff --git a/app/lib/features/chat/shell/chat_shell_terminal_session.dart b/app/lib/features/chat/shell/chat_shell_terminal_session.dart index 01b5103e..e8b3c3ea 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_session.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_session.dart @@ -11,30 +11,51 @@ const int chatShellTerminalScrollback = 5000; /// /// It keeps no copy of typed input: [Terminal.onOutput] hands each key or /// paste straight to [onInput], which sends it. +/// +/// Several clients may draw one terminal. The emulator's automatic answers +/// to queries in the output (cursor position, device attributes) go to +/// [onReply] instead, so the server can let only the active client's +/// answers through; a view gaining focus calls [activate], which makes this +/// client the active one at its size ([onActivate]). class ChatShellTerminalSession { ChatShellTerminalSession( ChatShellRun run, { required this.onInput, required this.onResize, + this.onReply, + this.onActivate, }) : terminal = _ChatShellTerminal() { // Drawn at the process's own size until a view lays it out at its own. if (run.cols > 0 && run.rows > 0) terminal.resize(run.cols, run.rows); terminal.onOutput = _output; - terminal.onResize = (cols, rows, _, _) => onResize(cols, rows); + terminal.onResize = (cols, rows, _, _) { + _viewSize = (cols, rows); + onResize(cols, rows); + }; replay(run); } final Terminal terminal; - /// Receives input for the process; only called while the run is live. + /// Receives what the operator types for the process; only called while + /// the run is live. final void Function(String data) onInput; /// Receives the size the view laid the terminal out at. final void Function(int cols, int rows) onResize; + /// Receives the emulator's automatic answers to queries in the live + /// output; [onInput] receives them when this is null. + final void Function(String data)? onReply; + + /// Receives this client's size when a view of it gains focus. + final void Function(int cols, int rows)? onActivate; + int _end = 0; bool _live = false; bool _replaying = false; + bool _drawing = false; + (int, int)? _viewSize; /// The absolute output byte this terminal has drawn up to. int get end => _end; @@ -42,6 +63,16 @@ class ChatShellTerminalSession { /// Whether typing reaches a running process. bool get live => _live; + /// The size a view last laid the terminal out at; null before any did. + (int, int)? get viewSize => _viewSize; + + /// A view of this terminal gained focus: this client becomes the one the + /// process is sized for and whose answers it receives. + void activate() { + final size = _viewSize; + if (_live && size != null) onActivate?.call(size.$1, size.$2); + } + /// Draws [run]'s held output from scratch: on open, after a gap and after /// a readback replaced the card's copy. Answers the emulator gives to old /// queries in that output are not sent: the process asked them long ago. @@ -78,7 +109,13 @@ class ChatShellTerminalSession { replay(run); return; } - terminal.write(_drawable(run, text)); + // What the emulator sends while drawing output answers that output. + _drawing = true; + try { + terminal.write(_drawable(run, text)); + } finally { + _drawing = false; + } _end = end; } @@ -113,7 +150,13 @@ class ChatShellTerminalSession { } void _output(String data) { - if (_live && !_replaying) onInput(data); + if (!_live || _replaying) return; + final reply = onReply; + if (_drawing && reply != null) { + reply(data); + } else { + onInput(data); + } } /// Plain-pipe output has bare newlines, which a terminal draws as a line diff --git a/app/lib/features/chat/shell/chat_shell_terminal_view.dart b/app/lib/features/chat/shell/chat_shell_terminal_view.dart index 5497d57b..954a2d5d 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_view.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_view.dart @@ -94,6 +94,7 @@ class _ChatShellTerminalViewState extends State { final TerminalController _controller = TerminalController(); final FocusNode _focus = FocusNode(debugLabel: 'chat-shell-terminal'); final FocusNode _outputFocus = FocusNode(debugLabel: 'chat-shell-output'); + bool _focused = false; @override void initState() { @@ -101,10 +102,20 @@ class _ChatShellTerminalViewState extends State { // A paste while the terminal has focus goes to the process, not to the // chat composer. ChatComposerPasteFocus.registerInput(_focus); + _focus.addListener(_focusChanged); + } + + /// Focusing a terminal makes this client the one it is sized for, the + /// way typing in it does. + void _focusChanged() { + final focused = _focus.hasFocus; + if (focused && !_focused) widget.session.activate(); + _focused = focused; } @override void dispose() { + _focus.removeListener(_focusChanged); ChatComposerPasteFocus.unregisterInput(_focus); _controller.dispose(); _focus.dispose(); diff --git a/app/lib/features/chat/shell/chat_shell_terminals.dart b/app/lib/features/chat/shell/chat_shell_terminals.dart index 5ccb805b..fc40e233 100644 --- a/app/lib/features/chat/shell/chat_shell_terminals.dart +++ b/app/lib/features/chat/shell/chat_shell_terminals.dart @@ -43,7 +43,9 @@ class ChatShellTerminals { () => ChatShellTerminalSession( run, onInput: (data) => _input(run.id, data), + onReply: (data) => _input(run.id, data, reply: true), onResize: (cols, rows) => _resized(run.id, cols, rows), + onActivate: (cols, rows) => _activated(run.id, cols, rows), ), ); @@ -69,17 +71,35 @@ class ChatShellTerminals { _sessions[run.id]?.replay(run); } - void _input(String runId, String data) { + void _input(String runId, String data, {bool reply = false}) { if (_disposed) return; _inputs .putIfAbsent( runId, () => ChatShellInputPipe( - (data) => _repository.input(_sessionId, runId, data), + (data, reply) => _repository.input( + _sessionId, + runId, + data, + reply: reply, + // Typing makes this client the active one at its size. + size: reply ? null : _sessions[runId]?.viewSize, + ), (error) => onError(runId, error), ), ) - .add(data); + .add(data, reply: reply); + } + + /// A view of [runId] gained focus: it becomes the active client and the + /// process takes its size at once. + void _activated(String runId, int cols, int rows) { + if (_disposed || !(_sessions[runId]?.live ?? false)) return; + _resizes.remove(runId)?.cancel(); + _sentSizes[runId] = (cols, rows); + _repository + .resize(_sessionId, runId, cols, rows, activate: true) + .catchError((Object error) => onError(runId, error)); } void _resized(String runId, int cols, int rows) { @@ -110,16 +130,25 @@ class ChatShellTerminals { /// machine terminal's), in order: what arrives /// while a request is in flight goes in the next one. Nothing is kept once /// sent, and a refusal discards what was waiting rather than retyping it. +/// +/// The emulator's automatic answers ([add] with reply) travel in requests +/// of their own, marked so, never merged with typing on either side. class ChatShellInputPipe { ChatShellInputPipe(this._send, this._failed); - final Future Function(String data) _send; + final Future Function(String data, bool reply) _send; final void Function(Object error) _failed; - final StringBuffer _pending = StringBuffer(); + + /// Waiting text in order, each run of typing or of answers in one buffer. + final List<(StringBuffer, bool)> _pending = []; bool _busy = false; - void add(String data) { - _pending.write(data); + void add(String data, {bool reply = false}) { + if (data.isEmpty) return; + if (_pending.isEmpty || _pending.last.$2 != reply) { + _pending.add((StringBuffer(), reply)); + } + _pending.last.$1.write(data); if (!_busy) unawaited(_pump()); } @@ -127,19 +156,22 @@ class ChatShellInputPipe { _busy = true; try { while (_pending.isNotEmpty) { - var waiting = _pending.toString(); - _pending.clear(); + final (buffer, reply) = _pending.first; + var waiting = buffer.toString(); + buffer.clear(); var cut = waiting.length; if (cut > chatShellInputChunk) { cut = chatShellInputChunk; // Never split a surrogate pair across two requests. final unit = waiting.codeUnitAt(cut - 1); if (unit >= 0xD800 && unit <= 0xDBFF) cut--; - _pending.write(waiting.substring(cut)); + buffer.write(waiting.substring(cut)); + } else { + _pending.removeAt(0); } final chunk = waiting.substring(0, cut); waiting = ''; - await _send(chunk); + await _send(chunk, reply); } } catch (error) { _pending.clear(); diff --git a/app/lib/features/terminal/terminal_tab.dart b/app/lib/features/terminal/terminal_tab.dart index 61b571c9..c2ca4004 100644 --- a/app/lib/features/terminal/terminal_tab.dart +++ b/app/lib/features/terminal/terminal_tab.dart @@ -26,7 +26,9 @@ class TerminalTab extends ChangeNotifier { session = ChatShellTerminalSession( _run(), onInput: _input, + onReply: (data) => _input(data, reply: true), onResize: _resized, + onActivate: _activated, ); session.terminal.onTitleChange = _titled; } @@ -85,6 +87,10 @@ class TerminalTab extends ChangeNotifier { _sentSize = null; _update(info); unawaited(resume()); + // The new connection reports the size it draws at; the server applies + // it while no other client is the active one. + final size = session.viewSize; + if (size != null) _resized(size.$1, size.$2); } void disconnected() { @@ -182,19 +188,25 @@ class TerminalTab extends ChangeNotifier { _notify(); } - void _input(String data) { + /// Sends typed text, or with [reply] the emulator's automatic answer to a + /// query, which the server passes on only from the active client. Typing + /// carries the size this client draws at: it becomes the active client. + void _input(String data, {bool reply = false}) { if (_disposed || !connected) return; final id = _info.id; final gateway = _gateway; - (_pipe ??= ChatShellInputPipe( - (data) => gateway.call('terminal_input', { - 'terminal_request': {'terminal_id': id, 'data': data}, - }), - (failure) { - error = '$failure'; - _notify(); - }, - )).add(data); + (_pipe ??= ChatShellInputPipe((data, reply) { + final size = reply ? null : session.viewSize; + return gateway.call('terminal_input', { + 'terminal_request': { + 'terminal_id': id, + 'data': data, + if (reply) 'reply': true, + 'cols': ?size?.$1, + 'rows': ?size?.$2, + }, + }); + }, _failed)).add(data, reply: reply); } void _resized(int cols, int rows) { @@ -202,23 +214,40 @@ class TerminalTab extends ChangeNotifier { _resize?.cancel(); _resize = Timer(chatShellResizeDelay, () { if (_sentSize == (cols, rows) || !connected) return; - _sentSize = (cols, rows); - _gateway - .call('terminal_resize', { - 'terminal_request': { - 'terminal_id': _info.id, - 'cols': cols, - 'rows': rows, - }, - }) - .catchError((Object failure) { - error = '$failure'; - _notify(); - return {}; - }); + _sendSize(cols, rows, activate: false); }); } + /// A view gained focus: this client becomes the active one and the + /// terminal takes its size at once. + void _activated(int cols, int rows) { + if (_disposed || !_info.running || !connected) return; + _resize?.cancel(); + _sendSize(cols, rows, activate: true); + } + + void _sendSize(int cols, int rows, {required bool activate}) { + _sentSize = (cols, rows); + _gateway + .call('terminal_resize', { + 'terminal_request': { + 'terminal_id': _info.id, + 'cols': cols, + 'rows': rows, + if (activate) 'activate': true, + }, + }) + .catchError((Object failure) { + _failed(failure); + return {}; + }); + } + + void _failed(Object failure) { + error = '$failure'; + _notify(); + } + void _notify() { if (!_disposed) notifyListeners(); } diff --git a/app/notes/terminal-panel.md b/app/notes/terminal-panel.md index 44683a39..490aba67 100644 --- a/app/notes/terminal-panel.md +++ b/app/notes/terminal-panel.md @@ -107,8 +107,28 @@ data?, after?}`. when the login cannot ask for a password (below). - `terminal_list` → `terminals` (running and ended, oldest first; live records carry their current title, size and `stream`). -- `terminal_input {terminal_id, data}` (UTF-8, ≤ 16 KiB, 64-request queue), - `terminal_resize {terminal_id, cols, rows}` (clamped 20–500 × 4–200). +- `terminal_input {terminal_id, data, reply?, cols?, rows?}` (UTF-8, + ≤ 16 KiB, 64-request queue), `terminal_resize {terminal_id, cols, rows, + activate?}` (clamped 20–500 × 4–200). +- **Several clients on one terminal** (`terminal_viewers.go`, + `terminal_active.go`; chat terminal commands too): one *active* client + owns the PTY size and is the only one whose emulator's automatic answers + (`reply: true`: cursor position, device attributes) reach the shell, so + a query gets one answer, not one per client. The opener starts active; + typing (carrying the typist's `cols`/`rows`, applied before the input) + or focusing a terminal view (`terminal_resize` with `activate`) makes a + client active. Others' sizes are kept, not applied; when the active + connection closes the next most recent client's size is applied. The + client marks answers by what the emulator emits while drawing output + (`ChatShellTerminalSession.onReply`). +- **Input latency**: `PipelinesClient.call` sends `terminal_input`, + `terminal_resize`, `chat_shell_input` and `chat_shell_resize` at once + instead of behind the previous request's reply; the server reads them + onto a per-connection terminal lane (`terminal_lane.go`) handled in + order beside the ordinary loop, and `terminal_open` runs off the read + loop. `ChatShellInputPipe` still keeps one request in flight per + terminal (typing during it is coalesced; answers go in their own + requests). - `terminal_output {terminal_id, after}` → `terminal` with `output`, `output_start`, `output_end`, `stream`; subscribes the connection. - `terminal_close {terminal_id}` → the closed record (runs off the read diff --git a/app/test/core/transport/pipelines_client_test.dart b/app/test/core/transport/pipelines_client_test.dart index e71b78f6..084c22fb 100644 --- a/app/test/core/transport/pipelines_client_test.dart +++ b/app/test/core/transport/pipelines_client_test.dart @@ -72,6 +72,76 @@ void main() { await client.dispose(); }); + test('terminal keystrokes do not wait behind a slow request', () async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final connecting = client.connect(Uri.parse('ws://example.test')); + channel.readyCompleter.complete(); + await connecting; + Map sent(int i) => + jsonDecode(channel.outgoing[i] as String) as Map; + // A terminal_open waiting for its login prompt. + final open = client.call('terminal_open'); + final later = client.call('terminal_list'); + await Future.delayed(Duration.zero); + final keys = [ + for (final data in ['l', 's', '\r']) + client.call('terminal_input', { + 'terminal_request': {'terminal_id': 't', 'data': data}, + }), + ]; + final size = client.call('chat_shell_resize', { + 'chat_shell_run_request': {'cols': 80, 'rows': 24}, + }); + await Future.delayed(Duration.zero); + // The keystrokes and the size went out at once, in order; the ordinary + // request behind the slow one still waits for it. + expect(channel.outgoing, hasLength(5)); + expect( + [for (var i = 0; i < 5; i++) sent(i)['type']], + [ + 'terminal_open', + 'terminal_input', + 'terminal_input', + 'terminal_input', + 'chat_shell_resize', + ], + ); + expect( + [for (var i = 1; i < 4; i++) sent(i)['terminal_request']['data']], + ['l', 's', '\r'], + ); + for (var i = 1; i < 5; i++) { + channel.incoming.add( + jsonEncode({'id': sent(i)['id'], 'type': sent(i)['type']}), + ); + } + for (final key in keys) { + expect((await key)['type'], 'terminal_input'); + } + expect((await size)['type'], 'chat_shell_resize'); + channel.incoming.add( + jsonEncode({'id': sent(0)['id'], 'type': 'terminal_open'}), + ); + expect((await open)['type'], 'terminal_open'); + await Future.delayed(Duration.zero); + expect(sent(5)['type'], 'terminal_list'); + channel.incoming.add( + jsonEncode({'id': sent(5)['id'], 'type': 'terminal_list'}), + ); + expect((await later)['type'], 'terminal_list'); + await client.dispose(); + }); + + test('a keystroke while disconnected fails at once', () async { + final client = PipelinesClient(channelFactory: (_) => FakeChannel()); + await expectLater( + client.call('terminal_input', {'terminal_request': {}}), + throwsA(isA()), + ); + await client.dispose(); + }); + test('disconnect fails pending requests', () async { final channel = FakeChannel(); final client = PipelinesClient(channelFactory: (_) => channel); diff --git a/app/test/features/chat/shell/chat_shell_terminal_session_test.dart b/app/test/features/chat/shell/chat_shell_terminal_session_test.dart index 7394fed9..ee7a9f0b 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_session_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_session_test.dart @@ -67,6 +67,35 @@ void main() { expect(sent, hasLength(2)); }); + test('query answers go to onReply; focus reports the laid out size', () { + final typed = []; + final replies = []; + final activations = <(int, int)>[]; + final session = ChatShellTerminalSession( + _run('prompt'), + onInput: typed.add, + onReply: replies.add, + onResize: (_, _) {}, + onActivate: (cols, rows) => activations.add((cols, rows)), + ); + session.append(_run('prompt\x1b[6n'), '\x1b[6n', 6, 10); + session.terminal.textInput('y'); + expect(replies, ['\x1b[1;7R']); + expect(typed, ['y']); + // Drawn at the run's own size until a view lays it out. + expect(session.viewSize, isNull); + session.activate(); + expect(activations, isEmpty); + session.terminal.resize(90, 20); + expect(session.viewSize, (90, 20)); + session.activate(); + expect(activations, [(90, 20)]); + // A finished run claims nothing. + session.finish(_run('prompt', status: 'exited')); + session.activate(); + expect(activations, hasLength(1)); + }); + test('a chunk after a hole redraws the held copy', () { final session = ChatShellTerminalSession( _run('a\r\n'), diff --git a/app/test/features/chat/shell/chat_shell_terminal_test.dart b/app/test/features/chat/shell/chat_shell_terminal_test.dart index b6cf9af7..82c63b44 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_test.dart @@ -274,6 +274,47 @@ void main() { expect(gateway.bodies('chat_shell_input'), isEmpty); }); + testWidgets('focusing the terminal claims it at its size; typing carries ' + 'the size and query answers are marked', (tester) async { + await openRunning(tester, output: 'size? \x1b[6n'); + await tester.pump(const Duration(milliseconds: 200)); + final laidOut = gateway.bodies('chat_shell_resize').single; + // The replayed query is not answered; nothing was claimed yet. + expect(gateway.bodies('chat_shell_input'), isEmpty); + await tester.tap(find.byType(TerminalView)); + await tester.pump(); + final claim = gateway.bodies('chat_shell_resize').last; + expect(claim['activate'], isTrue); + expect((claim['cols'], claim['rows']), (laidOut['cols'], laidOut['rows'])); + // Typing carries this client's size. + await tester.sendKeyEvent(LogicalKeyboardKey.keyG); + await tester.pump(); + var inputs = gateway.bodies('chat_shell_input'); + expect(inputs.single['data'], 'g'); + expect(inputs.single['reply'], isNull); + expect( + (inputs.single['cols'], inputs.single['rows']), + (laidOut['cols'], laidOut['rows']), + ); + // A live query is answered with the answer marked, without a size. + gateway.emitOutput('run_t', '\x1b[6n', 'size? \x1b[6n'.length); + await tester.pump(); + await tester.pump(); + inputs = gateway.bodies('chat_shell_input'); + expect(inputs.last['data'], '\x1b[1;7R'); + expect(inputs.last['reply'], isTrue); + expect(inputs.last['cols'], isNull); + // Focusing again after the focus left claims again. + FocusManager.instance.primaryFocus?.unfocus(); + await tester.pump(); + await tester.tap(find.byType(TerminalView)); + await tester.pump(); + expect( + gateway.bodies('chat_shell_resize').where((b) => b['activate'] == true), + hasLength(2), + ); + }, variant: TargetPlatformVariant.only(TargetPlatform.linux)); + testWidgets('coloured output is drawn without its escape codes', ( tester, ) async { diff --git a/app/test/features/terminal/terminal_active_client_test.dart b/app/test/features/terminal/terminal_active_client_test.dart new file mode 100644 index 00000000..ec9af476 --- /dev/null +++ b/app/test/features/terminal/terminal_active_client_test.dart @@ -0,0 +1,101 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminals.dart'; +import 'package:pipelines_app/features/terminal/terminal_info.dart'; +import 'package:pipelines_app/features/terminal/terminal_tab.dart'; + +import 'terminal_fixtures.dart'; + +void main() { + testWidgets('answers are marked, typing carries the size, focus activates', ( + tester, + ) async { + final gateway = TerminalGateway(); + final tab = TerminalTab( + machineId: 'm', + machineName: 'm', + gateway: gateway, + info: TerminalInfo.fromJson(gateway.add('t1')), + ); + // Before a view lays it out, focus has no size to claim. + tab.session.activate(); + await tester.pump(); + expect(gateway.bodies('terminal_resize'), isEmpty); + + tab.session.terminal.resize(100, 30); + await tester.pump(chatShellResizeDelay); + expect(gateway.bodies('terminal_resize'), [ + {'terminal_id': 't1', 'cols': 100, 'rows': 30}, + ]); + + // A cursor position query in the output: the answer is marked. + tab.frame({'output': '\x1b[6n', 'offset': 0, 'end': 4}); + await tester.pump(); + // Typing carries the size this client draws at. + tab.session.terminal.textInput('ls'); + await tester.pump(); + expect(gateway.bodies('terminal_input'), [ + {'terminal_id': 't1', 'data': '\x1b[1;1R', 'reply': true}, + {'terminal_id': 't1', 'data': 'ls', 'cols': 100, 'rows': 30}, + ]); + + // A view gaining focus claims the terminal at once, at its size. + tab.session.activate(); + await tester.pump(); + expect(gateway.bodies('terminal_resize').last, { + 'terminal_id': 't1', + 'cols': 100, + 'rows': 30, + 'activate': true, + }); + + // A new connection reports its size again. + tab.attach(gateway, TerminalInfo.fromJson(gateway.terminals['t1']!)); + await tester.pump(chatShellResizeDelay); + expect(gateway.bodies('terminal_resize'), hasLength(3)); + expect(gateway.bodies('terminal_resize').last, { + 'terminal_id': 't1', + 'cols': 100, + 'rows': 30, + }); + tab.dispose(); + }); + + test('the input pipe keeps answers and typing apart, in order', () async { + final sent = <(String, bool)>[]; + final pipe = ChatShellInputPipe((data, reply) async { + sent.add((data, reply)); + await Future.delayed(Duration.zero); + }, (_) {}); + pipe.add('a'); + // While the first is in flight, typing, an answer and typing wait. + pipe.add('b'); + pipe.add('c'); + pipe.add('\x1b[1;1R', reply: true); + pipe.add('d'); + pipe.add('${'x' * chatShellInputChunk}y'); + await pumpEventQueue(); + expect(sent, [ + ('a', false), + ('bc', false), + ('\x1b[1;1R', true), + ('d${'x' * (chatShellInputChunk - 1)}', false), + ('xy', false), + ]); + }); + + test('a refusal drops what was waiting and reports once', () async { + final failures = []; + final sent = []; + final pipe = ChatShellInputPipe((data, reply) async { + sent.add(data); + await Future.delayed(Duration.zero); + throw StateError('not running'); + }, failures.add); + pipe.add('a'); + pipe.add('b'); + pipe.add('?', reply: true); + await pumpEventQueue(); + expect(sent, ['a']); + expect(failures, hasLength(1)); + }); +} diff --git a/docs/cli.md b/docs/cli.md index 2570615b..c649953b 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1315,8 +1315,18 @@ app's terminal panel). Every request carries `terminal_request` pipelines`), never the operator's tmux. At most 8 running terminals per machine. - `terminal_list` replies with `terminals` (running and ended, oldest first). -- `terminal_input {terminal_id, data}` writes UTF-8 input (at most 16 KiB); - `terminal_resize {terminal_id, cols, rows}` resizes. Neither is logged. +- `terminal_input {terminal_id, data, reply?, cols?, rows?}` writes UTF-8 + input (at most 16 KiB); `terminal_resize {terminal_id, cols, rows, + activate?}` reports the size a client draws at. Neither is logged. With + several clients on one terminal, the *active* client (the opener, then + whichever most recently typed or sent `activate`, i.e. focused it) owns + the terminal's size, and only its emulator's automatic query answers + (`reply: true`) reach the shell; others' are acknowledged and dropped. + Typed input may carry the sender's `cols`/`rows`, applied first. When the + active connection closes, the next most recent client's size is applied. + `chat_shell_input`/`chat_shell_resize` follow the same rules. Input and + resize requests are handled on a lane of their own per connection, in + order, never behind a slow request read before them. - `terminal_output {terminal_id, after}` replies with the retained output (1 MiB tail) from byte `after` of the stream named `stream`. Opening or reading subscribes the connection to the terminal's output frames. diff --git a/internal/protocol/chat_shell_run.go b/internal/protocol/chat_shell_run.go index 90ae515d..88a93fb4 100644 --- a/internal/protocol/chat_shell_run.go +++ b/internal/protocol/chat_shell_run.go @@ -65,7 +65,8 @@ const ( // ChatShellRunRequest names one session and either a new command or a run. // OperationID is the optional retry identity of chat_shell_share's prompt. // Cols and Rows size a new run's terminal (chat_shell_run) or resize a running -// one (chat_shell_resize); Data is chat_shell_input's typed text; After is +// one (chat_shell_resize) and may accompany typed chat_shell_input (the size +// its client draws at); Data is chat_shell_input's typed text; After is // chat_shell_run_output's resume offset. type ChatShellRunRequest struct { SessionID string `json:"session_id"` @@ -78,6 +79,11 @@ type ChatShellRunRequest struct { After int64 `json:"after,omitempty"` // RunIDs names the runs of chat_shell_dismiss and chat_shell_restore. RunIDs []string `json:"run_ids,omitempty"` + // Reply marks chat_shell_input as an automatic answer of the client's + // emulator; Activate marks chat_shell_resize as the client focusing the + // terminal (see ChatShellInput and ChatShellResize). + Reply bool `json:"reply,omitempty"` + Activate bool `json:"activate,omitempty"` } // ChatShellRunRecord is one operator command and what it produced. Output is diff --git a/internal/protocol/chat_shell_terminal.go b/internal/protocol/chat_shell_terminal.go index 5e82c527..1b92c76d 100644 --- a/internal/protocol/chat_shell_terminal.go +++ b/internal/protocol/chat_shell_terminal.go @@ -13,10 +13,24 @@ const ( // (Ctrl-C is "\u0003", Enter is "\r", arrow keys are their escape // sequences); the bytes written are exactly its UTF-8 encoding. Input is // never persisted or logged; the reply carries no body. + // + // Several clients may draw one terminal; the one that most recently typed + // or focused it (marked activate on a resize), or else the first to + // attach, is its active client. Reply marks Data + // as the client emulator's automatic answer to a terminal query (cursor + // position, device attributes) rather than typing: it reaches the process + // only from the active client and is otherwise acknowledged and dropped, + // so a query gets one answer. Typed input makes its client active; it may + // carry Cols and Rows, the size that client draws at, which the terminal + // then takes before the input is written. ChatShellInput = "chat_shell_input" - // ChatShellResize sets a running terminal command's size (cols, rows); the - // process receives SIGWINCH. The last resize from any client wins. The - // reply echoes the run. + // ChatShellResize reports the size (cols, rows) a client draws a running + // terminal command at. The terminal takes the active client's size (the + // process receives SIGWINCH); a resize marked activate makes its client + // the active one (it focused the terminal). When the active client's + // connection closes, the next most recently active client's last size is + // applied. A client that does not set the fields behaves as before: its + // typing makes it active. The reply echoes the run with the size applied. ChatShellResize = "chat_shell_resize" ) diff --git a/internal/protocol/terminal.go b/internal/protocol/terminal.go index 70da0950..e330483c 100644 --- a/internal/protocol/terminal.go +++ b/internal/protocol/terminal.go @@ -20,10 +20,15 @@ const ( // oldest first, without output. The body is optional. TerminalList = "terminal_list" // TerminalInput writes Data (UTF-8, control characters included, at most - // ChatShellInputLimit bytes) to a running terminal. No reply body. + // ChatShellInputLimit bytes) to a running terminal. No reply body. Reply + // marks an automatic answer of the client's emulator, which reaches the + // terminal only from its active client; typed input may carry the size + // (cols, rows) the client draws at (as chat_shell_input). TerminalInput = "terminal_input" - // TerminalResize sets a running terminal's size (cols, rows); the reply - // echoes the terminal. + // TerminalResize reports the size (cols, rows) a client draws a running + // terminal at; the terminal takes its active client's size, and Activate + // makes the sender active (as chat_shell_resize). The opener of a + // terminal is its first active client. The reply echoes the terminal. TerminalResize = "terminal_resize" // TerminalOutput reads one terminal with its retained output from the // absolute byte After on (all of it when After precedes the retained @@ -68,6 +73,9 @@ type TerminalRequest struct { Rows int `json:"rows,omitempty"` Data string `json:"data,omitempty"` After int64 `json:"after,omitempty"` + // Reply (terminal_input) and Activate (terminal_resize): see above. + Reply bool `json:"reply,omitempty"` + Activate bool `json:"activate,omitempty"` } // TerminalRecord is one terminal. Output and OutputStart are set only on diff --git a/internal/server/chat_shell_run_handlers.go b/internal/server/chat_shell_run_handlers.go index 6abab624..19c1c34f 100644 --- a/internal/server/chat_shell_run_handlers.go +++ b/internal/server/chat_shell_run_handlers.go @@ -56,6 +56,7 @@ func handleChatShellRunRequest(ctx context.Context, request protocol.Message, br fail(err) return } + runner.attachViewer(clientID, sessionID, record.ID, record.Cols, record.Rows) _ = write(protocol.Message{Type: protocol.ChatShellRun, ID: request.ID, ChatShellRun: &record}) case protocol.ChatShellStop: record, err := runner.Stop(sessionID, body.RunID) @@ -92,13 +93,13 @@ func handleChatShellRunRequest(ctx context.Context, request protocol.Message, br } _ = write(protocol.Message{Type: protocol.ChatShellRestore, ID: request.ID, ChatShellRuns: runs}) case protocol.ChatShellInput: - if err := runner.Input(sessionID, body.RunID, body.Data); err != nil { + if err := runner.ClientInput(clientID, sessionID, body.RunID, body.Data, body.Reply, body.Cols, body.Rows); err != nil { fail(err) return } _ = write(protocol.Message{Type: protocol.ChatShellInput, ID: request.ID}) case protocol.ChatShellResize: - record, err := runner.Resize(sessionID, body.RunID, body.Cols, body.Rows) + record, err := runner.ClientResize(clientID, sessionID, body.RunID, body.Cols, body.Rows, body.Activate) if err != nil { fail(err) return diff --git a/internal/server/chat_shell_runner.go b/internal/server/chat_shell_runner.go index 1de83da0..abf72ad6 100644 --- a/internal/server/chat_shell_runner.go +++ b/internal/server/chat_shell_runner.go @@ -66,6 +66,8 @@ type chatShellProcess struct { // input feeds it in order (chat_shell_terminal.go). terminal *os.File input chan []byte + // viewers are the connections drawing the terminal (terminal_viewers.go). + viewers terminalViewers // closed is set once the reader is closed; a read still blocked on a // terminal a descendant holds open records nothing after it. closed bool diff --git a/internal/server/chat_shell_terminal_ws_test.go b/internal/server/chat_shell_terminal_ws_test.go index cf241f2a..afd71235 100644 --- a/internal/server/chat_shell_terminal_ws_test.go +++ b/internal/server/chat_shell_terminal_ws_test.go @@ -37,7 +37,9 @@ func TestChatShellTerminalOverWebsocket(t *testing.T) { resize := shellRequest(protocol.ChatShellResize, "size", run.ID, "") resize.ChatShellRunRequest.Cols, resize.ChatShellRunRequest.Rows = 120, 33 writeChat(t, ctx, conns[1], resize) - if got := readShellFrame(t, ctx, conns[1], func(m protocol.Message) bool { return m.ID == "size" }); got.Type != protocol.ChatShellResize || got.ChatShellRun.Cols != 120 { + // The starter stays the active client until the watcher types: then the + // watcher's size applies (stty size below). + if got := readShellFrame(t, ctx, conns[1], func(m protocol.Message) bool { return m.ID == "size" }); got.Type != protocol.ChatShellResize || got.ChatShellRun.Cols != 80 { t.Fatalf("resize reply = %+v", got) } input := shellRequest(protocol.ChatShellInput, "in", run.ID, "") diff --git a/internal/server/terminal_active.go b/internal/server/terminal_active.go new file mode 100644 index 00000000..c1f4e382 --- /dev/null +++ b/internal/server/terminal_active.go @@ -0,0 +1,160 @@ +package server + +import ( + "errors" + "log" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// The active-client policy (terminal_viewers.go) applied to machine +// terminals and to chats' terminal commands: requests name their +// connection, and a connection that closes hands the terminal to the next. + +// ClientInput is Input from clientID: typing makes it the active client +// (its size, cols x rows when it sent one, else its last, is applied +// first); an automatic reply (reply) from any other client is acknowledged +// and dropped. +func (m *terminalManager) ClientInput(clientID, id, data string, reply bool, cols, rows int) error { + if p := m.process(id); p != nil && p.running() { + if reply && !p.viewers.answers(clientID) { + return nil + } + if !reply { + if size := p.viewers.typedAt(clientID, cols, rows); size.ok && !p.sized(size) { + if err := p.applySize(size.cols, size.rows); err != nil { + log.Printf("terminal %s resize: %v", id, err) + } + } + } + } + return m.Input(id, data) +} + +// ClientResize records the size clientID draws terminal id at and applies +// it when clientID is (or, with activate, becomes) the active client. The +// record carries the size the terminal has. +func (m *terminalManager) ClientResize(clientID, id string, cols, rows int, activate bool) (protocol.TerminalRecord, error) { + if cols <= 0 || rows <= 0 { + return protocol.TerminalRecord{}, errors.New("positive cols and rows are required") + } + p, err := m.live(id) + if err != nil { + return protocol.TerminalRecord{}, err + } + if size := p.viewers.resize(clientID, cols, rows, activate); size.ok { + return m.Resize(id, size.cols, size.rows) + } + return p.snapshot(false, 0), nil +} + +// attachViewer records clientID as drawing terminal id (it read it). +func (m *terminalManager) attachViewer(clientID, id string) { + if p := m.process(id); p != nil { + p.viewers.attach(clientID) + } +} + +// detach drops clientID's connection: its output frames, and its part in +// every terminal it drew; a terminal it was active in takes the next +// client's size. +func (m *terminalManager) detach(clientID string) { + m.clients.detach(clientID) + m.mu.Lock() + terms := make(map[string]*terminalProcess, len(m.terms)) + for id, p := range m.terms { + terms[id] = p + } + m.mu.Unlock() + for id, p := range terms { + if size := p.viewers.leave(clientID); size.ok && p.running() { + if err := p.applySize(size.cols, size.rows); err != nil { + log.Printf("terminal %s resize: %v", id, err) + } + } + } +} + +// ClientInput is Input from clientID, under the same policy as the machine +// terminals' ClientInput. +func (r *chatShellRunner) ClientInput(clientID, sessionID, runID, data string, reply bool, cols, rows int) error { + if p := r.activeProcess(sessionID, runID); p != nil && p.terminal != nil { + if reply && !p.viewers.answers(clientID) { + return nil + } + if !reply { + if size := p.viewers.typedAt(clientID, cols, rows); size.ok && !p.sized(size) { + if _, err := r.Resize(sessionID, runID, size.cols, size.rows); err != nil { + log.Printf("chat shell %s resize: %v", runID, err) + } + } + } + } + return r.Input(sessionID, runID, data) +} + +// ClientResize is Resize from clientID, applied only when it is (or, with +// activate, becomes) the active client. +func (r *chatShellRunner) ClientResize(clientID, sessionID, runID string, cols, rows int, activate bool) (protocol.ChatShellRunRecord, error) { + if cols <= 0 || rows <= 0 { + return protocol.ChatShellRunRecord{}, errors.New("positive cols and rows are required") + } + p, err := r.terminalProcess(sessionID, runID) + if err != nil { + return protocol.ChatShellRunRecord{}, err + } + if size := p.viewers.resize(clientID, cols, rows, activate); size.ok { + return r.Resize(sessionID, runID, size.cols, size.rows) + } + p.mu.Lock() + defer p.mu.Unlock() + return p.record, nil +} + +// attachViewer makes clientID, which started runID at cols x rows, its +// active client. +func (r *chatShellRunner) attachViewer(clientID, sessionID, runID string, cols, rows int) { + if p := r.activeProcess(sessionID, runID); p != nil && p.terminal != nil && cols > 0 && rows > 0 { + p.viewers.resize(clientID, cols, rows, true) + } +} + +// leave drops clientID's part in every running terminal command it drew. +func (r *chatShellRunner) leave(clientID string) { + if r == nil { + return + } + type run struct{ sessionID, runID string } + r.mu.Lock() + procs := make(map[run]*chatShellProcess, len(r.active)) + for id, p := range r.active { + procs[run{p.record.SessionID, id}] = p + } + r.mu.Unlock() + for key, p := range procs { + if p.terminal == nil { + continue + } + if size := p.viewers.leave(clientID); size.ok { + if _, err := r.Resize(key.sessionID, key.runID, size.cols, size.rows); err != nil { + log.Printf("chat shell %s resize: %v", key.runID, err) + } + } + } +} + +// sized reports whether the terminal already has size (clamped). +func (p *terminalProcess) sized(size terminalSize) bool { + cols, rows := chatShellTerminalSize(size.cols, size.rows) + p.mu.Lock() + defer p.mu.Unlock() + return p.record.Cols == cols && p.record.Rows == rows +} + +// sized reports whether the terminal command already has size (clamped). +func (p *chatShellProcess) sized(size terminalSize) bool { + cols, rows := chatShellTerminalSize(size.cols, size.rows) + p.mu.Lock() + defer p.mu.Unlock() + return p.record.Cols == cols && p.record.Rows == rows +} diff --git a/internal/server/terminal_active_test.go b/internal/server/terminal_active_test.go new file mode 100644 index 00000000..ce00ccc8 --- /dev/null +++ b/internal/server/terminal_active_test.go @@ -0,0 +1,189 @@ +//go:build darwin || linux + +package server + +import ( + "context" + "fmt" + "strings" + "testing" + "time" + + "github.com/coder/websocket" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// readTerminalText reads conn's output frames of id, from wherever its +// subscription started, until the text contains want. +func readTerminalText(t *testing.T, ctx context.Context, conn *websocket.Conn, id, want string) string { + t.Helper() + var seen strings.Builder + for !strings.Contains(seen.String(), want) { + seen.WriteString(readShellFrame(t, ctx, conn, func(m protocol.Message) bool { + return m.Type == protocol.TerminalEvent && m.TerminalEvent.TerminalID == id && m.TerminalEvent.Terminal == nil + }).TerminalEvent.Output) + } + return seen.String() +} + +// Two clients draw one terminal: only the active client's emulator answers +// reach the shell, the terminal takes the active client's size, typing or +// focusing makes a client active, and when the active client leaves the +// next one's size comes back. +func TestTerminalTwoClientsActiveClient(t *testing.T) { + terminalHome(t) + ctx, _, conns := dialChatConns(t, Options{OperatorRegistry: newOperatorStore(t)}, 2) + a, b := conns[0], conns[1] + term := terminalReply(t, ctx, a, terminalRequest(protocol.TerminalOpen, "open", protocol.TerminalRequest{Cols: 156, Rows: 37})).Terminal + terminalLogIn(t, ctx, a, term.ID) + terminalReply(t, ctx, b, terminalRequest(protocol.TerminalOutput, "read", protocol.TerminalRequest{TerminalID: term.ID})) + // b draws it smaller; the opener is active and keeps its size. + if got := terminalReply(t, ctx, b, terminalRequest(protocol.TerminalResize, "small", protocol.TerminalRequest{TerminalID: term.ID, Cols: 121, Rows: 11})); got.Terminal == nil || got.Terminal.Cols != 156 || got.Terminal.Rows != 37 { + t.Fatalf("background resize = %+v", got) + } + // A query both emulators answer: only the active client's answer arrives. + terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "ask", protocol.TerminalRequest{TerminalID: term.ID, Data: "read -r ans; echo got:$ans; stty size\r"})) + if got := terminalReply(t, ctx, b, terminalRequest(protocol.TerminalInput, "b-reply", protocol.TerminalRequest{TerminalID: term.ID, Data: "b-answer\r", Reply: true})); got.Type != protocol.TerminalInput { + t.Fatalf("dropped reply is acknowledged: %+v", got) + } + terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "a-reply", protocol.TerminalRequest{TerminalID: term.ID, Data: "a-answer\r", Reply: true})) + text := readTerminalText(t, ctx, a, term.ID, "37 156") + if !strings.Contains(text, "got:a-answer") || strings.Contains(text, "b-answer") { + t.Fatalf("output = %q", text) + } + // b types: it becomes active at its own size, before its keystrokes. + terminalReply(t, ctx, b, terminalRequest(protocol.TerminalInput, "b-type", protocol.TerminalRequest{TerminalID: term.ID, Data: "stty size\r"})) + readTerminalText(t, ctx, a, term.ID, "11 121") + // Now a's answers are the ones dropped. + terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "a-late", protocol.TerminalRequest{TerminalID: term.ID, Data: "echo a-late-$((1+1))\r", Reply: true})) + // a focuses its terminal: active again at its size. + if got := terminalReply(t, ctx, a, terminalRequest(protocol.TerminalResize, "focus", protocol.TerminalRequest{TerminalID: term.ID, Cols: 150, Rows: 40, Activate: true})); got.Terminal.Cols != 150 || got.Terminal.Rows != 40 { + t.Fatalf("activate = %+v", got) + } + terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "a-type", protocol.TerminalRequest{TerminalID: term.ID, Data: "stty size\r"})) + if text := readTerminalText(t, ctx, a, term.ID, "40 150"); strings.Contains(text, "a-late-2") { + t.Fatalf("a background answer reached the shell: %q", text) + } + // a leaves: b, the next most recent, has its size back. + a.Close(websocket.StatusNormalClosure, "") + deadline := time.Now().Add(5 * time.Second) + for { + list := terminalReply(t, ctx, b, terminalRequest(protocol.TerminalList, "list", protocol.TerminalRequest{})) + if len(list.Terminals) == 1 && list.Terminals[0].Cols == 121 && list.Terminals[0].Rows == 11 { + break + } + if time.Now().After(deadline) { + t.Fatalf("size after the active client left = %+v", list.Terminals) + } + time.Sleep(20 * time.Millisecond) + } + // And b's emulator answers now reach the shell. + terminalReply(t, ctx, b, terminalRequest(protocol.TerminalInput, "b-answers", protocol.TerminalRequest{TerminalID: term.ID, Data: "stty size\r", Reply: true})) + readTerminalText(t, ctx, b, term.ID, "11 121") +} + +// A chat's terminal command watched by two clients follows the same policy. +func TestChatShellTerminalTwoClientsActiveClient(t *testing.T) { + ctx, conns, _ := shellChat(t) + a, b := conns[0], conns[1] + start := shellRequest(protocol.ChatShellRun, "r1", "", `read -r first; echo got:$first; read -r second; stty size; echo done`) + start.ChatShellRunRequest.Cols, start.ChatShellRunRequest.Rows = 100, 30 + writeChat(t, ctx, a, start) + run := readShellFrame(t, ctx, a, func(m protocol.Message) bool { return m.ID == "r1" }).ChatShellRun + resize := shellRequest(protocol.ChatShellResize, "size", run.ID, "") + resize.ChatShellRunRequest.Cols, resize.ChatShellRunRequest.Rows = 120, 33 + writeChat(t, ctx, b, resize) + if got := readShellFrame(t, ctx, b, func(m protocol.Message) bool { return m.ID == "size" }); got.ChatShellRun == nil || got.ChatShellRun.Cols != 100 { + t.Fatalf("background resize = %+v", got) + } + send := func(conn *websocket.Conn, id, data string, reply bool, cols, rows int) { + t.Helper() + input := shellRequest(protocol.ChatShellInput, id, run.ID, "") + input.ChatShellRunRequest.Data, input.ChatShellRunRequest.Reply = data, reply + input.ChatShellRunRequest.Cols, input.ChatShellRunRequest.Rows = cols, rows + writeChat(t, ctx, conn, input) + if got := readShellFrame(t, ctx, conn, func(m protocol.Message) bool { return m.ID == id }); got.Type != protocol.ChatShellInput { + t.Fatalf("input %s = %+v", id, got) + } + } + send(b, "b-reply", "b-answer\r", true, 0, 0) + send(a, "a-reply", "a-answer\r", true, 0, 0) + // b types the second line carrying the size it now draws at: it becomes + // active at that size before the keystrokes are written. + send(b, "b-type", "next\r", false, 90, 20) + _, output := finishedShell(t, ctx, a, run.ID) + if !strings.Contains(output, "got:a-answer") || strings.Contains(output, "b-answer") || !strings.Contains(output, "20 90") { + t.Fatalf("output = %q", output) + } +} + +// Keystrokes take their own lane: they are answered, in order, while an +// ordinary request on the same connection is still being handled. +func TestTerminalInputDoesNotWaitBehindSlowRequest(t *testing.T) { + store := newOperatorStore(t) + gate := make(chan struct{}) + broker := scriptedChat() + broker.block = true + broker.createGate, broker.createStarted = gate, make(chan struct{}) + ctx, _, conns := dialChatConns(t, Options{Chat: broker, OperatorRegistry: store}, 1) + conn := conns[0] + dir := t.TempDir() + if err := store.RecordOperatorSession(ctx, "ses_1", dir, "Shell", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + writeChat(t, ctx, conn, protocol.Message{Type: protocol.ChatSubscribe, ID: "sub", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}}) + readShellFrame(t, ctx, conn, func(m protocol.Message) bool { return m.ID == "sub" }) + run := runShell(t, ctx, conn, "r1", `for i in $(seq 1 40); do read -r line; echo "seen:$line"; done`) + defer close(gate) + writeChat(t, ctx, conn, protocol.Message{Type: protocol.ChatCreate, ID: "slow", ChatCreate: &protocol.ChatCreateRequest{Title: "slow", Directory: dir, OperationID: "slow-op"}}) + select { + case <-broker.createStarted: + case <-time.After(5 * time.Second): + t.Fatal("chat_create never reached the broker") + } + // Forty keystroke requests, written without waiting for replies. + started := time.Now() + for i := 1; i <= 40; i++ { + input := shellRequest(protocol.ChatShellInput, fmt.Sprintf("in-%d", i), run.ID, "") + input.ChatShellRunRequest.Data = fmt.Sprintf("k%02d\r", i) + writeChat(t, ctx, conn, input) + } + var output strings.Builder + replies := 0 + for replies < 40 || !strings.Contains(output.String(), "seen:k40") { + m := readShellFrame(t, ctx, conn, func(m protocol.Message) bool { + return strings.HasPrefix(m.ID, "in-") || m.ID == "slow" || + m.Type == protocol.ChatShellRunEvent && m.ChatShellRunEvent.RunID == run.ID && m.ChatShellRunEvent.Run == nil + }) + switch { + case m.ID == "slow": + t.Fatal("the slow request answered first; it should still be waiting") + case m.Type == protocol.Error: + t.Fatalf("input refused: %+v", m) + case strings.HasPrefix(m.ID, "in-"): + replies++ + if m.ID != fmt.Sprintf("in-%d", replies) { + t.Fatalf("reply %d is %s", replies, m.ID) + } + default: + output.WriteString(m.ChatShellRunEvent.Output) + } + } + t.Logf("40 keystrokes answered and echoed in %s behind a blocked request", time.Since(started)) + // The shell saw them in the order they were typed. + var want strings.Builder + for i := 1; i <= 40; i++ { + fmt.Fprintf(&want, "seen:k%02d\r\n", i) + } + got := output.String() + var seen strings.Builder + for _, line := range strings.Split(got, "\r\n") { + if strings.HasPrefix(line, "seen:") { + seen.WriteString(line + "\r\n") + } + } + if seen.String() != want.String() { + t.Fatalf("order = %q", seen.String()) + } +} diff --git a/internal/server/terminal_handlers.go b/internal/server/terminal_handlers.go index bd8bd219..f1af1053 100644 --- a/internal/server/terminal_handlers.go +++ b/internal/server/terminal_handlers.go @@ -45,11 +45,12 @@ func handleTerminalRequest(ctx context.Context, request protocol.Message, m *ter records, err = m.List(ctx) reply.Terminals = records case protocol.TerminalInput: - err = m.Input(body.TerminalID, body.Data) + err = m.ClientInput(clientID, body.TerminalID, body.Data, body.Reply, body.Cols, body.Rows) case protocol.TerminalResize: - record, err = m.Resize(body.TerminalID, body.Cols, body.Rows) + record, err = m.ClientResize(clientID, body.TerminalID, body.Cols, body.Rows, body.Activate) case protocol.TerminalOutput: m.clients.subscribe(clientID, body.TerminalID) + m.attachViewer(clientID, body.TerminalID) record, err = m.Output(ctx, body.TerminalID, body.After) case protocol.TerminalClose: record, err = m.Close(ctx, body.TerminalID) diff --git a/internal/server/terminal_lane.go b/internal/server/terminal_lane.go new file mode 100644 index 00000000..45516f0d --- /dev/null +++ b/internal/server/terminal_lane.go @@ -0,0 +1,75 @@ +package server + +import ( + "context" + "sync" + + "github.com/coder/websocket" + "github.com/coder/websocket/wsjson" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// connectionQueue bounds the requests read ahead of their handling on one +// connection, per lane. The app sends one ordinary request at a time, so +// the ordinary lane rarely holds more than a few. +const connectionQueue = 256 + +// isTerminalLaneRequest reports the requests a connection handles on its +// terminal lane: what a terminal's keystrokes and size become. They are +// quick (a queued write, an ioctl) and ordered among themselves, and must +// never wait behind an ordinary request read before them on the same +// connection (an elevation's password check, a chat backend call). +func isTerminalLaneRequest(kind string) bool { + switch kind { + case protocol.TerminalInput, protocol.TerminalResize, protocol.ChatShellInput, protocol.ChatShellResize: + return true + } + return false +} + +// readConnectionRequests reads conn's requests until it fails or ctx ends. +// Terminal-lane requests are handled in arrival order by lane on a goroutine +// of their own; the others are returned, in arrival order, for the +// connection's ordinary loop, and the channel closes when reading stops. +// Order is kept within each lane, not across them: a client that needs a +// terminal request to follow an ordinary one (input after terminal_open) +// waits for its reply first. stop ends the reading and waits for the lane +// to finish what it took. +func readConnectionRequests(ctx context.Context, conn *websocket.Conn, lane func(context.Context, protocol.Message)) (requests <-chan protocol.Message, stop func()) { + ctx, cancel := context.WithCancel(ctx) + ordinary := make(chan protocol.Message, connectionQueue) + terminal := make(chan protocol.Message, connectionQueue) + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + for request := range terminal { + lane(ctx, request) + } + }() + go func() { + defer wg.Done() + defer close(ordinary) + defer close(terminal) + for { + var request protocol.Message + if err := wsjson.Read(ctx, conn, &request); err != nil { + return + } + queue := ordinary + if isTerminalLaneRequest(request.Type) { + queue = terminal + } + select { + case queue <- request: + case <-ctx.Done(): + return + } + } + }() + return ordinary, func() { + cancel() + wg.Wait() + } +} diff --git a/internal/server/terminal_manager.go b/internal/server/terminal_manager.go index 91af233a..5ffcc3a3 100644 --- a/internal/server/terminal_manager.go +++ b/internal/server/terminal_manager.go @@ -125,6 +125,8 @@ func (m *terminalManager) start(clientID, id, dir string, cmd *exec.Cmd, cols, r m.terms[id] = p if clientID != "" { m.clients.subscribe(clientID, id) + // The opener draws it first: it is the active client. + p.viewers.resize(clientID, cols, rows, true) } m.wg.Add(1) go m.supervise(p, cmd, terminal) @@ -256,17 +258,23 @@ func (m *terminalManager) Resize(id string, cols, rows int) (protocol.TerminalRe if err != nil { return protocol.TerminalRecord{}, err } + if err := p.applySize(cols, rows); err != nil { + return protocol.TerminalRecord{}, err + } + return p.snapshot(false, 0), nil +} + +// applySize sets the terminal's PTY to cols x rows (clamped). +func (p *terminalProcess) applySize(cols, rows int) error { cols, rows = chatShellTerminalSize(cols, rows) p.mu.Lock() p.record.Cols, p.record.Rows = cols, rows terminal := p.pty p.mu.Unlock() if terminal != nil { - if err := resizeChatShellTerminal(terminal, cols, rows); err != nil { - return protocol.TerminalRecord{}, err - } + return resizeChatShellTerminal(terminal, cols, rows) } - return p.snapshot(false, 0), nil + return nil } // Output is one terminal with its retained output from byte after on. A diff --git a/internal/server/terminal_process.go b/internal/server/terminal_process.go index 2d7f2aec..506f888a 100644 --- a/internal/server/terminal_process.go +++ b/internal/server/terminal_process.go @@ -35,6 +35,8 @@ type terminalProcess struct { // refused: the login never asked for a password; the terminal is // forgotten without being listed. refused bool + // viewers are the connections drawing it (terminal_viewers.go). + viewers terminalViewers } func newTerminalProcess(record protocol.TerminalRecord) *terminalProcess { diff --git a/internal/server/terminal_viewers.go b/internal/server/terminal_viewers.go new file mode 100644 index 00000000..865421f4 --- /dev/null +++ b/internal/server/terminal_viewers.go @@ -0,0 +1,155 @@ +package server + +import "sync" + +// terminalViewers is the set of client connections drawing one terminal (a +// machine terminal or a chat's terminal command), most recently active +// first. The first is the active client: the terminal's size is the size it +// draws at, and only its emulator's automatic answers to terminal queries +// (cursor position, device attributes) reach the process. Every client's +// emulator answers each query it draws, so without this a query got one +// answer per client, and the size was whichever client resized last, even +// after it left. +// +// A client becomes active by typing, by a resize marked activate (the +// client focused the terminal), or by being the first to attach or resize. +// When the active client leaves, the next most recent one becomes active +// and its last size is applied. The zero value is ready to use. +type terminalViewers struct { + mu sync.Mutex + list []terminalViewer +} + +type terminalViewer struct { + client string + cols, rows int +} + +// terminalSize is a size to apply to the terminal, when ok. +type terminalSize struct { + cols, rows int + ok bool +} + +func (v *terminalViewers) indexLocked(client string) int { + for i, viewer := range v.list { + if viewer.client == client { + return i + } + } + return -1 +} + +// frontLocked moves client to the front, adding it when absent, and +// returns its entry. +func (v *terminalViewers) frontLocked(client string) *terminalViewer { + viewer := terminalViewer{client: client} + if i := v.indexLocked(client); i >= 0 { + viewer = v.list[i] + v.list = append(v.list[:i], v.list[i+1:]...) + } + v.list = append([]terminalViewer{viewer}, v.list...) + return &v.list[0] +} + +// attach records client as drawing the terminal (it opened or read it): the +// active one when no client is. +func (v *terminalViewers) attach(client string) { + if client == "" { + return + } + v.mu.Lock() + defer v.mu.Unlock() + if v.indexLocked(client) < 0 { + v.list = append(v.list, terminalViewer{client: client}) + } +} + +// resize records the size client draws the terminal at and reports the +// size to apply: client's, when it is (or, with activate, becomes) the +// active client, or when the active client has not reported a size yet. +// An unknown client (empty) always applies its size, as before clients +// were told apart. +func (v *terminalViewers) resize(client string, cols, rows int, activate bool) terminalSize { + if client == "" { + return terminalSize{cols, rows, true} + } + v.mu.Lock() + defer v.mu.Unlock() + i := v.indexLocked(client) + switch { + case activate || len(v.list) == 0 || i == 0: + viewer := v.frontLocked(client) + viewer.cols, viewer.rows = cols, rows + return terminalSize{cols, rows, true} + case i < 0: + v.list = append(v.list, terminalViewer{client: client, cols: cols, rows: rows}) + default: + v.list[i].cols, v.list[i].rows = cols, rows + } + front := v.list[0] + return terminalSize{cols, rows, front.cols == 0 || front.rows == 0} +} + +// typedAt is typed from a client drawing the terminal at cols x rows +// (zero when it did not say): it becomes the active client at that size. +func (v *terminalViewers) typedAt(client string, cols, rows int) terminalSize { + if client != "" && cols > 0 && rows > 0 { + return v.resize(client, cols, rows, true) + } + return v.typed(client) +} + +// typed makes client, which typed into the terminal, the active client and +// reports its last size when that changes who is active. +func (v *terminalViewers) typed(client string) terminalSize { + if client == "" { + return terminalSize{} + } + v.mu.Lock() + defer v.mu.Unlock() + if len(v.list) > 0 && v.list[0].client == client { + return terminalSize{} + } + viewer := v.frontLocked(client) + return terminalSize{viewer.cols, viewer.rows, viewer.cols > 0 && viewer.rows > 0} +} + +// answers reports whether client's emulator's automatic answers reach the +// process: only the active client's do, or anyone's while no client is +// known. +func (v *terminalViewers) answers(client string) bool { + if client == "" { + return true + } + v.mu.Lock() + defer v.mu.Unlock() + return len(v.list) == 0 || v.list[0].client == client +} + +// leave forgets client (its connection closed) and, when it was the active +// client, reports the size of the next one, which becomes active. +func (v *terminalViewers) leave(client string) terminalSize { + v.mu.Lock() + defer v.mu.Unlock() + i := v.indexLocked(client) + if i < 0 { + return terminalSize{} + } + v.list = append(v.list[:i], v.list[i+1:]...) + if i != 0 || len(v.list) == 0 { + return terminalSize{} + } + next := v.list[0] + return terminalSize{next.cols, next.rows, next.cols > 0 && next.rows > 0} +} + +// active is the active client, or empty (tests). +func (v *terminalViewers) active() string { + v.mu.Lock() + defer v.mu.Unlock() + if len(v.list) == 0 { + return "" + } + return v.list[0].client +} diff --git a/internal/server/terminal_viewers_test.go b/internal/server/terminal_viewers_test.go new file mode 100644 index 00000000..95b279ff --- /dev/null +++ b/internal/server/terminal_viewers_test.go @@ -0,0 +1,60 @@ +package server + +import "testing" + +func TestTerminalViewersActiveClient(t *testing.T) { + var v terminalViewers + // The first client to resize is active and sizes the terminal. + if got := v.resize("a", 156, 37, false); got != (terminalSize{156, 37, true}) { + t.Fatalf("first resize = %+v", got) + } + v.attach("b") + // Another client's size is kept but not applied; its answers are dropped. + if got := v.resize("b", 121, 11, false); got.ok { + t.Fatalf("background resize applied: %+v", got) + } + if !v.answers("a") || v.answers("b") || v.answers("stranger") { + t.Fatal("only the active client answers") + } + // Typing hands the terminal to b, at b's size; typing again changes nothing. + if got := v.typed("b"); got != (terminalSize{121, 11, true}) { + t.Fatalf("typed = %+v", got) + } + if got := v.typed("b"); got.ok || v.active() != "b" || v.answers("a") { + t.Fatalf("typed again = %+v, active %q", got, v.active()) + } + // Focusing (activate) hands it back at a's new size. + if got := v.resize("a", 150, 40, true); got != (terminalSize{150, 40, true}) || v.active() != "a" { + t.Fatalf("activate = %+v", got) + } + // A background client leaving changes nothing; the active one leaving + // hands the terminal to the next most recent, at its last size. + v.attach("c") + if got := v.leave("c"); got.ok { + t.Fatalf("background leave = %+v", got) + } + if got := v.leave("a"); got != (terminalSize{121, 11, true}) || v.active() != "b" || !v.answers("b") { + t.Fatalf("leave = %+v, active %q", got, v.active()) + } + if got := v.leave("b"); got.ok || v.active() != "" || !v.answers("anyone") { + t.Fatalf("last leave = %+v", got) + } +} + +func TestTerminalViewersWithoutSizes(t *testing.T) { + var v terminalViewers + v.attach("reader") + // The active client has drawn nothing yet: another's size is applied. + if got := v.resize("other", 90, 20, false); !got.ok || v.active() != "reader" { + t.Fatalf("resize = %+v, active %q", got, v.active()) + } + // Typing from a client of unknown size makes it active without a resize. + if got := v.typed("typist"); got.ok || v.active() != "typist" { + t.Fatalf("typed = %+v", got) + } + // A connection that is not told apart (tests, internal callers) always + // applies and answers. + if got := v.resize("", 10, 5, false); !got.ok || !v.answers("") { + t.Fatalf("anonymous = %+v", got) + } +} diff --git a/internal/server/terminal_ws_test.go b/internal/server/terminal_ws_test.go index 3d76ebfb..78b24605 100644 --- a/internal/server/terminal_ws_test.go +++ b/internal/server/terminal_ws_test.go @@ -117,12 +117,14 @@ func TestTerminalOverWebsocket(t *testing.T) { t.Fatalf("input reply = %+v", got) } _, end := readTerminalUntil(t, ctx, conns[0], term.ID, 0, "sum-42") + // The second client draws it larger; the opener stays the active client + // (terminal_active_test.go) until the second one types below. resized := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalResize, "size", protocol.TerminalRequest{TerminalID: term.ID, Cols: 120, Rows: 33})) - if resized.Type != protocol.TerminalResize || resized.Terminal.Cols != 120 || resized.Terminal.Rows != 33 { + if resized.Type != protocol.TerminalResize || resized.Terminal.Cols != 80 || resized.Terminal.Rows != 24 { t.Fatalf("resize reply = %+v", resized) } list := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalList, "list", protocol.TerminalRequest{})) - if len(list.Terminals) != 1 || list.Terminals[0].ID != term.ID || list.Terminals[0].Cols != 120 || list.Terminals[0].Output != "" { + if len(list.Terminals) != 1 || list.Terminals[0].ID != term.ID || list.Terminals[0].Cols != 80 || list.Terminals[0].Output != "" { t.Fatalf("list = %+v", list.Terminals) } // The second client reads everything once, then only what follows. diff --git a/internal/server/websocket.go b/internal/server/websocket.go index 9992cfa4..0aa9ed07 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -267,7 +267,10 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin // Terminal lifecycle changes reach every connection; output only the // connections that opened or read that terminal. terminals.clients.attach(clientID, write) - defer terminals.clients.detach(clientID) + defer terminals.detach(clientID) + // A closed connection hands the chats' terminal commands it was + // active in to their next client. + defer func() { hub.shellRunner().leave(clientID) }() if notes != nil { defer notes.detach(clientID) } @@ -276,16 +279,23 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin // previous, whose reply the client would discard as stale anyway. cancelChatSearch := func() {} defer func() { cancelChatSearch() }() - for { - var request protocol.Message - if err := wsjson.Read(connCtx, conn, &request); err != nil { + // Keystrokes and sizes take their own lane (terminal_lane.go), so + // they never wait behind a slow request read before them. The lane + // is drained before the deferred detaches above run. + requests, stopReading := readConnectionRequests(connCtx, conn, func(laneCtx context.Context, request protocol.Message) { + if elevation.refuse(request, elevationKey, write) { return } - if request.Type != protocol.ChatShellInput && request.Type != protocol.ChatShellResize && - request.Type != protocol.TerminalInput && request.Type != protocol.TerminalResize { - // Keystrokes would be one line each; their data is never logged. - log.Printf("command received: client=%s type=%q id=%q pipeline=%d version=%d", r.RemoteAddr, request.Type, request.ID, request.PipelineID, request.Version) + if isTerminalRequest(request.Type) { + handleTerminalRequest(laneCtx, request, terminals, clientID, write) + return } + handleChat(laneCtx, request, options.Chat, hub, registry, clientID, write) + }) + defer stopReading() + for request := range requests { + // Keystrokes take the terminal lane and are never logged. + log.Printf("command received: client=%s type=%q id=%q pipeline=%d version=%d", r.RemoteAddr, request.Type, request.ID, request.PipelineID, request.Version) if request.Type == protocol.Submit && !options.AllowAuthoring { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "pipeline authoring is disabled on this execution server; ask the operator to publish through an explicitly enabled authoring server"}) continue @@ -327,9 +337,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin continue } if isTerminalRequest(request.Type) { - // Closing waits for the shell to go; it never delays input - // to the other terminals behind it. - if request.Type == protocol.TerminalClose { + // Opening waits up to the login's prompt wait and closing for + // the shell to go; neither delays the requests behind it. + if request.Type == protocol.TerminalClose || request.Type == protocol.TerminalOpen { go handleTerminalRequest(connCtx, request, terminals, clientID, write) } else { handleTerminalRequest(connCtx, request, terminals, clientID, write) From 2bcb62b5d8963432c530168e97f3d4191822e40a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:38:35 +0000 Subject: [PATCH 14/17] xterm: draw strikethrough, concealed text, overline and underline styles SGR 9 (strikethrough) and 53 (overline) were stored but never drawn, and SGR 8 (conceal) still showed the text. They are drawn now, and underline styles use the matching line style: double (21, 4:2), curly (4:3, wavy), dotted (4:4) and dashed (4:5). Concealed cells keep their background. Co-Authored-By: Claude Opus 5.5 --- .../attribute_paint_test.dart | 76 +++++++++++++++++++ app/test/third_party_xterm/paint_fixture.dart | 9 +++ .../xterm/lib/src/core/buffer/cell_flags.dart | 2 + app/third_party/xterm/lib/src/ui/painter.dart | 32 ++++++-- .../xterm/lib/src/ui/terminal_text_style.dart | 10 ++- 5 files changed, 123 insertions(+), 6 deletions(-) create mode 100644 app/test/third_party_xterm/attribute_paint_test.dart diff --git a/app/test/third_party_xterm/attribute_paint_test.dart b/app/test/third_party_xterm/attribute_paint_test.dart new file mode 100644 index 00000000..75a91ff7 --- /dev/null +++ b/app/test/third_party_xterm/attribute_paint_test.dart @@ -0,0 +1,76 @@ +import 'package:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:xterm/xterm.dart'; + +import 'paint_fixture.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final size = fixturePainter().cellSize; + final w = size.width.ceil(); + final h = size.height.ceil(); + + Future cell(CellData data) => Pixels.paint( + w, + h * 2, // room for decorations drawn below the cell + (canvas) => fixturePainter().paintCell(canvas, Offset.zero, data), + ); + + /// The rows of the cell that contain painted pixels. + Future> inkRows(CellData data) async { + final pixels = await cell(data); + return [ + for (var y = 0; y < h * 2; y++) + if (pixels.rowHasInk(y)) y, + ]; + } + + test('a plain space draws nothing', () async { + expect(await inkRows(cellOf(' ')), isEmpty); + }); + + test('strikethrough (SGR 9) draws a line through the middle', () async { + final rows = await inkRows(cellOf(' ', flags: CellAttr.strikethrough)); + expect(rows, isNotEmpty); + expect(rows.every((y) => y > h * 0.2 && y < h * 0.8), isTrue); + }); + + test('overline (SGR 53) draws at the top, underline at the bottom', () async { + final over = await inkRows(cellOf(' ', flags: CellAttr.overline)); + expect(over, isNotEmpty); + expect(over.first, lessThan(h * 0.3)); + + final under = await inkRows(cellOf(' ', flags: CellAttr.underline)); + expect(under, isNotEmpty); + expect(under.last, greaterThan(h * 0.6)); + }); + + test('double underline (SGR 21) draws two lines', () async { + const doubled = CellAttr.underline | (2 << CellAttr.underlineStyleShift); + final single = await inkRows(cellOf(' ', flags: CellAttr.underline)); + final two = await inkRows(cellOf(' ', flags: doubled)); + expect(two.length, greaterThan(single.length)); + }); + + test( + 'concealed text (SGR 8) keeps its background, hides the glyph', + () async { + final shown = await cell(cellOf('M')); + expect(shown.count(foregroundColor), greaterThan(0)); + + final hidden = await cell(cellOf('M', flags: CellAttr.invisible)); + expect(hidden.count(foregroundColor), 0); + + final inverse = await cell( + cellOf('M', flags: CellAttr.invisible | CellAttr.inverse), + ); + expect( + inverse.count(foregroundColor), + greaterThan(0), + reason: 'background', + ); + expect(inverse.count(backgroundColor), 0, reason: 'no glyph'); + }, + ); +} diff --git a/app/test/third_party_xterm/paint_fixture.dart b/app/test/third_party_xterm/paint_fixture.dart index 134f5036..09d83cd5 100644 --- a/app/test/third_party_xterm/paint_fixture.dart +++ b/app/test/third_party_xterm/paint_fixture.dart @@ -75,6 +75,15 @@ class Pixels { ); } + /// Whether row [y] has any painted (non-transparent) pixel; decorations + /// are antialiased, so their exact colour varies. + bool rowHasInk(int y) { + for (var x = 0; x < width; x++) { + if (_rgba.getUint8((y * width + x) * 4 + 3) != 0) return true; + } + return false; + } + /// How many pixels in [rect] are exactly [color]. int count(Color color, [Rect? rect]) { final area = diff --git a/app/third_party/xterm/lib/src/core/buffer/cell_flags.dart b/app/third_party/xterm/lib/src/core/buffer/cell_flags.dart index 97c5b8aa..ccdf1085 100644 --- a/app/third_party/xterm/lib/src/core/buffer/cell_flags.dart +++ b/app/third_party/xterm/lib/src/core/buffer/cell_flags.dart @@ -6,4 +6,6 @@ abstract class CellFlags { static const blink = 1 << 4; static const inverse = 1 << 5; static const invisible = 1 << 6; + static const strikethrough = 1 << 7; + static const overline = 1 << 11; } diff --git a/app/third_party/xterm/lib/src/ui/painter.dart b/app/third_party/xterm/lib/src/ui/painter.dart index 4d70426b..876d0fe7 100644 --- a/app/third_party/xterm/lib/src/ui/painter.dart +++ b/app/third_party/xterm/lib/src/ui/painter.dart @@ -206,6 +206,9 @@ class TerminalPainter { final charCode = cellData.content & CellContent.codepointMask; if (charCode == 0) return; + // SGR 8 (conceal): the cell keeps its background, the text is hidden. + if (cellData.flags & CellFlags.invisible != 0) return; + final cacheKey = cellData.getHash() ^ _textScaler.hashCode; var paragraph = _paragraphCache.getLayoutFromCache(cacheKey); @@ -220,21 +223,27 @@ class TerminalPainter { color = color.withOpacity(0.5); } + final underline = cellFlags & CellFlags.underline != 0; + const decorated = + CellFlags.underline | CellFlags.strikethrough | CellFlags.overline; final style = _textStyle.toTextStyle( color: color, bold: cellFlags & CellFlags.bold != 0, italic: cellFlags & CellFlags.italic != 0, - underline: cellFlags & CellFlags.underline != 0, + underline: underline, + strikethrough: cellFlags & CellFlags.strikethrough != 0, + overline: cellFlags & CellFlags.overline != 0, + decorationStyle: underline ? _underlineStyle(cellFlags) : null, ); - // Flutter does not draw an underline below a space which is not between + // Flutter does not draw a decoration on a space which is not between // other regular characters. As only single characters are drawn, this // will never produce an underline below a space in the terminal. As a // workaround the regular space CodePoint 0x20 is replaced with - // the CodePoint 0xA0. This is a non breaking space and a underline can be - // drawn below it. + // the CodePoint 0xA0. This is a non breaking space and a decoration can + // be drawn on it. var char = String.fromCharCode(charCode); - if (cellFlags & CellFlags.underline != 0 && charCode == 0x20) { + if (cellFlags & decorated != 0 && charCode == 0x20) { char = String.fromCharCode(0xA0); } @@ -249,6 +258,19 @@ class TerminalPainter { canvas.drawParagraph(paragraph, offset); } + /// The line style of the underline in [flags] (SGR 4:1-4:5, 21). + static TextDecorationStyle _underlineStyle(int flags) { + final style = + (flags & CellAttr.underlineStyleMask) >> CellAttr.underlineStyleShift; + return switch (style) { + 2 => TextDecorationStyle.double, + 3 => TextDecorationStyle.wavy, + 4 => TextDecorationStyle.dotted, + 5 => TextDecorationStyle.dashed, + _ => TextDecorationStyle.solid, + }; + } + /// Paints the background of a cell represented by [cellData] to [canvas] at /// [offset]. @pragma('vm:prefer-inline') diff --git a/app/third_party/xterm/lib/src/ui/terminal_text_style.dart b/app/third_party/xterm/lib/src/ui/terminal_text_style.dart index 8da3b287..d97acd72 100644 --- a/app/third_party/xterm/lib/src/ui/terminal_text_style.dart +++ b/app/third_party/xterm/lib/src/ui/terminal_text_style.dart @@ -57,8 +57,12 @@ class TerminalStyle { bool bold = false, bool italic = false, bool underline = false, + bool strikethrough = false, + bool overline = false, + TextDecorationStyle? decorationStyle, }) { return TextStyle( + decorationStyle: decorationStyle, fontSize: fontSize, height: height, fontFamily: fontFamily, @@ -67,7 +71,11 @@ class TerminalStyle { backgroundColor: backgroundColor, fontWeight: bold ? FontWeight.bold : FontWeight.normal, fontStyle: italic ? FontStyle.italic : FontStyle.normal, - decoration: underline ? TextDecoration.underline : TextDecoration.none, + decoration: TextDecoration.combine([ + if (underline) TextDecoration.underline, + if (strikethrough) TextDecoration.lineThrough, + if (overline) TextDecoration.overline, + ]), ); } From fea34941d3b4b38877584ef3878adf95b9ee6b23 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:39:00 +0000 Subject: [PATCH 15/17] xterm: answer DSR 6 one-based; list the local patches The cursor position report sent zero-based coordinates (the app's terminal session overrides it with the same fix, which keeps working). The vendored README now lists every local patch. Co-Authored-By: Claude Opus 5.5 --- .../cursor_movement_test.dart | 5 ++++ app/third_party/xterm/README.md | 27 ++++++++++++------- .../xterm/lib/src/core/escape/emitter.dart | 4 ++- 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/app/test/third_party_xterm/cursor_movement_test.dart b/app/test/third_party_xterm/cursor_movement_test.dart index c932c482..7816b278 100644 --- a/app/test/third_party_xterm/cursor_movement_test.dart +++ b/app/test/third_party_xterm/cursor_movement_test.dart @@ -52,6 +52,11 @@ void main() { expect(t.buffer.cursorY, 3); }); + test('DSR 6 reports the one-based cursor position', () { + final t = FixtureTerminal()..feed('\x1b[3;7H\x1b[6n'); + expect(t.takeReplies(), '\x1b[3;7R'); + }); + test('zero counts mean one', () { final t = FixtureTerminal()..feed('\x1b[0C\x1b[0B'); expect(t.buffer.cursorX, 1); diff --git a/app/third_party/xterm/README.md b/app/third_party/xterm/README.md index fb792648..fa2ffc63 100644 --- a/app/third_party/xterm/README.md +++ b/app/third_party/xterm/README.md @@ -15,12 +15,21 @@ still compiles as part of every app build. Local patches (keep this list current): -- colon-form SGR subparameters (`4:3`, `38:2::r:g:b`, `58`/`59`) -- DCS/APC/PM/SOS strings consumed rather than printed -- full RIS (`ESC c`) reset -- DECSCUSR cursor shapes, SCOSC/SCORC, CHT, CBT, HPA, HPR, VPR -- OSC 10/11/12 colour queries, OSC 8/52/7 callbacks -- alternate screen 1049 cursor restore, separate DECCKM mode -- mouse wheel, drag/motion and middle-button reporting; Shift selection override -- cursor and attribute rendering (inverse block cursor, strikethrough, conceal) -- focus reporting (`?1004`) +- CSI parsing: colon subparameters (`4:3`, `38:2::r:g:b`, `58`/`59`), + intermediates and private prefixes (`CSI > 4;2 m` is not SGR), empty + parameters as defaults; SGR 21 is double underline, 53/55 overline +- DCS/APC/PM/SOS strings consumed rather than printed; DECRQSS (`m`, `r`, + ` q`) answered +- RIS (`ESC c`) full reset and DECSTR (`CSI ! p`) +- DECSCUSR cursor shapes (blinking is stored, not animated); SCOSC/SCORC, + CHT, CBT, HPA, HPR, VPR; HTS sets tab stops; DSR 6 one-based +- OSC 10/11/12 colour queries from the view's theme; OSC 8 links on cells + (`Terminal.hyperlinkAt`); OSC 52 set (`onClipboardSet`, no reads); OSC 7 + (`onWorkingDirectoryChange`) +- alternate screen 1049 restores the cursor; arrow keys follow DECCKM +- mouse: wheel 64/65, screen-cell coordinates, drag (1002) and motion + (1003) reporting, middle button, Shift+drag selects + (`ui/mouse_listener.dart`) +- rendering: block cursor shows the character inverted, underline/bar + cursor position, strikethrough, conceal, overline, underline styles +- focus reporting (`?1004`, `Terminal.focusInput`, called by `TerminalView`) 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 e697f73a..f30a8f67 100644 --- a/app/third_party/xterm/lib/src/core/escape/emitter.dart +++ b/app/third_party/xterm/lib/src/core/escape/emitter.dart @@ -19,8 +19,10 @@ class EscapeEmitter { return '\x1b[0n'; } + /// The CPR reply for the zero-based cursor ([x], [y]); the protocol is + /// one-based. String cursorPosition(int x, int y) { - return '\x1b[$y;${x}R'; + return '\x1b[${y + 1};${x + 1}R'; } String bracketedPaste(String text) { From e08afcaffdc15d7fa87fc468501ef452ba6dc48f Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:43:36 +0000 Subject: [PATCH 16/17] Drop an unnecessary import in the xterm attribute paint test Co-Authored-By: Claude Opus 5.5 --- app/test/third_party_xterm/attribute_paint_test.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/app/test/third_party_xterm/attribute_paint_test.dart b/app/test/third_party_xterm/attribute_paint_test.dart index 75a91ff7..6812a8ba 100644 --- a/app/test/third_party_xterm/attribute_paint_test.dart +++ b/app/test/third_party_xterm/attribute_paint_test.dart @@ -1,4 +1,3 @@ -import 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:xterm/xterm.dart'; From 85cdc845fa663d1fa0e1265393b5d28398cd17ef Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 23:45:06 +0000 Subject: [PATCH 17/17] Terminal fixture: opt-in emulator attribute showcase ?terminalAttrs=1 prints colon-form SGR, underline styles, strikethrough, overline, conceal, swallowed DCS/APC/OSC strings and a block cursor over a character in the build terminal, for browser captures of the vendored xterm's rendering. Without the parameter the fixture is unchanged. Co-Authored-By: Claude Opus 5.5 --- app/tool/perf/terminal_fixture.dart | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app/tool/perf/terminal_fixture.dart b/app/tool/perf/terminal_fixture.dart index bc6c26bf..3431937c 100644 --- a/app/tool/perf/terminal_fixture.dart +++ b/app/tool/perf/terminal_fixture.dart @@ -18,6 +18,21 @@ const String _prompt = '\x1b[1;32moperator@mac\x1b[0m:\x1b[1;34m%s\x1b[0m\$ '; String _promptAt(String folder) => _prompt.replaceFirst('%s', folder); +/// `?terminalAttrs=1`: emulator features to capture (app/third_party/xterm), +/// printed after the build terminal's prompt. The DCS, APC and OSC strings +/// must not print; the cursor ends on the `b` of `abc` as a block. +const String _attributeShowcase = + 'printf showcase\r\n' + '\x1b[4:3mcurly 4:3\x1b[0m \x1b[21mdouble 21\x1b[0m ' + '\x1b[4:4mdotted\x1b[0m \x1b[9mstrike 9\x1b[0m ' + '\x1b[53moverline\x1b[0m [\x1b[8mhidden\x1b[0m]\r\n' + '\x1b[38:2::255:128:0morange 38:2::\x1b[0m ' + '\x1b[48:5:24m bg 48:5:24 \x1b[0m ' + '\x1bP\$qm\x1b\\\x1b_apc\x1b\\' + '\x1b]8;;https://example.com\x1b\\link\x1b]8;;\x1b\\ ' + '\x1b]11;#000000\x07after strings\r\n' + 'abc\x1b[2D'; + void configureTerminalFixture(Map params) { _enabled = params['terminals'] == '1'; if (!_enabled) return; @@ -47,6 +62,9 @@ void configureTerminalFixture(Map params) { '\x1b[1;34mDesktop\x1b[0m \x1b[1;34mDocuments\x1b[0m ' '\x1b[1;34mDownloads\x1b[0m \x1b[1;34msrc\x1b[0m notes.md\r\n' '${_promptAt('~')}'; + if (params['terminalAttrs'] == '1') { + _output['term_build'] = _output['term_build']! + _attributeShowcase; + } final mode = switch (params['terminal']) { 'panel' => TerminalMode.panel, 'float' => TerminalMode.float,