Truly independent web browser
LibWebView: Add a headless mode that shows the page in a terminal
Aliaksandr Kalenik19072f460895
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cppindex 7b494193bef..37fd07305dd 100644--- a/Libraries/LibWebView/Application.cpp+++ b/Libraries/LibWebView/Application.cpp@@ -81,6 +81,10 @@#include <LibWebView/WebDriverBrowserConnection.h>#include <LibWebView/WorkerAgentManager.h>+#if !defined(AK_OS_WINDOWS)+# include <LibWebView/TerminalWebView.h>+#endif+#if defined(AK_OS_MACOS)# include <LibIPC/MachBootstrapListener.h># include <LibIPC/Transport.h>@@ -292,6 +296,7 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)Optional<HeadlessMode> headless_mode;Optional<int> window_width;Optional<int> window_height;+ Optional<double> device_pixel_ratio;Optional<u32> screenshot_delay;Optional<StringView> screenshot_path;bool new_window = false;@@ -343,7 +348,7 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)args_parser.add_option(Core::ArgsParser::Option {.argument_mode = Core::ArgsParser::OptionArgumentMode::Optional,- .help_string = "Run Ladybird without a browser window. Mode may be 'screenshot' (default), 'layout-tree', 'text', or 'manual'.",+ .help_string = "Run Ladybird without a browser window. Mode may be 'screenshot' (default), 'layout-tree', 'text', 'manual', or 'terminal'.",.long_name = "headless",.value_name = "mode",.accept_value = [&](StringView value) {@@ -358,6 +363,10 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)headless_mode = HeadlessMode::Text;else if (value.equals_ignoring_ascii_case("manual"sv))headless_mode = HeadlessMode::Manual;+#if !defined(AK_OS_WINDOWS)+ else if (value.equals_ignoring_ascii_case("terminal"sv))+ headless_mode = HeadlessMode::Terminal;+#endifreturn headless_mode.has_value();},@@ -367,6 +376,7 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)args_parser.add_option(screenshot_path, "Save screenshots to the given location (only supported for headless screenshot mode)", "screenshot-path", 0, "path");args_parser.add_option(window_width, "Set viewport width in pixels (default: 800) (currently only supported for headless mode)", "window-width", 0, "pixels");args_parser.add_option(window_height, "Set viewport height in pixels (default: 600) (currently only supported for headless mode)", "window-height", 0, "pixels");+ args_parser.add_option(device_pixel_ratio, "Set the device pixel ratio (default: 1) (only supported for headless terminal mode)", "device-pixel-ratio", 0, "ratio");args_parser.add_option(certificates, "Path to a certificate file", "certificate", 'C', "certificate");args_parser.add_option(Core::ArgsParser::Option {.argument_mode = Core::ArgsParser::OptionArgumentMode::Required,@@ -556,6 +566,13 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)m_browser_options.window_width = *window_width;if (window_height.has_value())m_browser_options.window_height = *window_height;+ if (device_pixel_ratio.has_value())+ m_browser_options.device_pixel_ratio = *device_pixel_ratio;++#if !defined(AK_OS_WINDOWS)+ if (headless_mode == HeadlessMode::Terminal)+ TRY(TerminalWebView::take_over_terminal());+#endifif (webdriver_browser_endpoint.has_value())m_browser_options.webdriver_browser_endpoint = *webdriver_browser_endpoint;@@ -2092,7 +2109,12 @@ ErrorOr<int> Application::execute()auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);auto theme = TRY(Gfx::load_system_theme(theme_path.string()));- view = HeadlessWebView::create(move(theme), { m_browser_options.window_width, m_browser_options.window_height });+#if !defined(AK_OS_WINDOWS)+ if (*m_browser_options.headless_mode == HeadlessMode::Terminal)+ view = TRY(TerminalWebView::create(move(theme), m_browser_options.device_pixel_ratio));+ else+#endif+ view = HeadlessWebView::create(move(theme), { m_browser_options.window_width, m_browser_options.window_height });if (!m_browser_options.webdriver_browser_endpoint.has_value()) {if (m_browser_options.urls.size() != 1)@@ -2109,6 +2131,7 @@ ErrorOr<int> Application::execute()load_page_for_info_and_exit(*m_event_loop, *view, m_browser_options.urls.first(), WebView::PageInfoType::Text);break;case HeadlessMode::Manual:+ case HeadlessMode::Terminal:load_page_and_exit_on_close(*m_event_loop, *view, m_browser_options.urls.first());break;case HeadlessMode::Test:diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txtindex 81ee52fd263..07dae5e2fca 100644--- a/Libraries/LibWebView/CMakeLists.txt+++ b/Libraries/LibWebView/CMakeLists.txt@@ -111,6 +111,10 @@ elseif (LINUX)list(APPEND SOURCES AudioDaemonSocket.cpp CrashReportPOSIX.cpp)endif()+if (NOT WIN32)+ list(APPEND SOURCES TerminalInputParser.cpp TerminalWebView.cpp)+endif()+if (LINUX OR CMAKE_SYSTEM_NAME STREQUAL "FreeBSD")# Web notifications reach the desktop's notification daemon over the session bus.pkg_check_modules(DBUS REQUIRED IMPORTED_TARGET dbus-1)diff --git a/Libraries/LibWebView/Options.h b/Libraries/LibWebView/Options.hindex e310b5ee982..f2e3116e5f2 100644--- a/Libraries/LibWebView/Options.h+++ b/Libraries/LibWebView/Options.h@@ -24,6 +24,7 @@ enum class HeadlessMode {LayoutTree,Text,Manual,+ Terminal,Test,};@@ -97,6 +98,7 @@ struct BrowserOptions {u32 screenshot_delay { 1 };int window_width { 800 };int window_height { 600 };+ double device_pixel_ratio { 1.0 };NewWindow new_window { NewWindow::No };AllowPopups allow_popups { AllowPopups::No };DisableScripting disable_scripting { DisableScripting::No };diff --git a/Libraries/LibWebView/TerminalInputParser.cpp b/Libraries/LibWebView/TerminalInputParser.cppnew file mode 100644index 00000000000..e2411bb3d1d--- /dev/null+++ b/Libraries/LibWebView/TerminalInputParser.cpp@@ -0,0 +1,464 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/StringView.h>+#include <AK/Utf8View.h>+#include <LibWebView/TerminalInputParser.h>++namespace WebView {++using Web::UIEvents::KeyCode;+using Web::UIEvents::KeyModifier;+using Web::UIEvents::MouseButton;++static constexpr u8 escape = 0x1b;+static constexpr auto bracketed_paste_end = "\x1b[201~"sv;++// The modifier bits of the keyboard protocol, which SGR mouse reports carry two bits higher and without Super.+static KeyModifier modifiers_from_terminal_bits(u32 bits)+{+ auto modifiers = KeyModifier::Mod_None;+ if (bits & 1)+ modifiers |= KeyModifier::Mod_Shift;+ if (bits & 2)+ modifiers |= KeyModifier::Mod_Alt;+ if (bits & 4)+ modifiers |= KeyModifier::Mod_Ctrl;+ if (bits & 8)+ modifiers |= KeyModifier::Mod_Super;+ return modifiers;+}++static TerminalKeyReport key_press(KeyCode key, u32 code_point = 0, KeyModifier modifiers = KeyModifier::Mod_None)+{+ return { .key = key, .code_point = code_point, .modifiers = modifiers };+}++static TerminalKeyReport legacy_encoded(TerminalKeyReport report)+{+ report.is_legacy_encoding = true;+ return report;+}++// A key the keyboard protocol reports by number: a code point, or one of its private-use numbers for keys without one.+static TerminalKeyReport key_press_for_key_number(u32 number)+{+ switch (number) {+ case 0x1b:+ return key_press(KeyCode::Key_Escape, 0x1b);+ case '\r':+ return key_press(KeyCode::Key_Return, '\n');+ case '\t':+ return key_press(KeyCode::Key_Tab, '\t');+ case 0x7f:+ case '\b':+ return key_press(KeyCode::Key_Backspace, '\b');+ case 57358:+ return key_press(KeyCode::Key_CapsLock);+ case 57359:+ return key_press(KeyCode::Key_ScrollLock);+ case 57360:+ return key_press(KeyCode::Key_NumLock);+ case 57361:+ return key_press(KeyCode::Key_PrintScreen);+ case 57362:+ return key_press(KeyCode::Key_PauseBreak);+ case 57363:+ return key_press(KeyCode::Key_Menu);+ case 57441:+ return key_press(KeyCode::Key_LeftShift);+ case 57442:+ return key_press(KeyCode::Key_LeftControl);+ case 57443:+ return key_press(KeyCode::Key_LeftAlt);+ case 57444:+ return key_press(KeyCode::Key_LeftSuper);+ case 57447:+ return key_press(KeyCode::Key_RightShift);+ case 57448:+ return key_press(KeyCode::Key_RightControl);+ case 57449:+ return key_press(KeyCode::Key_RightAlt);+ case 57450:+ return key_press(KeyCode::Key_RightSuper);+ default:+ break;+ }+ // The rest of the private-use area holds keys this view has no key code for.+ if (number >= 0xe000 && number < 0xf900)+ return key_press(KeyCode::Key_Invalid);+ return key_press(Web::UIEvents::code_point_to_key_code(number), number);+}++// The keys of CSI 1;<modifiers> <letter> and SS3 <letter>.+static KeyCode key_for_letter(u8 letter)+{+ switch (letter) {+ case 'A':+ return KeyCode::Key_Up;+ case 'B':+ return KeyCode::Key_Down;+ case 'C':+ return KeyCode::Key_Right;+ case 'D':+ return KeyCode::Key_Left;+ case 'H':+ return KeyCode::Key_Home;+ case 'F':+ return KeyCode::Key_End;+ case 'P':+ return KeyCode::Key_F1;+ case 'Q':+ return KeyCode::Key_F2;+ case 'S':+ return KeyCode::Key_F4;+ default:+ return KeyCode::Key_Invalid;+ }+}++// The keys of CSI <number>;<modifiers> ~.+static KeyCode key_for_tilde_number(u32 number)+{+ switch (number) {+ case 1:+ case 7:+ return KeyCode::Key_Home;+ case 2:+ return KeyCode::Key_Insert;+ case 3:+ return KeyCode::Key_Delete;+ case 4:+ case 8:+ return KeyCode::Key_End;+ case 5:+ return KeyCode::Key_PageUp;+ case 6:+ return KeyCode::Key_PageDown;+ case 11:+ return KeyCode::Key_F1;+ case 12:+ return KeyCode::Key_F2;+ case 13:+ return KeyCode::Key_F3;+ case 14:+ return KeyCode::Key_F4;+ case 15:+ return KeyCode::Key_F5;+ case 17:+ return KeyCode::Key_F6;+ case 18:+ return KeyCode::Key_F7;+ case 19:+ return KeyCode::Key_F8;+ case 20:+ return KeyCode::Key_F9;+ case 21:+ return KeyCode::Key_F10;+ case 23:+ return KeyCode::Key_F11;+ case 24:+ return KeyCode::Key_F12;+ default:+ return KeyCode::Key_Invalid;+ }+}++// "<modifiers>[:<event type>]", where the modifiers are one more than their bits and the event type is 1 for a press,+// 2 for a repeat and 3 for a release.+static void apply_modifier_field(StringView field, TerminalKeyReport& report)+{+ if (field.is_empty())+ return;+ auto parts = field.split_view(':', SplitBehavior::KeepEmpty);+ if (auto modifiers = parts[0].to_number<u32>(); modifiers.has_value() && *modifiers > 0)+ report.modifiers = modifiers_from_terminal_bits(*modifiers - 1);+ if (parts.size() < 2)+ return;+ switch (parts[1].to_number<u32>().value_or(1)) {+ case 2:+ report.phase = TerminalKeyReport::Phase::Repeat;+ break;+ case 3:+ report.phase = TerminalKeyReport::Phase::Release;+ break;+ default:+ report.phase = TerminalKeyReport::Phase::Press;+ break;+ }+}++static Optional<TerminalMouseReport> mouse_report(u32 button_code, Gfx::IntPoint position, bool is_release)+{+ static constexpr u32 motion_bit = 32;+ static constexpr u32 wheel_bit = 64;+ static constexpr u32 extra_button_bit = 128;++ TerminalMouseReport report { .modifiers = modifiers_from_terminal_bits((button_code >> 2) & 7), .position = position };+ auto low_bits = static_cast<int>(button_code & 3);++ if (button_code & wheel_bit) {+ report.kind = TerminalMouseReport::Kind::Wheel;+ report.wheel_steps = low_bits < 2 ? Gfx::IntPoint { 0, low_bits == 0 ? -1 : 1 } : Gfx::IntPoint { low_bits == 2 ? -1 : 1, 0 };+ return report;+ }+ if (button_code & motion_bit) {+ report.kind = TerminalMouseReport::Kind::Motion;+ return report;+ }+ // Without the extra-button bit, 3 is a legacy release of no button in particular.+ if (low_bits == 3 && !(button_code & extra_button_bit))+ return {};+ report.button = Web::UIEvents::button_code_to_mouse_button(static_cast<i16>(low_bits + (button_code & extra_button_bit ? 3 : 0)));+ if (report.button == MouseButton::None)+ return {};+ report.kind = is_release ? TerminalMouseReport::Kind::Release : TerminalMouseReport::Kind::Press;+ return report;+}++Optional<size_t> TerminalInputParser::parse_control_sequence(ReadonlyBytes bytes, Vector<TerminalInput>& inputs)+{+ size_t index = 2;+ while (index < bytes.size() && bytes[index] >= 0x30 && bytes[index] <= 0x3f)+ ++index;+ auto parameters_end = index;+ while (index < bytes.size() && bytes[index] >= 0x20 && bytes[index] <= 0x2f)+ ++index;+ if (index >= bytes.size())+ return {};++ auto final_byte = bytes[index];+ size_t consumed = index + 1;+ if (final_byte < 0x40 || final_byte > 0x7e)+ return consumed;++ StringView parameters { bytes.slice(2, parameters_end - 2) };+ auto has_intermediates = parameters_end != index;++ if (parameters.starts_with('<') && (final_byte == 'M' || final_byte == 'm')) {+ auto fields = parameters.substring_view(1).split_view(';');+ if (fields.size() != 3)+ return consumed;+ auto button_code = fields[0].to_number<u32>();+ auto x = fields[1].to_number<int>();+ auto y = fields[2].to_number<int>();+ if (!button_code.has_value() || !x.has_value() || !y.has_value())+ return consumed;+ // Pixel coordinates count from one.+ if (auto report = mouse_report(*button_code, { *x - 1, *y - 1 }, final_byte == 'm'); report.has_value())+ inputs.append(report.release_value());+ return consumed;+ }++ if (final_byte == '~' && parameters == "200"sv) {+ m_paste = ByteBuffer {};+ return consumed;+ }++ if (parameters.is_empty() && (final_byte == 'I' || final_byte == 'O')) {+ inputs.append(TerminalFocusChange { .has_focus = final_byte == 'I' });+ return consumed;+ }++ if (parameters.starts_with('?') && final_byte == 'u' && !has_intermediates) {+ inputs.append(TerminalKeyboardProtocolFlags { .flags = parameters.substring_view(1).to_number<u32>().value_or(0) });+ return consumed;+ }++ // Replies to queries this parser has no use for, such as DECRQM and device attributes.+ if (has_intermediates || parameters.starts_with('?') || parameters.starts_with('>') || parameters.starts_with('='))+ return consumed;++ auto fields = parameters.split_view(';', SplitBehavior::KeepEmpty);++ if (final_byte == 't') {+ if (fields.size() == 3 && fields[0] == "4"sv) {+ auto height = fields[1].to_number<int>();+ auto width = fields[2].to_number<int>();+ if (height.has_value() && width.has_value())+ inputs.append(TerminalPixelSizeReport { .size = { *width, *height } });+ }+ return consumed;+ }++ TerminalKeyReport report;+ if (final_byte == 'u') {+ auto key_numbers = fields.is_empty() ? Vector<StringView> {} : fields[0].split_view(':', SplitBehavior::KeepEmpty);+ auto key_number = key_numbers.is_empty() ? Optional<u32> {} : key_numbers[0].to_number<u32>();+ if (!key_number.has_value())+ return consumed;+ report = key_press_for_key_number(*key_number);+ if (key_numbers.size() > 1)+ report.shifted_code_point = key_numbers[1].to_number<u32>();+ if (fields.size() > 2) {+ for (auto text : fields[2].split_view(':')) {+ if (auto code_point = text.to_number<u32>(); code_point.has_value())+ report.text_code_points.append(*code_point);+ }+ }+ } else if (final_byte == '~') {+ auto number = fields.is_empty() ? Optional<u32> {} : fields[0].to_number<u32>();+ report = key_press(number.has_value() ? key_for_tilde_number(*number) : KeyCode::Key_Invalid);+ } else {+ report = key_press(key_for_letter(final_byte));+ }+ if (report.key == KeyCode::Key_Invalid)+ return consumed;+ if (fields.size() > 1)+ apply_modifier_field(fields[1], report);+ inputs.append(move(report));+ return consumed;+}++Optional<size_t> TerminalInputParser::parse_one(ReadonlyBytes bytes, Vector<TerminalInput>& inputs)+{+ if (m_paste.has_value()) {+ if (auto end = StringView { bytes }.find(bracketed_paste_end); end.has_value()) {+ m_paste->append(bytes.slice(0, *end));+ inputs.append(TerminalPaste { .text = ByteString { m_paste->bytes() } });+ m_paste.clear();+ return *end + bracketed_paste_end.length();+ }++ // Keep what may be the start of the end marker for the next chunk.+ size_t kept = 0;+ for (size_t length = min(bracketed_paste_end.length() - 1, bytes.size()); length > 0; --length) {+ if (StringView { bytes.slice(bytes.size() - length) } == bracketed_paste_end.substring_view(0, length)) {+ kept = length;+ break;+ }+ }+ m_paste->append(bytes.slice(0, bytes.size() - kept));+ if (kept == bytes.size())+ return {};+ return bytes.size() - kept;+ }++ if (bytes[0] == escape) {+ if (bytes.size() < 2)+ return {};++ switch (bytes[1]) {+ case '[':+ return parse_control_sequence(bytes, inputs);++ case 'O': {+ if (bytes.size() < 3)+ return {};+ auto key = bytes[2] == 'R' ? KeyCode::Key_F3 : key_for_letter(bytes[2]);+ if (key != KeyCode::Key_Invalid)+ inputs.append(legacy_encoded(key_press(key)));+ return 3;+ }++ case '_': {+ auto end = StringView { bytes }.find("\x1b\\"sv, 2);+ if (!end.has_value())+ return {};+ StringView body { bytes.slice(2, *end - 2) };+ if (body.starts_with('G')) {+ inputs.append(TerminalGraphicsReply { .text = body.substring_view(1) });+ } else if (body.starts_with("ladybird;"sv)) {+ auto command = body.substring_view("ladybird;"sv.length());+ auto separator = command.find(';');+ if (separator.has_value())+ inputs.append(TerminalCommand { .name = command.substring_view(0, *separator), .argument = command.substring_view(*separator + 1) });+ else+ inputs.append(TerminalCommand { .name = command, .argument = {} });+ }+ return *end + 2;+ }++ case ']':+ case 'P': {+ // An OSC or DCS reply, which ends with BEL (OSC only) or ST.+ for (size_t index = 2; index < bytes.size(); ++index) {+ if (bytes[1] == ']' && bytes[index] == 0x07)+ return index + 1;+ if (bytes[index] == escape && index + 1 < bytes.size() && bytes[index + 1] == '\\')+ return index + 2;+ }+ return {};+ }++ default: {+ // Legacy Alt+key: the key, with ESC before it.+ Vector<TerminalInput> key_inputs;+ auto key_consumed = parse_one(bytes.slice(1), key_inputs);+ if (!key_consumed.has_value())+ return {};+ for (auto& input : key_inputs) {+ if (auto* key = input.get_pointer<TerminalKeyReport>()) {+ key->modifiers |= KeyModifier::Mod_Alt;+ key->is_legacy_encoding = true;+ }+ inputs.append(move(input));+ }+ return 1 + *key_consumed;+ }+ }+ }++ // Legacy bytes: UTF-8 text and control characters.+ auto lead = bytes[0];+ size_t length = lead < 0x80 ? 1 : (lead >> 5) == 0x6 ? 2+ : (lead >> 4) == 0xe ? 3+ : (lead >> 3) == 0x1e ? 4+ : 1;+ if (bytes.size() < length)+ return {};++ Utf8View view { StringView { bytes.slice(0, length) } };+ if (!view.validate())+ return length;+ auto code_point = *view.begin();++ TerminalKeyReport report;+ if (code_point == 0x00) {+ report = key_press(KeyCode::Key_Space, ' ', KeyModifier::Mod_Ctrl);+ } else if (code_point >= 0x01 && code_point <= 0x1a && code_point != '\t' && code_point != '\r' && code_point != '\n' && code_point != '\b') {+ auto letter = 'a' + code_point - 1;+ report = key_press(Web::UIEvents::code_point_to_key_code(letter), letter, KeyModifier::Mod_Ctrl);+ } else if (code_point >= 0x1c && code_point <= 0x1f) {+ auto character = "\\]^_"sv[code_point - 0x1c];+ report = key_press(Web::UIEvents::code_point_to_key_code(character), character, KeyModifier::Mod_Ctrl);+ } else {+ report = key_press_for_key_number(code_point == '\n' ? '\r' : code_point);+ if (code_point >= ' ' && code_point != 0x7f)+ report.text_code_points.append(code_point);+ }+ if (report.key != KeyCode::Key_Invalid)+ inputs.append(legacy_encoded(move(report)));+ return length;+}++Vector<TerminalInput> TerminalInputParser::parse(ReadonlyBytes chunk)+{+ Vector<TerminalInput> inputs;+ m_pending.append(chunk);++ // Without the keyboard protocol, the Escape key arrives as a lone ESC. Anything else that starts with one arrives+ // with the rest of its sequence.+ if (!m_paste.has_value() && m_pending.size() == 1 && m_pending[0] == escape) {+ m_pending.clear();+ inputs.append(legacy_encoded(key_press_for_key_number(escape)));+ return inputs;+ }++ auto bytes = m_pending.bytes();+ size_t offset = 0;+ while (offset < bytes.size()) {+ auto consumed = parse_one(bytes.slice(offset), inputs);+ if (!consumed.has_value())+ break;+ offset += *consumed;+ }++ m_pending = MUST(ByteBuffer::copy(bytes.slice(offset)));+ return inputs;+}++}diff --git a/Libraries/LibWebView/TerminalInputParser.h b/Libraries/LibWebView/TerminalInputParser.hnew file mode 100644index 00000000000..21fcae2c9a9--- /dev/null+++ b/Libraries/LibWebView/TerminalInputParser.h@@ -0,0 +1,101 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/ByteBuffer.h>+#include <AK/ByteString.h>+#include <AK/Optional.h>+#include <AK/Variant.h>+#include <AK/Vector.h>+#include <LibGfx/Point.h>+#include <LibGfx/Size.h>+#include <LibWebCommon/UIEvents/KeyCode.h>+#include <LibWebCommon/UIEvents/MouseButton.h>+#include <LibWebView/Forward.h>++namespace WebView {++// An SGR mouse report with pixel coordinates (modes 1006 and 1016), from the pane's top-left pixel.+struct TerminalMouseReport {+ enum class Kind : u8 {+ Press,+ Release,+ Motion,+ Wheel,+ };++ Kind kind { Kind::Motion };+ Web::UIEvents::MouseButton button { Web::UIEvents::MouseButton::None };+ // For a wheel report, the direction it scrolls in: -1, 0 or 1 on each axis.+ Gfx::IntPoint wheel_steps {};+ Web::UIEvents::KeyModifier modifiers { Web::UIEvents::KeyModifier::Mod_None };+ Gfx::IntPoint position {};+};++// A key, as the Kitty keyboard protocol reports it, or as legacy bytes do.+struct TerminalKeyReport {+ enum class Phase : u8 {+ Press,+ Repeat,+ Release,+ };++ Web::UIEvents::KeyCode key { Web::UIEvents::KeyCode::Key_Invalid };+ // The character of the key without Shift, as a key event carries it; zero for keys without one, like arrows.+ u32 code_point { 0 };+ Optional<u32> shifted_code_point {};+ Web::UIEvents::KeyModifier modifiers { Web::UIEvents::KeyModifier::Mod_None };+ Phase phase { Phase::Press };+ Vector<u32> text_code_points {};+ // Legacy encodings, such as plain bytes, report presses only, even from a terminal that reports releases.+ bool is_legacy_encoding { false };+};++struct TerminalPaste {+ ByteString text {};+};++struct TerminalFocusChange {+ bool has_focus { false };+};++// A command sent to the pane's input as ESC _ ladybird;<name>;<argument> ESC \, which no key types.+struct TerminalCommand {+ ByteString name {};+ ByteString argument {};+};++struct TerminalGraphicsReply {+ ByteString text {};+};++struct TerminalKeyboardProtocolFlags {+ u32 flags { 0 };+};++struct TerminalPixelSizeReport {+ Gfx::IntSize size {};+};++using TerminalInput = Variant<TerminalMouseReport, TerminalKeyReport, TerminalPaste, TerminalFocusChange, TerminalCommand, TerminalGraphicsReply, TerminalKeyboardProtocolFlags, TerminalPixelSizeReport>;++// Turns the bytes a terminal sends into input. A chunk can end partway through a sequence; the rest is kept for the+// next chunk.+class WEBVIEW_API TerminalInputParser {+public:+ Vector<TerminalInput> parse(ReadonlyBytes chunk);++private:+ // Each returns how many bytes it consumed, or nothing when the sequence continues past the end of the bytes.+ Optional<size_t> parse_one(ReadonlyBytes, Vector<TerminalInput>&);+ Optional<size_t> parse_control_sequence(ReadonlyBytes, Vector<TerminalInput>&);++ ByteBuffer m_pending;+ Optional<ByteBuffer> m_paste;+};++}diff --git a/Libraries/LibWebView/TerminalWebView.cpp b/Libraries/LibWebView/TerminalWebView.cppnew file mode 100644index 00000000000..366c8615e20--- /dev/null+++ b/Libraries/LibWebView/TerminalWebView.cpp@@ -0,0 +1,705 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Base64.h>+#include <AK/CharacterTypes.h>+#include <AK/NeverDestroyed.h>+#include <AK/StringBuilder.h>+#include <AK/Utf8View.h>+#include <LibCore/EventLoop.h>+#include <LibCore/File.h>+#include <LibCore/Notifier.h>+#include <LibCore/System.h>+#include <LibCore/Timer.h>+#include <LibGfx/Bitmap.h>+#include <LibGfx/SharedImageBuffer.h>+#include <LibWebCommon/Page/InputEvent.h>+#include <LibWebView/Application.h>+#include <LibWebView/PageBackingStores.h>+#include <LibWebView/TerminalWebView.h>+#include <LibWebView/URL.h>++#include <fcntl.h>+#include <signal.h>+#include <sys/ioctl.h>+#include <unistd.h>++namespace WebView {++using Web::UIEvents::KeyCode;+using Web::UIEvents::KeyModifier;+using Web::UIEvents::MouseButton;++static int s_terminal_fd = -1;+static NeverDestroyed<ByteString> s_log_path;++// One wheel report from the terminal scrolls one line, as terminals send a report for each line a wheel or touchpad+// scrolls.+static constexpr double wheel_pixels_per_terminal_wheel_report = 40;++static constexpr auto double_click_interval = AK::Duration::from_milliseconds(500);+static constexpr int double_click_distance_in_device_pixels = 4;++// The Kitty keyboard protocol's flags.+static constexpr u32 keyboard_protocol_disambiguates_escape_codes = 1;+static constexpr u32 keyboard_protocol_reports_event_types = 2;+static constexpr u32 keyboard_protocol_reports_all_keys_as_escape_codes = 8;+static constexpr u32 keyboard_protocol_reports_associated_text = 16;+static constexpr u32 requested_keyboard_protocol_flags = keyboard_protocol_disambiguates_escape_codes+ | keyboard_protocol_reports_event_types+ | keyboard_protocol_reports_all_keys_as_escape_codes+ | keyboard_protocol_reports_associated_text;++static constexpr auto delete_all_images = "\x1b_Ga=d,d=A,q=2\x1b\\"sv;+static constexpr auto query_pane_pixel_size = "\x1b[14t"sv;++static constexpr u32 first_image_id = 1;+// Raw bytes per chunk of an image sent inline, which base64 makes the protocol's largest chunk of 4096 bytes.+static constexpr size_t direct_transmission_raw_chunk_size = 3072;+static constexpr size_t direct_transmission_flush_size = 256 * KiB;++static ByteString temporary_frame_path(u64 transmission_number)+{+ // The terminal only reads image files whose path names them as such, in a temporary directory.+ return ByteString::formatted("/tmp/tty-graphics-protocol-ladybird-{}-{}.rgb", getpid(), transmission_number);+}++static void append_graphics_command(StringBuilder& builder, StringView keys, StringView payload)+{+ builder.appendff("\x1b_G{};{}\x1b\\", keys, payload);+}++ErrorOr<void> TerminalWebView::take_over_terminal()+{+ if (!TRY(Core::System::isatty(STDIN_FILENO)) || !TRY(Core::System::isatty(STDOUT_FILENO)))+ return Error::from_string_literal("Terminal mode needs to run in a terminal");++ s_terminal_fd = TRY(Core::System::dup(STDOUT_FILENO));+ TRY(Core::System::fcntl(s_terminal_fd, F_SETFD, FD_CLOEXEC));++ *s_log_path = ByteString::formatted("/tmp/ladybird-terminal-{}.log", getpid());+ auto log_fd = TRY(Core::System::open(*s_log_path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644));++ auto message = ByteString::formatted("Ladybird logs to {}\r\n", *s_log_path);+ (void)Core::System::write(s_terminal_fd, message.bytes());++ // Helper processes inherit these, so what any of them prints goes to the log rather than over the page.+ if (::dup2(log_fd, STDOUT_FILENO) < 0 || ::dup2(log_fd, STDERR_FILENO) < 0)+ return Error::from_syscall("dup2"sv, errno);+ TRY(Core::System::close(log_fd));+ return {};+}++TerminalWebView::PaneGeometry TerminalWebView::query_pane_geometry()+{+ struct winsize size {};+ if (ioctl(s_terminal_fd, TIOCGWINSZ, &size) < 0)+ return {};+ return { .rows = size.ws_row, .columns = size.ws_col, .pixel_size = { size.ws_xpixel, size.ws_ypixel } };+}++ErrorOr<NonnullOwnPtr<TerminalWebView>> TerminalWebView::create(Core::AnonymousBuffer theme, double device_pixel_ratio)+{+ if (s_terminal_fd < 0)+ return Error::from_string_literal("The terminal must be taken over before a terminal view is created");++ auto geometry = query_pane_geometry();+ auto page_pixel_size = geometry.page_pixel_size();+ if (page_pixel_size.is_empty())+ page_pixel_size = { 800, 600 };++ auto view = adopt_own(*new TerminalWebView(move(theme), page_pixel_size.to_type<Web::DevicePixels>(), device_pixel_ratio));+ view->m_pane_geometry = geometry;+ view->enter_terminal_modes();+ view->initialize_tab(Web::HTML::VisibilityState::Visible);+ view->set_presents_from_cpu_memory(true);+ view->show_notice(ByteString::formatted("logging to {}", *s_log_path));+ return view;+}++TerminalWebView::TerminalWebView(Core::AnonymousBuffer theme, Web::DevicePixelSize viewport_size, double device_pixel_ratio)+ : HeadlessWebView(move(theme), viewport_size)+{+ m_device_pixel_ratio = device_pixel_ratio;++ on_title_change = [this](auto const&) { draw_status_line(); };+ on_url_change = [this](auto const&) { draw_status_line(); };+ on_loading_state_change = [this](bool) { draw_status_line(); };+}++TerminalWebView::~TerminalWebView()+{+ leave_terminal_modes();+}++void TerminalWebView::quit()+{+ if (!m_terminal_modes_entered)+ return;+ leave_terminal_modes();+ Core::EventLoop::current().quit(0);+}++void TerminalWebView::write_to_terminal(StringView text)+{+ auto bytes = text.bytes();+ while (!bytes.is_empty()) {+ auto written = Core::System::write(s_terminal_fd, bytes);+ if (written.is_error()) {+ if (written.error().code() == EINTR || written.error().code() == EAGAIN)+ continue;+ return;+ }+ bytes = bytes.slice(written.value());+ }+}++void TerminalWebView::enter_terminal_modes()+{+ if (::tcgetattr(STDIN_FILENO, &m_original_terminal_attributes) == 0) {+ auto raw_attributes = m_original_terminal_attributes;+ cfmakeraw(&raw_attributes);+ ::tcsetattr(STDIN_FILENO, TCSANOW, &raw_attributes);+ }+ m_terminal_modes_entered = true;++ // Alternate screen, hidden cursor, mouse reports for every motion with SGR pixel coordinates, focus reports,+ // bracketed paste and the keyboard protocol; then ask which keyboard flags took.+ write_to_terminal(ByteString::formatted(+ "\x1b[?1049h\x1b[?25l\x1b[2J"+ "\x1b[?1003h\x1b[?1006h\x1b[?1016h\x1b[?1004h\x1b[?2004h"+ "\x1b[>{}u\x1b[?u",+ requested_keyboard_protocol_flags));+ if (m_pane_geometry.pixel_size.is_empty())+ write_to_terminal(query_pane_pixel_size);++ m_input_notifier = Core::Notifier::construct(STDIN_FILENO, Core::Notifier::Type::Read);+ m_input_notifier->on_activation = [this] {+ u8 buffer[64 * KiB];+ auto read = Core::System::read(STDIN_FILENO, { buffer, sizeof(buffer) });+ if (read.is_error()) {+ if (read.error().code() != EINTR && read.error().code() != EAGAIN)+ quit();+ return;+ }+ if (read.value() == 0) {+ quit();+ return;+ }+ for (auto const& input : m_input_parser.parse({ buffer, read.value() }))+ handle_input(input);+ };++ m_signal_handler_ids.append(Core::EventLoop::register_signal(SIGWINCH, [this](int) {+ m_pane_geometry = query_pane_geometry();+ if (m_pane_geometry.pixel_size.is_empty())+ write_to_terminal(query_pane_pixel_size);+ apply_pane_geometry();+ }));+ for (auto signal_number : { SIGTERM, SIGHUP }) {+ m_signal_handler_ids.append(Core::EventLoop::register_signal(signal_number, [this](int) {+ quit();+ }));+ }+}++void TerminalWebView::leave_terminal_modes()+{+ if (!m_terminal_modes_entered)+ return;+ m_terminal_modes_entered = false;++ m_input_notifier = nullptr;+ for (auto id : m_signal_handler_ids)+ Core::EventLoop::unregister_signal(id);+ m_signal_handler_ids.clear();++ write_to_terminal("\x1b[<u\x1b[?2004l\x1b[?1004l\x1b[?1016l\x1b[?1006l\x1b[?1003l"sv);+ write_to_terminal(delete_all_images);+ write_to_terminal("\x1b[?25h\x1b[?1049l"sv);+ ::tcsetattr(STDIN_FILENO, TCSANOW, &m_original_terminal_attributes);++ // The terminal deletes each frame's file once it reads it. Remove any it had not read yet.+ for (u64 number = m_image_data_transmissions > 4 ? m_image_data_transmissions - 4 : 0; number < m_image_data_transmissions; ++number)+ (void)Core::System::unlink(temporary_frame_path(number));+}++void TerminalWebView::apply_pane_geometry()+{+ m_drawn_status_line = {};+ m_frame_needs_full_redraw = true;+ m_displayed_image_id.clear();+ write_to_terminal(delete_all_images);+ write_to_terminal("\x1b[2J"sv);+ draw_status_line();++ auto page_pixel_size = m_pane_geometry.page_pixel_size();+ if (page_pixel_size.is_empty())+ return;+ if (page_pixel_size != viewport_size().to_type<int>())+ reset_viewport_size(page_pixel_size.to_type<Web::DevicePixels>());+ schedule_frame_flush();+}++void TerminalWebView::did_accept_presented_backing_store(i32, Gfx::IntRect damage_rect)+{+ m_pending_damage = m_pending_damage.has_value() ? m_pending_damage->united(damage_rect) : damage_rect;+ schedule_frame_flush();+}++void TerminalWebView::schedule_frame_flush()+{+ if (m_frame_flush_scheduled)+ return;+ m_frame_flush_scheduled = true;+ Core::deferred_invoke([weak_this = make_weak_ptr<TerminalWebView>()] {+ if (!weak_this)+ return;+ weak_this->m_frame_flush_scheduled = false;+ weak_this->flush_frame();+ });+}++void TerminalWebView::flush_frame()+{+ if (!m_terminal_modes_entered)+ return;++ auto frame = backing_stores().displayed_frame();+ if (!frame.has_value() || !frame->shared_image_buffer)+ return;+ auto bitmap = frame->shared_image_buffer->bitmap_if_present();+ if (!bitmap) {+ show_notice("frames are not in CPU memory");+ return;+ }++ if (auto result = transmit_frame(*bitmap); result.is_error())+ show_notice(ByteString::formatted("cannot draw frame: {}", result.error()));+ m_pending_damage.clear();+ m_frame_needs_full_redraw = false;+}++static ErrorOr<void> convert_to_rgb(Gfx::Bitmap const& bitmap, Gfx::IntRect rect, ByteBuffer& pixels)+{+ TRY(pixels.try_resize(static_cast<size_t>(rect.width()) * rect.height() * 3));+ auto red_is_low_byte = bitmap.format() == Gfx::BitmapFormat::RGBA8888 || bitmap.format() == Gfx::BitmapFormat::RGBx8888;+ auto* out = pixels.data();+ for (int y = rect.y(); y < rect.y() + rect.height(); ++y) {+ auto const* scanline = bitmap.scanline(y);+ for (int x = rect.x(); x < rect.x() + rect.width(); ++x) {+ auto pixel = scanline[x];+ u8 low = pixel & 0xff;+ u8 middle = (pixel >> 8) & 0xff;+ u8 high = (pixel >> 16) & 0xff;+ *out++ = red_is_low_byte ? low : high;+ *out++ = middle;+ *out++ = red_is_low_byte ? high : low;+ }+ }+ return {};+}++ErrorOr<void> TerminalWebView::send_image_data(StringView keys, ReadonlyBytes pixels)+{+ StringBuilder command;+ if (m_graphics_transmission == GraphicsTransmission::TemporaryFile) {+ auto path = temporary_frame_path(m_image_data_transmissions++);+ auto file = TRY(Core::File::open(path, Core::File::OpenMode::Write | Core::File::OpenMode::Truncate, 0600));+ TRY(file->write_until_depleted(pixels));+ append_graphics_command(command, ByteString::formatted("{},t=t", keys), TRY(encode_base64(path.bytes())));+ write_to_terminal(command.string_view());+ return {};+ }++ for (size_t offset = 0; offset < pixels.size(); offset += direct_transmission_raw_chunk_size) {+ auto chunk = pixels.slice(offset, min(direct_transmission_raw_chunk_size, pixels.size() - offset));+ auto has_more_chunks = offset + direct_transmission_raw_chunk_size < pixels.size();+ auto chunk_keys = offset == 0 ? ByteString::formatted("{},m={}", keys, has_more_chunks ? 1 : 0) : ByteString::formatted("m={}", has_more_chunks ? 1 : 0);+ append_graphics_command(command, chunk_keys, TRY(encode_base64(chunk)));+ if (command.length() >= direct_transmission_flush_size || !has_more_chunks) {+ write_to_terminal(command.string_view());+ command.clear();+ }+ }+ return {};+}++ErrorOr<void> TerminalWebView::transmit_frame(Gfx::Bitmap const& bitmap)+{+ // A frame laid out for a larger pane than this one is cut to fit above the status line.+ auto size = bitmap.size();+ auto page_pixel_size = m_pane_geometry.page_pixel_size();+ if (!page_pixel_size.is_empty())+ size = { min(size.width(), page_pixel_size.width()), min(size.height(), page_pixel_size.height()) };+ if (size.is_empty())+ return {};+ Gfx::IntRect frame_rect { {}, size };++ auto shows_frame_of_this_size = !m_frame_needs_full_redraw && m_displayed_image_id.has_value() && m_displayed_image_size == size;+ auto damage_rect = m_pending_damage.value_or(Gfx::IntRect {}).intersected(frame_rect);+ if (shows_frame_of_this_size && damage_rect.is_empty())+ return {};++ // Only the damaged part of a frame is sent, as an edit of the image on display.+ if (m_sends_damaged_rectangles && shows_frame_of_this_size && damage_rect != frame_rect) {+ TRY(convert_to_rgb(bitmap, damage_rect, m_frame_pixels));+ auto keys = ByteString::formatted("a=f,r=1,i={},x={},y={},s={},v={},f=24,q=1", *m_displayed_image_id, damage_rect.x(), damage_rect.y(), damage_rect.width(), damage_rect.height());+ return send_image_data(keys, m_frame_pixels);+ }++ TRY(convert_to_rgb(bitmap, frame_rect, m_frame_pixels));+ auto image_id = m_displayed_image_id == first_image_id ? first_image_id + 1 : first_image_id;+ write_to_terminal("\x1b[1;1H"sv);+ TRY(send_image_data(ByteString::formatted("a=T,f=24,s={},v={},i={},p=1,C=1,q=1", size.width(), size.height(), image_id), m_frame_pixels));+ // The new frame is placed before the old one goes, so the pane never shows neither.+ if (m_displayed_image_id.has_value())+ write_to_terminal(ByteString::formatted("\x1b_Ga=d,d=I,i={},q=2\x1b\\", *m_displayed_image_id));++ m_displayed_image_id = image_id;+ m_displayed_image_size = size;+ return {};+}++void TerminalWebView::handle_input(TerminalInput const& input)+{+ input.visit(+ [this](TerminalMouseReport const& report) {+ handle_mouse_report(report);+ },+ [this](TerminalKeyReport const& report) {+ handle_key_report(report);+ },+ [this](TerminalPaste const& paste) {+ if (m_url_prompt_text.has_value()) {+ m_url_prompt_text = ByteString::formatted("{}{}", *m_url_prompt_text, paste.text);+ draw_status_line();+ return;+ }+ commit_text_from_input_method(Utf16String::from_utf8(paste.text));+ },+ [this](TerminalFocusChange const& focus_change) {+ set_has_system_focus(focus_change.has_focus);+ },+ [this](TerminalCommand const& command) {+ handle_command(command);+ },+ [this](TerminalGraphicsReply const& reply) {+ if (reply.text.ends_with(";OK"sv))+ return;+ if (m_graphics_transmission == GraphicsTransmission::TemporaryFile) {+ // A terminal on another machine cannot read this machine's files.+ m_graphics_transmission = GraphicsTransmission::Direct;+ show_notice("sending frames inline");+ m_frame_needs_full_redraw = true;+ schedule_frame_flush();+ return;+ }+ show_notice(ByteString::formatted("graphics: {}", reply.text));+ },+ [this](TerminalKeyboardProtocolFlags const& flags) {+ m_terminal_reports_key_releases = (flags.flags & keyboard_protocol_reports_event_types) != 0;+ },+ [this](TerminalPixelSizeReport const& report) {+ if (!m_pane_geometry.pixel_size.is_empty())+ return;+ m_pane_geometry.pixel_size = report.size;+ apply_pane_geometry();+ });+}++static Web::MouseEvent mouse_event(Web::MouseEvent::Type type, Gfx::IntPoint position, MouseButton button, MouseButton buttons, KeyModifier modifiers)+{+ Web::MouseEvent event {};+ event.type = type;+ event.position = position.to_type<Web::DevicePixels>();+ event.screen_position = event.position;+ event.button = button;+ event.buttons = buttons;+ event.modifiers = modifiers;+ return event;+}++void TerminalWebView::handle_mouse_report(TerminalMouseReport const& report)+{+ auto viewport = viewport_size().to_type<int>();+ auto is_in_status_line = report.position.y() >= viewport.height();+ auto position_in_page = Gfx::IntPoint {+ clamp(report.position.x(), 0, max(0, viewport.width() - 1)),+ clamp(report.position.y(), 0, max(0, viewport.height() - 1)),+ };++ switch (report.kind) {+ case TerminalMouseReport::Kind::Wheel: {+ if (is_in_status_line)+ return;+ auto event = mouse_event(Web::MouseEvent::Type::MouseWheel, position_in_page, MouseButton::None, m_held_mouse_buttons, report.modifiers);+ event.wheel_delta_x = report.wheel_steps.x() * wheel_pixels_per_terminal_wheel_report;+ event.wheel_delta_y = report.wheel_steps.y() * wheel_pixels_per_terminal_wheel_report;+ event.wheel_tick_120ths_x = Web::wheel_tick_120ths_from_pixel_delta(event.wheel_delta_x, Web::WheelDeltaPrecision::Discrete);+ event.wheel_tick_120ths_y = Web::wheel_tick_120ths_from_pixel_delta(event.wheel_delta_y, Web::WheelDeltaPrecision::Discrete);+ event.wheel_delta_precision = Web::WheelDeltaPrecision::Discrete;+ enqueue_input_event(move(event));+ return;+ }++ case TerminalMouseReport::Kind::Motion:+ // A drag that leaves the page keeps going at its edge.+ if (is_in_status_line && m_held_mouse_buttons == MouseButton::None)+ return;+ enqueue_input_event(mouse_event(Web::MouseEvent::Type::MouseMove, position_in_page, MouseButton::None, m_held_mouse_buttons, report.modifiers));+ return;++ case TerminalMouseReport::Kind::Release: {+ if (!has_flag(m_held_mouse_buttons, report.button))+ return;+ m_held_mouse_buttons &= ~report.button;+ auto event = mouse_event(Web::MouseEvent::Type::MouseUp, position_in_page, report.button, m_held_mouse_buttons, report.modifiers);+ event.click_count = m_click_count;+ enqueue_input_event(move(event));+ return;+ }++ case TerminalMouseReport::Kind::Press: {+ if (is_in_status_line) {+ open_url_prompt();+ return;+ }++ auto now = MonotonicTime::now();+ auto distance = max(abs(position_in_page.x() - m_last_press_position.x()), abs(position_in_page.y() - m_last_press_position.y()));+ if (report.button == m_last_pressed_mouse_button && now - m_last_press_time < double_click_interval && distance <= double_click_distance_in_device_pixels * m_device_pixel_ratio)+ ++m_click_count;+ else+ m_click_count = 1;+ m_last_pressed_mouse_button = report.button;+ m_last_press_position = position_in_page;+ m_last_press_time = now;++ m_held_mouse_buttons |= report.button;+ auto event = mouse_event(Web::MouseEvent::Type::MouseDown, position_in_page, report.button, m_held_mouse_buttons, report.modifiers);+ event.click_count = m_click_count;+ enqueue_input_event(move(event));+ return;+ }+ }+}++static bool is_typed_character(u32 code_point)+{+ return code_point >= ' ' && code_point != 0x7f;+}++static bool has_shortcut_modifier(KeyModifier modifiers)+{+ return (modifiers & (KeyModifier::Mod_Ctrl | KeyModifier::Mod_Super)) != 0;+}++// The code point a key event carries, as the Qt UI takes it from the text a key types.+static u32 code_point_for_key_event(TerminalKeyReport const& report)+{+ if (!report.text_code_points.is_empty())+ return report.text_code_points.first();+ if (has_flag(report.modifiers, KeyModifier::Mod_Shift) && is_typed_character(report.code_point))+ return report.shifted_code_point.value_or(to_ascii_uppercase(report.code_point));+ return report.code_point;+}++bool TerminalWebView::handle_browser_shortcut(TerminalKeyReport const& report)+{+ auto is_key_with = [&](KeyCode key, KeyModifier modifiers) {+ return report.key == key && report.modifiers == modifiers;+ };++ if (is_key_with(KeyCode::Key_Q, KeyModifier::Mod_Ctrl)) {+ quit();+ return true;+ }+ if (is_key_with(KeyCode::Key_L, KeyModifier::Mod_Ctrl)) {+ open_url_prompt();+ return true;+ }+ if (is_key_with(KeyCode::Key_R, KeyModifier::Mod_Ctrl) || is_key_with(KeyCode::Key_F5, KeyModifier::Mod_None)) {+ reload();+ return true;+ }+ // Terminals that follow the macOS convention send Option+Left and Option+Right as Alt+B and Alt+F, the keys that+ // move a shell's cursor by words.+ if (is_key_with(KeyCode::Key_Left, KeyModifier::Mod_Alt) || is_key_with(KeyCode::Key_B, KeyModifier::Mod_Alt)) {+ traverse_the_history_by_delta(-1);+ return true;+ }+ if (is_key_with(KeyCode::Key_Right, KeyModifier::Mod_Alt) || is_key_with(KeyCode::Key_F, KeyModifier::Mod_Alt)) {+ traverse_the_history_by_delta(1);+ return true;+ }+ return false;+}++void TerminalWebView::handle_url_prompt_key(TerminalKeyReport const& report)+{+ if (report.phase == TerminalKeyReport::Phase::Release)+ return;++ switch (report.key) {+ case KeyCode::Key_Escape:+ m_url_prompt_text.clear();+ break;+ case KeyCode::Key_Return:+ open_url(m_url_prompt_text.release_value());+ break;+ case KeyCode::Key_Backspace: {+ Utf8View text { m_url_prompt_text->view() };+ if (!text.is_empty())+ m_url_prompt_text = ByteString { text.unicode_substring_view(0, text.length() - 1).as_string() };+ break;+ }+ default: {+ auto code_point = code_point_for_key_event(report);+ if (has_shortcut_modifier(report.modifiers) || !is_typed_character(code_point))+ break;+ StringBuilder builder;+ builder.append(*m_url_prompt_text);+ builder.append_code_point(code_point);+ m_url_prompt_text = builder.to_byte_string();+ break;+ }+ }+ draw_status_line();+}++void TerminalWebView::handle_key_report(TerminalKeyReport const& report)+{+ if (m_url_prompt_text.has_value()) {+ handle_url_prompt_key(report);+ return;+ }++ if (report.phase != TerminalKeyReport::Phase::Release && handle_browser_shortcut(report))+ return;++ auto code_point = code_point_for_key_event(report);+ auto types_text = code_point != 0 && (!report.text_code_points.is_empty() || !has_shortcut_modifier(report.modifiers));++ auto key_event = [&](Web::KeyEvent::Type type, bool repeat) {+ Web::KeyEvent event {};+ event.type = type;+ event.key = report.key;+ event.modifiers = report.modifiers;+ event.code_point = code_point;+ event.repeat = repeat;+ event.should_insert_text = type == Web::KeyEvent::Type::KeyDown && types_text;+ return event;+ };++ // A release goes to the page only after its press did, which a shortcut, the URL prompt, or a terminal that turns+ // the press into another key keeps from it.+ auto& is_down_in_page = m_key_is_down_in_page[to_underlying(report.key)];+ switch (report.phase) {+ case TerminalKeyReport::Phase::Press:+ enqueue_input_event(key_event(Web::KeyEvent::Type::KeyDown, false));+ if (report.is_legacy_encoding || !m_terminal_reports_key_releases)+ enqueue_input_event(key_event(Web::KeyEvent::Type::KeyUp, false));+ else+ is_down_in_page = true;+ break;+ case TerminalKeyReport::Phase::Repeat:+ enqueue_input_event(key_event(Web::KeyEvent::Type::KeyDown, true));+ break;+ case TerminalKeyReport::Phase::Release:+ if (!exchange(is_down_in_page, false))+ break;+ enqueue_input_event(key_event(Web::KeyEvent::Type::KeyUp, false));+ break;+ }+}++void TerminalWebView::handle_command(TerminalCommand const& command)+{+ if (command.name == "open"sv) {+ open_url(command.argument);+ } else if (command.name == "back"sv) {+ traverse_the_history_by_delta(-1);+ } else if (command.name == "forward"sv) {+ traverse_the_history_by_delta(1);+ } else if (command.name == "reload"sv) {+ reload();+ } else if (command.name == "quit"sv) {+ quit();+ } else if (command.name == "frames"sv) {+ m_sends_damaged_rectangles = command.argument == "damage"sv;+ m_frame_needs_full_redraw = true;+ schedule_frame_flush();+ show_notice(m_sends_damaged_rectangles ? "sending damaged rectangles" : "sending whole frames");+ } else {+ show_notice(ByteString::formatted("unknown command: {}", command.name));+ }+}++void TerminalWebView::open_url_prompt()+{+ m_url_prompt_text = displayed_url().serialize().to_byte_string();+ draw_status_line();+}++void TerminalWebView::open_url(StringView text)+{+ auto url = sanitize_url(text, Application::settings().search_engine_settings().engine);+ if (!url.has_value()) {+ show_notice(ByteString::formatted("not a URL: {}", text));+ return;+ }+ load(*url);+}++void TerminalWebView::show_notice(ByteString notice)+{+ m_notice = move(notice);+ draw_status_line();++ if (!m_notice_timer) {+ m_notice_timer = Core::Timer::create_single_shot(AK::Duration::from_seconds(5), [this] {+ m_notice = {};+ draw_status_line();+ });+ }+ m_notice_timer->restart();+}++void TerminalWebView::draw_status_line()+{+ if (!m_terminal_modes_entered || m_pane_geometry.rows <= 0 || m_pane_geometry.columns <= 0)+ return;++ StringBuilder text;+ if (m_url_prompt_text.has_value()) {+ text.appendff(" Go to: {}█", *m_url_prompt_text);+ } else {+ auto url = displayed_url().serialize();+ auto heading = title().is_empty() ? url.to_byte_string() : title().to_byte_string();+ text.appendff(" {} — {}", heading, url);+ text.append(" ctrl-l url · ctrl-r reload · alt-←/→ history · ctrl-q quit"sv);+ if (!m_notice.is_empty())+ text.appendff(" · {}", m_notice);+ }+ Utf8View text_view { text.string_view() };+ auto visible_length = min(text_view.length(), static_cast<size_t>(max(0, m_pane_geometry.columns - 2)));+ auto visible_text = text_view.unicode_substring_view(0, visible_length);++ StringBuilder line;+ line.appendff("\x1b[{};1H\x1b[2K", m_pane_geometry.rows);+ if (!m_url_prompt_text.has_value())+ line.appendff("\x1b[{}m●\x1b[0m", is_loading() ? 33 : 32);+ line.appendff("\x1b[2m{}\x1b[0m", visible_text.as_string());++ auto status_line = line.to_byte_string();+ if (status_line == m_drawn_status_line)+ return;+ m_drawn_status_line = status_line;+ write_to_terminal(status_line);+}++}diff --git a/Libraries/LibWebView/TerminalWebView.h b/Libraries/LibWebView/TerminalWebView.hnew file mode 100644index 00000000000..f64bc4a3c9f--- /dev/null+++ b/Libraries/LibWebView/TerminalWebView.h@@ -0,0 +1,115 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Array.h>+#include <AK/ByteBuffer.h>+#include <AK/ByteString.h>+#include <AK/Optional.h>+#include <AK/Time.h>+#include <LibCore/Forward.h>+#include <LibGfx/Rect.h>+#include <LibWebCommon/UIEvents/MouseButton.h>+#include <LibWebView/HeadlessWebView.h>+#include <LibWebView/TerminalInputParser.h>++#include <termios.h>++namespace WebView {++// A view that shows its page in the terminal it was started from: frames as Kitty graphics, and the terminal's mouse+// and keyboard reports as input. The last row of the terminal is a status line.+class WEBVIEW_API TerminalWebView final : public HeadlessWebView {+public:+ // Keeps the terminal for drawing, and sends what this process and every helper it starts would print there to a+ // log file instead. Must run before any helper process is started.+ static ErrorOr<void> take_over_terminal();++ static ErrorOr<NonnullOwnPtr<TerminalWebView>> create(Core::AnonymousBuffer theme, double device_pixel_ratio);+ virtual ~TerminalWebView() override;++private:+ struct PaneGeometry {+ int rows { 0 };+ int columns { 0 };+ Gfx::IntSize pixel_size;++ int cell_width() const { return columns > 0 ? pixel_size.width() / columns : 0; }+ int cell_height() const { return rows > 0 ? pixel_size.height() / rows : 0; }+ // Everything but the last row, which holds the status line.+ Gfx::IntSize page_pixel_size() const { return { columns * cell_width(), (rows - 1) * cell_height() }; }+ };++ enum class GraphicsTransmission : u8 {+ TemporaryFile,+ Direct,+ };++ TerminalWebView(Core::AnonymousBuffer theme, Web::DevicePixelSize viewport_size, double device_pixel_ratio);++ static PaneGeometry query_pane_geometry();++ // ^ViewImplementation+ virtual void did_accept_presented_backing_store(i32 bitmap_id, Gfx::IntRect damage_rect) override;++ void enter_terminal_modes();+ void leave_terminal_modes();+ void quit();+ void write_to_terminal(StringView);++ void apply_pane_geometry();++ void schedule_frame_flush();+ void flush_frame();+ ErrorOr<void> transmit_frame(Gfx::Bitmap const&);+ ErrorOr<void> send_image_data(StringView keys, ReadonlyBytes pixels);++ void handle_input(TerminalInput const&);+ void handle_mouse_report(TerminalMouseReport const&);+ void handle_key_report(TerminalKeyReport const&);+ bool handle_browser_shortcut(TerminalKeyReport const&);+ void handle_url_prompt_key(TerminalKeyReport const&);+ void handle_command(TerminalCommand const&);++ void open_url_prompt();+ void open_url(StringView);+ void show_notice(ByteString);+ void draw_status_line();++ struct termios m_original_terminal_attributes {};+ bool m_terminal_modes_entered { false };+ RefPtr<Core::Notifier> m_input_notifier;+ Vector<int> m_signal_handler_ids;+ TerminalInputParser m_input_parser;+ bool m_terminal_reports_key_releases { false };+ Array<bool, 256> m_key_is_down_in_page {};++ PaneGeometry m_pane_geometry;++ bool m_frame_flush_scheduled { false };+ bool m_frame_needs_full_redraw { true };+ Optional<Gfx::IntRect> m_pending_damage;+ ByteBuffer m_frame_pixels;+ u64 m_image_data_transmissions { 0 };+ GraphicsTransmission m_graphics_transmission { GraphicsTransmission::TemporaryFile };+ bool m_sends_damaged_rectangles { false };+ Optional<u32> m_displayed_image_id;+ Gfx::IntSize m_displayed_image_size;++ Web::UIEvents::MouseButton m_held_mouse_buttons { Web::UIEvents::MouseButton::None };+ Web::UIEvents::MouseButton m_last_pressed_mouse_button { Web::UIEvents::MouseButton::None };+ Gfx::IntPoint m_last_press_position;+ MonotonicTime m_last_press_time { MonotonicTime::now_coarse() };+ int m_click_count { 0 };++ Optional<ByteString> m_url_prompt_text;+ ByteString m_notice;+ RefPtr<Core::Timer> m_notice_timer;+ ByteString m_drawn_status_line;+};++}