From 2c5e1f1a3e820d7be239db6878a6d3ee7ad32154 Mon Sep 17 00:00:00 2001 From: Jason Stiebs Date: Thu, 15 Oct 2026 15:54:40 -0500 Subject: [PATCH 1/2] Add a native terminal input and cell surface --- CHANGELOG.md | 5 + apps/gpui/guides/ui/text-and-editing.md | 64 ++ apps/gpui/lib/gpui/event.ex | 30 +- apps/gpui/lib/gpui/schema/surfaces.ex | 66 ++ apps/gpui/lib/gpui/terminal.ex | 100 ++ apps/gpui/mix.exs | 2 + apps/gpui/native/src/generated/schema.rs | 141 +++ apps/gpui/test/gpui/schema/extension_test.exs | 1 + apps/gpui/test/gpui/schema_test.exs | 3 + apps/gpui/test/gpui/terminal_test.exs | 74 ++ .../native/src/generated/schema.rs | 141 +++ .../native/src/element/component.rs | 1 + .../native/src/element/component/controls.rs | 8 +- .../src/element/component/data_table.rs | 5 + .../native/src/element/component/terminal.rs | 892 ++++++++++++++++++ .../native/src/element/component/tree.rs | 4 + .../element/component/uniform_collection.rs | 2 + .../element/component/virtual_collection.rs | 5 + .../src/element/component/virtual_list.rs | 4 + apps/gpui_native/native/src/element/mod.rs | 2 + .../gpui_native/native/src/generated/atoms.rs | 112 +-- .../native/src/generated/event_contract.rs | 16 +- .../native/src/generated/event_payloads.rs | 18 + .../native/src/generated/events.rs | 58 +- .../native/src/generated/extensions.rs | 8 + .../native/src/generated/schema.rs | 141 +++ .../native/src/generated/vanilla_schema.rs | 141 +++ apps/gpui_native/native/src/window.rs | 11 +- .../test/gpui/test/native/terminal_test.exs | 171 ++++ codegen/gpui/codegen/native/event/contract.ex | 8 +- codegen/gpui/codegen/native/event/payloads.ex | 27 +- codegen/gpui/codegen/native/events.ex | 16 +- .../codegen/native/event/contract_test.exs | 2 + 33 files changed, 2199 insertions(+), 80 deletions(-) create mode 100644 apps/gpui/lib/gpui/terminal.ex create mode 100644 apps/gpui/test/gpui/terminal_test.exs create mode 100644 apps/gpui_native/native/src/element/component/terminal.rs create mode 100644 apps/gpui_native/test/test/gpui/test/native/terminal_test.exs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5920c7b1..9f2bf473 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- Add `GPUI.Terminal.surface/1`: an application-owned fixed-cell grid with + raw modifier-bearing keys, committed text/IME, multiline clipboard paste, + native selection/copy, scrollback, and measured cell/viewport events. + No terminal parser, PTY, SSH client, or command-line editor is embedded. + ## 0.2.0 - 2026-09-08 ### Breaking changes diff --git a/apps/gpui/guides/ui/text-and-editing.md b/apps/gpui/guides/ui/text-and-editing.md index f04fbd57..6cae958a 100644 --- a/apps/gpui/guides/ui/text-and-editing.md +++ b/apps/gpui/guides/ui/text-and-editing.md @@ -6,6 +6,70 @@ revisioned editable surfaces, see [Editable text surfaces](editable-text.html). Implementation details remain in [Editable text internals](editable-text-internals.html). +## Application-owned terminals + +`GPUI.Terminal.surface/1` is a fixed-cell display and input boundary, not a +terminal emulator or editable text field. The application owns the escape +parser, retained rows, terminal modes, PTY/SSH lifecycle, and key encoding. +Both vanilla and component-capable hosts implement the `terminal` extension. + +```elixir +GPUI.Terminal.surface(%{ + id: "console", + label: "Remote console", + columns: 80, + rows: [ + [%{text: "ready ", columns: 6, color: {:rgb, 0x80CC90}}, + %{text: "界", columns: 2}] + ], + cursor_row: 0, + cursor_column: 8, + focus_request: 1, + "phx-keystroke": "terminal-key", + "phx-text": "terminal-text", + "phx-paste": "terminal-paste", + "phx-resize": "terminal-size", + "phx-range": "terminal-visible" +}) +``` + +Rows are ordered oldest first. Runs can combine printable ASCII cells; wide, +combining, or fallback graphemes occupy individual one- or two-column runs. +They can specify foreground/background, normal/bold weight, and normal/italic +style. Every glyph is placed on the measured grid with ligatures disabled. +The cursor is separate paint, never a character in selectable/copied text. +Keep `reset_request` stable across ordinary rerenders and increment it when +replacing the terminal session. It clears native scroll/selection/composition. + +Events deliberately separate three input sources: + +- `:keystroke`: `%{key: key, control: boolean, alt: boolean, shift: boolean, + platform: boolean, repeat: boolean}` for editing/navigation/control/meta keys. +- `:text`: committed Unicode text. IME preedit remains native and is not sent + to the application until committed. Do not reconstruct a local input line. +- `:paste`: clipboard text with tabs and newlines intact. The application + decides paste confirmation and terminal-mode/bracketed-paste encoding. + +Printable keys are not emitted a second time as keystrokes. Platform shortcuts +other than select-all/copy/paste remain application commands. On non-macOS +hosts, Control-Shift-C/V also copy/paste. Native mouse selection copies retained +rows; scrolling and Shift-PageUp/PageDown browse history. Shift-End or typing +returns to the tail. Small trackpad deltas accumulate rather than disappearing. + +`:resize` reports `%{columns: integer, rows: integer, cell_width: number, +cell_height: number}` using actual font shaping and viewport dimensions. +Zero-sized hidden surfaces do not request a resize. `:range` optionally reports +the exclusive `{first, last}` visible row range as the ordinary range event map. +Do not estimate font widths or feed hidden geometry to a remote PTY. + +Override `font_family` when desired; the defaults are Menlo on macOS, Consolas +on Windows, and DejaVu Sans Mono on other platforms, not the proportional UI font. + +The public boundary limits snapshots to 10,000 retained rows, 512 columns, +and 8 MiB of text. These are display bounds, not application scrollback policy. +The native host paints only visible rows; no remote bytes, escape sequence, or +clipboard text is executed by GPUI. + ## Rich selectable text `rich_text/1` renders consumer-produced text and shaping runs without moving diff --git a/apps/gpui/lib/gpui/event.ex b/apps/gpui/lib/gpui/event.ex index 71498c5d..aa94c99a 100644 --- a/apps/gpui/lib/gpui/event.ex +++ b/apps/gpui/lib/gpui/event.ex @@ -8,7 +8,11 @@ defmodule GPUI.Event do defstruct [:type, :window_id, :event, :value, attrs: %{}] @type type :: - :click + :keystroke + | :text + | :paste + | :resize + | :click | :command | :change | :select @@ -57,6 +61,10 @@ defmodule GPUI.Event do } @routed_types [ + :keystroke, + :text, + :paste, + :resize, :click, :command, :change, @@ -200,6 +208,12 @@ defmodule GPUI.Event do defp normalize_value(type, event) when type in [:keydown, :keyup], do: require_value(event, &is_binary/1) + defp normalize_value(:keystroke, event), do: require_value(event, &valid_keystroke?/1) + defp normalize_value(:resize, event), do: require_value(event, &valid_terminal_size?/1) + + defp normalize_value(type, event) when type in [:text, :paste], + do: require_value(event, &bounded_string?(&1, 1_048_576, true)) + defp normalize_value(:range, event), do: require_value(event, &valid_range?/1) defp normalize_value(:transaction, event), do: require_value(event, &is_map/1) defp normalize_value(:selection, event), do: require_value(event, &is_list/1) @@ -223,6 +237,20 @@ defmodule GPUI.Event do defp fetch_value(event), do: Map.fetch(event, :value) + defp valid_keystroke?(%{key: key} = value) do + bounded_string?(key, 128, false) and + Enum.all?([:control, :alt, :shift, :platform, :repeat], &is_boolean(Map.get(value, &1))) + end + + defp valid_keystroke?(_), do: false + + defp valid_terminal_size?(%{columns: cols, rows: rows, cell_width: width, cell_height: height}) do + is_integer(cols) and cols in 1..512 and is_integer(rows) and rows in 1..256 and + finite_number?(width) and width > 0 and finite_number?(height) and height > 0 + end + + defp valid_terminal_size?(_), do: false + defp valid_change_value?(value) when is_binary(value) or is_boolean(value) or is_nil(value), do: true diff --git a/apps/gpui/lib/gpui/schema/surfaces.ex b/apps/gpui/lib/gpui/schema/surfaces.ex index 428c9191..1dcfb5b3 100644 --- a/apps/gpui/lib/gpui/schema/surfaces.ex +++ b/apps/gpui/lib/gpui/schema/surfaces.ex @@ -2,6 +2,72 @@ defmodule GPUI.Schema.Surfaces do @moduledoc "Neutral specialized surfaces implemented directly with vanilla GPUI." @behaviour GPUI.Schema.Provider @components [ + %{ + __struct__: GPUI.Schema.Component, + tag: :ui_terminal, + kind: :terminal_component, + attrs: [ + id: :string, + label: :required_string, + columns: {:default, :positive_integer, 80}, + cursor_row: {:default, :non_negative_integer, 0}, + cursor_column: {:default, :non_negative_integer, 0}, + cursor_visible: {:default, :boolean, true}, + font_family: {:default, :string}, + font_size: {:default, :positive_number, 14.0}, + line_height: {:default, :positive_number, 20.0}, + focus_request: {:default, :non_negative_integer, 0}, + reset_request: {:default, :non_negative_integer, 0}, + disabled: :boolean + ], + children: true, + events: [ + keystroke: :"phx-keystroke", + text: :"phx-text", + paste: :"phx-paste", + resize: :"phx-resize", + range: :"phx-range" + ], + extension: %{ + __struct__: GPUI.Schema.Extension, + id: :terminal, + version: 1, + capabilities: [:cell_grid, :raw_keyboard, :committed_text, :clipboard, :cell_geometry] + }, + public_hidden_attrs: [], + public_required_attrs: [:id, :label], + public_slots: [], + required_events: [], + stateful: false + }, + %{ + __struct__: GPUI.Schema.Component, + tag: :ui_terminal_row, + kind: :terminal_row_component, + attrs: [], + children: true, + events: [], + extension: nil, + public_hidden_attrs: [], + public_required_attrs: [], + public_slots: [], + required_events: [], + stateful: false + }, + %{ + __struct__: GPUI.Schema.Component, + tag: :ui_terminal_cell, + kind: :terminal_cell_component, + attrs: [text: :required_string, columns: {:default, :positive_integer, 1}, italic: :boolean], + children: false, + events: [], + extension: nil, + public_hidden_attrs: [], + public_required_attrs: [:text], + public_slots: [], + required_events: [], + stateful: false + }, %{ __struct__: GPUI.Schema.Component, attrs: [ diff --git a/apps/gpui/lib/gpui/terminal.ex b/apps/gpui/lib/gpui/terminal.ex new file mode 100644 index 00000000..f8ccf7ae --- /dev/null +++ b/apps/gpui/lib/gpui/terminal.ex @@ -0,0 +1,100 @@ +defmodule GPUI.Terminal do + @moduledoc """ + A native fixed-cell display and input boundary for application-owned terminals. + + GPUI does not parse escape sequences, open a PTY, or edit a remote command line. + Pass retained rows (oldest first), with each run declaring its terminal-column + width. The last visible rows follow the tail until the user scrolls. Mouse + selection and platform copy/paste remain native. `phx-text` emits committed + text, `phx-paste` preserves clipboard newlines, and `phx-keystroke` emits + logical keys with modifiers; do not forward printable keys a second time. + + Row runs accept `text`, `columns`, and ordinary text style keys `color`, + `background`, `font_weight`, and `font_style`. Split wide/fallback glyphs into + their own runs to preserve exact grid placement. Cursor coordinates address + retained rows, not pixels. `reset_request` clears selection/scroll on session + changes; `focus_request` requests focus without recreating the surface. + """ + alias GPUI.{Element, Schema} + @max_rows 10_000 + @max_columns 512 + @max_bytes 8 * 1024 * 1024 + @style_keys ~w(color background font_weight font_style)a + + @doc "Builds a bounded terminal surface from application-owned cell runs." + @spec surface(map()) :: Element.t() + def surface(assigns) do + {rows, attrs} = Map.pop(assigns, :rows, []) + columns = Map.get(attrs, :columns, 80) + + unless is_integer(columns) and columns in 1..@max_columns and + is_list(rows) and length(rows) <= @max_rows do + raise ArgumentError, "terminal allows 1–512 columns and at most 10000 retained rows" + end + + children = Enum.map(rows, &row(&1, columns)) + + bytes = + Enum.reduce(rows, 0, fn runs, size -> + Enum.reduce(runs, size, &(byte_size(&1.text) + &2)) + end) + + if bytes > @max_bytes, do: raise(ArgumentError, "terminal text exceeds 8 MiB") + + attrs = + attrs + |> Schema.apply_defaults(:ui_terminal) + |> Schema.validate_component_assigns!(:ui_terminal) + + %Element{type: :ui_terminal, attrs: Map.to_list(attrs), children: children} + end + + defp row(runs, columns) when is_list(runs) do + {children, used} = + Enum.map_reduce(runs, 0, fn run, used -> + unless is_map(run), do: raise(ArgumentError, "terminal runs must be maps") + text = Map.get(run, :text) + width = Map.get(run, :columns) + + unless is_binary(text) and String.valid?(text) and byte_size(text) <= 65_536 and + not String.match?(text, ~r/[\x00-\x1f\x7f]/u) and + is_integer(width) and width > 0 and used + width <= columns and + ((byte_size(text) == width and String.match?(text, ~r/\A[\x20-\x7e]+\z/)) or + (match?({_, ""}, String.next_grapheme(text)) and width in [1, 2])) and + Map.keys(run) -- [:text, :columns | @style_keys] == [] do + raise ArgumentError, "terminal runs require bounded single-line text and column spans" + end + + cell = %Element{ + type: :ui_terminal_cell, + attrs: [ + text: text, + columns: width, + italic: Map.get(run, :font_style) in [:italic, "italic"], + style: cell_style(run) + ] + } + + {cell, used + width} + end) + + _ = used + %Element{type: :ui_terminal_row, children: children} + end + + defp row(_, _), do: raise(ArgumentError, "terminal rows must be lists of runs") + + defp cell_style(run) do + weight = + case Map.get(run, :font_weight, :normal) do + weight when weight in [:normal, "normal"] -> :normal + weight when weight in [:bold, "bold"] -> :bold + _ -> raise ArgumentError, "terminal font_weight must be normal or bold" + end + + unless Map.get(run, :font_style, :normal) in [:normal, "normal", :italic, "italic"], + do: raise(ArgumentError, "terminal font_style must be normal or italic") + + run |> Map.take([:color, :background]) |> Map.put(:font_weight, weight) |> Map.to_list() + end +end diff --git a/apps/gpui/mix.exs b/apps/gpui/mix.exs index 8d2f5eda..1b45d5ff 100644 --- a/apps/gpui/mix.exs +++ b/apps/gpui/mix.exs @@ -123,6 +123,7 @@ defmodule GPUI.MixProject do ], "Advanced infrastructure": [GPUI.Session], Text: [ + GPUI.Terminal, GPUI.Text.Buffer, GPUI.Text.Position, GPUI.Text.Range, @@ -189,6 +190,7 @@ defmodule GPUI.MixProject do GPUI.Debug, GPUI.Dev.Reload, GPUI.View, + GPUI.Terminal, GPUI.Text.Buffer, GPUI.Text.Position, GPUI.Text.Range, diff --git a/apps/gpui/native/src/generated/schema.rs b/apps/gpui/native/src/generated/schema.rs index 59048a50..1a020581 100644 --- a/apps/gpui/native/src/generated/schema.rs +++ b/apps/gpui/native/src/generated/schema.rs @@ -9,6 +9,9 @@ pub enum GeneratedComponentKind { Input, Image, Text, + TerminalComponent, + TerminalRowComponent, + TerminalCellComponent, EdgeFadeComponent, FrostComponent, PaintComponent, @@ -2017,6 +2020,107 @@ impl AccessibilityRole { #[derive(Clone, Debug)] #[cfg(feature = "real-gpui")] #[allow(dead_code)] +pub(crate) struct TerminalComponentNode { + pub(crate) style: StyleAttrs, + pub(crate) id: String, + pub(crate) label: String, + pub(crate) columns: u64, + pub(crate) cursor_row: u64, + pub(crate) cursor_column: u64, + pub(crate) cursor_visible: bool, + pub(crate) font_family: String, + pub(crate) font_size: f64, + pub(crate) line_height: f64, + pub(crate) focus_request: u64, + pub(crate) reset_request: u64, + pub(crate) disabled: bool, + pub(crate) children: Vec, + pub(crate) keystroke: Option, + pub(crate) text: Option, + pub(crate) paste: Option, + pub(crate) resize: Option, + pub(crate) range: Option, +} +#[cfg(feature = "real-gpui")] +#[allow(clippy::redundant_field_names)] +#[allow(clippy::useless_vec)] +pub(crate) fn decode_generated_terminal_component<'a>( + term: Term<'a>, +) -> NifResult { + require_extension_version(term, "terminal", 1)?; + Ok(TerminalComponentNode { + style: decode_style(term)?, + id: component_id(term)?, + label: component_required_string_attr(term, atoms::label())?, + columns: component_positive_integer_attr(term, atoms::columns())?.unwrap_or(80), + cursor_row: component_non_negative_integer_attr(term, atoms::cursor_row())? + .unwrap_or(0), + cursor_column: component_non_negative_integer_attr(term, atoms::cursor_column())? + .unwrap_or(0), + cursor_visible: component_bool_attr(term, atoms::cursor_visible())? + .unwrap_or(true), + font_family: component_string_attr(term, atoms::font_family())? + .unwrap_or_default(), + font_size: component_positive_number_attr(term, atoms::font_size())? + .unwrap_or(14.0), + line_height: component_positive_number_attr(term, atoms::line_height())? + .unwrap_or(20.0), + focus_request: component_non_negative_integer_attr(term, atoms::focus_request())? + .unwrap_or(0), + reset_request: component_non_negative_integer_attr(term, atoms::reset_request())? + .unwrap_or(0), + disabled: component_bool_attr(term, atoms::disabled())?.unwrap_or(false), + children: decode_children(term)?, + keystroke: component_string_attr(term, atoms::phx_keystroke())?, + text: component_string_attr(term, atoms::phx_text())?, + paste: component_string_attr(term, atoms::phx_paste())?, + resize: component_string_attr(term, atoms::phx_resize())?, + range: component_string_attr(term, atoms::phx_range())?, + }) +} +#[derive(Clone, Debug)] +#[cfg(feature = "real-gpui")] +#[allow(dead_code)] +pub(crate) struct TerminalRowComponentNode { + pub(crate) style: StyleAttrs, + pub(crate) children: Vec, +} +#[cfg(feature = "real-gpui")] +#[allow(clippy::redundant_field_names)] +#[allow(clippy::useless_vec)] +pub(crate) fn decode_generated_terminal_row_component<'a>( + term: Term<'a>, +) -> NifResult { + Ok(TerminalRowComponentNode { + style: decode_style(term)?, + children: decode_children(term)?, + }) +} +#[derive(Clone, Debug)] +#[cfg(feature = "real-gpui")] +#[allow(dead_code)] +pub(crate) struct TerminalCellComponentNode { + pub(crate) style: StyleAttrs, + pub(crate) text: String, + pub(crate) columns: u64, + pub(crate) italic: bool, +} +#[cfg(feature = "real-gpui")] +#[allow(clippy::redundant_field_names)] +#[allow(clippy::useless_vec)] +pub(crate) fn decode_generated_terminal_cell_component<'a>( + term: Term<'a>, +) -> NifResult { + Ok(TerminalCellComponentNode { + style: decode_style(term)?, + text: component_required_string_attr(term, atoms::text())?, + columns: component_positive_integer_attr(term, atoms::columns())?.unwrap_or(1), + italic: component_bool_attr(term, atoms::italic())?.unwrap_or(false), + }) +} +#[derive(Clone, Debug)] +#[cfg(feature = "real-gpui")] +#[allow(dead_code)] pub(crate) struct EdgeFadeComponentNode { pub(crate) style: StyleAttrs, pub(crate) id: String, @@ -2109,6 +2213,9 @@ pub(crate) enum ElementNode { AnchoredLayer(AnchoredLayerNode), TextSurface(TextSurfaceNode), Input(InputNode), + TerminalComponent(TerminalComponentNode), + TerminalRowComponent(TerminalRowComponentNode), + TerminalCellComponent(TerminalCellComponentNode), EdgeFadeComponent(EdgeFadeComponentNode), FrostComponent(FrostComponentNode), PaintComponent(PaintComponentNode), @@ -2129,6 +2236,9 @@ pub enum GeneratedElementTag { TextInput, Img, Text, + UiTerminal, + UiTerminalRow, + UiTerminalCell, UiEdgeFade, UiFrost, UiPaint, @@ -2148,6 +2258,9 @@ pub fn decode_generated_element_tag(tag: &str) -> GeneratedElementTag { "text_input" => GeneratedElementTag::TextInput, "img" => GeneratedElementTag::Img, "text" => GeneratedElementTag::Text, + "ui_terminal" => GeneratedElementTag::UiTerminal, + "ui_terminal_row" => GeneratedElementTag::UiTerminalRow, + "ui_terminal_cell" => GeneratedElementTag::UiTerminalCell, "ui_edge_fade" => GeneratedElementTag::UiEdgeFade, "ui_frost" => GeneratedElementTag::UiFrost, "ui_paint" => GeneratedElementTag::UiPaint, @@ -2168,6 +2281,13 @@ pub fn generated_component_kind(tag: GeneratedElementTag) -> GeneratedComponentK GeneratedElementTag::TextInput => GeneratedComponentKind::Input, GeneratedElementTag::Img => GeneratedComponentKind::Image, GeneratedElementTag::Text => GeneratedComponentKind::Text, + GeneratedElementTag::UiTerminal => GeneratedComponentKind::TerminalComponent, + GeneratedElementTag::UiTerminalRow => { + GeneratedComponentKind::TerminalRowComponent + } + GeneratedElementTag::UiTerminalCell => { + GeneratedComponentKind::TerminalCellComponent + } GeneratedElementTag::UiEdgeFade => GeneratedComponentKind::EdgeFadeComponent, GeneratedElementTag::UiFrost => GeneratedComponentKind::FrostComponent, GeneratedElementTag::UiPaint => GeneratedComponentKind::PaintComponent, @@ -2188,6 +2308,18 @@ pub(crate) fn decode_generated_element_node<'a>( GeneratedComponentKind::Input => decode_input_node(term, tag), GeneratedComponentKind::Image => decode_image_node(term, tag), GeneratedComponentKind::Text => decode_text_node(term, tag), + GeneratedComponentKind::TerminalComponent => { + decode_generated_terminal_component(term) + .map(|node| ElementNode::TerminalComponent(node)) + } + GeneratedComponentKind::TerminalRowComponent => { + decode_generated_terminal_row_component(term) + .map(|node| ElementNode::TerminalRowComponent(node)) + } + GeneratedComponentKind::TerminalCellComponent => { + decode_generated_terminal_cell_component(term) + .map(|node| ElementNode::TerminalCellComponent(node)) + } GeneratedComponentKind::EdgeFadeComponent => { decode_generated_edge_fade_component(term) .map(|node| ElementNode::EdgeFadeComponent(node)) @@ -2211,6 +2343,15 @@ pub(crate) fn render_generated_component_node( context: &mut element::ElementRenderContext<'_, '_>, ) -> gpui::AnyElement { match node { + ElementNode::TerminalComponent(node) => { + element::component::terminal::render(node, context) + } + ElementNode::TerminalRowComponent(node) => { + element::component::terminal::render_row(node, context) + } + ElementNode::TerminalCellComponent(node) => { + element::component::terminal::render_cell(node, context) + } ElementNode::EdgeFadeComponent(node) => { element::component::edge_fade::render_edge_fade(node, context) } diff --git a/apps/gpui/test/gpui/schema/extension_test.exs b/apps/gpui/test/gpui/schema/extension_test.exs index d48b4fc1..97af9f79 100644 --- a/apps/gpui/test/gpui/schema/extension_test.exs +++ b/apps/gpui/test/gpui/schema/extension_test.exs @@ -5,6 +5,7 @@ defmodule GPUI.Schema.ExtensionTest do test "exposes versioned presentation contracts from the canonical component schema" do assert [ + %Extension{id: :terminal, version: 1}, %Extension{id: :edge_fade, version: 1}, %Extension{id: :frost, version: 1}, %Extension{id: :paint, version: 1} diff --git a/apps/gpui/test/gpui/schema_test.exs b/apps/gpui/test/gpui/schema_test.exs index 0a4a6d9a..9bc0e3a2 100644 --- a/apps/gpui/test/gpui/schema_test.exs +++ b/apps/gpui/test/gpui/schema_test.exs @@ -14,6 +14,9 @@ defmodule GPUI.SchemaTest do :text_input, :img, :text, + :ui_terminal, + :ui_terminal_row, + :ui_terminal_cell, :ui_edge_fade, :ui_frost, :ui_paint diff --git a/apps/gpui/test/gpui/terminal_test.exs b/apps/gpui/test/gpui/terminal_test.exs new file mode 100644 index 00000000..a666a0ce --- /dev/null +++ b/apps/gpui/test/gpui/terminal_test.exs @@ -0,0 +1,74 @@ +defmodule GPUI.TerminalTest do + use ExUnit.Case, async: true + alias GPUI.{Element, Event, Terminal} + + test "terminal surface declares cells, not a second editable line buffer" do + surface = + Terminal.surface(%{ + id: "console", + label: "Remote console", + columns: 4, + rows: [[%{text: "a", columns: 1}, %{text: "界", columns: 2, color: {:rgb, 0xFF0000}}]], + cursor_row: 0, + cursor_column: 3, + "phx-keystroke": "key", + "phx-text": "text", + "phx-paste": "paste", + "phx-resize": "size" + }) + + payload = Element.to_payload(surface) + assert payload.type == :ui_terminal + assert [%{type: :ui_terminal_row, children: cells}] = payload.children + assert Enum.map(cells, & &1.attrs.text) == ["a", "界"] + end + + test "bounds rows, spans and cell text before crossing the native boundary" do + for rows <- [ + [[%{text: "x", columns: 0}]], + [[%{text: "x\n", columns: 1}]], + [[%{text: "x", columns: 5}]], + List.duplicate([], 10_001) + ] do + assert_raise ArgumentError, fn -> + Terminal.surface(%{id: "t", label: "Console", columns: 4, rows: rows}) + end + end + end + + test "raw keystrokes preserve modifiers independently of committed text and paste" do + value = %{key: "c", control: true, alt: false, shift: false, platform: false, repeat: false} + + assert {:ok, %{value: ^value}} = + Event.normalize(%{type: :keystroke, event: "key", window_id: 1, value: value}) + + assert {:ok, %{value: "hello\nworld"}} = + Event.normalize(%{type: :paste, event: "paste", window_id: 1, value: "hello\nworld"}) + + assert {:ok, %{value: "界"}} = + Event.normalize(%{type: :text, event: "text", window_id: 1, value: "界"}) + + assert {:error, _} = + Event.normalize(%{ + type: :keystroke, + event: "key", + window_id: 1, + value: %{value | control: "true"} + }) + end + + test "resize reports measured cells and integral PTY dimensions" do + value = %{columns: 80, rows: 24, cell_width: 8.25, cell_height: 19.0} + + assert {:ok, %{value: ^value}} = + Event.normalize(%{type: :resize, event: "size", window_id: 1, value: value}) + + assert {:error, _} = + Event.normalize(%{ + type: :resize, + event: "size", + window_id: 1, + value: %{value | cell_width: 0} + }) + end +end diff --git a/apps/gpui_components/native/src/generated/schema.rs b/apps/gpui_components/native/src/generated/schema.rs index bea7448a..62c71e35 100644 --- a/apps/gpui_components/native/src/generated/schema.rs +++ b/apps/gpui_components/native/src/generated/schema.rs @@ -9,6 +9,9 @@ pub enum GeneratedComponentKind { Input, Image, Text, + TerminalComponent, + TerminalRowComponent, + TerminalCellComponent, EdgeFadeComponent, FrostComponent, PaintComponent, @@ -2204,6 +2207,107 @@ pub(crate) fn append_radio_option( #[derive(Clone, Debug)] #[cfg(feature = "real-gpui")] #[allow(dead_code)] +pub(crate) struct TerminalComponentNode { + pub(crate) style: StyleAttrs, + pub(crate) id: String, + pub(crate) label: String, + pub(crate) columns: u64, + pub(crate) cursor_row: u64, + pub(crate) cursor_column: u64, + pub(crate) cursor_visible: bool, + pub(crate) font_family: String, + pub(crate) font_size: f64, + pub(crate) line_height: f64, + pub(crate) focus_request: u64, + pub(crate) reset_request: u64, + pub(crate) disabled: bool, + pub(crate) children: Vec, + pub(crate) keystroke: Option, + pub(crate) text: Option, + pub(crate) paste: Option, + pub(crate) resize: Option, + pub(crate) range: Option, +} +#[cfg(feature = "real-gpui")] +#[allow(clippy::redundant_field_names)] +#[allow(clippy::useless_vec)] +pub(crate) fn decode_generated_terminal_component<'a>( + term: Term<'a>, +) -> NifResult { + require_extension_version(term, "terminal", 1)?; + Ok(TerminalComponentNode { + style: decode_style(term)?, + id: component_id(term)?, + label: component_required_string_attr(term, atoms::label())?, + columns: component_positive_integer_attr(term, atoms::columns())?.unwrap_or(80), + cursor_row: component_non_negative_integer_attr(term, atoms::cursor_row())? + .unwrap_or(0), + cursor_column: component_non_negative_integer_attr(term, atoms::cursor_column())? + .unwrap_or(0), + cursor_visible: component_bool_attr(term, atoms::cursor_visible())? + .unwrap_or(true), + font_family: component_string_attr(term, atoms::font_family())? + .unwrap_or_default(), + font_size: component_positive_number_attr(term, atoms::font_size())? + .unwrap_or(14.0), + line_height: component_positive_number_attr(term, atoms::line_height())? + .unwrap_or(20.0), + focus_request: component_non_negative_integer_attr(term, atoms::focus_request())? + .unwrap_or(0), + reset_request: component_non_negative_integer_attr(term, atoms::reset_request())? + .unwrap_or(0), + disabled: component_bool_attr(term, atoms::disabled())?.unwrap_or(false), + children: decode_children(term)?, + keystroke: component_string_attr(term, atoms::phx_keystroke())?, + text: component_string_attr(term, atoms::phx_text())?, + paste: component_string_attr(term, atoms::phx_paste())?, + resize: component_string_attr(term, atoms::phx_resize())?, + range: component_string_attr(term, atoms::phx_range())?, + }) +} +#[derive(Clone, Debug)] +#[cfg(feature = "real-gpui")] +#[allow(dead_code)] +pub(crate) struct TerminalRowComponentNode { + pub(crate) style: StyleAttrs, + pub(crate) children: Vec, +} +#[cfg(feature = "real-gpui")] +#[allow(clippy::redundant_field_names)] +#[allow(clippy::useless_vec)] +pub(crate) fn decode_generated_terminal_row_component<'a>( + term: Term<'a>, +) -> NifResult { + Ok(TerminalRowComponentNode { + style: decode_style(term)?, + children: decode_children(term)?, + }) +} +#[derive(Clone, Debug)] +#[cfg(feature = "real-gpui")] +#[allow(dead_code)] +pub(crate) struct TerminalCellComponentNode { + pub(crate) style: StyleAttrs, + pub(crate) text: String, + pub(crate) columns: u64, + pub(crate) italic: bool, +} +#[cfg(feature = "real-gpui")] +#[allow(clippy::redundant_field_names)] +#[allow(clippy::useless_vec)] +pub(crate) fn decode_generated_terminal_cell_component<'a>( + term: Term<'a>, +) -> NifResult { + Ok(TerminalCellComponentNode { + style: decode_style(term)?, + text: component_required_string_attr(term, atoms::text())?, + columns: component_positive_integer_attr(term, atoms::columns())?.unwrap_or(1), + italic: component_bool_attr(term, atoms::italic())?.unwrap_or(false), + }) +} +#[derive(Clone, Debug)] +#[cfg(feature = "real-gpui")] +#[allow(dead_code)] pub(crate) struct EdgeFadeComponentNode { pub(crate) style: StyleAttrs, pub(crate) id: String, @@ -3836,6 +3940,9 @@ pub(crate) enum ElementNode { AnchoredLayer(AnchoredLayerNode), TextSurface(TextSurfaceNode), Input(InputNode), + TerminalComponent(TerminalComponentNode), + TerminalRowComponent(TerminalRowComponentNode), + TerminalCellComponent(TerminalCellComponentNode), EdgeFadeComponent(EdgeFadeComponentNode), FrostComponent(FrostComponentNode), PaintComponent(PaintComponentNode), @@ -3901,6 +4008,9 @@ pub enum GeneratedElementTag { TextInput, Img, Text, + UiTerminal, + UiTerminalRow, + UiTerminalCell, UiEdgeFade, UiFrost, UiPaint, @@ -3965,6 +4075,9 @@ pub fn decode_generated_element_tag(tag: &str) -> GeneratedElementTag { "text_input" => GeneratedElementTag::TextInput, "img" => GeneratedElementTag::Img, "text" => GeneratedElementTag::Text, + "ui_terminal" => GeneratedElementTag::UiTerminal, + "ui_terminal_row" => GeneratedElementTag::UiTerminalRow, + "ui_terminal_cell" => GeneratedElementTag::UiTerminalCell, "ui_edge_fade" => GeneratedElementTag::UiEdgeFade, "ui_frost" => GeneratedElementTag::UiFrost, "ui_paint" => GeneratedElementTag::UiPaint, @@ -4030,6 +4143,13 @@ pub fn generated_component_kind(tag: GeneratedElementTag) -> GeneratedComponentK GeneratedElementTag::TextInput => GeneratedComponentKind::Input, GeneratedElementTag::Img => GeneratedComponentKind::Image, GeneratedElementTag::Text => GeneratedComponentKind::Text, + GeneratedElementTag::UiTerminal => GeneratedComponentKind::TerminalComponent, + GeneratedElementTag::UiTerminalRow => { + GeneratedComponentKind::TerminalRowComponent + } + GeneratedElementTag::UiTerminalCell => { + GeneratedComponentKind::TerminalCellComponent + } GeneratedElementTag::UiEdgeFade => GeneratedComponentKind::EdgeFadeComponent, GeneratedElementTag::UiFrost => GeneratedComponentKind::FrostComponent, GeneratedElementTag::UiPaint => GeneratedComponentKind::PaintComponent, @@ -4131,6 +4251,18 @@ pub(crate) fn decode_generated_element_node<'a>( GeneratedComponentKind::Input => decode_input_node(term, tag), GeneratedComponentKind::Image => decode_image_node(term, tag), GeneratedComponentKind::Text => decode_text_node(term, tag), + GeneratedComponentKind::TerminalComponent => { + decode_generated_terminal_component(term) + .map(|node| ElementNode::TerminalComponent(node)) + } + GeneratedComponentKind::TerminalRowComponent => { + decode_generated_terminal_row_component(term) + .map(|node| ElementNode::TerminalRowComponent(node)) + } + GeneratedComponentKind::TerminalCellComponent => { + decode_generated_terminal_cell_component(term) + .map(|node| ElementNode::TerminalCellComponent(node)) + } GeneratedComponentKind::EdgeFadeComponent => { decode_generated_edge_fade_component(term) .map(|node| ElementNode::EdgeFadeComponent(node)) @@ -4333,6 +4465,15 @@ pub(crate) fn render_generated_component_node( context: &mut element::ElementRenderContext<'_, '_>, ) -> gpui::AnyElement { match node { + ElementNode::TerminalComponent(node) => { + element::component::terminal::render(node, context) + } + ElementNode::TerminalRowComponent(node) => { + element::component::terminal::render_row(node, context) + } + ElementNode::TerminalCellComponent(node) => { + element::component::terminal::render_cell(node, context) + } ElementNode::EdgeFadeComponent(node) => { element::component::edge_fade::render_edge_fade(node, context) } diff --git a/apps/gpui_native/native/src/element/component.rs b/apps/gpui_native/native/src/element/component.rs index 7cb1c883..a38fc394 100644 --- a/apps/gpui_native/native/src/element/component.rs +++ b/apps/gpui_native/native/src/element/component.rs @@ -31,6 +31,7 @@ pub(crate) mod split; pub(crate) mod switch; #[cfg(feature = "components")] pub(crate) mod tabs; +pub(crate) mod terminal; pub(crate) mod text_surface; #[cfg(feature = "components")] pub(crate) mod tree; diff --git a/apps/gpui_native/native/src/element/component/controls.rs b/apps/gpui_native/native/src/element/component/controls.rs index 91af0414..27230632 100644 --- a/apps/gpui_native/native/src/element/component/controls.rs +++ b/apps/gpui_native/native/src/element/component/controls.rs @@ -10,7 +10,7 @@ pub(crate) fn render_button_component( context: &mut ElementRenderContext<'_, '_>, ) -> gpui::AnyElement { use crate::{push_event, NativeEvent}; - use gpui::{IntoElement, ParentElement}; + use gpui::{InteractiveElement, IntoElement, ParentElement}; use gpui_component::{ button::{Button, ButtonVariants}, Disableable, Selectable, Sizable, @@ -28,6 +28,7 @@ pub(crate) fn render_button_component( .filter(|prompt| !prompt.is_empty()) .unwrap_or_else(|| "Choose a file".to_string()); let file_max_bytes = node.file_max_bytes.min(25 * 1_024 * 1_024) as usize; + let test_id = node.id.clone(); let mut button = Button::new(node.id); button = match node.variant.as_deref() { @@ -122,7 +123,10 @@ pub(crate) fn render_button_component( }); } - apply_component_styles(button, node.style).into_any_element() + let element = gpui::div() + .id(format!("{}-display-action", test_id)) + .child(apply_component_styles(button, node.style)); + crate::element::register_test_target(element, test_id, None, context).into_any_element() } #[cfg(feature = "components")] diff --git a/apps/gpui_native/native/src/element/component/data_table.rs b/apps/gpui_native/native/src/element/component/data_table.rs index 752079e4..ccdfcdc6 100644 --- a/apps/gpui_native/native/src/element/component/data_table.rs +++ b/apps/gpui_native/native/src/element/component/data_table.rs @@ -479,6 +479,7 @@ fn render_visible_rows( id_namespace: format!("table-{}-{}-{}", table.id, row_id, column.id), active_input_ids: &mut active_input_ids, input_entities: &mut component.collection.input_entities, + terminal_entities: &mut component.collection.terminal_entities, components: &mut component.collection.components, window, cx, @@ -537,6 +538,10 @@ fn render_visible_rows( .collection .input_entities .retain(|input_id, _entity| active_input_ids.contains(input_id)); + component + .collection + .terminal_entities + .retain(|id, _entity| active_input_ids.contains(id)); component.collection.components.finish_render(window, cx); rendered } diff --git a/apps/gpui_native/native/src/element/component/terminal.rs b/apps/gpui_native/native/src/element/component/terminal.rs new file mode 100644 index 00000000..9fe61a89 --- /dev/null +++ b/apps/gpui_native/native/src/element/component/terminal.rs @@ -0,0 +1,892 @@ +//! Native mechanics for an application-owned terminal. No VT parser or PTY lives here. +use crate::element::{ElementNode, ElementRenderContext}; +use crate::{ + gpui, push_event, EventValue, InputKind, NativeEvent, SharedRuntime, TerminalCellComponentNode, + TerminalComponentNode, TerminalRowComponentNode, +}; +use gpui::{ + div, fill, point, px, size, App, AppContext, Bounds, ClipboardItem, Context, + ElementInputHandler, EntityInputHandler, FocusHandle, InteractiveElement, IntoElement, + KeyDownEvent, MouseButton, ParentElement, Pixels, Render, ShapedLine, + StatefulInteractiveElement, Styled, TextAlign, TextRun, UTF16Selection, Window, +}; +use std::ops::Range; +use unicode_segmentation::UnicodeSegmentation; + +const MAX_INPUT_BYTES: usize = 1_048_576; +const MAX_ROWS: usize = 10_000; +const MAX_TEXT_BYTES: usize = 8 * 1_048_576; +#[cfg(target_os = "macos")] +const DEFAULT_MONO_FAMILY: &str = "Menlo"; +#[cfg(target_os = "windows")] +const DEFAULT_MONO_FAMILY: &str = "Consolas"; +#[cfg(not(any(target_os = "macos", target_os = "windows")))] +const DEFAULT_MONO_FAMILY: &str = "DejaVu Sans Mono"; + +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +struct CellPoint { + row: usize, + column: usize, +} + +#[derive(Clone, Debug)] +struct Run { + text: String, + columns: usize, + color: Option, + background: Option, + bold: bool, + italic: bool, +} + +pub(crate) struct Terminal { + node: TerminalComponentNode, + rows: Vec>, + runtime: SharedRuntime, + window_id: u64, + focus: FocusHandle, + reset_request: u64, + top: usize, + tail: bool, + selection: Option<(CellPoint, CellPoint)>, + dragging: bool, + marked: String, + marked_selection: Range, + bounds: Bounds, + cell_width: f32, + cell_height: f32, + visible_rows: usize, + last_size: Option<(usize, usize, u32, u32)>, + last_range: Option<(usize, usize)>, + scroll_remainder: f32, +} + +fn decode_rows(node: &TerminalComponentNode) -> Option>> { + if node.columns == 0 || node.columns > 512 || node.children.len() > MAX_ROWS { + return None; + } + let mut bytes = 0usize; + let mut rows = Vec::with_capacity(node.children.len()); + for row in &node.children { + let ElementNode::TerminalRowComponent(row) = row else { + return None; + }; + let mut used = 0u64; + let mut runs = Vec::with_capacity(row.children.len()); + for cell in &row.children { + let ElementNode::TerminalCellComponent(cell) = cell else { + return None; + }; + bytes = bytes.checked_add(cell.text.len())?; + used = used.checked_add(cell.columns)?; + if bytes > MAX_TEXT_BYTES + || cell.columns == 0 + || used > node.columns + || cell.text.chars().any(char::is_control) + || !(cell.text.is_ascii() && cell.text.len() == cell.columns as usize + || cell.text.graphemes(true).count() == 1 && cell.columns <= 2) + { + return None; + } + runs.push(Run { + text: cell.text.clone(), + columns: cell.columns as usize, + color: cell.style.color, + background: cell.style.background, + bold: cell.style.font_weight.as_deref() == Some("bold"), + italic: cell.italic, + }); + } + rows.push(runs); + } + Some(rows) +} + +impl Terminal { + pub(crate) fn input_focused(&self, window: &Window) -> bool { + !self.node.disabled && self.focus.is_focused(window) + } + + fn new( + node: TerminalComponentNode, + runtime: SharedRuntime, + window_id: u64, + cx: &mut Context, + ) -> Self { + let rows = decode_rows(&node).unwrap_or_default(); + Self { + node, + rows, + runtime, + window_id, + focus: cx.focus_handle(), + reset_request: 0, + top: 0, + tail: true, + selection: None, + dragging: false, + marked: String::new(), + marked_selection: 0..0, + bounds: Bounds::default(), + cell_width: 8.0, + cell_height: 20.0, + visible_rows: 1, + last_size: None, + last_range: None, + scroll_remainder: 0.0, + } + } + + fn reconcile( + &mut self, + node: TerminalComponentNode, + _window: &mut Window, + _cx: &mut Context, + ) { + if node.reset_request != self.reset_request || node.columns != self.node.columns { + self.reset_request = node.reset_request; + self.selection = None; + self.marked.clear(); + self.marked_selection = 0..0; + self.tail = true; + self.scroll_remainder = 0.0; + } + self.rows = decode_rows(&node).unwrap_or_default(); + self.node = node; + self.clamp_scroll(); + } + + fn clamp_scroll(&mut self) { + let end = self.rows.len().saturating_sub(self.visible_rows); + self.top = if self.tail { end } else { self.top.min(end) }; + } + + fn emit_text(&mut self, kind: InputKind, event: Option, text: String) { + if self.node.disabled || text.is_empty() || text.len() > MAX_INPUT_BYTES { + return; + } + self.tail = true; + self.selection = None; + self.clamp_scroll(); + if let Some(event) = event { + let _ = push_event( + &self.runtime, + NativeEvent::Input { + kind, + window_id: self.window_id, + event, + value: Some(EventValue::String(text)), + }, + ); + } + } + + fn key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context) { + if self.node.disabled { + return; + } + let key = event.keystroke.key.as_str(); + if key.is_empty() { + return; + } + let mods = event.keystroke.modifiers; + if !self.marked.is_empty() && !mods.control && !mods.alt && !mods.platform { + return; + } + // Platform shortcuts remain application commands, not remote input. + if mods.platform + || (cfg!(not(target_os = "macos")) + && mods.control + && mods.shift + && matches!(key, "c" | "v")) + { + match key { + "c" => { + if let Some(text) = self.selected_text() { + cx.write_to_clipboard(ClipboardItem::new_string(text)); + } + } + "v" => { + if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) { + if text.len() > MAX_INPUT_BYTES { + window.play_system_bell(); + return; + } + self.emit_text(InputKind::Paste, self.node.paste.clone(), text); + } + } + "a" => { + self.selection = Some(( + CellPoint { row: 0, column: 0 }, + CellPoint { + row: self.rows.len().saturating_sub(1), + column: self.node.columns as usize, + }, + )); + } + _ => return, + } + cx.stop_propagation(); + cx.notify(); + return; + } + if mods.shift && matches!(key, "pageup" | "pagedown" | "home" | "end") { + let page = self.visible_rows.saturating_sub(1).max(1); + self.top = match key { + "pageup" => self.top.saturating_sub(page), + "pagedown" => self.top.saturating_add(page), + "home" => 0, + _ => self.rows.len(), + }; + self.tail = key == "end"; + self.clamp_scroll(); + cx.stop_propagation(); + cx.notify(); + return; + } + // Ordinary Unicode text is committed through EntityInputHandler, including + // IME. Never emit both the printable key and its committed text. + if !mods.control && !mods.alt && (key.chars().count() == 1 || key == "space") { + return; + } + self.tail = true; + self.selection = None; + self.clamp_scroll(); + if let Some(event_name) = &self.node.keystroke { + let _ = push_event( + &self.runtime, + NativeEvent::Keystroke { + window_id: self.window_id, + event: event_name.clone(), + value: crate::event::KeyStroke { + key: key.to_string(), + control: mods.control, + alt: mods.alt, + shift: mods.shift, + platform: mods.platform, + repeat: event.is_held, + }, + }, + ); + } + cx.stop_propagation(); + cx.notify(); + } + + fn point(&self, position: gpui::Point) -> CellPoint { + let row = ((f32::from(position.y - self.bounds.top()) / self.cell_height) + .floor() + .max(0.0) as usize) + .saturating_add(self.top) + .min(self.rows.len().saturating_sub(1)); + let column = (f32::from(position.x - self.bounds.left()) / self.cell_width) + .round() + .max(0.0) as usize; + CellPoint { + row, + column: column.min(self.node.columns as usize), + } + } + + fn selected_text(&self) -> Option { + if self.rows.is_empty() { + return None; + } + let (a, b) = self.selection?; + if a == b { + return None; + } + let (start, end) = (a.min(b), a.max(b)); + let mut lines = Vec::new(); + for row in start.row..=end.row.min(self.rows.len().saturating_sub(1)) { + let left = if row == start.row { start.column } else { 0 }; + let right = if row == end.row { + end.column + } else { + self.node.columns as usize + }; + lines.push( + copy_row(&self.rows[row], left, right) + .trim_end() + .to_string(), + ); + } + Some(lines.join("\n")) + } + + fn prepare( + &mut self, + bounds: Bounds, + window: &mut Window, + ) -> Vec<(gpui::Point, ShapedLine, usize)> { + self.bounds = bounds; + let family = if self.node.font_family.is_empty() { + DEFAULT_MONO_FAMILY + } else { + &self.node.font_family + }; + let mut font = gpui::font(family.to_string()); + font.features = gpui::FontFeatures::disable_ligatures(); + let font_size = px((self.node.font_size as f32).clamp(6.0, 96.0)); + let foreground: gpui::Hsla = gpui::rgba(self.node.style.color.unwrap_or(0xe5e5e5ff)).into(); + let sample = window.text_system().shape_line( + "M".into(), + font_size, + &[TextRun { + len: 1, + font: font.clone(), + color: foreground, + background_color: None, + underline: None, + strikethrough: None, + }], + None, + ); + self.cell_width = f32::from(sample.width).max(1.0); + self.cell_height = (self.node.line_height as f32).clamp(f32::from(font_size), 128.0); + let columns = (f32::from(bounds.size.width) / self.cell_width) + .floor() + .clamp(1.0, 512.0) as usize; + self.visible_rows = (f32::from(bounds.size.height) / self.cell_height) + .floor() + .clamp(1.0, 256.0) as usize; + self.clamp_scroll(); + let range = ( + self.top, + (self.top + self.visible_rows).min(self.rows.len()), + ); + if self.last_range != Some(range) { + self.last_range = Some(range); + if let Some(event) = &self.node.range { + let _ = push_event( + &self.runtime, + NativeEvent::VirtualRange { + window_id: self.window_id, + event: event.clone(), + first: range.0 as u64, + last: range.1 as u64, + }, + ); + } + } + let key = ( + columns, + self.visible_rows, + self.cell_width.to_bits(), + self.cell_height.to_bits(), + ); + if bounds.size.width > px(0.0) + && bounds.size.height > px(0.0) + && self.last_size != Some(key) + { + self.last_size = Some(key); + if let Some(event) = &self.node.resize { + let _ = push_event( + &self.runtime, + NativeEvent::TerminalResize { + window_id: self.window_id, + event: event.clone(), + value: crate::event::TerminalSize { + columns: columns as u64, + rows: self.visible_rows as u64, + cell_width: self.cell_width as f64, + cell_height: self.cell_height as f64, + }, + }, + ); + } + } + let mut shaped = Vec::new(); + for (visible_row, row) in self + .rows + .iter() + .skip(self.top) + .take(self.visible_rows) + .enumerate() + { + let mut column = 0; + for run in row { + let mut run_font = font.clone(); + if run.bold { + run_font.weight = gpui::FontWeight::BOLD; + } + if run.italic { + run_font.style = gpui::FontStyle::Italic; + } + let graphemes = run.text.graphemes(true).collect::>(); + let span = run.columns / graphemes.len().max(1); + for grapheme in graphemes { + if grapheme == " " { + column += span; + continue; + } + let text = window.text_system().shape_line( + grapheme.to_string().into(), + font_size, + &[TextRun { + len: grapheme.len(), + font: run_font.clone(), + color: run + .color + .map(|c| gpui::rgba(c).into()) + .unwrap_or(foreground), + background_color: None, + underline: None, + strikethrough: None, + }], + None, + ); + shaped.push(( + point( + bounds.left() + px(column as f32 * self.cell_width), + bounds.top() + px(visible_row as f32 * self.cell_height), + ), + text, + span, + )); + column += span; + } + } + } + if !self.marked.is_empty() { + let text = window.text_system().shape_line( + self.marked.clone().into(), + font_size, + &[TextRun { + len: self.marked.len(), + font, + color: foreground, + background_color: None, + underline: Some(gpui::UnderlineStyle { + color: Some(foreground), + thickness: px(1.0), + wavy: false, + }), + strikethrough: None, + }], + None, + ); + shaped.push(( + point( + bounds.left() + px(self.node.cursor_column as f32 * self.cell_width), + bounds.top() + + px(self.node.cursor_row.saturating_sub(self.top as u64) as f32 + * self.cell_height), + ), + text, + self.node.columns as usize, + )); + } + shaped + } + + fn paint( + &self, + shaped: Vec<(gpui::Point, ShapedLine, usize)>, + window: &mut Window, + cx: &mut App, + ) { + let selection = self.selection.map(|(a, b)| (a.min(b), a.max(b))); + for (visible_row, row) in self + .rows + .iter() + .skip(self.top) + .take(self.visible_rows) + .enumerate() + { + let mut column = 0; + for run in row { + if let Some(color) = run.background { + window.paint_quad(fill( + Bounds::new( + point( + self.bounds.left() + px(column as f32 * self.cell_width), + self.bounds.top() + px(visible_row as f32 * self.cell_height), + ), + size( + px(run.columns as f32 * self.cell_width), + px(self.cell_height), + ), + ), + gpui::rgba(color), + )); + } + column += run.columns; + } + if let Some((start, end)) = selection { + let logical_row = self.top + visible_row; + if (start.row..=end.row).contains(&logical_row) { + let left = if start.row == logical_row { + start.column + } else { + 0 + }; + let right = if end.row == logical_row { + end.column + } else { + self.node.columns as usize + }; + window.paint_quad(fill( + Bounds::new( + point( + self.bounds.left() + px(left as f32 * self.cell_width), + self.bounds.top() + px(visible_row as f32 * self.cell_height), + ), + size( + px(right.saturating_sub(left) as f32 * self.cell_width), + px(self.cell_height), + ), + ), + gpui::Hsla::from(gpui::rgba(self.node.style.color.unwrap_or(0xe5e5e5ff))) + .opacity(0.25), + )); + } + } + } + for (origin, line, columns) in shaped { + window.with_content_mask( + Some(gpui::ContentMask { + bounds: Bounds::new( + origin, + size(px(columns as f32 * self.cell_width), px(self.cell_height)), + ), + }), + |window| { + let _ = line.paint( + origin, + px(self.cell_height), + TextAlign::Left, + None, + window, + cx, + ); + }, + ); + } + let row = self.node.cursor_row as usize; + if self.node.cursor_visible + && row >= self.top + && row < self.top + self.visible_rows + && self.focus.is_focused(window) + { + window.paint_quad(fill( + Bounds::new( + point( + self.bounds.left() + px(self.node.cursor_column as f32 * self.cell_width), + self.bounds.top() + + px( + (row - self.top) as f32 * self.cell_height + self.cell_height - 2.0, + ), + ), + size(px(self.cell_width), px(2.0)), + ), + gpui::rgba(self.node.style.color.unwrap_or(0xe5e5e5ff)), + )); + } + } +} + +fn copy_row(runs: &[Run], left: usize, right: usize) -> String { + let mut column = 0; + let mut text = String::new(); + for run in runs { + let graphemes = run.text.graphemes(true).collect::>(); + let width = run.columns / graphemes.len().max(1); + for grapheme in graphemes { + if column < right && column + width > left { + text.push_str(grapheme); + } + column += width; + } + } + text +} + +impl Render for Terminal { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let prepare = cx.entity(); + let paint = cx.entity(); + div() + .size_full() + .relative() + .overflow_hidden() + .id("terminal-input") + .key_context("GPUITerminal") + .track_focus(&self.focus) + .on_key_down(cx.listener(Self::key_down)) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, event: &gpui::MouseDownEvent, window, cx| { + this.focus.focus(window, cx); + let point = this.point(event.position); + this.selection = Some((point, point)); + this.dragging = true; + cx.notify(); + }), + ) + .on_mouse_move( + cx.listener(|this, event: &gpui::MouseMoveEvent, _window, cx| { + if event.pressed_button != Some(MouseButton::Left) { + this.dragging = false; + } + if this.dragging { + let point = this.point(event.position); + if let Some((anchor, _)) = this.selection { + this.selection = Some((anchor, point)); + } + cx.notify(); + } + }), + ) + .on_mouse_up( + MouseButton::Left, + cx.listener(|this, _event, _window, _cx| this.dragging = false), + ) + .on_scroll_wheel( + cx.listener(|this, event: &gpui::ScrollWheelEvent, _window, cx| { + let delta = f32::from(event.delta.pixel_delta(px(this.cell_height)).y); + this.scroll_remainder -= delta / this.cell_height; + let rows = this.scroll_remainder.trunc() as isize; + this.scroll_remainder -= rows as f32; + this.top = this.top.saturating_add_signed(rows); + this.tail = this.top >= this.rows.len().saturating_sub(this.visible_rows); + this.clamp_scroll(); + cx.stop_propagation(); + cx.notify(); + }), + ) + .child( + gpui::canvas( + move |bounds, window, cx| { + prepare.update(cx, |terminal, _| terminal.prepare(bounds, window)) + }, + move |bounds, shaped, window, cx| { + paint.update(cx, |terminal, cx| { + if !terminal.node.disabled { + window.handle_input( + &terminal.focus, + ElementInputHandler::new(bounds, paint.clone()), + cx, + ); + } + terminal.paint(shaped, window, cx); + }); + }, + ) + .size_full(), + ) + } +} + +// A terminal has no locally editable command line. Only an uncommitted IME +// composition is retained; commit emits text once and leaves remote editing to +// the PTY. Clipboard paste takes the separate path above and keeps newlines. +impl EntityInputHandler for Terminal { + fn text_for_range( + &mut self, + range: Range, + adjusted: &mut Option>, + _: &mut Window, + _: &mut Context, + ) -> Option { + let (bytes, utf16) = composition_range(&self.marked, range); + *adjusted = Some(utf16); + Some(self.marked[bytes].to_string()) + } + fn selected_text_range( + &mut self, + _: bool, + _: &mut Window, + _: &mut Context, + ) -> Option { + Some(UTF16Selection { + range: self.marked_selection.clone(), + reversed: false, + }) + } + fn marked_text_range(&self, _: &mut Window, _: &mut Context) -> Option> { + (!self.marked.is_empty()).then(|| 0..self.marked.encode_utf16().count()) + } + fn unmark_text(&mut self, _: &mut Window, cx: &mut Context) { + self.marked.clear(); + self.marked_selection = 0..0; + cx.notify(); + } + fn replace_text_in_range( + &mut self, + _: Option>, + text: &str, + _: &mut Window, + cx: &mut Context, + ) { + self.marked.clear(); + self.marked_selection = 0..0; + self.emit_text(InputKind::Text, self.node.text.clone(), text.to_string()); + cx.notify(); + } + fn replace_and_mark_text_in_range( + &mut self, + _: Option>, + text: &str, + selection: Option>, + _: &mut Window, + cx: &mut Context, + ) { + if text.len() <= MAX_INPUT_BYTES { + self.marked = text.to_string(); + let end = text.encode_utf16().count(); + self.marked_selection = composition_range(text, selection.unwrap_or(end..end)).1; + } + cx.notify(); + } + fn bounds_for_range( + &mut self, + _: Range, + _: Bounds, + _: &mut Window, + _: &mut Context, + ) -> Option> { + Some(Bounds::new( + point( + self.bounds.left() + px(self.node.cursor_column as f32 * self.cell_width), + self.bounds.top() + + px(self.node.cursor_row.saturating_sub(self.top as u64) as f32 + * self.cell_height), + ), + size(px(self.cell_width), px(self.cell_height)), + )) + } + fn character_index_for_point( + &mut self, + _: gpui::Point, + _: &mut Window, + _: &mut Context, + ) -> Option { + Some(0) + } +} + +pub(crate) fn render( + node: TerminalComponentNode, + context: &mut ElementRenderContext<'_, '_>, +) -> gpui::AnyElement { + let id = format!("terminal-{}-{}", context.id_namespace, node.id); + context.active_input_ids.insert(id.clone()); + let terminal = if let Some(terminal) = context.terminal_entities.get(&id).cloned() { + terminal.update(context.cx, |terminal, cx| { + terminal.reconcile(node.clone(), context.window, cx) + }); + terminal + } else { + let terminal = context + .cx + .new(|cx| Terminal::new(node.clone(), context.runtime.clone(), context.window_id, cx)); + terminal.update(context.cx, |terminal, cx| { + terminal.reconcile(node.clone(), context.window, cx) + }); + context.terminal_entities.insert(id, terminal.clone()); + terminal + }; + if let Ok(mut handles) = context.runtime.focus_handles.lock() { + handles.insert( + (context.window_id, node.id.clone()), + terminal.read(context.cx).focus.clone(), + ); + } + let focus = terminal.read(context.cx).focus.clone(); + crate::element::request_native_focus( + &focus, + node.id.clone(), + if node.disabled { 0 } else { node.focus_request }, + context.runtime.clone(), + context.window_id, + context, + ); + crate::element::apply_generated_render_styles(div().size_full(), node.style) + .id(node.id.clone()) + .debug_selector(|| node.id) + .role(gpui::Role::TextInput) + .aria_label(node.label) + .child(terminal) + .into_any_element() +} + +pub(crate) fn render_row( + _node: TerminalRowComponentNode, + _context: &mut ElementRenderContext<'_, '_>, +) -> gpui::AnyElement { + div().into_any_element() +} +pub(crate) fn render_cell( + _node: TerminalCellComponentNode, + _context: &mut ElementRenderContext<'_, '_>, +) -> gpui::AnyElement { + div().into_any_element() +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn copied_selection_has_no_cursor_artifact_and_respects_wide_cells() { + let runs = vec![ + Run { + text: "ab".into(), + columns: 2, + color: None, + background: None, + bold: false, + italic: false, + }, + Run { + text: "界".into(), + columns: 2, + color: None, + background: None, + bold: false, + italic: false, + }, + Run { + text: "cd".into(), + columns: 2, + color: None, + background: None, + bold: false, + italic: false, + }, + ]; + assert_eq!(copy_row(&runs, 1, 5), "b界c"); + assert_eq!(copy_row(&runs, 3, 4), "界"); + } + + #[test] + fn composition_ranges_never_split_surrogate_pairs() { + assert_eq!(composition_range("a😀b", 1..3), (1..5, 1..3)); + assert_eq!(composition_range("a😀b", 2..3), (1..5, 1..3)); + assert_eq!(composition_range("a😀b", 99..100), (6..6, 4..4)); + } +} + +fn composition_range(text: &str, requested: Range) -> (Range, Range) { + let mut offsets = text + .char_indices() + .scan(0usize, |utf16, (byte, ch)| { + let point = (byte, *utf16); + *utf16 += ch.len_utf16(); + Some(point) + }) + .collect::>(); + offsets.push((text.len(), text.encode_utf16().count())); + let start = offsets + .iter() + .rev() + .find(|(_, n)| *n <= requested.start) + .copied() + .unwrap_or((0, 0)); + let end = offsets + .iter() + .find(|(_, n)| *n >= requested.end.max(requested.start)) + .copied() + .unwrap_or(*offsets.last().unwrap()); + (start.0..end.0, start.1..end.1) +} diff --git a/apps/gpui_native/native/src/element/component/tree.rs b/apps/gpui_native/native/src/element/component/tree.rs index 94570b85..f86dbefc 100644 --- a/apps/gpui_native/native/src/element/component/tree.rs +++ b/apps/gpui_native/native/src/element/component/tree.rs @@ -291,6 +291,7 @@ fn render_visible( id_namespace: format!("tree-{tree_id}-{item_id}"), active_input_ids: &mut active_input_ids, input_entities: &mut component.input_entities, + terminal_entities: &mut component.terminal_entities, components: &mut component.components, window, cx, @@ -347,6 +348,9 @@ fn render_visible( component .input_entities .retain(|input_id, _entity| active_input_ids.contains(input_id)); + component + .terminal_entities + .retain(|id, _entity| active_input_ids.contains(id)); component.components.finish_render(window, cx); let input_prefix = format!("gpui-elixir-input-{window_id}-tree-{tree_id}-"); diff --git a/apps/gpui_native/native/src/element/component/uniform_collection.rs b/apps/gpui_native/native/src/element/component/uniform_collection.rs index 53a6730d..9928fb62 100644 --- a/apps/gpui_native/native/src/element/component/uniform_collection.rs +++ b/apps/gpui_native/native/src/element/component/uniform_collection.rs @@ -13,6 +13,7 @@ pub(crate) struct ComponentUniformCollection { pub(crate) pending_requested_range: Option>, pub(crate) range_emit_scheduled: bool, pub(crate) input_entities: HashMap>, + pub(crate) terminal_entities: HashMap>, pub(crate) components: ComponentRegistry, } @@ -26,6 +27,7 @@ impl ComponentUniformCollection { pending_requested_range: None, range_emit_scheduled: false, input_entities: HashMap::new(), + terminal_entities: HashMap::new(), components: ComponentRegistry::default(), } } diff --git a/apps/gpui_native/native/src/element/component/virtual_collection.rs b/apps/gpui_native/native/src/element/component/virtual_collection.rs index daaf10f9..ef919ce7 100644 --- a/apps/gpui_native/native/src/element/component/virtual_collection.rs +++ b/apps/gpui_native/native/src/element/component/virtual_collection.rs @@ -24,6 +24,7 @@ pub(crate) struct ComponentVirtualCollection { #[derive(Default)] struct VirtualItemState { input_entities: std::collections::HashMap>, + terminal_entities: std::collections::HashMap>, components: crate::element::component_registry::ComponentRegistry, } @@ -234,6 +235,7 @@ fn render_variable_item( id_namespace: format!("variable-{collection_id}-{}", item.id), active_input_ids: &mut active_input_ids, input_entities: &mut item_state.input_entities, + terminal_entities: &mut item_state.terminal_entities, components: &mut item_state.components, window, cx, @@ -247,6 +249,9 @@ fn render_variable_item( item_state .input_entities .retain(|input_id, _entity| active_input_ids.contains(input_id)); + item_state + .terminal_entities + .retain(|id, _entity| active_input_ids.contains(id)); item_state.components.finish_render(window, cx); apply_generated_render_styles(gpui::div(), item.style.clone()) diff --git a/apps/gpui_native/native/src/element/component/virtual_list.rs b/apps/gpui_native/native/src/element/component/virtual_list.rs index 1eb4f821..8e6d5559 100644 --- a/apps/gpui_native/native/src/element/component/virtual_list.rs +++ b/apps/gpui_native/native/src/element/component/virtual_list.rs @@ -255,6 +255,7 @@ fn render_visible_items( id_namespace: format!("virtual-{list_id}-{item_id}"), active_input_ids: &mut active_input_ids, input_entities: &mut component.input_entities, + terminal_entities: &mut component.terminal_entities, components: &mut component.components, window, cx, @@ -291,6 +292,9 @@ fn render_visible_items( component .input_entities .retain(|input_id, _entity| active_input_ids.contains(input_id)); + component + .terminal_entities + .retain(|id, _entity| active_input_ids.contains(id)); component.components.finish_render(window, cx); let input_prefix = format!("gpui-elixir-input-{window_id}-virtual-{list_id}-"); diff --git a/apps/gpui_native/native/src/element/mod.rs b/apps/gpui_native/native/src/element/mod.rs index e726b861..0af3593d 100644 --- a/apps/gpui_native/native/src/element/mod.rs +++ b/apps/gpui_native/native/src/element/mod.rs @@ -17,6 +17,8 @@ pub(crate) struct ElementRenderContext<'a, 'cx> { pub(crate) id_namespace: String, pub(crate) active_input_ids: &'a mut HashSet, pub(crate) input_entities: &'a mut HashMap>, + pub(crate) terminal_entities: + &'a mut HashMap>, #[cfg(feature = "components")] pub(crate) components: &'a mut component_registry::ComponentRegistry, pub(crate) window: &'a mut gpui::Window, diff --git a/apps/gpui_native/native/src/generated/atoms.rs b/apps/gpui_native/native/src/generated/atoms.rs index 566aca13..5fa6e533 100644 --- a/apps/gpui_native/native/src/generated/atoms.rs +++ b/apps/gpui_native/native/src/generated/atoms.rs @@ -19,36 +19,38 @@ mod atoms { "children", cleanable = "cleanable", click = "click", clipboard = "clipboard", clipboard_text = "clipboard_text", clipboard_write = "clipboard_write", closable = "closable", close_button = "close_button", collapsed = "collapsed", collapsible - = "collapsible", color = "color", command = "command", commands = "commands", - compact = "compact", content = "content", copy = "copy", cursor = "cursor", dark - = "dark", dashed = "dashed", data = "data", decorations = "decorations", delay = - "delay", disabled = "disabled", display = "display", drag_enter = "drag_enter", - drag_leave = "drag_leave", drag_move = "drag_move", drop = "drop", edges = - "edges", error = "error", event = "event", expanded = "expanded", fallback = - "fallback", file_max_bytes = "file_max_bytes", file_prompt = "file_prompt", - file_read = "file_read", first = "first", fit = "fit", flex = "flex", flex_basis - = "flex_basis", flex_direction = "flex_direction", flex_grow = "flex_grow", - flex_shrink = "flex_shrink", flex_wrap = "flex_wrap", focus = "focus", - focus_request = "focus_request", follow = "follow", follow_request = - "follow_request", font_size = "font_size", font_weight = "font_weight", format = - "format", gap = "gap", geometry = "geometry", geometry_ranges = - "geometry_ranges", gpui_component = "gpui_component", hard_tabs = "hard_tabs", - header_height = "header_height", headless = "headless", height = "height", - hit_test = "hit_test", hoverable = "hoverable", id = "id", indeterminate = - "indeterminate", inline_projections = "inline_projections", inset = "inset", - inset_x = "inset_x", inset_y = "inset_y", invalid_position = "invalid_position", - invalid_range = "invalid_range", invalid_selection = "invalid_selection", - item_height = "item_height", justify_content = "justify_content", keyboard = - "keyboard", keydown = "keydown", keyup = "keyup", kind = "kind", label = "label", - last = "last", left = "left", level = "level", light = "light", line_height = - "line_height", link = "link", loading = "loading", margin = "margin", - margin_bottom = "margin_bottom", margin_left = "margin_left", margin_right = - "margin_right", margin_top = "margin_top", margin_x = "margin_x", margin_y = - "margin_y", masked = "masked", max = "max", max_columns = "max_columns", - max_height = "max_height", max_lines = "max_lines", max_sizes = "max_sizes", - max_width = "max_width", menu = "menu", min = "min", min_height = "min_height", - min_lines = "min_lines", min_sizes = "min_sizes", min_width = "min_width", - missing_resource = "missing_resource", mode = "mode", motion_delay = + = "collapsible", color = "color", columns = "columns", command = "command", + commands = "commands", compact = "compact", content = "content", copy = "copy", + cursor = "cursor", cursor_column = "cursor_column", cursor_row = "cursor_row", + cursor_visible = "cursor_visible", dark = "dark", dashed = "dashed", data = + "data", decorations = "decorations", delay = "delay", disabled = "disabled", + display = "display", drag_enter = "drag_enter", drag_leave = "drag_leave", + drag_move = "drag_move", drop = "drop", edges = "edges", error = "error", event = + "event", expanded = "expanded", fallback = "fallback", file_max_bytes = + "file_max_bytes", file_prompt = "file_prompt", file_read = "file_read", first = + "first", fit = "fit", flex = "flex", flex_basis = "flex_basis", flex_direction = + "flex_direction", flex_grow = "flex_grow", flex_shrink = "flex_shrink", flex_wrap + = "flex_wrap", focus = "focus", focus_request = "focus_request", follow = + "follow", follow_request = "follow_request", font_family = "font_family", + font_size = "font_size", font_weight = "font_weight", format = "format", gap = + "gap", geometry = "geometry", geometry_ranges = "geometry_ranges", gpui_component + = "gpui_component", hard_tabs = "hard_tabs", header_height = "header_height", + headless = "headless", height = "height", hit_test = "hit_test", hoverable = + "hoverable", id = "id", indeterminate = "indeterminate", inline_projections = + "inline_projections", inset = "inset", inset_x = "inset_x", inset_y = "inset_y", + invalid_position = "invalid_position", invalid_range = "invalid_range", + invalid_selection = "invalid_selection", italic = "italic", item_height = + "item_height", justify_content = "justify_content", keyboard = "keyboard", + keydown = "keydown", keystroke = "keystroke", keyup = "keyup", kind = "kind", + label = "label", last = "last", left = "left", level = "level", light = "light", + line_height = "line_height", link = "link", loading = "loading", margin = + "margin", margin_bottom = "margin_bottom", margin_left = "margin_left", + margin_right = "margin_right", margin_top = "margin_top", margin_x = "margin_x", + margin_y = "margin_y", masked = "masked", max = "max", max_columns = + "max_columns", max_height = "max_height", max_lines = "max_lines", max_sizes = + "max_sizes", max_width = "max_width", menu = "menu", min = "min", min_height = + "min_height", min_lines = "min_lines", min_sizes = "min_sizes", min_width = + "min_width", missing_resource = "missing_resource", mode = "mode", motion_delay = "motion_delay", motion_duration = "motion_duration", motion_easing = "motion_easing", motion_from_opacity = "motion_from_opacity", motion_from_x = "motion_from_x", motion_from_y = "motion_from_y", motion_policy = @@ -61,34 +63,36 @@ mod atoms { overlapping_edits = "overlapping_edits", overlay = "overlay", overscan = "overscan", padding = "padding", padding_bottom = "padding_bottom", padding_left = "padding_left", padding_right = "padding_right", padding_top = "padding_top", - padding_x = "padding_x", padding_y = "padding_y", parent_id = "parent_id", - phx_blur = "phx-blur", phx_bounds_change = "phx-bounds-change", phx_cell_change = - "phx-cell-change", phx_change = "phx-change", phx_click = "phx-click", - phx_clipboard_read = "phx-clipboard-read", phx_clipboard_write = + padding_x = "padding_x", padding_y = "padding_y", parent_id = "parent_id", paste + = "paste", phx_blur = "phx-blur", phx_bounds_change = "phx-bounds-change", + phx_cell_change = "phx-cell-change", phx_change = "phx-change", phx_click = + "phx-click", phx_clipboard_read = "phx-clipboard-read", phx_clipboard_write = "phx-clipboard-write", phx_copy = "phx-copy", phx_drag_enter = "phx-drag-enter", phx_drag_leave = "phx-drag-leave", phx_drag_move = "phx-drag-move", phx_drop = "phx-drop", phx_file_read = "phx-file-read", phx_focus = "phx-focus", phx_geometry_change = "phx-geometry-change", phx_hit_test = "phx-hit-test", - phx_keydown = "phx-keydown", phx_keyup = "phx-keyup", phx_link = "phx-link", - phx_range = "phx-range", phx_range_geometry_change = "phx-range-geometry-change", - phx_release = "phx-release", phx_search = "phx-search", phx_select = - "phx-select", phx_selection_change = "phx-selection-change", phx_sort = - "phx-sort", phx_submit = "phx-submit", phx_toggle = "phx-toggle", phx_transaction - = "phx-transaction", phx_viewport_change = "phx-viewport-change", placeholder = - "placeholder", position = "position", position_mode = "position_mode", position_x - = "position_x", position_y = "position_y", priority = "priority", range = - "range", range_geometry = "range_geometry", raster = "raster", reason = "reason", - reduced_transparency = "reduced_transparency", release = "release", - resize_request = "resize_request", resource_ref = "resource_ref", resource_type = - "resource_type", reveal = "reveal", reveal_index = "reveal_index", reveal_request - = "reveal_request", reveal_strategy = "reveal_strategy", reverse = "reverse", - revision = "revision", right = "right", runs = "runs", scale = "scale", - scroll_request = "scroll_request", scroll_to = "scroll_to", search = "search", - search_placeholder = "search_placeholder", select = "select", selectable = - "selectable", selected = "selected", selected_column = "selected_column", - selected_index = "selected_index", selection = "selection", set_size = - "set_size", show_line_numbers = "show_line_numbers", show_whitespaces = - "show_whitespaces", side = "side", size = "size", sizes = "sizes", soft_wrap = + phx_keydown = "phx-keydown", phx_keystroke = "phx-keystroke", phx_keyup = + "phx-keyup", phx_link = "phx-link", phx_paste = "phx-paste", phx_range = + "phx-range", phx_range_geometry_change = "phx-range-geometry-change", phx_release + = "phx-release", phx_resize = "phx-resize", phx_search = "phx-search", phx_select + = "phx-select", phx_selection_change = "phx-selection-change", phx_sort = + "phx-sort", phx_submit = "phx-submit", phx_text = "phx-text", phx_toggle = + "phx-toggle", phx_transaction = "phx-transaction", phx_viewport_change = + "phx-viewport-change", placeholder = "placeholder", position = "position", + position_mode = "position_mode", position_x = "position_x", position_y = + "position_y", priority = "priority", range = "range", range_geometry = + "range_geometry", raster = "raster", reason = "reason", reduced_transparency = + "reduced_transparency", release = "release", reset_request = "reset_request", + resize = "resize", resize_request = "resize_request", resource_ref = + "resource_ref", resource_type = "resource_type", reveal = "reveal", reveal_index + = "reveal_index", reveal_request = "reveal_request", reveal_strategy = + "reveal_strategy", reverse = "reverse", revision = "revision", right = "right", + runs = "runs", scale = "scale", scroll_request = "scroll_request", scroll_to = + "scroll_to", search = "search", search_placeholder = "search_placeholder", select + = "select", selectable = "selectable", selected = "selected", selected_column = + "selected_column", selected_index = "selected_index", selection = "selection", + set_size = "set_size", show_line_numbers = "show_line_numbers", show_whitespaces + = "show_whitespaces", side = "side", size = "size", sizes = "sizes", soft_wrap = "soft_wrap", sort = "sort", sort_column = "sort_column", sort_direction = "sort_direction", sortable = "sortable", stale_revision = "stale_revision", status = "status", step = "step", stride = "stride", style = "style", style_runs diff --git a/apps/gpui_native/native/src/generated/event_contract.rs b/apps/gpui_native/native/src/generated/event_contract.rs index d81eedd3..c3d798ae 100644 --- a/apps/gpui_native/native/src/generated/event_contract.rs +++ b/apps/gpui_native/native/src/generated/event_contract.rs @@ -7,6 +7,10 @@ pub(crate) enum NativeEvent { Click { window_id: u64, event: String }, Command { window_id: u64, event: String }, Input { kind: InputKind, window_id: u64, event: String, value: Option }, + #[cfg(feature = "real-gpui")] + Keystroke { window_id: u64, event: String, value: KeyStroke }, + #[cfg(feature = "real-gpui")] + TerminalResize { window_id: u64, event: String, value: TerminalSize }, #[cfg(feature = "components")] Transaction { window_id: u64, @@ -57,7 +61,7 @@ pub(crate) enum NativeEvent { WindowCloseRequest { window_id: u64 }, WindowFocus { focused: bool, window_id: u64 }, WindowClosed { window_id: u64 }, - #[cfg(feature = "components")] + #[cfg(feature = "real-gpui")] VirtualRange { window_id: u64, event: String, first: u64, last: u64 }, #[cfg(feature = "components")] FileDialog { @@ -87,6 +91,14 @@ pub(crate) fn encode_native_event<'a>( NativeEvent::Input { kind, window_id, event, value } => { encode_input_event(env, &kind, window_id, event, value) } + #[cfg(feature = "real-gpui")] + NativeEvent::Keystroke { window_id, event, value } => { + encode_keystroke_event(env, window_id, event, value) + } + #[cfg(feature = "real-gpui")] + NativeEvent::TerminalResize { window_id, event, value } => { + encode_terminal_resize_event(env, window_id, event, value) + } #[cfg(feature = "components")] NativeEvent::Transaction { window_id, event, transaction, revision } => { encode_revisioned_transaction_event( @@ -186,7 +198,7 @@ pub(crate) fn encode_native_event<'a>( NativeEvent::WindowClosed { window_id } => { encode_window_event(env, atoms::window_closed(), window_id) } - #[cfg(feature = "components")] + #[cfg(feature = "real-gpui")] NativeEvent::VirtualRange { window_id, event, first, last } => { encode_virtual_range_event(env, window_id, event, first, last) } diff --git a/apps/gpui_native/native/src/generated/event_payloads.rs b/apps/gpui_native/native/src/generated/event_payloads.rs index 0d817739..a1a809a1 100644 --- a/apps/gpui_native/native/src/generated/event_payloads.rs +++ b/apps/gpui_native/native/src/generated/event_payloads.rs @@ -11,6 +11,24 @@ pub(crate) struct ElementBoundsGeometry { pub(crate) coordinate_space: String, } #[derive(Clone, Debug, PartialEq, rustler::NifMap)] +#[cfg(feature = "real-gpui")] +pub(crate) struct KeyStroke { + pub(crate) key: String, + pub(crate) control: bool, + pub(crate) alt: bool, + pub(crate) shift: bool, + pub(crate) platform: bool, + pub(crate) repeat: bool, +} +#[derive(Clone, Debug, PartialEq, rustler::NifMap)] +#[cfg(feature = "real-gpui")] +pub(crate) struct TerminalSize { + pub(crate) columns: u64, + pub(crate) rows: u64, + pub(crate) cell_width: f64, + pub(crate) cell_height: f64, +} +#[derive(Clone, Debug, PartialEq, rustler::NifMap)] #[cfg_attr(not(feature = "components"), allow(dead_code))] pub(crate) struct TransferEventValue { pub(crate) session_id: u64, diff --git a/apps/gpui_native/native/src/generated/events.rs b/apps/gpui_native/native/src/generated/events.rs index e8495dd6..56d47a27 100644 --- a/apps/gpui_native/native/src/generated/events.rs +++ b/apps/gpui_native/native/src/generated/events.rs @@ -38,6 +38,11 @@ pub(crate) enum InputKind { Change, KeyDown, KeyUp, + Keystroke, + Text, + Paste, + Resize, + Range, DragEnter, DragMove, DragLeave, @@ -47,7 +52,6 @@ pub(crate) enum InputKind { FileRead, Select, Search, - Range, Link, CellChange, Sort, @@ -70,6 +74,11 @@ impl InputKind { Self::Change => atoms::change(), Self::KeyDown => atoms::keydown(), Self::KeyUp => atoms::keyup(), + Self::Keystroke => atoms::keystroke(), + Self::Text => atoms::text(), + Self::Paste => atoms::paste(), + Self::Resize => atoms::resize(), + Self::Range => atoms::range(), Self::DragEnter => atoms::drag_enter(), Self::DragMove => atoms::drag_move(), Self::DragLeave => atoms::drag_leave(), @@ -79,7 +88,6 @@ impl InputKind { Self::FileRead => atoms::file_read(), Self::Select => atoms::select(), Self::Search => atoms::search(), - Self::Range => atoms::range(), Self::Link => atoms::link(), Self::CellChange => atoms::cell_change(), Self::Sort => atoms::sort(), @@ -195,6 +203,38 @@ pub(crate) fn encode_value_event<'a>( ) } #[cfg(feature = "real-gpui")] +pub(crate) fn encode_virtual_range_event<'a>( + env: Env<'a>, + window_id: u64, + event: String, + first: u64, + last: u64, +) -> NifResult> { + let value = encode_event_map( + env, + vec![(atoms::first(), first.encode(env)), (atoms::last(), last.encode(env))], + )?; + encode_value_event(env, atoms::range(), window_id, event, value) +} +#[cfg(feature = "real-gpui")] +pub(crate) fn encode_keystroke_event<'a>( + env: Env<'a>, + window_id: u64, + event: String, + value: KeyStroke, +) -> NifResult> { + encode_value_event(env, atoms::keystroke(), window_id, event, value.encode(env)) +} +#[cfg(feature = "real-gpui")] +pub(crate) fn encode_terminal_resize_event<'a>( + env: Env<'a>, + window_id: u64, + event: String, + value: TerminalSize, +) -> NifResult> { + encode_value_event(env, atoms::resize(), window_id, event, value.encode(env)) +} +#[cfg(feature = "real-gpui")] pub(crate) fn encode_bounds_event<'a>( env: Env<'a>, window_id: u64, @@ -249,20 +289,6 @@ pub(crate) fn encode_transfer_event<'a>( encode_value_event(env, kind.atom(), window_id, event, value.encode(env)) } #[cfg(feature = "components")] -pub(crate) fn encode_virtual_range_event<'a>( - env: Env<'a>, - window_id: u64, - event: String, - first: u64, - last: u64, -) -> NifResult> { - let value = encode_event_map( - env, - vec![(atoms::first(), first.encode(env)), (atoms::last(), last.encode(env))], - )?; - encode_value_event(env, atoms::range(), window_id, event, value) -} -#[cfg(feature = "components")] pub(crate) fn encode_file_dialog_event<'a>( env: Env<'a>, window_id: u64, diff --git a/apps/gpui_native/native/src/generated/extensions.rs b/apps/gpui_native/native/src/generated/extensions.rs index 610fd731..1b380033 100644 --- a/apps/gpui_native/native/src/generated/extensions.rs +++ b/apps/gpui_native/native/src/generated/extensions.rs @@ -1,5 +1,13 @@ // This file is generated by RustQ. Do not edit by hand. +pub const TERMINAL_EXTENSION_VERSION: u32 = 1; +pub const TERMINAL_EXTENSION_CAPABILITIES: &[&str] = &[ + "cell_grid", + "raw_keyboard", + "committed_text", + "clipboard", + "cell_geometry", +]; pub const EDGE_FADE_EXTENSION_VERSION: u32 = 1; pub const EDGE_FADE_EXTENSION_CAPABILITIES: &[&str] = &[ "linear_gradient", diff --git a/apps/gpui_native/native/src/generated/schema.rs b/apps/gpui_native/native/src/generated/schema.rs index bea7448a..62c71e35 100644 --- a/apps/gpui_native/native/src/generated/schema.rs +++ b/apps/gpui_native/native/src/generated/schema.rs @@ -9,6 +9,9 @@ pub enum GeneratedComponentKind { Input, Image, Text, + TerminalComponent, + TerminalRowComponent, + TerminalCellComponent, EdgeFadeComponent, FrostComponent, PaintComponent, @@ -2204,6 +2207,107 @@ pub(crate) fn append_radio_option( #[derive(Clone, Debug)] #[cfg(feature = "real-gpui")] #[allow(dead_code)] +pub(crate) struct TerminalComponentNode { + pub(crate) style: StyleAttrs, + pub(crate) id: String, + pub(crate) label: String, + pub(crate) columns: u64, + pub(crate) cursor_row: u64, + pub(crate) cursor_column: u64, + pub(crate) cursor_visible: bool, + pub(crate) font_family: String, + pub(crate) font_size: f64, + pub(crate) line_height: f64, + pub(crate) focus_request: u64, + pub(crate) reset_request: u64, + pub(crate) disabled: bool, + pub(crate) children: Vec, + pub(crate) keystroke: Option, + pub(crate) text: Option, + pub(crate) paste: Option, + pub(crate) resize: Option, + pub(crate) range: Option, +} +#[cfg(feature = "real-gpui")] +#[allow(clippy::redundant_field_names)] +#[allow(clippy::useless_vec)] +pub(crate) fn decode_generated_terminal_component<'a>( + term: Term<'a>, +) -> NifResult { + require_extension_version(term, "terminal", 1)?; + Ok(TerminalComponentNode { + style: decode_style(term)?, + id: component_id(term)?, + label: component_required_string_attr(term, atoms::label())?, + columns: component_positive_integer_attr(term, atoms::columns())?.unwrap_or(80), + cursor_row: component_non_negative_integer_attr(term, atoms::cursor_row())? + .unwrap_or(0), + cursor_column: component_non_negative_integer_attr(term, atoms::cursor_column())? + .unwrap_or(0), + cursor_visible: component_bool_attr(term, atoms::cursor_visible())? + .unwrap_or(true), + font_family: component_string_attr(term, atoms::font_family())? + .unwrap_or_default(), + font_size: component_positive_number_attr(term, atoms::font_size())? + .unwrap_or(14.0), + line_height: component_positive_number_attr(term, atoms::line_height())? + .unwrap_or(20.0), + focus_request: component_non_negative_integer_attr(term, atoms::focus_request())? + .unwrap_or(0), + reset_request: component_non_negative_integer_attr(term, atoms::reset_request())? + .unwrap_or(0), + disabled: component_bool_attr(term, atoms::disabled())?.unwrap_or(false), + children: decode_children(term)?, + keystroke: component_string_attr(term, atoms::phx_keystroke())?, + text: component_string_attr(term, atoms::phx_text())?, + paste: component_string_attr(term, atoms::phx_paste())?, + resize: component_string_attr(term, atoms::phx_resize())?, + range: component_string_attr(term, atoms::phx_range())?, + }) +} +#[derive(Clone, Debug)] +#[cfg(feature = "real-gpui")] +#[allow(dead_code)] +pub(crate) struct TerminalRowComponentNode { + pub(crate) style: StyleAttrs, + pub(crate) children: Vec, +} +#[cfg(feature = "real-gpui")] +#[allow(clippy::redundant_field_names)] +#[allow(clippy::useless_vec)] +pub(crate) fn decode_generated_terminal_row_component<'a>( + term: Term<'a>, +) -> NifResult { + Ok(TerminalRowComponentNode { + style: decode_style(term)?, + children: decode_children(term)?, + }) +} +#[derive(Clone, Debug)] +#[cfg(feature = "real-gpui")] +#[allow(dead_code)] +pub(crate) struct TerminalCellComponentNode { + pub(crate) style: StyleAttrs, + pub(crate) text: String, + pub(crate) columns: u64, + pub(crate) italic: bool, +} +#[cfg(feature = "real-gpui")] +#[allow(clippy::redundant_field_names)] +#[allow(clippy::useless_vec)] +pub(crate) fn decode_generated_terminal_cell_component<'a>( + term: Term<'a>, +) -> NifResult { + Ok(TerminalCellComponentNode { + style: decode_style(term)?, + text: component_required_string_attr(term, atoms::text())?, + columns: component_positive_integer_attr(term, atoms::columns())?.unwrap_or(1), + italic: component_bool_attr(term, atoms::italic())?.unwrap_or(false), + }) +} +#[derive(Clone, Debug)] +#[cfg(feature = "real-gpui")] +#[allow(dead_code)] pub(crate) struct EdgeFadeComponentNode { pub(crate) style: StyleAttrs, pub(crate) id: String, @@ -3836,6 +3940,9 @@ pub(crate) enum ElementNode { AnchoredLayer(AnchoredLayerNode), TextSurface(TextSurfaceNode), Input(InputNode), + TerminalComponent(TerminalComponentNode), + TerminalRowComponent(TerminalRowComponentNode), + TerminalCellComponent(TerminalCellComponentNode), EdgeFadeComponent(EdgeFadeComponentNode), FrostComponent(FrostComponentNode), PaintComponent(PaintComponentNode), @@ -3901,6 +4008,9 @@ pub enum GeneratedElementTag { TextInput, Img, Text, + UiTerminal, + UiTerminalRow, + UiTerminalCell, UiEdgeFade, UiFrost, UiPaint, @@ -3965,6 +4075,9 @@ pub fn decode_generated_element_tag(tag: &str) -> GeneratedElementTag { "text_input" => GeneratedElementTag::TextInput, "img" => GeneratedElementTag::Img, "text" => GeneratedElementTag::Text, + "ui_terminal" => GeneratedElementTag::UiTerminal, + "ui_terminal_row" => GeneratedElementTag::UiTerminalRow, + "ui_terminal_cell" => GeneratedElementTag::UiTerminalCell, "ui_edge_fade" => GeneratedElementTag::UiEdgeFade, "ui_frost" => GeneratedElementTag::UiFrost, "ui_paint" => GeneratedElementTag::UiPaint, @@ -4030,6 +4143,13 @@ pub fn generated_component_kind(tag: GeneratedElementTag) -> GeneratedComponentK GeneratedElementTag::TextInput => GeneratedComponentKind::Input, GeneratedElementTag::Img => GeneratedComponentKind::Image, GeneratedElementTag::Text => GeneratedComponentKind::Text, + GeneratedElementTag::UiTerminal => GeneratedComponentKind::TerminalComponent, + GeneratedElementTag::UiTerminalRow => { + GeneratedComponentKind::TerminalRowComponent + } + GeneratedElementTag::UiTerminalCell => { + GeneratedComponentKind::TerminalCellComponent + } GeneratedElementTag::UiEdgeFade => GeneratedComponentKind::EdgeFadeComponent, GeneratedElementTag::UiFrost => GeneratedComponentKind::FrostComponent, GeneratedElementTag::UiPaint => GeneratedComponentKind::PaintComponent, @@ -4131,6 +4251,18 @@ pub(crate) fn decode_generated_element_node<'a>( GeneratedComponentKind::Input => decode_input_node(term, tag), GeneratedComponentKind::Image => decode_image_node(term, tag), GeneratedComponentKind::Text => decode_text_node(term, tag), + GeneratedComponentKind::TerminalComponent => { + decode_generated_terminal_component(term) + .map(|node| ElementNode::TerminalComponent(node)) + } + GeneratedComponentKind::TerminalRowComponent => { + decode_generated_terminal_row_component(term) + .map(|node| ElementNode::TerminalRowComponent(node)) + } + GeneratedComponentKind::TerminalCellComponent => { + decode_generated_terminal_cell_component(term) + .map(|node| ElementNode::TerminalCellComponent(node)) + } GeneratedComponentKind::EdgeFadeComponent => { decode_generated_edge_fade_component(term) .map(|node| ElementNode::EdgeFadeComponent(node)) @@ -4333,6 +4465,15 @@ pub(crate) fn render_generated_component_node( context: &mut element::ElementRenderContext<'_, '_>, ) -> gpui::AnyElement { match node { + ElementNode::TerminalComponent(node) => { + element::component::terminal::render(node, context) + } + ElementNode::TerminalRowComponent(node) => { + element::component::terminal::render_row(node, context) + } + ElementNode::TerminalCellComponent(node) => { + element::component::terminal::render_cell(node, context) + } ElementNode::EdgeFadeComponent(node) => { element::component::edge_fade::render_edge_fade(node, context) } diff --git a/apps/gpui_native/native/src/generated/vanilla_schema.rs b/apps/gpui_native/native/src/generated/vanilla_schema.rs index 59048a50..1a020581 100644 --- a/apps/gpui_native/native/src/generated/vanilla_schema.rs +++ b/apps/gpui_native/native/src/generated/vanilla_schema.rs @@ -9,6 +9,9 @@ pub enum GeneratedComponentKind { Input, Image, Text, + TerminalComponent, + TerminalRowComponent, + TerminalCellComponent, EdgeFadeComponent, FrostComponent, PaintComponent, @@ -2017,6 +2020,107 @@ impl AccessibilityRole { #[derive(Clone, Debug)] #[cfg(feature = "real-gpui")] #[allow(dead_code)] +pub(crate) struct TerminalComponentNode { + pub(crate) style: StyleAttrs, + pub(crate) id: String, + pub(crate) label: String, + pub(crate) columns: u64, + pub(crate) cursor_row: u64, + pub(crate) cursor_column: u64, + pub(crate) cursor_visible: bool, + pub(crate) font_family: String, + pub(crate) font_size: f64, + pub(crate) line_height: f64, + pub(crate) focus_request: u64, + pub(crate) reset_request: u64, + pub(crate) disabled: bool, + pub(crate) children: Vec, + pub(crate) keystroke: Option, + pub(crate) text: Option, + pub(crate) paste: Option, + pub(crate) resize: Option, + pub(crate) range: Option, +} +#[cfg(feature = "real-gpui")] +#[allow(clippy::redundant_field_names)] +#[allow(clippy::useless_vec)] +pub(crate) fn decode_generated_terminal_component<'a>( + term: Term<'a>, +) -> NifResult { + require_extension_version(term, "terminal", 1)?; + Ok(TerminalComponentNode { + style: decode_style(term)?, + id: component_id(term)?, + label: component_required_string_attr(term, atoms::label())?, + columns: component_positive_integer_attr(term, atoms::columns())?.unwrap_or(80), + cursor_row: component_non_negative_integer_attr(term, atoms::cursor_row())? + .unwrap_or(0), + cursor_column: component_non_negative_integer_attr(term, atoms::cursor_column())? + .unwrap_or(0), + cursor_visible: component_bool_attr(term, atoms::cursor_visible())? + .unwrap_or(true), + font_family: component_string_attr(term, atoms::font_family())? + .unwrap_or_default(), + font_size: component_positive_number_attr(term, atoms::font_size())? + .unwrap_or(14.0), + line_height: component_positive_number_attr(term, atoms::line_height())? + .unwrap_or(20.0), + focus_request: component_non_negative_integer_attr(term, atoms::focus_request())? + .unwrap_or(0), + reset_request: component_non_negative_integer_attr(term, atoms::reset_request())? + .unwrap_or(0), + disabled: component_bool_attr(term, atoms::disabled())?.unwrap_or(false), + children: decode_children(term)?, + keystroke: component_string_attr(term, atoms::phx_keystroke())?, + text: component_string_attr(term, atoms::phx_text())?, + paste: component_string_attr(term, atoms::phx_paste())?, + resize: component_string_attr(term, atoms::phx_resize())?, + range: component_string_attr(term, atoms::phx_range())?, + }) +} +#[derive(Clone, Debug)] +#[cfg(feature = "real-gpui")] +#[allow(dead_code)] +pub(crate) struct TerminalRowComponentNode { + pub(crate) style: StyleAttrs, + pub(crate) children: Vec, +} +#[cfg(feature = "real-gpui")] +#[allow(clippy::redundant_field_names)] +#[allow(clippy::useless_vec)] +pub(crate) fn decode_generated_terminal_row_component<'a>( + term: Term<'a>, +) -> NifResult { + Ok(TerminalRowComponentNode { + style: decode_style(term)?, + children: decode_children(term)?, + }) +} +#[derive(Clone, Debug)] +#[cfg(feature = "real-gpui")] +#[allow(dead_code)] +pub(crate) struct TerminalCellComponentNode { + pub(crate) style: StyleAttrs, + pub(crate) text: String, + pub(crate) columns: u64, + pub(crate) italic: bool, +} +#[cfg(feature = "real-gpui")] +#[allow(clippy::redundant_field_names)] +#[allow(clippy::useless_vec)] +pub(crate) fn decode_generated_terminal_cell_component<'a>( + term: Term<'a>, +) -> NifResult { + Ok(TerminalCellComponentNode { + style: decode_style(term)?, + text: component_required_string_attr(term, atoms::text())?, + columns: component_positive_integer_attr(term, atoms::columns())?.unwrap_or(1), + italic: component_bool_attr(term, atoms::italic())?.unwrap_or(false), + }) +} +#[derive(Clone, Debug)] +#[cfg(feature = "real-gpui")] +#[allow(dead_code)] pub(crate) struct EdgeFadeComponentNode { pub(crate) style: StyleAttrs, pub(crate) id: String, @@ -2109,6 +2213,9 @@ pub(crate) enum ElementNode { AnchoredLayer(AnchoredLayerNode), TextSurface(TextSurfaceNode), Input(InputNode), + TerminalComponent(TerminalComponentNode), + TerminalRowComponent(TerminalRowComponentNode), + TerminalCellComponent(TerminalCellComponentNode), EdgeFadeComponent(EdgeFadeComponentNode), FrostComponent(FrostComponentNode), PaintComponent(PaintComponentNode), @@ -2129,6 +2236,9 @@ pub enum GeneratedElementTag { TextInput, Img, Text, + UiTerminal, + UiTerminalRow, + UiTerminalCell, UiEdgeFade, UiFrost, UiPaint, @@ -2148,6 +2258,9 @@ pub fn decode_generated_element_tag(tag: &str) -> GeneratedElementTag { "text_input" => GeneratedElementTag::TextInput, "img" => GeneratedElementTag::Img, "text" => GeneratedElementTag::Text, + "ui_terminal" => GeneratedElementTag::UiTerminal, + "ui_terminal_row" => GeneratedElementTag::UiTerminalRow, + "ui_terminal_cell" => GeneratedElementTag::UiTerminalCell, "ui_edge_fade" => GeneratedElementTag::UiEdgeFade, "ui_frost" => GeneratedElementTag::UiFrost, "ui_paint" => GeneratedElementTag::UiPaint, @@ -2168,6 +2281,13 @@ pub fn generated_component_kind(tag: GeneratedElementTag) -> GeneratedComponentK GeneratedElementTag::TextInput => GeneratedComponentKind::Input, GeneratedElementTag::Img => GeneratedComponentKind::Image, GeneratedElementTag::Text => GeneratedComponentKind::Text, + GeneratedElementTag::UiTerminal => GeneratedComponentKind::TerminalComponent, + GeneratedElementTag::UiTerminalRow => { + GeneratedComponentKind::TerminalRowComponent + } + GeneratedElementTag::UiTerminalCell => { + GeneratedComponentKind::TerminalCellComponent + } GeneratedElementTag::UiEdgeFade => GeneratedComponentKind::EdgeFadeComponent, GeneratedElementTag::UiFrost => GeneratedComponentKind::FrostComponent, GeneratedElementTag::UiPaint => GeneratedComponentKind::PaintComponent, @@ -2188,6 +2308,18 @@ pub(crate) fn decode_generated_element_node<'a>( GeneratedComponentKind::Input => decode_input_node(term, tag), GeneratedComponentKind::Image => decode_image_node(term, tag), GeneratedComponentKind::Text => decode_text_node(term, tag), + GeneratedComponentKind::TerminalComponent => { + decode_generated_terminal_component(term) + .map(|node| ElementNode::TerminalComponent(node)) + } + GeneratedComponentKind::TerminalRowComponent => { + decode_generated_terminal_row_component(term) + .map(|node| ElementNode::TerminalRowComponent(node)) + } + GeneratedComponentKind::TerminalCellComponent => { + decode_generated_terminal_cell_component(term) + .map(|node| ElementNode::TerminalCellComponent(node)) + } GeneratedComponentKind::EdgeFadeComponent => { decode_generated_edge_fade_component(term) .map(|node| ElementNode::EdgeFadeComponent(node)) @@ -2211,6 +2343,15 @@ pub(crate) fn render_generated_component_node( context: &mut element::ElementRenderContext<'_, '_>, ) -> gpui::AnyElement { match node { + ElementNode::TerminalComponent(node) => { + element::component::terminal::render(node, context) + } + ElementNode::TerminalRowComponent(node) => { + element::component::terminal::render_row(node, context) + } + ElementNode::TerminalCellComponent(node) => { + element::component::terminal::render_cell(node, context) + } ElementNode::EdgeFadeComponent(node) => { element::component::edge_fade::render_edge_fade(node, context) } diff --git a/apps/gpui_native/native/src/window.rs b/apps/gpui_native/native/src/window.rs index ad612b06..8ba279ee 100644 --- a/apps/gpui_native/native/src/window.rs +++ b/apps/gpui_native/native/src/window.rs @@ -113,6 +113,7 @@ pub(crate) struct ElixirRoot { pub(crate) runtime: SharedRuntime, pub(crate) window_id: u64, input_entities: HashMap>, + terminal_entities: HashMap>, #[cfg(feature = "components")] pub(crate) components: crate::element::component_registry::ComponentRegistry, command_subscription: Option, @@ -142,6 +143,7 @@ impl ElixirRoot { runtime, window_id, input_entities: HashMap::new(), + terminal_entities: HashMap::new(), #[cfg(feature = "components")] components: crate::element::component_registry::ComponentRegistry::default(), command_subscription: None, @@ -211,7 +213,11 @@ impl ElixirRoot { #[cfg(not(feature = "components"))] let component_input_focused = false; - primitive_input_focused || component_input_focused + let terminal_focused = self + .terminal_entities + .values() + .any(|terminal| terminal.read(cx).input_focused(window)); + primitive_input_focused || component_input_focused || terminal_focused } fn observe_commands(&mut self, window: &gpui::Window, cx: &mut gpui::Context) { @@ -276,6 +282,7 @@ impl gpui::Render for ElixirRoot { id_namespace: "root".to_string(), active_input_ids: &mut active_input_ids, input_entities: &mut self.input_entities, + terminal_entities: &mut self.terminal_entities, #[cfg(feature = "components")] components: &mut self.components, window: _window, @@ -283,6 +290,8 @@ impl gpui::Render for ElixirRoot { }); self.input_entities .retain(|input_id, _entity| active_input_ids.contains(input_id)); + self.terminal_entities + .retain(|id, _entity| active_input_ids.contains(id)); #[cfg(feature = "components")] self.components.finish_render(_window, cx); diff --git a/apps/gpui_native/test/test/gpui/test/native/terminal_test.exs b/apps/gpui_native/test/test/gpui/test/native/terminal_test.exs new file mode 100644 index 00000000..1cb50868 --- /dev/null +++ b/apps/gpui_native/test/test/gpui/test/native/terminal_test.exs @@ -0,0 +1,171 @@ +defmodule GPUI.Test.Native.TerminalTest do + use GPUI.Test, native: [size: {480, 240}] + + defmodule View do + use GPUI.View + + def render(assigns) do + GPUI.Terminal.surface(%{ + id: "terminal", + label: "Console", + columns: 40, + rows: Map.get(assigns, :rows, [[%{text: "remote$ ", columns: 8}]]), + cursor_column: 8, + focus_request: 1, + disabled: Map.get(assigns, :disabled, false), + style: [width: {:px, 480}, height: {:px, 240}], + "phx-keystroke": "key", + "phx-text": "text", + "phx-paste": "paste", + "phx-resize": "size", + "phx-range": "visible" + }) + end + end + + test "typing is committed text, not a cumulative local command buffer", %{ui: ui} do + render(ui, View, %{}) + settle(ui) + focus(ui, "terminal") + type(ui, "abc") + + for text <- ["a", "b", "c"] do + assert_receive {:gpui, ^ui, {:event, %{type: :text, event: "text", value: ^text}}} + end + + press(ui, "up") + assert_receive {:gpui, ^ui, {:event, %{type: :keystroke, value: %{key: "up"}}}} + type(ui, "界") + assert_receive {:gpui, ^ui, {:event, %{type: :text, value: "界"}}} + refute_receive {:gpui, ^ui, {:event, %{type: :text, value: "abc界"}}} + end + + test "backspace, delete, arrows, Enter and control/meta chords carry modifiers", %{ui: ui} do + render(ui, View, %{}) + settle(ui) + focus(ui, "terminal") + + for key <- ["backspace", "delete", "left", "enter"] do + press(ui, key) + assert_receive {:gpui, ^ui, {:event, %{type: :keystroke, value: %{key: ^key}}}} + end + + press(ui, "ctrl-c") + assert_receive {:gpui, ^ui, {:event, %{type: :keystroke, value: %{key: "c", control: true}}}} + press(ui, "alt-b") + assert_receive {:gpui, ^ui, {:event, %{type: :keystroke, value: %{key: "b", alt: true}}}} + refute_receive {:gpui, ^ui, {:event, %{type: :text}}} + end + + test "viewport dimensions come from measured cells", %{ui: ui} do + render(ui, View, %{}) + settle(ui) + assert_receive {:gpui, ^ui, {:event, %{type: :resize, value: size}}} + viewport = bounds(ui, "terminal") + assert size.cell_width > 0 + assert size.cell_height == 20 + assert size.columns == min(512, trunc(viewport.width / size.cell_width)) + assert size.rows == min(256, trunc(viewport.height / size.cell_height)) + end + + test "styled cells cross the same native style boundary as ordinary text", %{ui: ui} do + render(ui, View, + rows: [ + [ + %{ + text: "ready", + columns: 5, + color: {:rgb, 0x00FF00}, + background: {:rgb, 0x19191E}, + font_weight: "bold", + font_style: "italic" + } + ] + ] + ) + + settle(ui) + assert bounds(ui, "terminal").width == 480 + end + + test "disabled and restored surfaces complete frames without losing their input identity", %{ + ui: ui + } do + render(ui, View, %{}) + settle(ui) + + for _ <- 1..5 do + render(ui, View, disabled: true) + settle(ui) + focus(ui, "terminal") + type(ui, "ignored") + refute_receive {:gpui, ^ui, {:event, %{type: :text}}} + render(ui, View, disabled: false) + settle(ui) + focus(ui, "terminal") + type(ui, "z") + assert_receive {:gpui, ^ui, {:event, %{type: :text, value: "z"}}} + end + end + + defmodule ClipboardView do + use GPUI.View + alias GPUI.UI + + def render(assigns) do + ~GPUI""" +
+ {GPUI.Test.Native.TerminalTest.View.render(assigns)} + + +
+ """ + end + end + + test "clipboard paste preserves multiline text without emitting ordinary text twice", %{ui: ui} do + render(ui, ClipboardView, %{}) + settle(ui) + click(ui, "seed") + assert_receive {:gpui, ^ui, {:event, %{event: "seeded"}}} + focus(ui, "terminal") + press(ui, "cmd-v") + assert_receive {:gpui, ^ui, {:event, %{type: :paste, value: "first\nsecond"}}} + refute_receive {:gpui, ^ui, {:event, %{type: :text}}} + end + + test "native selection copies retained rows without cursor decorations", %{ui: ui} do + render(ui, ClipboardView, + rows: [ + [%{text: "first", columns: 5}], + [%{text: "界", columns: 2}, %{text: "x", columns: 1}] + ] + ) + + settle(ui) + focus(ui, "terminal") + press(ui, "cmd-a") + press(ui, "cmd-c") + click(ui, "read") + assert_receive {:gpui, ^ui, {:event, %{type: :clipboard, value: %{text: "first\n界x"}}}} + end + + test "scrollback stays put until input returns it to the tail", %{ui: ui} do + rows = + for n <- 1..50 do + text = "line #{n}" + [%{text: text, columns: byte_size(text)}] + end + + render(ui, View, rows: rows) + settle(ui) + focus(ui, "terminal") + assert_receive {:gpui, ^ui, {:event, %{type: :range, value: %{first: 38, last: 50}}}} + press(ui, "shift-pageup") + assert_receive {:gpui, ^ui, {:event, %{type: :range, value: %{first: 27, last: 39}}}} + type(ui, "x") + assert_receive {:gpui, ^ui, {:event, %{type: :text, value: "x"}}} + assert_receive {:gpui, ^ui, {:event, %{type: :range, value: %{first: 38, last: 50}}}} + end +end diff --git a/codegen/gpui/codegen/native/event/contract.ex b/codegen/gpui/codegen/native/event/contract.ex index 2bbed651..86aed0a4 100644 --- a/codegen/gpui/codegen/native/event/contract.ex +++ b/codegen/gpui/codegen/native/event/contract.ex @@ -16,7 +16,11 @@ defmodule GPUI.Codegen.Native.Event.Contract do {:Click, nil, named, :encode_named_event, [:env, atom(:click), :window_id, :event]}, {:Command, nil, named, :encode_named_event, [:env, atom(:command), :window_id, :event]}, {:Input, nil, [kind: quote(do: InputKind.t())] ++ named ++ [value: value], - :encode_input_event, [:env, A.ref(:kind), :window_id, :event, :value]} + :encode_input_event, [:env, A.ref(:kind), :window_id, :event, :value]}, + {:Keystroke, "real-gpui", named ++ [value: quote(do: KeyStroke.t())], + :encode_keystroke_event, [:env, :window_id, :event, :value]}, + {:TerminalResize, "real-gpui", named ++ [value: quote(do: TerminalSize.t())], + :encode_terminal_resize_event, [:env, :window_id, :event, :value]} ] ++ revisioned(named) ++ [ @@ -46,7 +50,7 @@ defmodule GPUI.Codegen.Native.Event.Contract do ]}, {:WindowClosed, nil, window, :encode_window_event, [:env, atom(:window_closed), :window_id]}, - {:VirtualRange, "components", + {:VirtualRange, "real-gpui", named ++ [first: quote(do: RustQ.Type.u64()), last: quote(do: RustQ.Type.u64())], :encode_virtual_range_event, [:env, :window_id, :event, :first, :last]}, {:FileDialog, "components", diff --git a/codegen/gpui/codegen/native/event/payloads.ex b/codegen/gpui/codegen/native/event/payloads.ex index 59af7872..bee2d32f 100644 --- a/codegen/gpui/codegen/native/event/payloads.ex +++ b/codegen/gpui/codegen/native/event/payloads.ex @@ -16,6 +16,22 @@ defmodule GPUI.Codegen.Native.Event.Payloads do required(:coordinate_space) => String.t() } + @type key_stroke :: %{ + required(:key) => String.t(), + required(:control) => boolean(), + required(:alt) => boolean(), + required(:shift) => boolean(), + required(:platform) => boolean(), + required(:repeat) => boolean() + } + + @type terminal_size :: %{ + required(:columns) => R.u64(), + required(:rows) => R.u64(), + required(:cell_width) => R.f64(), + required(:cell_height) => R.f64() + } + @type transfer_payload :: %{ required(:text) => R.option(String.t()), required(:external_paths) => R.vec(String.t()) @@ -34,7 +50,13 @@ defmodule GPUI.Codegen.Native.Event.Payloads do def items do MetaAST.struct_type_items( __MODULE__, - [:element_bounds_geometry, :transfer_payload, :transfer_event_value], + [ + :element_bounds_geometry, + :key_stroke, + :terminal_size, + :transfer_payload, + :transfer_event_value + ], derive: [:Clone, :Debug, :PartialEq, :"rustler::NifMap"], vis: :crate, field_vis: :crate, @@ -44,6 +66,9 @@ defmodule GPUI.Codegen.Native.Event.Payloads do %{name: :ElementBoundsGeometry} = item -> %{item | attrs: [A.attr(:cfg, feature: "real-gpui")]} + %{name: name} = item when name in [:KeyStroke, :TerminalSize] -> + %{item | attrs: [A.attr(:cfg, feature: "real-gpui")]} + item -> %{item | attrs: [A.attr(:cfg_attr, not: [feature: "components"], allow: [:dead_code])]} end) diff --git a/codegen/gpui/codegen/native/events.ex b/codegen/gpui/codegen/native/events.ex index b737cfdd..60ffefe8 100644 --- a/codegen/gpui/codegen/native/events.ex +++ b/codegen/gpui/codegen/native/events.ex @@ -25,6 +25,18 @@ defmodule GPUI.Codegen.Native.Events do Definitions.define_input_kind(:gpui_component) Definitions.define_event_impls(:gpui_component) + @spec encode_keystroke_event(Env.t(R.lifetime(:a)), R.u64(), String.t(), KeyStroke.t()) :: + R.nif_result(Term.t(R.lifetime(:a))) + defrust(encode_keystroke_event(env, window_id, event, value), + do: encode_value_event(env, Atoms.keystroke(), window_id, event, value.encode(env)) + ) + + @spec encode_terminal_resize_event(Env.t(R.lifetime(:a)), R.u64(), String.t(), TerminalSize.t()) :: + R.nif_result(Term.t(R.lifetime(:a))) + defrust(encode_terminal_resize_event(env, window_id, event, value), + do: encode_value_event(env, Atoms.resize(), window_id, event, value.encode(env)) + ) + @spec encode_file_dialog_event( Env.t(R.lifetime(:a)), R.u64(), @@ -421,6 +433,9 @@ defmodule GPUI.Codegen.Native.Events do ] real_gpui_only = [ + :encode_virtual_range_event, + :encode_keystroke_event, + :encode_terminal_resize_event, :encode_bounds_event, :encode_focus_event, :encode_missing_resource_event @@ -429,7 +444,6 @@ defmodule GPUI.Codegen.Native.Events do component_only = [ :encode_clipboard_event, :encode_transfer_event, - :encode_virtual_range_event, :encode_file_dialog_event, :encode_file_dialog_selected, :encode_file_dialog_cancelled, diff --git a/test/gpui/codegen/native/event/contract_test.exs b/test/gpui/codegen/native/event/contract_test.exs index 519f14c2..7de01527 100644 --- a/test/gpui/codegen/native/event/contract_test.exs +++ b/test/gpui/codegen/native/event/contract_test.exs @@ -15,6 +15,8 @@ defmodule GPUI.Codegen.Native.Event.ContractTest do :Click, :Command, :Input, + :Keystroke, + :TerminalResize, :Transaction, :Selection, :Viewport, From e8827a8c8f4fe0d396742539922e259f2d9b8021 Mon Sep 17 00:00:00 2001 From: Chris McCord Date: Sat, 17 Oct 2026 16:55:16 -0400 Subject: [PATCH 2/2] Send Tab to terminals and report Up/Down from one-line inputs A focused terminal now binds Tab and Shift-Tab in its own key context, so they reach the remote shell (completion, reverse completion) instead of the window's focus traversal. A disabled terminal still lets Tab move focus on. UI.input accepts phx-keydown. A one-line input has no use for Up and Down, so it reports them, captured before the input's own no-op handlers stop them; a search box can move a highlight through its results. --- .../gpui/components/schema_declarations.ex | 1 + .../native/src/generated/host_contract.rs | 2 + .../native/src/generated/schema.rs | 2 + .../native/src/element/component/form.rs | 29 +++++++++++- .../native/src/element/component/terminal.rs | 47 +++++++++++++++++-- .../native/src/generated/schema.rs | 2 + apps/gpui_native/native/src/native_test.rs | 1 + apps/gpui_native/native/src/window.rs | 1 + .../test/gpui/test/native/controls_test.exs | 29 ++++++++++++ .../test/gpui/test/native/terminal_test.exs | 37 +++++++++++++++ 10 files changed, 145 insertions(+), 6 deletions(-) diff --git a/apps/gpui_components/lib/gpui/components/schema_declarations.ex b/apps/gpui_components/lib/gpui/components/schema_declarations.ex index 69db4a4c..f45478de 100644 --- a/apps/gpui_components/lib/gpui/components/schema_declarations.ex +++ b/apps/gpui_components/lib/gpui/components/schema_declarations.ex @@ -355,6 +355,7 @@ defmodule GPUI.Components.Schema.Declarations do events: [ change: :"phx-change", submit: :"phx-submit", + keydown: :"phx-keydown", focus: :"phx-focus", blur: :"phx-blur" ], diff --git a/apps/gpui_components/native/src/generated/host_contract.rs b/apps/gpui_components/native/src/generated/host_contract.rs index 719979dc..86820cc5 100644 --- a/apps/gpui_components/native/src/generated/host_contract.rs +++ b/apps/gpui_components/native/src/generated/host_contract.rs @@ -21,6 +21,7 @@ pub enum ComponentEvent { FileRead(ComponentFileDialogEvent), Select(ComponentValueEvent), Submit(ComponentValueEvent), + Keydown(ComponentInputEvent), Focus(ComponentEventEnvelope), Blur(ComponentEventEnvelope), Search(ComponentValueEvent), @@ -45,6 +46,7 @@ impl ComponentEvent { Self::FileRead(value) => &value.envelope, Self::Select(value) => &value.envelope, Self::Submit(value) => &value.envelope, + Self::Keydown(value) => &value.envelope, Self::Focus(value) => value, Self::Blur(value) => value, Self::Search(value) => &value.envelope, diff --git a/apps/gpui_components/native/src/generated/schema.rs b/apps/gpui_components/native/src/generated/schema.rs index 62c71e35..b50ef531 100644 --- a/apps/gpui_components/native/src/generated/schema.rs +++ b/apps/gpui_components/native/src/generated/schema.rs @@ -2875,6 +2875,7 @@ pub(crate) struct InputComponentNode { pub(crate) loading: bool, pub(crate) change: Option, pub(crate) submit: Option, + pub(crate) keydown: Option, pub(crate) focus: Option, pub(crate) blur: Option, } @@ -2899,6 +2900,7 @@ pub(crate) fn decode_generated_input_component<'a>( loading: component_bool_attr(term, atoms::loading())?.unwrap_or(false), change: component_string_attr(term, atoms::phx_change())?, submit: component_string_attr(term, atoms::phx_submit())?, + keydown: component_string_attr(term, atoms::phx_keydown())?, focus: component_string_attr(term, atoms::phx_focus())?, blur: component_string_attr(term, atoms::phx_blur())?, }) diff --git a/apps/gpui_native/native/src/element/component/form.rs b/apps/gpui_native/native/src/element/component/form.rs index 43c4ce0f..a48e5b07 100644 --- a/apps/gpui_native/native/src/element/component/form.rs +++ b/apps/gpui_native/native/src/element/component/form.rs @@ -299,6 +299,33 @@ pub(crate) fn render_input_component( .flex() .w_full() .h(gpui::px(component_height)); + + // A one-line input ignores Up and Down, so they are reported instead: a + // search box can move a highlight through its results. They are captured + // on the way down, before the input's own no-op handlers stop them. + if let Some(event) = node.keydown.clone() { + let runtime = context.runtime.clone(); + let window_id = context.window_id; + + let report = move |key: &'static str| { + let _ = push_event( + &runtime, + NativeEvent::Input { + kind: InputKind::KeyDown, + window_id, + event: event.clone(), + value: Some(EventValue::String(key.to_string())), + }, + ); + }; + + let report_down = report.clone(); + accessible_element = accessible_element + .capture_action(move |_: &gpui_component::input::MoveUp, _window, _cx| report("up")) + .capture_action(move |_: &gpui_component::input::MoveDown, _window, _cx| { + report_down("down") + }); + } if let Some(value) = accessibility_value { accessible_element = accessible_element.aria_value(value); } @@ -730,7 +757,7 @@ pub(crate) fn render_input_component( placeholder: node.placeholder, focus_request: node.focus_request, change: node.change, - keydown: None, + keydown: node.keydown, keyup: None, focus: node.focus, blur: node.blur, diff --git a/apps/gpui_native/native/src/element/component/terminal.rs b/apps/gpui_native/native/src/element/component/terminal.rs index 9fe61a89..82f519ac 100644 --- a/apps/gpui_native/native/src/element/component/terminal.rs +++ b/apps/gpui_native/native/src/element/component/terminal.rs @@ -5,14 +5,28 @@ use crate::{ TerminalComponentNode, TerminalRowComponentNode, }; use gpui::{ - div, fill, point, px, size, App, AppContext, Bounds, ClipboardItem, Context, + actions, div, fill, point, px, size, App, AppContext, Bounds, ClipboardItem, Context, ElementInputHandler, EntityInputHandler, FocusHandle, InteractiveElement, IntoElement, - KeyDownEvent, MouseButton, ParentElement, Pixels, Render, ShapedLine, + KeyBinding, KeyDownEvent, Modifiers, MouseButton, ParentElement, Pixels, Render, ShapedLine, StatefulInteractiveElement, Styled, TextAlign, TextRun, UTF16Selection, Window, }; use std::ops::Range; use unicode_segmentation::UnicodeSegmentation; +actions!(gpui_terminal, [SendTab, SendBackTab]); + +const KEY_CONTEXT: &str = "GPUITerminal"; + +/// Binds Tab and Shift-Tab inside a focused terminal, where they belong to the +/// remote shell (completion, reverse completion) rather than moving focus. The +/// terminal's context sits deeper than any window-level binding, so these win. +pub(crate) fn bind_terminal_keys(cx: &mut App) { + cx.bind_keys([ + KeyBinding::new("tab", SendTab, Some(KEY_CONTEXT)), + KeyBinding::new("shift-tab", SendBackTab, Some(KEY_CONTEXT)), + ]); +} + const MAX_INPUT_BYTES: usize = 1_048_576; const MAX_ROWS: usize = 10_000; const MAX_TEXT_BYTES: usize = 8 * 1_048_576; @@ -249,6 +263,11 @@ impl Terminal { if !mods.control && !mods.alt && (key.chars().count() == 1 || key == "space") { return; } + self.send_keystroke(key, mods, event.is_held, cx); + cx.stop_propagation(); + } + + fn send_keystroke(&mut self, key: &str, mods: Modifiers, repeat: bool, cx: &mut Context) { self.tail = true; self.selection = None; self.clamp_scroll(); @@ -264,15 +283,31 @@ impl Terminal { alt: mods.alt, shift: mods.shift, platform: mods.platform, - repeat: event.is_held, + repeat, }, }, ); } - cx.stop_propagation(); cx.notify(); } + // A disabled terminal leaves Tab to the window, which moves focus on. + fn send_tab(&mut self, _: &SendTab, _window: &mut Window, cx: &mut Context) { + if self.node.disabled { + cx.propagate(); + return; + } + self.send_keystroke("tab", Modifiers::default(), false, cx); + } + + fn send_back_tab(&mut self, _: &SendBackTab, _window: &mut Window, cx: &mut Context) { + if self.node.disabled { + cx.propagate(); + return; + } + self.send_keystroke("tab", Modifiers::shift(), false, cx); + } + fn point(&self, position: gpui::Point) -> CellPoint { let row = ((f32::from(position.y - self.bounds.top()) / self.cell_height) .floor() @@ -611,9 +646,11 @@ impl Render for Terminal { .relative() .overflow_hidden() .id("terminal-input") - .key_context("GPUITerminal") + .key_context(KEY_CONTEXT) .track_focus(&self.focus) .on_key_down(cx.listener(Self::key_down)) + .on_action(cx.listener(Self::send_tab)) + .on_action(cx.listener(Self::send_back_tab)) .on_mouse_down( MouseButton::Left, cx.listener(|this, event: &gpui::MouseDownEvent, window, cx| { diff --git a/apps/gpui_native/native/src/generated/schema.rs b/apps/gpui_native/native/src/generated/schema.rs index 62c71e35..b50ef531 100644 --- a/apps/gpui_native/native/src/generated/schema.rs +++ b/apps/gpui_native/native/src/generated/schema.rs @@ -2875,6 +2875,7 @@ pub(crate) struct InputComponentNode { pub(crate) loading: bool, pub(crate) change: Option, pub(crate) submit: Option, + pub(crate) keydown: Option, pub(crate) focus: Option, pub(crate) blur: Option, } @@ -2899,6 +2900,7 @@ pub(crate) fn decode_generated_input_component<'a>( loading: component_bool_attr(term, atoms::loading())?.unwrap_or(false), change: component_string_attr(term, atoms::phx_change())?, submit: component_string_attr(term, atoms::phx_submit())?, + keydown: component_string_attr(term, atoms::phx_keydown())?, focus: component_string_attr(term, atoms::phx_focus())?, blur: component_string_attr(term, atoms::phx_blur())?, }) diff --git a/apps/gpui_native/native/src/native_test.rs b/apps/gpui_native/native/src/native_test.rs index 61e3fee0..da39df93 100644 --- a/apps/gpui_native/native/src/native_test.rs +++ b/apps/gpui_native/native/src/native_test.rs @@ -163,6 +163,7 @@ fn initialize(width: f32, height: f32) -> TestSession { let mut app = gpui::TestAppContext::single(); app.update(gpui_component::init); + app.update(crate::element::component::terminal::bind_terminal_keys); let runtime = Arc::new(crate::runtime::RuntimeState::new()); let state = Arc::new(crate::WindowState::new( ElementNode::empty_root(), diff --git a/apps/gpui_native/native/src/window.rs b/apps/gpui_native/native/src/window.rs index 8ba279ee..21d40848 100644 --- a/apps/gpui_native/native/src/window.rs +++ b/apps/gpui_native/native/src/window.rs @@ -523,6 +523,7 @@ pub(crate) fn run_gpui( gpui_component::init(cx); bind_input_keys(cx); + crate::element::component::terminal::bind_terminal_keys(cx); let window_closed_subscription = cx.on_window_closed(move |_cx, platform_id| { let _ = command_tx.unbounded_send(WindowCommand::PlatformClosed { platform_id }); diff --git a/apps/gpui_native/test/test/gpui/test/native/controls_test.exs b/apps/gpui_native/test/test/gpui/test/native/controls_test.exs index 533930fb..7ff8ab4a 100644 --- a/apps/gpui_native/test/test/gpui/test/native/controls_test.exs +++ b/apps/gpui_native/test/test/gpui/test/native/controls_test.exs @@ -85,6 +85,35 @@ defmodule GPUI.Test.Native.ControlsTest do {:event, %{type: :change, event: "name_changed", value: "X\nAda"}}} end + defmodule NavigableInputView do + use GPUI.View + + @impl GPUI.View + def render(assigns) do + ~GPUI""" + + """ + end + end + + # A one-line input has no use for Up and Down, so a search box can move a + # highlight through its results with them. + test "a single-line input reports Up and Down and keeps editing its text", %{ui: ui} do + render(ui, NavigableInputView, value: "") + settle(ui) + + press(ui, :arrow_down) + assert_receive {:gpui, ^ui, {:event, %{type: :keydown, event: "search_key", value: "down"}}} + press(ui, :arrow_up) + assert_receive {:gpui, ^ui, {:event, %{type: :keydown, event: "search_key", value: "up"}}} + + type(ui, "ab") + assert_receive {:gpui, ^ui, {:event, %{type: :change, event: "search_changed", value: "a"}}} + render(ui, NavigableInputView, value: "a") + assert_receive {:gpui, ^ui, {:event, %{type: :change, event: "search_changed", value: "ab"}}} + end + test "controlled input restores rejected edits and blocks disabled typing", %{ui: ui} do render_input(ui) settle(ui) diff --git a/apps/gpui_native/test/test/gpui/test/native/terminal_test.exs b/apps/gpui_native/test/test/gpui/test/native/terminal_test.exs index 1cb50868..85496965 100644 --- a/apps/gpui_native/test/test/gpui/test/native/terminal_test.exs +++ b/apps/gpui_native/test/test/gpui/test/native/terminal_test.exs @@ -57,6 +57,43 @@ defmodule GPUI.Test.Native.TerminalTest do refute_receive {:gpui, ^ui, {:event, %{type: :text}}} end + defmodule TabView do + use GPUI.View + alias GPUI.UI + + def render(assigns) do + ~GPUI""" +
+ {GPUI.Test.Native.TerminalTest.View.render(assigns)} + +
+ """ + end + end + + test "Tab and Shift-Tab reach a focused terminal instead of moving focus", %{ui: ui} do + render(ui, TabView, %{}) + settle(ui) + focus(ui, "terminal") + + press(ui, "tab") + assert_receive {:gpui, ^ui, {:event, %{type: :keystroke, value: %{key: "tab", shift: false}}}} + press(ui, "shift-tab") + assert_receive {:gpui, ^ui, {:event, %{type: :keystroke, value: %{key: "tab", shift: true}}}} + + # Focus stayed in the terminal. + type(ui, "x") + assert_receive {:gpui, ^ui, {:event, %{type: :text, value: "x"}}} + end + + test "a disabled terminal lets Tab move focus on", %{ui: ui} do + render(ui, TabView, disabled: true) + settle(ui) + focus(ui, "terminal") + press(ui, "tab") + refute_receive {:gpui, ^ui, {:event, %{type: :keystroke}}} + end + test "viewport dimensions come from measured cells", %{ui: ui} do render(ui, View, %{}) settle(ui)