Truly independent web browser
UI/Qt: Rework the browser chrome
Andreas Kling9e0caee0507e
diff --git a/.devcontainer/features/ladybird/install-ubuntu.sh b/.devcontainer/features/ladybird/install-ubuntu.shindex c5fd96527d7..0a67a2b2201 100644--- a/.devcontainer/features/ladybird/install-ubuntu.sh+++ b/.devcontainer/features/ladybird/install-ubuntu.sh@@ -31,7 +31,7 @@ install_cmake() {### Install packagesapt update -y-apt install -y autoconf autoconf-archive automake build-essential ccache curl fonts-liberation2 git glslang-tools libdrm-dev libgl1-mesa-dev libncurses-dev libpulse-dev libtool libxcb-icccm4-dev lsb-release nasm ninja-build pkg-config python3 qt6-base-private-dev qt6-positioning-dev qt6-tools-dev-tools qt6-wayland shellcheck tar unzip zip+apt install -y autoconf autoconf-archive automake build-essential ccache curl fonts-liberation2 git glslang-tools libdrm-dev libgl1-mesa-dev libncurses-dev libpulse-dev libtool libwayland-dev libxcb-icccm4-dev lsb-release nasm ninja-build pkg-config python3 qt6-base-private-dev qt6-positioning-dev qt6-tools-dev-tools qt6-wayland shellcheck tar unzip zipinstall_cmakediff --git a/Documentation/BuildInstructionsLadybird.md b/Documentation/BuildInstructionsLadybird.mdindex 7525ccc1891..0f3bd03399a 100644--- a/Documentation/BuildInstructionsLadybird.md+++ b/Documentation/BuildInstructionsLadybird.md@@ -20,7 +20,7 @@ CMake 3.30 or newer must be available in $PATH.<!-- Note: If you change something here, please also change it in the `devcontainer/devcontainer.json` file. -->```bash-sudo apt install autoconf autoconf-archive automake build-essential ccache cmake curl fonts-liberation2 git glslang-tools libdrm-dev libgl1-mesa-dev libncurses-dev libpulse-dev libtool libxcb-icccm4-dev nasm ninja-build pkg-config python3-venv qt6-base-private-dev qt6-positioning-dev qt6-tools-dev-tools qt6-wayland tar unzip zip+sudo apt install autoconf autoconf-archive automake build-essential ccache cmake curl fonts-liberation2 git glslang-tools libdrm-dev libgl1-mesa-dev libncurses-dev libpulse-dev libtool libwayland-dev libxcb-icccm4-dev nasm ninja-build pkg-config python3-venv qt6-base-private-dev qt6-positioning-dev qt6-tools-dev-tools qt6-wayland tar unzip zip```#### CMake 3.30 or newer:@@ -70,7 +70,7 @@ sudo apt update && sudo apt install g++-16 libstdc++-16-dev### Arch Linux/Manjaro:```-sudo pacman -S --needed autoconf-archive base-devel ccache cmake curl git less libgl libpulse nasm ninja python qt6-base qt6-positioning qt6-tools ttf-liberation tar unzip xcb-util-wm zip+sudo pacman -S --needed autoconf-archive base-devel ccache cmake curl git less libgl libpulse nasm ninja python qt6-base qt6-positioning qt6-tools ttf-liberation tar unzip wayland xcb-util-wm zip```### Fedora or derivatives:diff --git a/Tests/UI/Qt/CMakeLists.txt b/Tests/UI/Qt/CMakeLists.txtindex a28bb9149d9..be27bc7b735 100644--- a/Tests/UI/Qt/CMakeLists.txt+++ b/Tests/UI/Qt/CMakeLists.txt@@ -3,6 +3,19 @@ if (NOT Qt6_FOUND)return()endif()+# The chrome's styles take their colors from the theme, which follows the system's appearance.+function(add_chrome_style_sources target)+ target_sources(${target} PRIVATE+ "${LADYBIRD_SOURCE_DIR}/UI/Qt/SystemAppearance.cpp"+ "${LADYBIRD_SOURCE_DIR}/UI/Qt/Theme.cpp"+ )+ if (APPLE)+ target_sources(${target} PRIVATE "${LADYBIRD_SOURCE_DIR}/UI/Qt/SystemAppearanceMac.mm")+ target_link_libraries(${target} PRIVATE "-framework AppKit")+ endif()+ set_target_properties(${target} PROPERTIES AUTOMOC ON)+endfunction()+add_library(QtEventLoopTestMain OBJECTQtEventLoopTestMain.cpp"${LADYBIRD_SOURCE_DIR}/Libraries/LibTest/AssertionHandler.cpp"@@ -70,12 +83,13 @@ if (APPLE OR LINUX)"${LADYBIRD_SOURCE_DIR}/UI/Qt/ReportReview.cpp""${LADYBIRD_SOURCE_DIR}/UI/Qt/StringUtils.cpp")+ add_chrome_style_sources(TestCrashReportReviewWidget)deploy_qt_offscreen_platform_plugin(TestCrashReportReviewWidget)endif()ladybird_test("TestScreenshotSelectionOverlay.cpp" UI/QtCUSTOM_MAIN "$<TARGET_OBJECTS:QtTestMain>"- LIBS LibURL Qt::Core Qt::Gui Qt::Widgets+ LIBS LibCore LibURL Qt::Core Qt::Gui Qt::Widgets)target_sources(TestScreenshotSelectionOverlay PRIVATE"${LADYBIRD_SOURCE_DIR}/UI/Qt/ChromeStyle.cpp"@@ -84,8 +98,21 @@ target_sources(TestScreenshotSelectionOverlay PRIVATE"${LADYBIRD_SOURCE_DIR}/UI/Qt/ScreenshotSelectionOverlay.cpp""${LADYBIRD_SOURCE_DIR}/UI/Qt/StringUtils.cpp")+add_chrome_style_sources(TestScreenshotSelectionOverlay)deploy_qt_offscreen_platform_plugin(TestScreenshotSelectionOverlay)+ladybird_test("TestChromeIcons.cpp" UI/Qt+ CUSTOM_MAIN "$<TARGET_OBJECTS:QtTestMain>"+ LIBS LibURL Qt::Core Qt::Gui Qt::Widgets+)+target_sources(TestChromeIcons PRIVATE+ "${LADYBIRD_SOURCE_DIR}/UI/Qt/ChromeStyle.cpp"+ "${LADYBIRD_SOURCE_DIR}/UI/Qt/Icon.cpp"+ "${LADYBIRD_SOURCE_DIR}/UI/Qt/StringUtils.cpp"+)+add_chrome_style_sources(TestChromeIcons)+deploy_qt_offscreen_platform_plugin(TestChromeIcons)+ladybird_test("TestScreenshotViewer.cpp" UI/QtCUSTOM_MAIN "$<TARGET_OBJECTS:QtTestMain>"LIBS LibURL Qt::Core Qt::Gui Qt::Widgets@@ -95,6 +122,7 @@ target_sources(TestScreenshotViewer PRIVATE"${LADYBIRD_SOURCE_DIR}/UI/Qt/ScreenshotViewer.cpp""${LADYBIRD_SOURCE_DIR}/UI/Qt/StringUtils.cpp")+add_chrome_style_sources(TestScreenshotViewer)deploy_qt_offscreen_platform_plugin(TestScreenshotViewer)ladybird_test("TestWebCompatReportReview.cpp" UI/Qt@@ -108,6 +136,7 @@ target_sources(TestWebCompatReportReview PRIVATE"${LADYBIRD_SOURCE_DIR}/UI/Qt/StringUtils.cpp""${LADYBIRD_SOURCE_DIR}/UI/Qt/WebCompatReportReview.cpp")+add_chrome_style_sources(TestWebCompatReportReview)deploy_qt_offscreen_platform_plugin(TestWebCompatReportReview)ladybird_test("TestHiddenPageSizing.cpp" UI/Qt@@ -138,6 +167,7 @@ target_sources(TestProcessManagerWindow PRIVATE"${LADYBIRD_SOURCE_DIR}/UI/Qt/ProcessManagerWindow.cpp""${LADYBIRD_SOURCE_DIR}/UI/Qt/StringUtils.cpp")+add_chrome_style_sources(TestProcessManagerWindow)target_compile_definitions(TestProcessManagerWindow PRIVATE TEST_RESOURCE_ROOT="${LADYBIRD_SOURCE_DIR}/Base/res")deploy_qt_offscreen_platform_plugin(TestProcessManagerWindow)@@ -166,14 +196,17 @@ deploy_qt_offscreen_platform_plugin(TestNativeWindowContainerFocus)ladybird_test("TestJavaScriptDialog.cpp" UI/QtCUSTOM_MAIN "$<TARGET_OBJECTS:QtTestMain>"- LIBS LibURL Qt::Core Qt::Gui Qt::Widgets+ LIBS LibCore LibURL Qt::Core Qt::Gui Qt::Widgets)target_sources(TestJavaScriptDialog PRIVATE"${LADYBIRD_SOURCE_DIR}/UI/Qt/ChromeStyle.cpp"+ "${LADYBIRD_SOURCE_DIR}/UI/Qt/Icon.cpp""${LADYBIRD_SOURCE_DIR}/UI/Qt/JavaScriptDialog.cpp""${LADYBIRD_SOURCE_DIR}/UI/Qt/NativeTextEditingLineEdit.cpp"+ "${LADYBIRD_SOURCE_DIR}/UI/Qt/Popover.cpp""${LADYBIRD_SOURCE_DIR}/UI/Qt/StringUtils.cpp")+add_chrome_style_sources(TestJavaScriptDialog)deploy_qt_offscreen_platform_plugin(TestJavaScriptDialog)ladybird_test("TestWindowCloseCoordinator.cpp" UI/Qt LIBS Qt::Core)diff --git a/Tests/UI/Qt/TestChromeIcons.cpp b/Tests/UI/Qt/TestChromeIcons.cppnew file mode 100644index 00000000000..a7f6dd9ee6b--- /dev/null+++ b/Tests/UI/Qt/TestChromeIcons.cpp@@ -0,0 +1,36 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/StdLibExtras.h>+#include <LibTest/TestCase.h>+#include <UI/Qt/Icon.h>++#include <QImage>+#include <QPixmap>++static bool has_visible_pixel(QPixmap const& pixmap)+{+ auto image = pixmap.toImage();+ for (int y = 0; y < image.height(); ++y) {+ for (int x = 0; x < image.width(); ++x) {+ if (qAlpha(image.pixel(x, y)) != 0)+ return true;+ }+ }+ return false;+}++// Every icon is drawn at each device pixel ratio, which takes the 1x screen's own drawings for the icons that have them.+TEST_CASE(every_chrome_icon_draws_at_every_device_pixel_ratio)+{+ for (auto value = to_underlying(Ladybird::ChromeIcon::Back); value <= to_underlying(Ladybird::ChromeIcon::WindowClose); ++value) {+ auto icon = static_cast<Ladybird::ChromeIcon>(value);+ for (auto device_pixel_ratio : Ladybird::ICON_DEVICE_PIXEL_RATIOS) {+ auto pixmap = Ladybird::create_chrome_icon_pixmap(icon, QColor(0, 0, 0), device_pixel_ratio);+ EXPECT(has_visible_pixel(pixmap));+ }+ }+}diff --git a/Tests/UI/Qt/TestJavaScriptDialog.cpp b/Tests/UI/Qt/TestJavaScriptDialog.cppindex a33e90f229b..f27902d4a02 100644--- a/Tests/UI/Qt/TestJavaScriptDialog.cpp+++ b/Tests/UI/Qt/TestJavaScriptDialog.cpp@@ -8,6 +8,7 @@#include <LibTest/TestCase.h>#include <QApplication>+#include <QCheckBox>#include <QDialogButtonBox>#include <QFrame>#include <QKeyEvent>@@ -147,6 +148,31 @@ TEST_CASE(alert_and_confirm_report_the_expected_results)EXPECT(completion.accepted);}+TEST_CASE(only_offered_dialogs_can_block_further_dialogs)+{+ QWidget web_view;+ web_view.resize(800, 600);+ web_view.show();++ Ladybird::JavaScriptDialog dialog(&web_view);+ auto* checkbox = dialog.findChild<QCheckBox*>("LadybirdJavaScriptDialogBlockFurtherDialogs");+ VERIFY(checkbox);++ dialog.show_alert("https://example.com", "First alert");+ EXPECT(checkbox->isHidden());+ checkbox->setChecked(true);+ dialog.accept();+ EXPECT(!dialog.blocks_further_dialogs());++ dialog.show_confirm("https://example.com", "Second dialog", Ladybird::JavaScriptDialog::OfferToBlockFurtherDialogs::Yes);+ EXPECT(checkbox->isVisible());+ EXPECT(!checkbox->isChecked());+ EXPECT(!dialog.blocks_further_dialogs());+ checkbox->setChecked(true);+ dialog.dismiss();+ EXPECT(dialog.blocks_further_dialogs());+}+TEST_CASE(prompt_supports_defaults_updates_and_keyboard_completion){QWidget web_view;@@ -361,7 +387,7 @@ TEST_CASE(dialog_takes_its_views_size_when_it_opens)EXPECT_EQ(dialog.geometry(), web_view.rect());auto* panel = dialog.findChild<QFrame*>("LadybirdJavaScriptDialogPanel");VERIFY(panel);- EXPECT_EQ(panel->minimumWidth(), 320);+ EXPECT_EQ(panel->width(), 440);dialog.dismiss();}diff --git a/Tests/UI/Qt/TestProcessManagerWindow.cpp b/Tests/UI/Qt/TestProcessManagerWindow.cppindex d791671ff9c..86d58afb9f2 100644--- a/Tests/UI/Qt/TestProcessManagerWindow.cpp+++ b/Tests/UI/Qt/TestProcessManagerWindow.cpp@@ -64,9 +64,9 @@ TEST_CASE(search_keeps_matching_child_processes_visible)auto* processes = window.findChild<QTreeWidget*>();auto* search = window.findChild<QLineEdit*>();- auto* browser = new QTreeWidgetItem(processes, { "Browser", "123" });- auto* page = new QTreeWidgetItem(processes, { "WebContent - Example", "456" });- auto* frame = new QTreeWidgetItem(page, { "WebContent - Child frame", "789" });+ auto* browser = new QTreeWidgetItem(processes, { "Browser", {}, {}, "123" });+ auto* page = new QTreeWidgetItem(processes, { "WebContent - Example", {}, {}, "456" });+ auto* frame = new QTreeWidgetItem(page, { "WebContent - Child frame", {}, {}, "789" });search->setText("CHILD");EXPECT(browser->isHidden());@@ -127,7 +127,7 @@ TEST_CASE(browser_is_not_terminable_and_can_be_copied)if (action->text() == "Copy PID") {EXPECT(action->isEnabled());action->trigger();- EXPECT_EQ(QApplication::clipboard()->text(), browser->text(1));+ EXPECT_EQ(QApplication::clipboard()->text(), browser->text(3));}}}@@ -159,22 +159,34 @@ TEST_CASE(end_process_terminates_a_child_and_handles_disappearing_selection)auto* processes = window.findChild<QTreeWidget*>();auto* button = window.findChild<QPushButton*>();auto* timer = window.findChild<QTimer*>();- EXPECT_EQ(processes->topLevelItemCount(), 1);- auto* browser = processes->topLevelItem(0);- EXPECT_EQ(browser->childCount(), 1);- auto* child_item = browser->child(0);- EXPECT_EQ(child_item->data(1, Qt::UserRole).toLongLong(), pid);- EXPECT_EQ(child_item->data(1, Qt::UserRole + 1).toULongLong(), identity.child_id);- auto blank_icon = child_item->icon(0).pixmap(16, 16).toImage();+ auto find_row = [&](u64 child_id) -> QTreeWidgetItem* {+ for (int i = 0; i < processes->topLevelItemCount(); ++i) {+ if (processes->topLevelItem(i)->data(3, Qt::UserRole + 1).toULongLong() == child_id)+ return processes->topLevelItem(i);+ }+ return nullptr;+ };++ // A page process that shows no site is listed with the browser's own processes.+ EXPECT_EQ(processes->topLevelItemCount(), 2);+ auto* child_item = find_row(identity.child_id);+ EXPECT(child_item);+ EXPECT_EQ(child_item->data(3, Qt::UserRole).toLongLong(), pid);++ // A spare one is listed apart, under a heading of its own.manager.find_process(pid)->set_title("(spare)"_utf16);EXPECT(QMetaObject::invokeMethod(timer, "timeout", Qt::DirectConnection));- EXPECT(child_item->text(0).contains("(spare)"));- EXPECT(child_item->icon(0).pixmap(16, 16).toImage() != blank_icon);+ EXPECT_EQ(processes->topLevelItemCount(), 3);+ EXPECT_EQ(processes->topLevelItem(1)->text(0), QString("Spare"));+ EXPECT(find_row(identity.child_id));manager.find_process(pid)->set_title({});EXPECT(QMetaObject::invokeMethod(timer, "timeout", Qt::DirectConnection));- EXPECT_EQ(child_item->icon(0).pixmap(16, 16).toImage(), blank_icon);+ EXPECT_EQ(processes->topLevelItemCount(), 2);++ child_item = find_row(identity.child_id);processes->setCurrentItem(child_item);EXPECT(button->isEnabled());+ EXPECT_EQ(button->text(), QString("End Process"));bool inspected_menu = false;QTimer::singleShot(0, &window, [&] {auto* menu = qobject_cast<QMenu*>(QApplication::activePopupWidget());@@ -196,13 +208,13 @@ TEST_CASE(end_process_terminates_a_child_and_handles_disappearing_selection)EXPECT_EQ(WTERMSIG(status.status), SIGKILL);EXPECT(!button->isEnabled());- processes->setCurrentItem(browser->child(0));+ processes->setCurrentItem(find_row(identity.child_id));EXPECT(button->isEnabled());(void)manager.remove_process(identity.child_id);button->click();EXPECT(!button->isEnabled());EXPECT(QMetaObject::invokeMethod(timer, "timeout", Qt::DirectConnection));- EXPECT_EQ(browser->childCount(), 0);+ EXPECT(!find_row(identity.child_id));EXPECT(!button->isEnabled());EXPECT(processes->selectedItems().isEmpty());}diff --git a/Tests/UI/Qt/TestScreenshotSelectionOverlay.cpp b/Tests/UI/Qt/TestScreenshotSelectionOverlay.cppindex f16cacc3be6..acc84cc5b8c 100644--- a/Tests/UI/Qt/TestScreenshotSelectionOverlay.cpp+++ b/Tests/UI/Qt/TestScreenshotSelectionOverlay.cpp@@ -146,8 +146,8 @@ TEST_CASE(the_instructions_keep_their_padding_when_their_buttons_grow)QApplication::processEvents();for (auto* button : buttons) {- EXPECT(button->geometry().top() >= 12);- EXPECT(instructions->height() - button->geometry().bottom() - 1 >= 12);+ EXPECT(button->geometry().top() >= 8);+ EXPECT(instructions->height() - button->geometry().bottom() - 1 >= 8);}}diff --git a/Tests/UI/Qt/TestWebCompatReportReview.cpp b/Tests/UI/Qt/TestWebCompatReportReview.cppindex 81f1d94d27a..2efab16e8af 100644--- a/Tests/UI/Qt/TestWebCompatReportReview.cpp+++ b/Tests/UI/Qt/TestWebCompatReportReview.cpp@@ -50,9 +50,9 @@ TEST_CASE(the_review_shows_the_website_and_the_selected_screenshot)WebCompatReportReview review { test_page(), test_screenshot(), nullptr };review.show();- EXPECT_EQ(child<QLabel>(review, "WebCompatReportWebsite").text(), "https://example.com/broken");+ EXPECT_EQ(child<QLabel>(review, "WebCompatReportWebsite").text(), "example.com/broken");EXPECT(child<QWidget>(review, "WebCompatReportScreenshot").isVisible());- EXPECT_EQ(child<QPushButton>(review, "WebCompatReportSelectScreenshotButton").text(), "Retake screenshot");+ EXPECT_EQ(child<QPushButton>(review, "WebCompatReportSelectScreenshotButton").text(), "Retake");EXPECT(child<QPushButton>(review, "WebCompatReportRemoveScreenshotButton").isVisible());}@@ -98,7 +98,7 @@ TEST_CASE(a_report_without_a_screenshot_offers_to_take_one)review.set_screenshot(test_screenshot());EXPECT(child<QWidget>(review, "WebCompatReportScreenshot").isVisible());- EXPECT_EQ(select_button.text(), "Retake screenshot");+ EXPECT_EQ(select_button.text(), "Retake");}TEST_CASE(page_dumps_can_be_included_once_they_have_arrived)@@ -161,15 +161,25 @@ TEST_CASE(leaving_the_review_closes_its_tab)review.show();auto& review_close = child<QPushButton>(review, "WebCompatReportReviewCloseButton");- EXPECT_EQ(review_close.text(), "Close tab");+ EXPECT_EQ(review_close.text(), "Cancel");review_close.click();EXPECT_EQ(exits, 1);review.show_sent();+ auto& back_to_site = child<QPushButton>(review, "WebCompatReportBackToSiteButton");+ EXPECT_EQ(back_to_site.text(), "Back to the site");+ EXPECT(back_to_site.isVisible());+ back_to_site.click();+ EXPECT_EQ(exits, 2);++ // Closing the tab once the report is sent does not have to return to the site.+ auto closes = 0;+ review.on_close_tab = [&] { ++closes; };auto& close = child<QPushButton>(review, "WebCompatReportCloseButton");EXPECT_EQ(close.text(), "Close tab");close.click();EXPECT_EQ(exits, 2);+ EXPECT_EQ(closes, 1);}TEST_CASE(sending_can_be_canceled_until_the_report_is_sent)@@ -206,7 +216,8 @@ TEST_CASE(sending_can_be_canceled_until_the_report_is_sent)EXPECT(!retry.isVisible());EXPECT(!cancel.isVisible());EXPECT(close.isVisible());- EXPECT(close.isDefault());+ EXPECT(!close.isDefault());+ EXPECT(child<QPushButton>(review, "WebCompatReportBackToSiteButton").isVisible());}TEST_CASE(a_screenshot_is_shrunk_to_fit_a_report)diff --git a/UI/Qt/AllTabsPopover.cpp b/UI/Qt/AllTabsPopover.cppnew file mode 100644index 00000000000..a0e6cff47ab--- /dev/null+++ b/UI/Qt/AllTabsPopover.cpp@@ -0,0 +1,314 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <UI/Qt/AllTabsPopover.h>+#include <UI/Qt/ChromeStyle.h>+#include <UI/Qt/Icon.h>+#include <UI/Qt/Theme.h>++#include <QAction>+#include <QFontMetricsF>+#include <QFrame>+#include <QKeyEvent>+#include <QLabel>+#include <QLineEdit>+#include <QPainter>+#include <QPainterPath>+#include <QScrollArea>+#include <QScrollBar>+#include <QVBoxLayout>+#include <QtMath>++namespace Ladybird {++static constexpr int POPOVER_WIDTH = 384;+static constexpr int ROW_HEIGHT = 30;+static constexpr int ROW_RADIUS = 6;+static constexpr int ROW_HORIZONTAL_PADDING = 10;+static constexpr int ROW_ICON_SIZE = 16;+static constexpr int ROW_GAP = 10;+static constexpr int LIST_MAX_HEIGHT = 420;+// A list that scrolls fades out over the bottom of its visible part.+static constexpr int LIST_FADE_HEIGHT = 50;++// Rows of tabs, each with its favicon, title and site. The current tab's row is filled and its title bold.+class AllTabsList final : public QWidget {+public:+ AK_ALLOC_WITH_KMALLOC;++ // The open tabs keep a row highlighted for the keyboard, while the recently closed ones only follow the pointer.+ enum class Highlight : u8 {+ Keyboard,+ Pointer,+ };++ AllTabsList(Highlight highlight, QWidget* parent)+ : QWidget(parent)+ , m_highlight(highlight)+ {+ setMouseTracking(true);+ }++ Function<void(size_t)> on_activate;++ void set_entries(Vector<AllTabsPopover::Entry> entries)+ {+ m_entries = AK::move(entries);+ filter({});+ }++ void filter(QString const& query)+ {+ m_rows.clear();+ for (size_t index = 0; index < m_entries.size(); ++index) {+ auto const& entry = m_entries[index];+ if (query.isEmpty() || entry.title.contains(query, Qt::CaseInsensitive) || entry.detail.contains(query, Qt::CaseInsensitive))+ m_rows.append(index);+ }++ // The current tab starts out highlighted, and otherwise the first match.+ m_highlighted_row = m_rows.is_empty() || m_highlight == Highlight::Pointer ? -1 : 0;+ if (query.isEmpty()) {+ for (size_t row = 0; row < m_rows.size(); ++row) {+ if (m_entries[m_rows[row]].is_current)+ m_highlighted_row = static_cast<int>(row);+ }+ }+ setFixedSize(POPOVER_WIDTH - 12, static_cast<int>(m_rows.size()) * ROW_HEIGHT);+ update();+ }++ int highlighted_row() const { return m_highlighted_row; }+ QRect row_rect(int row) const { return { 0, row * ROW_HEIGHT, width(), ROW_HEIGHT }; }+ size_t row_count() const { return m_rows.size(); }++ void move_highlight(int delta)+ {+ if (m_rows.is_empty())+ return;+ m_highlighted_row = clamp(m_highlighted_row + delta, 0, static_cast<int>(m_rows.size()) - 1);+ update();+ }++ void activate_highlighted_row()+ {+ if (m_highlighted_row >= 0 && on_activate)+ on_activate(m_rows[m_highlighted_row]);+ }++private:+ virtual void paintEvent(QPaintEvent*) override+ {+ QPainter painter(this);+ painter.setRenderHint(QPainter::Antialiasing);+ auto const& panel = Theme::panel();++ auto title_font = font();+ auto detail_font = font();+ detail_font.setPixelSize(12);+ QFontMetricsF detail_metrics(detail_font);++ for (size_t row = 0; row < m_rows.size(); ++row) {+ auto const& entry = m_entries[m_rows[row]];+ auto rect = row_rect(static_cast<int>(row));++ if (entry.is_current || static_cast<int>(row) == m_highlighted_row) {+ QPainterPath path;+ path.addRoundedRect(QRectF(rect), ROW_RADIUS, ROW_RADIUS);+ painter.fillPath(path, static_cast<int>(row) == m_highlighted_row && !entry.is_current ? panel.pressed : panel.control);+ }++ auto x = rect.left() + ROW_HORIZONTAL_PADDING;+ QRect icon_rect { x, rect.center().y() - (ROW_ICON_SIZE / 2) + 1, ROW_ICON_SIZE, ROW_ICON_SIZE };+ auto icon = entry.icon.isNull() ? create_chrome_icon(ChromeIcon::Globe, panel.muted) : entry.icon;+ icon.paint(&painter, icon_rect);+ x += ROW_ICON_SIZE + ROW_GAP;++ auto right = rect.right() + 1 - ROW_HORIZONTAL_PADDING;+ auto detail_width = min(qCeil(detail_metrics.horizontalAdvance(entry.detail)), (right - x) / 2);+ painter.setFont(detail_font);+ painter.setPen(panel.muted);+ painter.drawText(QRect(right - detail_width, rect.top(), detail_width, rect.height()), Qt::AlignVCenter | Qt::AlignRight, detail_metrics.elidedText(entry.detail, Qt::ElideMiddle, detail_width));++ painter.setFont(title_font);+ painter.setPen(panel.text);+ auto title_width = right - detail_width - ROW_GAP - x;+ painter.drawText(QRect(x, rect.top(), title_width, rect.height()), Qt::AlignVCenter | Qt::AlignLeft, QFontMetrics(title_font).elidedText(entry.title, Qt::ElideRight, title_width));+ }++ // More rows below the visible part of the list fade in from under it.+ auto visible = visibleRegion().boundingRect();+ if (visible.bottom() < height() - 1) {+ auto fade_top = visible.bottom() + 1 - LIST_FADE_HEIGHT;+ QLinearGradient fade(0, fade_top, 0, visible.bottom() + 1);+ auto transparent_surface = panel.surface;+ transparent_surface.setAlpha(0);+ fade.setColorAt(0.0, transparent_surface);+ fade.setColorAt(1.0, panel.surface);+ painter.fillRect(QRect(0, fade_top, width(), LIST_FADE_HEIGHT), fade);+ }+ }++ virtual void mouseMoveEvent(QMouseEvent* event) override+ {+ auto row = event->position().toPoint().y() / ROW_HEIGHT;+ if (row >= 0 && row < static_cast<int>(m_rows.size()) && row != m_highlighted_row) {+ m_highlighted_row = row;+ update();+ }+ }++ virtual void leaveEvent(QEvent*) override+ {+ if (m_highlight == Highlight::Pointer && m_highlighted_row >= 0) {+ m_highlighted_row = -1;+ update();+ }+ }++ virtual void mouseReleaseEvent(QMouseEvent* event) override+ {+ if (event->button() != Qt::LeftButton || !rect().contains(event->position().toPoint()))+ return;+ m_highlighted_row = event->position().toPoint().y() / ROW_HEIGHT;+ activate_highlighted_row();+ }++ Highlight m_highlight { Highlight::Keyboard };+ Vector<AllTabsPopover::Entry> m_entries;+ Vector<size_t> m_rows;+ int m_highlighted_row { -1 };+};++AllTabsPopover::AllTabsPopover(QWidget* parent)+ : Popover(parent)+{+ setAccessibleName("All tabs");+ card().setObjectName("LadybirdAllTabsPopover");+ card().setFixedWidth(POPOVER_WIDTH);++ auto* layout = new QVBoxLayout(&card());+ layout->setContentsMargins(6, 8, 6, 6);+ layout->setSpacing(0);++ m_search_field = new QLineEdit(&card());+ m_search_field->setObjectName("LadybirdAllTabsSearch");+ m_search_field->setAccessibleName("Search tabs");+ m_search_field->addAction(create_chrome_icon(ChromeIcon::Search, Theme::panel().muted), QLineEdit::LeadingPosition);+ m_search_field->installEventFilter(this);+ QObject::connect(m_search_field, &QLineEdit::textChanged, this, [this] { update_search(); });+ auto* search_row = new QHBoxLayout;+ search_row->setContentsMargins(4, 0, 4, 0);+ search_row->addWidget(m_search_field);+ layout->addLayout(search_row);+ layout->addSpacing(8);++ m_tab_list = new AllTabsList(AllTabsList::Highlight::Keyboard, &card());+ m_tab_list->on_activate = [this](size_t index) {+ close();+ if (on_tab_activated)+ on_tab_activated(index);+ };++ m_scroll_area = new QScrollArea(&card());+ m_scroll_area->setObjectName("LadybirdAllTabsList");+ m_scroll_area->setFrameShape(QFrame::NoFrame);+ m_scroll_area->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);+ m_scroll_area->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);+ m_scroll_area->setWidget(m_tab_list);+ // NB: QScrollArea fills the background of the widget it scrolls, but the list sits on the card.+ m_tab_list->setAutoFillBackground(false);+ m_scroll_area->viewport()->setAutoFillBackground(false);+ // NB: The fade at the bottom of the list moves with the visible part, so scrolling repaints the whole list.+ QObject::connect(m_scroll_area->verticalScrollBar(), &QScrollBar::valueChanged, m_tab_list, qOverload<>(&QWidget::update));+ layout->addWidget(m_scroll_area);++ // The tabs closed most recently, below the open ones.+ m_recently_closed_section = new QWidget(&card());+ auto* section_layout = new QVBoxLayout(m_recently_closed_section);+ section_layout->setContentsMargins(0, 6, 0, 0);+ section_layout->setSpacing(0);+ auto* separator = new QFrame(m_recently_closed_section);+ separator->setObjectName("LadybirdPopoverSeparator");+ separator->setFixedHeight(1);+ auto* separator_row = new QHBoxLayout;+ separator_row->setContentsMargins(10, 0, 10, 0);+ separator_row->addWidget(separator);+ section_layout->addLayout(separator_row);+ section_layout->addSpacing(6);+ auto* heading = new QLabel("Recently closed", m_recently_closed_section);+ heading->setObjectName("LadybirdAllTabsHeading");+ heading->setContentsMargins(10, 4, 10, 4);+ section_layout->addWidget(heading);+ m_recently_closed_list = new AllTabsList(AllTabsList::Highlight::Pointer, m_recently_closed_section);+ m_recently_closed_list->on_activate = [this](size_t index) {+ close();+ if (on_recently_closed_activated)+ on_recently_closed_activated(index);+ };+ section_layout->addWidget(m_recently_closed_list);+ layout->addWidget(m_recently_closed_section);+}++void AllTabsPopover::set_recently_closed(Vector<Entry> entries)+{+ m_recently_closed_list->set_entries(AK::move(entries));+ update_search();+}++void AllTabsPopover::set_tabs(Vector<Entry> entries)+{+ m_search_field->setPlaceholderText(QString("Search %1 tabs").arg(entries.size()));+ m_tab_list->set_entries(AK::move(entries));+ m_search_field->clear();+ update_search();+}++void AllTabsPopover::update_search()+{+ auto query = m_search_field->text().trimmed();+ m_tab_list->filter(query);+ m_scroll_area->setFixedHeight(min(LIST_MAX_HEIGHT, m_tab_list->height()));+ m_recently_closed_list->filter(query);+ m_recently_closed_section->setVisible(m_recently_closed_list->row_count() > 0);+ if (auto row = m_tab_list->highlighted_row(); row >= 0)+ m_scroll_area->ensureVisible(0, m_tab_list->row_rect(row).center().y(), 0, ROW_HEIGHT);+ card().adjustSize();+ adjustSize();+}++void AllTabsPopover::showEvent(QShowEvent* event)+{+ Popover::showEvent(event);+ m_search_field->setFocus();+}++bool AllTabsPopover::eventFilter(QObject* watched, QEvent* event)+{+ if (watched == m_search_field && event->type() == QEvent::KeyPress) {+ auto key = static_cast<QKeyEvent*>(event)->key();+ if (key == Qt::Key_Up || key == Qt::Key_Down) {+ m_tab_list->move_highlight(key == Qt::Key_Up ? -1 : 1);+ m_scroll_area->ensureVisible(0, m_tab_list->row_rect(m_tab_list->highlighted_row()).center().y(), 0, ROW_HEIGHT);+ return true;+ }+ if (key == Qt::Key_Return || key == Qt::Key_Enter) {+ m_tab_list->activate_highlighted_row();+ return true;+ }+ }+ return Popover::eventFilter(watched, event);+}++void AllTabsPopover::update_chrome_style(QPalette const& palette)+{+ setPalette(palette);+ setStyleSheet(ChromeStyle::all_tabs_popover_style_sheet(palette));+ m_tab_list->update();+ m_recently_closed_list->update();+}++}diff --git a/UI/Qt/AllTabsPopover.h b/UI/Qt/AllTabsPopover.hnew file mode 100644index 00000000000..9e881e78ee7--- /dev/null+++ b/UI/Qt/AllTabsPopover.h@@ -0,0 +1,55 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Function.h>+#include <AK/Vector.h>+#include <UI/Qt/Popover.h>++#include <QIcon>++class QLineEdit;+class QScrollArea;++namespace Ladybird {++class AllTabsList;++// Every tab in the window, with a field that searches them.+class AllTabsPopover final : public Popover {+public:+ AK_ALLOC_WITH_KMALLOC;++ explicit AllTabsPopover(QWidget* parent);++ struct Entry {+ QIcon icon;+ QString title;+ QString detail;+ bool is_current { false };+ };+ void set_tabs(Vector<Entry>);+ void set_recently_closed(Vector<Entry>);+ void update_chrome_style(QPalette const&);++ Function<void(size_t)> on_tab_activated;+ Function<void(size_t)> on_recently_closed_activated;++private:+ virtual void showEvent(QShowEvent*) override;+ virtual bool eventFilter(QObject*, QEvent*) override;++ void update_search();++ QLineEdit* m_search_field { nullptr };+ QScrollArea* m_scroll_area { nullptr };+ AllTabsList* m_tab_list { nullptr };+ QWidget* m_recently_closed_section { nullptr };+ AllTabsList* m_recently_closed_list { nullptr };+};++}diff --git a/UI/Qt/Application.cpp b/UI/Qt/Application.cppindex 7ea3bc21c3b..82dc96de482 100644--- a/UI/Qt/Application.cpp+++ b/UI/Qt/Application.cpp@@ -20,6 +20,8 @@#include <UI/Qt/PictureInPictureWindow.h>#include <UI/Qt/ProcessManagerWindow.h>#include <UI/Qt/StringUtils.h>+#include <UI/Qt/Tab.h>+#include <UI/Qt/Theme.h>#include <UI/Qt/WebContentView.h>#if defined(AK_OS_MACOS)@@ -312,7 +314,7 @@ public:m_new_private_window_action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_N));QObject::connect(m_new_private_window_action, &QAction::triggered, this, []() { Application::the().open_new_window(WebView::IsPrivate::Yes); });- m_reopen_recently_closed_tab_action = make_action("&Reopen Recently Closed Tab");+ m_reopen_recently_closed_tab_action = make_action("&Reopen Closed Tab");m_reopen_recently_closed_tab_action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_T));QObject::connect(m_reopen_recently_closed_tab_action, &QAction::triggered, this, []() { Application::the().reopen_recently_closed_tab(Application::the().active_window_if_any()); });update_reopen_recently_closed_action();@@ -362,7 +364,21 @@ public:window->open_previous_tab();});- m_open_file_action = make_action("&Open File...");+ m_search_tabs_action = make_action("&Search Tabs…");+ m_search_tabs_action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_A));+ QObject::connect(m_search_tabs_action, &QAction::triggered, this, []() {+ if (auto* window = Application::the().active_window_if_any())+ window->show_all_tabs();+ });++ m_move_focus_action = make_action("Move &Focus Between Toolbar and Page");+ m_move_focus_action->setShortcut(QKeySequence(Qt::Key_F6));+ QObject::connect(m_move_focus_action, &QAction::triggered, this, []() {+ if (auto* window = Application::the().active_window_if_any())+ window->move_focus_between_chrome_and_page();+ });++ m_open_file_action = make_action("&Open File…");m_open_file_action->setShortcut(QKeySequence(QKeySequence::StandardKey::Open));QObject::connect(m_open_file_action, &QAction::triggered, this, []() { Application::the().open_file(); });@@ -371,7 +387,7 @@ public:m_toggle_bookmark_bar_action = create_application_action(*m_application_widget, application.toggle_bookmark_bar_action(), IncludeActionIcon::No);- m_find_in_page_action = make_action("&Find in Page...");+ m_find_in_page_action = make_action("&Find in Page…");m_find_in_page_action->setShortcuts(QKeySequence::keyBindings(QKeySequence::StandardKey::Find));QObject::connect(m_find_in_page_action, &QAction::triggered, this, []() {if (auto* window = Application::the().active_window_if_any())@@ -436,7 +452,7 @@ public:if (!m_reopen_recently_closed_tab_action)return;- m_reopen_recently_closed_tab_action->setText("&Reopen Recently Closed Tab");+ m_reopen_recently_closed_tab_action->setText("&Reopen Closed Tab");auto* active_window = Application::the().active_window_if_any();auto& session = active_window ? active_window->session() : WebView::Application::default_session();m_reopen_recently_closed_tab_action->setEnabled(session.session_store->has_closed_units());@@ -528,6 +544,8 @@ private:QAction* m_close_current_tab_action { nullptr };QAction* m_open_next_tab_action { nullptr };QAction* m_open_previous_tab_action { nullptr };+ QAction* m_search_tabs_action { nullptr };+ QAction* m_move_focus_action { nullptr };QAction* m_open_file_action { nullptr };QAction* m_open_settings_action { nullptr };QAction* m_open_downloads_action { nullptr };@@ -540,12 +558,34 @@ private:};Application::Application() = default;-Application::~Application() = default;+Application::~Application()+{+ // NB: A run stopped by a signal leaves its windows open for the next launch to recover. Their pages must still go+ // before the QApplication does, since the processes torn down after it end their navigations, which updates+ // their widgets.+ if (!m_application)+ return;+ Vector<QPointer<BrowserWindow>> windows;+ for (auto* widget : QApplication::topLevelWidgets()) {+ if (auto* window = as_if<BrowserWindow>(widget))+ windows.append(window);+ }+ for (auto& window : windows)+ delete window.data();+}void Application::show_process_manager(){- if (!m_process_manager_window)+ if (!m_process_manager_window) {m_process_manager_window = make<ProcessManagerWindow>(process_manager());+#if defined(AK_OS_MACOS)+ // The traffic lights are centered in the Task Manager's title bar, which is 52 px tall.+ m_process_manager_window->on_title_bar_change = [window = m_process_manager_window.ptr()] {+ hide_appkit_window_title(*window);+ offset_appkit_window_controls(*window, 3, 10);+ };+#endif+ }m_process_manager_window->show();m_process_manager_window->raise();m_process_manager_window->activateWindow();@@ -616,6 +656,22 @@ Optional<String> Application::ui_font_family() constreturn ak_string_from_qstring(QGuiApplication::font().family());}+// The widgets' palette follows the interface theme, and the system's appearance when the theme follows the system.+Web::CSS::PreferredColorScheme Application::interface_color_scheme() const+{+ return Theme::is_dark() ? Web::CSS::PreferredColorScheme::Dark : Web::CSS::PreferredColorScheme::Light;+}++// Bookmarking the page from the menu or its shortcut does what the star in the address field does.+void Application::toggle_bookmark_for_view(WebView::ViewImplementation& view)+{+ if (auto* tab = active_tab(); tab && &tab->view() == &view) {+ tab->show_bookmark_popover();+ return;+ }+ WebView::Application::toggle_bookmark_for_view(view);+}+bool Application::platform_reports_scroll_momentum() const{// Only Qt on macOS sends momentum scroll events.@@ -763,6 +819,43 @@ BrowserWindow* Application::restore_previous_session(WindowConfiguration const&return frontmost_window;}+void Application::offer_to_restore_unexpectedly_closed_tabs(BrowserWindow& window)+{+ auto& session_store = *WebView::Application::default_session().session_store;+ if (session_store.consecutive_unclean_exits() == 0)+ return;++ Vector<WebView::SessionWindowId> unit_ids;+ size_t tab_count = 0;+ for (auto const& unit : session_store.recently_closed_units(NumericLimits<size_t>::max())) {+ if (!unit.from_startup_recovery)+ continue;+ unit_ids.append(unit.id);+ tab_count += unit.tab_count;+ }+ if (unit_ids.is_empty() || !window.current_tab())+ return;++ window.current_tab()->show_restore_session_card(tab_count, [window = QPointer<BrowserWindow>(&window), unit_ids = AK::move(unit_ids)] {+ // A window that still shows only the new tab page it opened with is taken over by the tabs restored first.+ QPointer<Tab> new_tab_page;+ if (window && window->tab_count() == 1) {+ auto* tab = window->tab_at(0);+ if (tab->view().url() == WebView::Application::settings().new_tab_page_url() && !tab->view().navigate_back_action().enabled())+ new_tab_page = tab;+ }++ // NB: The units are listed most recently closed first, and reopening them oldest first keeps their order.+ for (size_t i = unit_ids.size(); i > 0; --i) {+ auto reopen_closed_window = new_tab_page && i == unit_ids.size() ? ReopenClosedWindow::InTargetWindow : ReopenClosedWindow::InNewWindow;+ Application::the().reopen_recently_closed_tab(window, unit_ids[i - 1], reopen_closed_window);+ }++ if (new_tab_page && window->tab_count() > 1)+ window->close_tab_without_keeping_it(window->tab_index(new_tab_page));+ });+}+void Application::open_startup_tabs(BrowserWindow& window, Vector<URL::URL> const& urls){auto const& new_tab_page_url = WebView::Application::settings().new_tab_page_url();@@ -924,11 +1017,11 @@ void Application::focus_location_editor()tab->focus_location_editor();}-void Application::reopen_recently_closed_tab(BrowserWindow* target_window)+void Application::reopen_recently_closed_tab(BrowserWindow* target_window, Optional<WebView::SessionWindowId> unit_id, ReopenClosedWindow reopen_closed_window){auto is_private = target_window ? target_window->is_private() : WebView::IsPrivate::No;auto& session = target_window ? target_window->session() : WebView::Application::default_session();- auto closed_unit = session.session_store->take_most_recently_closed();+ auto closed_unit = unit_id.has_value() ? session.session_store->take_closed_unit(*unit_id) : session.session_store->take_most_recently_closed();if (closed_unit.is_error()) {dbgln("Unable to reopen the most recently closed session unit: {}", closed_unit.error());return;@@ -950,7 +1043,7 @@ void Application::reopen_recently_closed_tab(BrowserWindow* target_window)break;}}- if (unit.was_window || !window) {+ if ((unit.was_window && reopen_closed_window == ReopenClosedWindow::InNewWindow) || !window) {auto configuration = unit.geometry.has_value() ? window_configuration_for(*unit.geometry) : configuration_for_new_window();window = &new_window({}, configuration, BrowserWindow::IsPopupWindow::No, is_private);}@@ -1717,6 +1810,7 @@ QMenuBar* Application::create_application_menu_bar(ForBrowserWindow for_browser_if (for_browser_window == ForBrowserWindow::Yes) {view_menu->addAction(open_next_tab_action());view_menu->addAction(open_previous_tab_action());+ view_menu->addAction(search_tabs_action());view_menu->addSeparator();auto* zoom_menu = view_menu->addMenu("&Zoom");@@ -1765,6 +1859,8 @@ DEFINE_APP_MENU_GETTER(QAction, reopen_recently_closed_tab_action);DEFINE_APP_MENU_GETTER(QAction, close_current_tab_action);DEFINE_APP_MENU_GETTER(QAction, open_next_tab_action);DEFINE_APP_MENU_GETTER(QAction, open_previous_tab_action);+DEFINE_APP_MENU_GETTER(QAction, search_tabs_action);+DEFINE_APP_MENU_GETTER(QAction, move_focus_action);DEFINE_APP_MENU_GETTER(QAction, open_file_action);DEFINE_APP_MENU_GETTER(QAction, open_settings_action);DEFINE_APP_MENU_GETTER(QAction, open_downloads_action);diff --git a/UI/Qt/Application.h b/UI/Qt/Application.hindex 066dd42a8bb..bf3cf2670a6 100644--- a/UI/Qt/Application.h+++ b/UI/Qt/Application.h@@ -55,12 +55,19 @@ public:// Opens the windows startup recovery kept open, and returns the frontmost one, if any.BrowserWindow* restore_previous_session(WindowConfiguration const& frontmost_window_configuration);+ // After the last run ended unexpectedly, offers to restore the tabs it left open that didn't come back by themselves.+ void offer_to_restore_unexpectedly_closed_tabs(BrowserWindow&);void open_startup_tabs(BrowserWindow&, Vector<URL::URL> const&);virtual WebView::SessionLaunchPolicy launch_restore_policy() const override;void open_new_tab();void open_new_window(WebView::IsPrivate);- void reopen_recently_closed_tab(BrowserWindow* target_window);+ enum class ReopenClosedWindow {+ InNewWindow,+ InTargetWindow,+ };+ // Reopens the given closed tab or window, or else the one closed most recently.+ void reopen_recently_closed_tab(BrowserWindow* target_window, Optional<WebView::SessionWindowId> = {}, ReopenClosedWindow = ReopenClosedWindow::InNewWindow);void open_file();void restart_private_browsing_session();@@ -103,6 +110,8 @@ public:QAction* close_current_tab_action();QAction* open_next_tab_action();QAction* open_previous_tab_action();+ QAction* search_tabs_action();+ QAction* move_focus_action();QAction* open_file_action();QAction* open_settings_action();QAction* open_downloads_action();@@ -130,6 +139,8 @@ private:virtual void create_platform_actions() override;virtual Optional<String> ui_font_family() const override;+ virtual Web::CSS::PreferredColorScheme interface_color_scheme() const override;+ virtual void toggle_bookmark_for_view(WebView::ViewImplementation&) override;#if !defined(AK_OS_MACOS)virtual Optional<String> system_font_family() const override;#endif@@ -168,7 +179,6 @@ private:virtual bool supports_system_menu_bar() const override;virtual bool supports_vertical_tabs() const override { return true; }virtual bool supports_private_browsing_windows() const override { return true; }- virtual bool supports_content_blocking_controls() const override { return true; }virtual bool supports_client_side_window_decorations() const override{#if defined(AK_OS_MACOS)diff --git a/UI/Qt/Autocomplete.cpp b/UI/Qt/Autocomplete.cppindex 960b493d9d4..5a52fbfa7e2 100644--- a/UI/Qt/Autocomplete.cpp+++ b/UI/Qt/Autocomplete.cpp@@ -6,6 +6,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/AnyOf.h>#include <AK/GenericShorthands.h>#include <AK/Platform.h>#include <AK/kmalloc.h>@@ -13,7 +14,11 @@#include <UI/Qt/Autocomplete.h>#include <UI/Qt/ChromeStyle.h>#include <UI/Qt/Icon.h>+#include <UI/Qt/Motion.h>+#include <UI/Qt/Popover.h>#include <UI/Qt/StringUtils.h>+#include <UI/Qt/SystemAppearance.h>+#include <UI/Qt/Theme.h>#include <QAbstractListModel>#include <QApplication>@@ -35,18 +40,30 @@#include <QTextLayout>#include <QTimer>#include <QVBoxLayout>+#include <QVariantAnimation>#include <QWindow>namespace Ladybird {-static constexpr int POPUP_PADDING = 8;+// The suggestions float in a card a little below the address field, as wide as the field.+static constexpr int POPUP_ANCHOR_GAP = 4;+static constexpr int POPUP_PADDING = 6;+static constexpr int POPUP_CORNER_RADIUS = 12;+// The card's shadow is drawn in a window of its own, with this much room around the card.+// NB: The shadow falls downward, so it needs less room above the card.+static constexpr QMargins POPUP_SHADOW_MARGINS { 60, 36, 60, 90 };+static constexpr int ROW_HEIGHT = 34;+static constexpr int ROW_CORNER_RADIUS = 6;static constexpr int CELL_HORIZONTAL_PADDING = 12;-static constexpr int CELL_VERTICAL_PADDING = 8;-static constexpr int CELL_ICON_SIZE = 20;-static constexpr int CELL_ICON_TEXT_SPACING = 10;-static constexpr int CELL_LABEL_VERTICAL_SPACING = 4;+static constexpr int CELL_ICON_SIZE = 16;+static constexpr int CELL_SPACING = 12;+// Search suggestions are set apart from pages by a line, with this much room above and below it.+static constexpr int GROUP_SEPARATOR_MARGIN = 5;+static constexpr int GROUP_SEPARATOR_INSET = 8;+static constexpr int GROUP_SEPARATOR_HEIGHT = (2 * GROUP_SEPARATOR_MARGIN) + 1;static constexpr int MINIMUM_POPUP_WIDTH = 100;-static constexpr size_t MAXIMUM_VISIBLE_AUTOCOMPLETE_SUGGESTIONS = 6;++static constexpr size_t MAXIMUM_VISIBLE_AUTOCOMPLETE_SUGGESTIONS = 8;enum AutocompleteRole {TitleRole = Qt::UserRole + 1,@@ -56,9 +73,11 @@ enum AutocompleteRole {SourceRole,SuggestionIndexRole,HighlightInputRole,+ StartsGroupRole,};-class AutocompletePopup final : public QFrame {+// The popup window is this card, with transparent corners.+class AutocompleteCard final : public QFrame {AK_ALLOC_WITH_KMALLOC;public:@@ -67,46 +86,43 @@ public:protected:virtual void paintEvent(QPaintEvent*) override{- // Translucent top-level frames need their styled background painted explicitly.- QStyleOption option;- option.initFrom(this);QPainter painter(this);- style()->drawPrimitive(QStyle::PE_Widget, &option, &painter, this);- auto separator_color = ChromeStyle::mix(palette().color(QPalette::Window), ChromeStyle::chrome_text(palette()), 0.12);- painter.fillRect(QRect(CELL_HORIZONTAL_PADDING, 0, width() - CELL_HORIZONTAL_PADDING * 2, 1), separator_color);+ painter.setRenderHint(QPainter::Antialiasing, true);+ auto const& panel = Theme::panel();+ painter.setBrush(panel.surface);+ painter.setPen(QPen(panel.edge, 1));+ painter.drawRoundedRect(QRectF(rect()).adjusted(0.5, 0.5, -0.5, -0.5), POPUP_CORNER_RADIUS, POPUP_CORNER_RADIUS);}};-static QFont autocomplete_primary_font()+static QFont autocomplete_title_font(){QFont font = QApplication::font();- if (font.pointSizeF() > 0)- font.setPointSizeF(font.pointSizeF() + 1.5);+ font.setPixelSize(13);font.setWeight(QFont::Normal);return font;}-static void draw_autocomplete_text(QPainter& painter, QRect const& rect, QString const& text, QString const& highlight_input, QFont font, QColor color, bool emphasize_origin = false)+static QFont autocomplete_detail_font()+{+ QFont font = QApplication::font();+ font.setPixelSize(12);+ return font;+}++static void draw_autocomplete_text(QPainter& painter, QRect const& rect, QString const& text, QString const& highlight_input, QFont font, QColor color){QFontMetrics font_metrics(font);auto input = ak_string_from_qstring(highlight_input);- // NB: Most of a matching suggestion is drawn in demibold, and an emphasized origin in medium. Elide at the heavier- // weight, or the end of the text and its ellipsis would not fit in the rect.+ // NB: Most of a matching suggestion is drawn in demibold. Elide at the heavier weight, or the end of the text and+ // its ellipsis would not fit in the rect.auto elision_font = font;if (!WebView::autocomplete_match_ranges(input, ak_string_from_qstring(text)).is_empty())elision_font.setWeight(QFont::DemiBold);- else if (emphasize_origin)- elision_font.setWeight(QFont::Medium);auto elided_text = QFontMetrics(elision_font).elidedText(text, Qt::ElideRight, rect.width());auto displayed_text = ak_string_from_qstring(elided_text);QList<QTextLayout::FormatRange> formats;- if (emphasize_origin) {- auto slash = elided_text.indexOf('/');- QTextCharFormat format;- format.setFontWeight(QFont::Medium);- formats.append({ 0, static_cast<int>(slash < 0 ? elided_text.length() : slash), move(format) });- }// The text you typed is drawn at the regular weight, and the rest of the suggestion stands out in demibold.auto match_ranges = WebView::autocomplete_match_ranges(input, displayed_text);if (!match_ranges.is_empty()) {@@ -133,30 +149,6 @@ static void draw_autocomplete_text(QPainter& painter, QRect const& rect, QStringlayout.draw(&painter, QPointF(rect.left(), rect.top() + (rect.height() - font_metrics.height()) / 2), {}, rect);}-static QFont autocomplete_secondary_font()-{- return QApplication::font();-}--static bool autocomplete_color_is_dark(QColor const& color)-{- return color.lightness() < 128;-}--static QColor autocomplete_selection_fill(QPalette const& palette)-{- auto text = ChromeStyle::chrome_text(palette);- if (!autocomplete_color_is_dark(text))- return ChromeStyle::mix(ChromeStyle::chrome_surface_pressed(palette), text, 0.06);-- auto surface = palette.color(QPalette::Base);- if (autocomplete_color_is_dark(surface))- surface = palette.color(QPalette::Window);- if (autocomplete_color_is_dark(surface))- surface = QColor(255, 255, 255);- return ChromeStyle::mix(surface, QColor(0, 0, 0), 0.08);-}-class AutocompleteModel final : public QAbstractListModel {public:AK_ALLOC_WITH_KMALLOC;@@ -224,6 +216,13 @@ public:return index.row();case HighlightInputRole:return qstring_from_ak_string(suggestion.highlight_input);+ case StartsGroupRole: {+ // Pages that follow search suggestions start a group of their own.+ if (suggestion_index == 0)+ return false;+ auto is_search = [](auto const& suggestion) { return suggestion.source == WebView::AutocompleteSuggestionSource::Search; };+ return is_search(m_suggestions[suggestion_index - 1]) != is_search(suggestion);+ }default:return {};}@@ -268,29 +267,36 @@ public:{if (!index.isValid())return {};- QFontMetrics primary_fm(autocomplete_primary_font());- if (index.data(TitleRole).toString().isEmpty())- return QSize(0, max(CELL_ICON_SIZE, primary_fm.height()) + CELL_VERTICAL_PADDING * 2);- QFontMetrics secondary_fm(autocomplete_secondary_font());- int content_height = max(CELL_ICON_SIZE,- primary_fm.height() + CELL_LABEL_VERTICAL_SPACING + secondary_fm.height());- return QSize(0, content_height + CELL_VERTICAL_PADDING * 2);+ auto height = ROW_HEIGHT;+ if (index.data(StartsGroupRole).toBool())+ height += GROUP_SEPARATOR_HEIGHT;+ return QSize(0, height);}void paint(QPainter* painter, QStyleOptionViewItem const& option, QModelIndex const& index) const override{painter->save();+ painter->setRenderHint(QPainter::Antialiasing, true);+ auto const& panel = Theme::panel();++ auto row_rect = option.rect;+ if (index.data(StartsGroupRole).toBool()) {+ auto separator_y = row_rect.top() + GROUP_SEPARATOR_MARGIN;+ painter->fillRect(QRect(row_rect.left() + GROUP_SEPARATOR_INSET, separator_y, row_rect.width() - (2 * GROUP_SEPARATOR_INSET), 1), panel.separator);+ row_rect.setTop(row_rect.top() + GROUP_SEPARATOR_HEIGHT);+ }+bool selected = option.state & QStyle::State_Selected;bool hovered = option.state & QStyle::State_MouseOver;- // A row under the mouse lights up the same way as the row selected with the keyboard.if (selected || hovered) {- auto rect = option.rect.adjusted(4, 2, -4, -2);- painter->setRenderHint(QPainter::Antialiasing, true);painter->setPen(Qt::NoPen);- painter->setBrush(autocomplete_selection_fill(option.palette));- painter->drawRoundedRect(rect, ChromeStyle::LOCATION_EDIT_CORNER_RADIUS, ChromeStyle::LOCATION_EDIT_CORNER_RADIUS);+ painter->setBrush(selected ? Theme::selected_row() : panel.control);+ painter->drawRoundedRect(QRectF(row_rect), ROW_CORNER_RADIUS, ROW_CORNER_RADIUS);}+ auto text_color = selected ? QColor(Qt::white) : panel.text;+ auto detail_color = selected ? QColor(255, 255, 255, 224) : panel.muted;+auto favicon = index.data(FaviconRole).value<QIcon>();auto source = static_cast<WebView::AutocompleteSuggestionSource>(index.data(SourceRole).toInt());@@ -298,56 +304,50 @@ public:auto title_text = index.data(TitleRole).toString();auto subtitle_text = index.data(SubtitleRole).toString();auto highlight_input = index.data(HighlightInputRole).toString();- auto secondary_text = subtitle_text.isEmpty() ? url_text : subtitle_text;- auto emphasize_origin = source != WebView::AutocompleteSuggestionSource::Search && subtitle_text.isEmpty();- int icon_x = option.rect.left() + CELL_HORIZONTAL_PADDING;- int icon_y = option.rect.top() + (option.rect.height() - CELL_ICON_SIZE) / 2;- QRect icon_rect(icon_x, icon_y, CELL_ICON_SIZE, CELL_ICON_SIZE);-- if (source == WebView::AutocompleteSuggestionSource::Search) {- create_chrome_icon(ChromeIcon::Search, option.palette).paint(painter, icon_rect);- } else if ((source == WebView::AutocompleteSuggestionSource::History || source == WebView::AutocompleteSuggestionSource::Bookmark || source == WebView::AutocompleteSuggestionSource::Adaptive) && !favicon.isNull()) {+ // A row shows what it is in full, then a muted detail: where a search goes, or the address of a page.+ auto primary_text = title_text.isEmpty() ? url_text : title_text;+ QString detail_text;+ if (source == WebView::AutocompleteSuggestionSource::Search || source == WebView::AutocompleteSuggestionSource::ChooseSearchEngine)+ detail_text = subtitle_text;+ else if (source == WebView::AutocompleteSuggestionSource::Bookmark)+ detail_text = title_text.isEmpty() ? QStringLiteral("Bookmark") : QStringLiteral("Bookmark · %1").arg(url_text);+ else if (!title_text.isEmpty())+ detail_text = url_text;++ int x = row_rect.left() + CELL_HORIZONTAL_PADDING;+ QRect icon_rect(x, row_rect.top() + (row_rect.height() - CELL_ICON_SIZE) / 2, CELL_ICON_SIZE, CELL_ICON_SIZE);+ auto icon_color = selected ? QColor(Qt::white) : panel.muted;+ if (source == WebView::AutocompleteSuggestionSource::Search || source == WebView::AutocompleteSuggestionSource::ChooseSearchEngine)+ create_chrome_icon(ChromeIcon::Search, icon_color).paint(painter, icon_rect);+ else if (!favicon.isNull())favicon.paint(painter, icon_rect);- } else {- create_chrome_icon(ChromeIcon::Globe, option.palette).paint(painter, icon_rect);- }-- if (source == WebView::AutocompleteSuggestionSource::Bookmark) {- static constexpr int badge_size = 9;- QRect badge_rect(icon_rect.right() - badge_size + 2, icon_rect.bottom() - badge_size + 2, badge_size, badge_size);- painter->setPen(Qt::NoPen);- painter->setBrush(ChromeStyle::chrome_surface(option.palette));- painter->drawEllipse(badge_rect.adjusted(-1, -1, 1, 1));- create_chrome_icon(ChromeIcon::StarFilled, option.palette).paint(painter, badge_rect);- }-- int text_x = icon_x + CELL_ICON_SIZE + CELL_ICON_TEXT_SPACING;- int text_width = option.rect.right() - text_x - CELL_HORIZONTAL_PADDING;- if (text_width < 0)- text_width = 0;-- QFontMetrics primary_fm(autocomplete_primary_font());- QFontMetrics secondary_fm(autocomplete_secondary_font());-- if (!title_text.isEmpty()) {- int block_height = primary_fm.height() + CELL_LABEL_VERTICAL_SPACING + secondary_fm.height();- int block_y = option.rect.top() + (option.rect.height() - block_height) / 2;-- auto primary_color = ChromeStyle::chrome_text(option.palette);- draw_autocomplete_text(*painter, QRect(text_x, block_y, text_width, primary_fm.height()), title_text, highlight_input, autocomplete_primary_font(), primary_color);-- painter->setFont(autocomplete_secondary_font());- auto secondary_color = ChromeStyle::chrome_muted_text(option.palette);- secondary_color.setAlpha(180);- painter->setPen(secondary_color);- draw_autocomplete_text(*painter,- QRect(text_x, block_y + primary_fm.height() + CELL_LABEL_VERTICAL_SPACING, text_width, secondary_fm.height()),- secondary_text, highlight_input, autocomplete_secondary_font(), secondary_color, emphasize_origin);- } else {- painter->setFont(QApplication::font());- auto text_color = ChromeStyle::chrome_text(option.palette);- draw_autocomplete_text(*painter, QRect(text_x, option.rect.top(), text_width, option.rect.height()), url_text, highlight_input, autocomplete_primary_font(), text_color, emphasize_origin);+ else+ create_chrome_icon(ChromeIcon::Globe, icon_color).paint(painter, icon_rect);+ x = icon_rect.right() + 1 + CELL_SPACING;++ auto right = row_rect.right() - CELL_HORIZONTAL_PADDING;++ auto title_font = autocomplete_title_font();+ auto detail_font = autocomplete_detail_font();+ auto available = max(0, right - x + 1);+ // NB: Measure the title at the heavier weight that most of a matching title is drawn in.+ auto measuring_font = title_font;+ measuring_font.setWeight(QFont::DemiBold);+ auto title_width = min(available, QFontMetrics(measuring_font).horizontalAdvance(primary_text) + 2);+ // NB: The offer to choose a search engine does not show the query, so nothing in it is highlighted.+ auto title_highlight = source == WebView::AutocompleteSuggestionSource::ChooseSearchEngine ? QString {} : highlight_input;+ draw_autocomplete_text(*painter, QRect(x, row_rect.top(), title_width, row_rect.height()), primary_text, title_highlight, title_font, text_color);++ if (!detail_text.isEmpty()) {+ auto detail_x = x + title_width + CELL_SPACING;+ auto detail_width = right - detail_x + 1;+ if (detail_width > 24) {+ painter->setFont(detail_font);+ painter->setPen(detail_color);+ auto elided = QFontMetrics(detail_font).elidedText(detail_text, Qt::ElideRight, detail_width);+ painter->drawText(QRect(detail_x, row_rect.top(), detail_width, row_rect.height()), Qt::AlignVCenter | Qt::AlignLeft, elided);+ }}painter->restore();@@ -368,12 +368,13 @@ void Autocomplete::create_popup(){// Use a non-activating top-level widget for its own translucent backing store. Its native window is embedded in the// browser window in position_popup().- m_popup = new AutocompletePopup(m_anchor->window(), Qt::ToolTip | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint);+ m_popup = new AutocompleteCard(m_anchor->window(), Qt::ToolTip | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint);connect(m_popup, &QObject::destroyed, this, [this] {// The popup dies with its parent window, which can go away while this object lives on (for// example when the tab is moved to another window); it is recreated on the next show.m_popup = nullptr;m_list_view = nullptr;+ m_opening_animation = nullptr;set_anchor_popup_open(false);});m_popup->setObjectName("LadybirdAutocompletePopup");@@ -386,10 +387,26 @@ void Autocomplete::create_popup()m_popup->setAttribute(Qt::WA_ShowWithoutActivating);m_popup->setAttribute(Qt::WA_X11DoNotAcceptFocus);m_popup->setFocusPolicy(Qt::NoFocus);- m_popup->setFrameShape(QFrame::StyledPanel);- m_popup->setFrameShadow(QFrame::Raised);+ m_popup->setFrameShape(QFrame::NoFrame);m_popup->hide();+ // The card casts the same shadow as popovers. The shadow is a window of its own behind the card, and it lets the+ // mouse through to the page, which a transparent room around the card in the card's window would not.+ m_shadow = new QWidget(m_anchor->window(), Qt::ToolTip | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint | Qt::WindowTransparentForInput);+ m_shadow->setAttribute(Qt::WA_TranslucentBackground);+#if defined(AK_OS_MACOS)+ m_shadow->setAttribute(Qt::WA_NativeWindow);+#endif+ m_shadow->setAttribute(Qt::WA_ShowWithoutActivating);+ m_shadow->setAttribute(Qt::WA_X11DoNotAcceptFocus);+ m_shadow->setAttribute(Qt::WA_TransparentForMouseEvents);+ auto* shadow_layout = new QVBoxLayout(m_shadow);+ shadow_layout->setContentsMargins(POPUP_SHADOW_MARGINS);+ auto* shadow_caster = new AutocompleteCard(m_shadow);+ cast_popover_shadow(*shadow_caster);+ shadow_layout->addWidget(shadow_caster);+ m_shadow->hide();+m_list_view = new QListView(m_popup);m_list_view->setObjectName("LadybirdAutocompleteList");m_list_view->setFocusPolicy(Qt::NoFocus);@@ -403,7 +420,7 @@ void Autocomplete::create_popup()update_chrome_style();auto* layout = new QVBoxLayout(m_popup);- layout->setContentsMargins(0, POPUP_PADDING, 0, ChromeStyle::LOCATION_EDIT_CORNER_RADIUS);+ layout->setContentsMargins(POPUP_PADDING, POPUP_PADDING, POPUP_PADDING, POPUP_PADDING);layout->setSpacing(0);layout->addWidget(m_list_view);@@ -421,6 +438,7 @@ Autocomplete::~Autocomplete()disconnect(m_popup, nullptr, this, nullptr);delete m_popup;}+ delete m_shadow.data();}void Autocomplete::update_chrome_style()@@ -434,6 +452,7 @@ void Autocomplete::update_chrome_style()m_list_view->setPalette(palette);m_popup->setStyleSheet(ChromeStyle::autocomplete_popup_style_sheet(palette));m_popup->update();+ m_shadow->update();m_list_view->viewport()->update();m_is_updating_chrome_style = false;}@@ -464,9 +483,32 @@ void Autocomplete::show_with_suggestions(Vector<WebView::AutocompleteSuggestion>update_chrome_style();position_popup();if (!m_popup->isVisible()) {+ // The panel fades in from 4 px above its place, unless the system asks for less motion.+ if (!m_opening_animation) {+ m_opening_animation = new QVariantAnimation(m_popup);+ m_opening_animation->setDuration(Motion::FAST);+ m_opening_animation->setEasingCurve(Motion::enter_easing());+ m_opening_animation->setStartValue(0.0);+ m_opening_animation->setEndValue(1.0);+ QObject::connect(m_opening_animation, &QVariantAnimation::valueChanged, m_popup, [this](QVariant const& value) {+ auto progress = value.toReal();+ m_opening_offset = SystemAppearance::prefers_reduced_motion() ? 0 : -4 * (1 - progress);+ set_floating_window_opacity(*m_popup, progress);+ set_floating_window_opacity(*m_shadow, progress);+ position_popup();+ });+ }+ auto reduce_motion = SystemAppearance::prefers_reduced_motion();+ m_opening_offset = reduce_motion ? 0 : -4;+ set_floating_window_opacity(*m_popup, 0);+ set_floating_window_opacity(*m_shadow, 0);+ m_shadow->show();m_popup->show();position_popup();+ m_opening_animation->stop();+ m_opening_animation->start();}+ m_shadow->raise();m_popup->raise();set_selected_suggestion(selected_suggestion_index);@@ -496,6 +538,7 @@ bool Autocomplete::close()if (!m_popup || !m_popup->isVisible())return false;m_popup->hide();+ m_shadow->hide();return true;}@@ -571,29 +614,33 @@ void Autocomplete::position_popup()auto* top_window = m_anchor->window();if (!top_window)return;- if (m_popup->parentWidget() != top_window) {- m_popup->setParent(top_window, Qt::ToolTip | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint);- m_popup->setAttribute(Qt::WA_ShowWithoutActivating);- m_popup->setAttribute(Qt::WA_X11DoNotAcceptFocus);- }+ for (QWidget* window : { static_cast<QWidget*>(m_shadow.data()), static_cast<QWidget*>(m_popup) }) {+ if (window->parentWidget() != top_window) {+ window->setParent(top_window, window->windowFlags());+ window->setAttribute(Qt::WA_ShowWithoutActivating);+ window->setAttribute(Qt::WA_X11DoNotAcceptFocus);+ }- // Embed the native window so it stacks above native web content without being animated independently of the- // location field by the window system.- (void)m_popup->winId();- m_popup->windowHandle()->setParent(top_window->windowHandle());+ // Embed the native window so it stacks above native web content without being animated independently of the+ // location field by the window system.+ (void)window->winId();+ window->windowHandle()->setParent(top_window->windowHandle());+ }- int width = max(m_anchor->width(), MINIMUM_POPUP_WIDTH);- int frame_overhead = m_popup->frameWidth() * 2;- auto popup_position = m_anchor->mapTo(top_window, QPoint(0, m_anchor->height()));- int popup_padding = POPUP_PADDING + ChromeStyle::LOCATION_EDIT_CORNER_RADIUS + frame_overhead;- int available_height = max(0, top_window->height() - popup_position.y() - popup_padding);+ // The card is as wide as the field and sits a little below it.+ int card_width = max(m_anchor->width(), MINIMUM_POPUP_WIDTH);+ auto card_position = m_anchor->mapTo(top_window, QPoint(0, m_anchor->height() + POPUP_ANCHOR_GAP + qRound(m_opening_offset)));+ int vertical_overhead = 2 * POPUP_PADDING;+ int available_height = max(0, top_window->height() - card_position.y() - vertical_overhead);int list_height = min(total_height, available_height);- int popup_height = list_height + popup_padding;m_list_view->setFixedHeight(list_height);- m_popup->setFixedSize(width, popup_height);+ m_popup->setFixedSize(card_width, list_height + vertical_overhead);- m_popup->setGeometry(QRect(popup_position, m_popup->size()));+ auto card = QRect(card_position, m_popup->size());+ m_shadow->setGeometry(card.marginsAdded(POPUP_SHADOW_MARGINS));+ m_popup->setGeometry(card);+ m_shadow->raise();m_popup->raise();}diff --git a/UI/Qt/Autocomplete.h b/UI/Qt/Autocomplete.hindex 42b9cd887b9..f04ef722cbd 100644--- a/UI/Qt/Autocomplete.h+++ b/UI/Qt/Autocomplete.h@@ -14,10 +14,12 @@#include <LibWebView/Autocomplete.h>#include <QObject>+#include <QPointer>class QFrame;class QLineEdit;class QListView;+class QVariantAnimation;namespace Ladybird {@@ -59,11 +61,16 @@ private:QLineEdit* m_anchor { nullptr };QFrame* m_popup { nullptr };+ // The card's shadow, in a window of its own that lets the mouse through.+ QPointer<QWidget> m_shadow;QListView* m_list_view { nullptr };AutocompleteModel* m_model { nullptr };AutocompleteDelegate* m_delegate { nullptr };bool m_is_updating_chrome_style { false };bool m_has_pending_chrome_style_update { false };+ // The panel slides down this far into place as it opens.+ qreal m_opening_offset { 0 };+ QVariantAnimation* m_opening_animation { nullptr };};}diff --git a/UI/Qt/BookmarkDialog.cpp b/UI/Qt/BookmarkDialog.cppindex 8fc7df417a6..14569e26924 100644--- a/UI/Qt/BookmarkDialog.cpp+++ b/UI/Qt/BookmarkDialog.cpp@@ -87,7 +87,7 @@ private:QIcon m_arrow;};-static void add_bookmark_folder_options(QComboBox& folder_combo, ReadonlySpan<WebView::BookmarkItem> items, QString const& prefix, Optional<String const&> excluded_folder_id)+static void add_bookmark_folder_options(QComboBox& folder_combo, QIcon const& folder_icon, ReadonlySpan<WebView::BookmarkItem> items, QString const& prefix, Optional<String const&> excluded_folder_id){for (auto const& item : items) {// A folder cannot be moved into itself or any of its descendants.@@ -96,12 +96,32 @@ static void add_bookmark_folder_options(QComboBox& folder_combo, ReadonlySpan<Weauto title = qstring_from_ak_string(item.folder().title.value_or("(no title)"_string));auto path = prefix.isEmpty() ? title : QString("%1 / %2").arg(prefix, title);- folder_combo.addItem(path, qstring_from_ak_string(item.id));+ folder_combo.addItem(folder_icon, path, qstring_from_ak_string(item.id));- add_bookmark_folder_options(folder_combo, item.folder().children, path, excluded_folder_id);+ add_bookmark_folder_options(folder_combo, folder_icon, item.folder().children, path, excluded_folder_id);}}+QComboBox* create_bookmark_folder_picker(QWidget* parent, ReadonlySpan<WebView::BookmarkItem> folders, Optional<String const&> selected_folder_id, Optional<String const&> excluded_folder_id)+{+ auto* folder_combo = new BookmarkFolderPicker(parent);+ auto folder_icon = create_chrome_icon(ChromeIcon::Folder, folder_combo->palette());+ folder_combo->setIconSize({ 14, 14 });+ folder_combo->addItem(folder_icon, "Bookmarks bar", QString {});+ add_bookmark_folder_options(*folder_combo, folder_icon, folders, {}, excluded_folder_id);+ if (folder_combo->count() > 1) {+ folder_combo->insertSeparator(1);+ folder_combo->setItemData(1, true, BOOKMARK_FOLDER_SEPARATOR_ROLE);+ }++ if (selected_folder_id.has_value()) {+ auto index = folder_combo->findData(qstring_from_ak_string(*selected_folder_id));+ if (index >= 0)+ folder_combo->setCurrentIndex(index);+ }+ return folder_combo;+}+BookmarkDialog::BookmarkDialog(QWidget* parent, Type type, Optional<URL::URL const&> current_url, Optional<String const&> current_title, Optional<String const&> selected_folder_id, ReadonlySpan<WebView::BookmarkItem> folders, Optional<String const&> excluded_folder_id): QDialog(parent){@@ -110,16 +130,16 @@ BookmarkDialog::BookmarkDialog(QWidget* parent, Type type, Optional<URL::URL conswitch (type) {case Type::AddBookmark:- setWindowTitle("Add Bookmark");+ setWindowTitle("Add bookmark");break;case Type::EditBookmark:- setWindowTitle("Edit Bookmark");+ setWindowTitle("Edit bookmark");break;case Type::AddFolder:- setWindowTitle("Add Folder");+ setWindowTitle("Add folder");break;case Type::EditFolder:- setWindowTitle("Edit Folder");+ setWindowTitle("Edit folder");break;}@@ -149,21 +169,9 @@ BookmarkDialog::BookmarkDialog(QWidget* parent, Type type, Optional<URL::URL conm_title_edit->setText(qstring_from_ak_string(*current_title));layout->addRow("Title:", m_title_edit);- m_folder_combo = new BookmarkFolderPicker(this);+ m_folder_combo = create_bookmark_folder_picker(this, folders, selected_folder_id, excluded_folder_id);m_folder_combo->setMinimumWidth(320);m_folder_combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);- m_folder_combo->addItem("Bookmarks Bar", QString {});- add_bookmark_folder_options(*m_folder_combo, folders, {}, excluded_folder_id);- if (m_folder_combo->count() > 1) {- m_folder_combo->insertSeparator(1);- m_folder_combo->setItemData(1, true, BOOKMARK_FOLDER_SEPARATOR_ROLE);- }-- if (selected_folder_id.has_value()) {- auto index = m_folder_combo->findData(qstring_from_ak_string(*selected_folder_id));- if (index >= 0)- m_folder_combo->setCurrentIndex(index);- }layout->addRow("Folder:", m_folder_combo);diff --git a/UI/Qt/BookmarkDialog.h b/UI/Qt/BookmarkDialog.hindex c5ee40dfb6a..c9b88a4f1cd 100644--- a/UI/Qt/BookmarkDialog.h+++ b/UI/Qt/BookmarkDialog.h@@ -20,6 +20,9 @@ class QLineEdit;namespace Ladybird {+// A drop-down of the bookmark folders to pick from, the Bookmarks Bar first.+QComboBox* create_bookmark_folder_picker(QWidget* parent, ReadonlySpan<WebView::BookmarkItem> folders, Optional<String const&> selected_folder_id = {}, Optional<String const&> excluded_folder_id = {});+class BookmarkDialog final : public QDialog {public:AK_ALLOC_WITH_KMALLOC;diff --git a/UI/Qt/BookmarkPopover.cpp b/UI/Qt/BookmarkPopover.cppnew file mode 100644index 00000000000..eca1afd5420--- /dev/null+++ b/UI/Qt/BookmarkPopover.cpp@@ -0,0 +1,208 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibWebView/Application.h>+#include <LibWebView/BookmarkStore.h>+#include <UI/Qt/BookmarkDialog.h>+#include <UI/Qt/BookmarkPopover.h>+#include <UI/Qt/ChromeStyle.h>+#include <UI/Qt/StringUtils.h>++#include <QComboBox>+#include <QFrame>+#include <QHBoxLayout>+#include <QLabel>+#include <QLineEdit>+#include <QPushButton>+#include <QVBoxLayout>++namespace Ladybird {++static constexpr int POPOVER_WIDTH = 320;++// The folder holding a bookmark, or none for the Bookmarks Bar, and the number of items in it.+struct BookmarkPlace {+ Optional<String> folder_id;+ size_t sibling_count { 0 };+};++static Optional<BookmarkPlace> find_bookmark_place(ReadonlySpan<WebView::BookmarkItem> items, StringView id, Optional<String> folder_id = {})+{+ for (auto const& item : items) {+ if (item.id == id)+ return BookmarkPlace { folder_id, items.size() };+ if (item.is_folder()) {+ if (auto place = find_bookmark_place(item.folder().children, id, item.id); place.has_value())+ return place;+ }+ }+ return {};+}++static size_t item_count_in_folder(ReadonlySpan<WebView::BookmarkItem> items, Optional<String> const& folder_id)+{+ if (!folder_id.has_value())+ return items.size();+ for (auto const& item : items) {+ if (!item.is_folder())+ continue;+ if (item.id == *folder_id)+ return item.folder().children.size();+ if (auto count = item_count_in_folder(item.folder().children, folder_id); count > 0)+ return count;+ }+ return 0;+}++BookmarkPopover::BookmarkPopover(QWidget* parent)+ : Popover(parent)+{+ setAccessibleName("Bookmark");+ card().setObjectName("LadybirdBookmarkPopover");+ card().setFixedWidth(POPOVER_WIDTH);++ auto* layout = new QVBoxLayout(&card());+ layout->setContentsMargins(14, 14, 14, 14);+ layout->setSpacing(12);++ m_title_label = new QLabel(&card());+ m_title_label->setObjectName("LadybirdBookmarkPopoverTitle");+ layout->addWidget(m_title_label);++ auto add_field = [&](QString const& label_text, QWidget* field) {+ auto* row = new QWidget(&card());+ auto* row_layout = new QVBoxLayout(row);+ row_layout->setContentsMargins(0, 0, 0, 0);+ row_layout->setSpacing(5);+ auto* label = new QLabel(label_text, row);+ label->setObjectName("LadybirdBookmarkPopoverLabel");+ label->setBuddy(field);+ row_layout->addWidget(label);+ field->setParent(row);+ row_layout->addWidget(field);+ layout->addWidget(row);+ return row;+ };++ m_name_field = new QLineEdit;+ m_name_field->setObjectName("LadybirdBookmarkPopoverName");+ // NB: The style sheet draws the field's focus, so the native focus ring isn't drawn over it.+ m_name_field->setAttribute(Qt::WA_MacShowFocusRect, false);+ m_name_field->setAccessibleName("Name");+ QObject::connect(m_name_field, &QLineEdit::returnPressed, this, [this] { close(); });+ add_field("Name", m_name_field);++ // NB: The picker is made anew each time the popover opens, as the folders may have changed.+ m_folder_row = add_field("Folder", new QWidget);++ auto* buttons = new QHBoxLayout;+ buttons->setContentsMargins(0, 2, 0, 0);+ buttons->setSpacing(8);+ auto* remove_button = new QPushButton("Remove", &card());+ remove_button->setObjectName("LadybirdBookmarkPopoverRemove");+ // NB: The platform style lays out a push button by a frame of its own rather than by the button, which would+ // make it overlap its neighbors.+ remove_button->setAttribute(Qt::WA_LayoutUsesWidgetRect);+ QObject::connect(remove_button, &QPushButton::clicked, this, [this] {+ m_is_removed = true;+ Function<void()> remove = [this] { WebView::Application::bookmark_store().remove_item(m_bookmark_id); };+ if (on_remove)+ on_remove(remove);+ else+ remove();+ close();+ });+ buttons->addWidget(remove_button);+ buttons->addStretch(1);+ auto* done_button = new QPushButton("Done", &card());+ done_button->setObjectName("LadybirdBookmarkPopoverDone");+ done_button->setAttribute(Qt::WA_LayoutUsesWidgetRect);+ done_button->setDefault(true);+ QObject::connect(done_button, &QPushButton::clicked, this, [this] { close(); });+ buttons->addWidget(done_button);+ layout->addLayout(buttons);+}++void BookmarkPopover::set_bookmark(String id, JustAdded just_added)+{+ m_bookmark_id = AK::move(id);+ m_is_removed = false;+ m_title_label->setText(just_added == JustAdded::Yes ? "Bookmark added" : "Edit bookmark");++ auto& store = WebView::Application::bookmark_store();+ auto item = store.find_item_by_id(m_bookmark_id);+ if (!item.has_value() || !item->is_bookmark())+ return;++ auto const& bookmark = item->bookmark();+ m_name_field->setText(qstring_from_ak_string(bookmark.title.value_or(bookmark.url.serialize())));++ auto place = find_bookmark_place(store.root_items(), m_bookmark_id);+ auto folder_id = place.has_value() ? place->folder_id : Optional<String> {};+ if (m_folder_picker)+ m_folder_picker->deleteLater();+ m_folder_picker = create_bookmark_folder_picker(m_folder_row, store.root_items(), folder_id);+ m_folder_picker->setObjectName("LadybirdBookmarkPopoverFolder");+ // NB: Long folder paths are cut short rather than widening the popover.+ m_folder_picker->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);+ m_folder_picker->setMinimumContentsLength(1);+ // NB: The platform style pads drop-downs for its own frame, which would shift the label above.+ m_folder_picker->setAttribute(Qt::WA_LayoutUsesWidgetRect);+ m_folder_picker->setAccessibleName("Folder");+ if (auto* row_layout = m_folder_row->layout(); row_layout->count() > 1) {+ auto* item = row_layout->takeAt(1);+ delete item->widget();+ delete item;+ }+ m_folder_row->layout()->addWidget(m_folder_picker);+ adjustSize();+}++void BookmarkPopover::save()+{+ auto& store = WebView::Application::bookmark_store();+ auto item = store.find_item_by_id(m_bookmark_id);+ if (!item.has_value() || !item->is_bookmark())+ return;++ auto url = item->bookmark().url;+ // NB: A bookmark without a title is shown by its URL, which is only kept as its title once it is edited.+ auto title = ak_string_from_qstring(m_name_field->text().trimmed());+ auto shown_title = item->bookmark().title.value_or(url.serialize());+ if (!title.is_empty() && title != shown_title)+ store.edit_bookmark(m_bookmark_id, url, AK::move(title));++ auto place = find_bookmark_place(store.root_items(), m_bookmark_id);+ auto target_folder_text = m_folder_picker ? m_folder_picker->currentData().toString() : QString {};+ auto target_folder_id = target_folder_text.isEmpty() ? Optional<String> {} : Optional<String> { ak_string_from_qstring(target_folder_text) };+ if (place.has_value() && place->folder_id != target_folder_id) {+ // A bookmark moved to another folder goes to the end of it.+ auto index = item_count_in_folder(store.root_items(), target_folder_id);+ store.move_item(m_bookmark_id, target_folder_id, index);+ }+}++void BookmarkPopover::showEvent(QShowEvent* event)+{+ Popover::showEvent(event);+ m_name_field->setFocus();+ m_name_field->selectAll();+}++void BookmarkPopover::hideEvent(QHideEvent* event)+{+ if (!m_is_removed)+ save();+ Popover::hideEvent(event);+}++void BookmarkPopover::update_chrome_style(QPalette const& palette)+{+ setPalette(palette);+ setStyleSheet(ChromeStyle::bookmark_popover_style_sheet(palette));+}++}diff --git a/UI/Qt/BookmarkPopover.h b/UI/Qt/BookmarkPopover.hnew file mode 100644index 00000000000..11a37decd07--- /dev/null+++ b/UI/Qt/BookmarkPopover.h@@ -0,0 +1,50 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/String.h>+#include <UI/Qt/Popover.h>++class QComboBox;+class QLabel;+class QLineEdit;++namespace Ladybird {++// The bookmark of the current page, opened from the star in the address field: its name, its folder, and a way to+// remove it. Changes are kept when the popover closes, unless the bookmark was removed.+class BookmarkPopover final : public Popover {+public:+ AK_ALLOC_WITH_KMALLOC;++ explicit BookmarkPopover(QWidget* parent);++ enum class JustAdded : u8 {+ No,+ Yes,+ };+ void set_bookmark(String id, JustAdded);+ void update_chrome_style(QPalette const&);++ // Removes the bookmark, by calling the given function.+ Function<void(Function<void()> const& remove)> on_remove;++private:+ virtual void showEvent(QShowEvent*) override;+ virtual void hideEvent(QHideEvent*) override;++ void save();++ String m_bookmark_id;+ QLabel* m_title_label { nullptr };+ QLineEdit* m_name_field { nullptr };+ QComboBox* m_folder_picker { nullptr };+ QWidget* m_folder_row { nullptr };+ bool m_is_removed { false };+};++}diff --git a/UI/Qt/BookmarksBar.cpp b/UI/Qt/BookmarksBar.cppindex 5a809a9d4b4..102400c28f1 100644--- a/UI/Qt/BookmarksBar.cpp+++ b/UI/Qt/BookmarksBar.cpp@@ -4,6 +4,8 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/HashMap.h>+#include <AK/HashTable.h>#include <AK/ScopeGuard.h>#include <LibWebView/Application.h>#include <LibWebView/BookmarkStore.h>@@ -11,41 +13,48 @@#include <UI/Qt/ChromeStyle.h>#include <UI/Qt/Icon.h>#include <UI/Qt/Menu.h>+#include <UI/Qt/Motion.h>#include <UI/Qt/StringUtils.h>+#include <UI/Qt/SystemAppearance.h>#include <UI/Qt/Tab.h>+#include <UI/Qt/Theme.h>#include <QAction>#include <QEvent>#include <QIcon>+#include <QLabel>#include <QMenu>#include <QMouseEvent>#include <QPointer>#include <QStyle>#include <QStyleOptionToolButton>#include <QStylePainter>+#include <QTimer>#include <QToolButton>+#include <QVariantAnimation>namespace Ladybird {-static constexpr int BOOKMARK_BUTTON_MAX_WIDTH = 150;-static constexpr int BOOKMARK_BUTTON_ICON_SIZE = 16;-static constexpr int BOOKMARK_BUTTON_MIN_HEIGHT = 24;-static constexpr int BOOKMARK_BUTTON_VERTICAL_PADDING = 8;-static constexpr int BOOKMARK_BUTTON_HORIZONTAL_PADDING = 7;+// Bookmarks are 24 px buttons with 6 px corners, their favicon padded less than their title.+static constexpr int BOOKMARK_BUTTON_MAX_WIDTH = 168;+static constexpr int BOOKMARK_BUTTON_ICON_SIZE = 14;+static constexpr int BOOKMARK_BUTTON_HEIGHT = 24;+static constexpr int BOOKMARK_BUTTON_CORNER_RADIUS = 6;+static constexpr int BOOKMARK_BUTTON_LEFT_PADDING = 6;+static constexpr int BOOKMARK_BUTTON_RIGHT_PADDING = 8;+static constexpr int BOOKMARK_TITLE_PIXEL_SIZE = 12;static constexpr int BOOKMARK_BUTTON_ICON_TEXT_SPACING = 6;static constexpr int BOOKMARK_BUTTON_TEXT_ELISION_PADDING = 2;static constexpr char const* BOOKMARK_ITEM_PROPERTY = "bookmark_item";static constexpr char const* BOOKMARK_CONTEXT_MENU_OPEN_PROPERTY = "bookmark_context_menu_open";+static constexpr char const* BOOKMARK_FOLDER_MENU_OPEN_PROPERTY = "bookmark_folder_menu_open";static QFont bookmark_title_font(QToolButton const& button){- return ChromeStyle::chrome_title_font(button.font());-}--static int bookmark_button_height(QFontMetrics const& font_metrics, int icon_height)-{- return max(BOOKMARK_BUTTON_MIN_HEIGHT, max(font_metrics.height(), icon_height) + BOOKMARK_BUTTON_VERTICAL_PADDING);+ auto font = ChromeStyle::chrome_title_font(button.font());+ font.setPixelSize(BOOKMARK_TITLE_PIXEL_SIZE);+ return font;}static QStyleOptionToolButton bookmark_button_style_option(QToolButton const& button)@@ -81,7 +90,8 @@ static QStyleOptionToolButton bookmark_button_style_option(QToolButton const& buoption.state |= QStyle::State_AutoRaise;if (button.menu())option.features |= QStyleOptionToolButton::HasMenu;- if (button.isDown())+ // NB: A folder's button stays pressed while its menu is open, also when the menu was opened by moving to it.+ if (button.isDown() || button.property(BOOKMARK_FOLDER_MENU_OPEN_PROPERTY).toBool())option.state |= QStyle::State_Sunken;if (button.property(BOOKMARK_CONTEXT_MENU_OPEN_PROPERTY).toBool())option.state |= QStyle::State_MouseOver;@@ -110,7 +120,7 @@ static BookmarkButtonLayout bookmark_button_layout(QToolButton const& button, QSlayout.icon_text_spacing = layout.icon_width > 0 && !text.isEmpty() ? BOOKMARK_BUTTON_ICON_TEXT_SPACING : 0;layout.content_rect = button_rect;- layout.content_rect.adjust(BOOKMARK_BUTTON_HORIZONTAL_PADDING, 0, -BOOKMARK_BUTTON_HORIZONTAL_PADDING, 0);+ layout.content_rect.adjust(BOOKMARK_BUTTON_LEFT_PADDING, 0, -BOOKMARK_BUTTON_RIGHT_PADDING, 0);layout.content_rect.adjust(0, 0, -layout.menu_indicator_width, 0);auto text_left = layout.content_rect.left() + layout.icon_width + layout.icon_text_spacing;@@ -127,7 +137,7 @@ static BookmarkButtonLayout bookmark_button_layout(QToolButton const& button, QS};}- auto preferred_width = (BOOKMARK_BUTTON_HORIZONTAL_PADDING * 2)+ auto preferred_width = BOOKMARK_BUTTON_LEFT_PADDING + BOOKMARK_BUTTON_RIGHT_PADDING+ layout.icon_width+ layout.icon_text_spacing+ QFontMetrics(bookmark_title_font(button)).horizontalAdvance(text)@@ -143,7 +153,11 @@ static void paint_bookmark_button(QToolButton& button)QStylePainter painter(&button);auto option = bookmark_button_style_option(button);- auto layout = bookmark_button_layout(button, option, option.text, button.rect());+ // While it slides in, a button is laid out at its full width and cut off by its edge, rather than squeezed.+ auto layout_rect = button.rect();+ if (auto full_width = button.property("slidingInWidth").toInt(); full_width > 0)+ layout_rect.setWidth(full_width);+ auto layout = bookmark_button_layout(button, option, option.text, layout_rect);auto frame_option = option;frame_option.icon = {};@@ -195,9 +209,56 @@ BookmarksBar::BookmarksBar(Tab* parent)void BookmarksBar::update_chrome_style(){- // Bookmark items are pills, like the tabs.- auto corner_radius = bookmark_button_height(fontMetrics(), iconSize().height()) / 2;- setStyleSheet(ChromeStyle::bookmarks_bar_style_sheet(m_tab->palette(), corner_radius));+ setStyleSheet(ChromeStyle::bookmarks_bar_style_sheet(Theme::chrome_palette(*m_tab), BOOKMARK_BUTTON_CORNER_RADIUS));+}++// A bookmark that is added slides into the bar, and the items after it move to make room. One that is removed slides+// out of it, and they close up after it.+void BookmarksBar::slide_in(QWidget& widget, int width)+{+ auto* animation = new QVariantAnimation(&widget);+ animation->setDuration(Motion::BASE);+ animation->setEasingCurve(Motion::move_easing());+ animation->setStartValue(0);+ animation->setEndValue(width);+ connect(animation, &QVariantAnimation::valueChanged, &widget, [&widget](QVariant const& value) {+ widget.setFixedWidth(value.toInt());+ });+ connect(animation, &QVariantAnimation::finished, &widget, [&widget] {+ widget.setProperty("slidingInWidth", {});+ widget.update();+ });+ widget.setProperty("slidingInWidth", width);+ widget.setFixedWidth(0);+ animation->start(QAbstractAnimation::DeleteWhenStopped);+}++void BookmarksBar::slide_out(int index, QPixmap const& image)+{+ auto items = actions();+ // The picture of the item is cut off by the edge of the room it leaves, as that closes.+ auto* placeholder = new QLabel(this);+ placeholder->setPixmap(image);+ placeholder->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);+ auto width = qRound(image.width() / image.devicePixelRatio());+ placeholder->setFixedSize(width, BOOKMARK_BUTTON_HEIGHT);+ auto* placeholder_action = index < items.size() ? insertWidget(items[index], placeholder) : addWidget(placeholder);++ auto* animation = new QVariantAnimation(placeholder);+ animation->setDuration(Motion::BASE);+ animation->setEasingCurve(Motion::move_easing());+ animation->setStartValue(width);+ animation->setEndValue(0);+ connect(animation, &QVariantAnimation::valueChanged, placeholder, [placeholder](QVariant const& value) {+ placeholder->setFixedWidth(value.toInt());+ });+ connect(animation, &QVariantAnimation::finished, this, [this, placeholder_action = QPointer { placeholder_action }] {+ if (placeholder_action) {+ removeAction(placeholder_action);+ placeholder_action->deleteLater();+ }+ });+ animation->start(QAbstractAnimation::DeleteWhenStopped);}void BookmarksBar::rebuild()@@ -207,6 +268,27 @@ void BookmarksBar::rebuild()menu->close();}+ // The items the bar showed before, so those added or removed since can slide in or out.+ auto animates = m_has_been_built && !SystemAppearance::prefers_reduced_motion();+ struct PreviousItem {+ int index { 0 };+ // A picture of the item, which slides out of the bar if the item is gone.+ QPixmap image;+ };+ HashMap<String, PreviousItem> previous_items;+ {+ int index = 0;+ for (auto* action : actions()) {+ auto id = action->property("id").toString();+ if (id.isEmpty())+ continue;+ auto* widget = widgetForAction(action);+ previous_items.set(ak_string_from_qstring(id), { index++, widget && animates ? widget->grab() : QPixmap {} });+ }+ }+ m_has_been_built = true;+ HashTable<String> current_ids;+clear();auto set_button_properties = [&](QToolButton* button, QString const& title) {@@ -217,7 +299,7 @@ void BookmarksBar::rebuild()auto option = bookmark_button_style_option(*button);QFontMetrics title_font_metrics(bookmark_title_font(*button));- auto height = bookmark_button_height(title_font_metrics, button->iconSize().height());+ auto height = BOOKMARK_BUTTON_HEIGHT;auto max_size_rect = QRect { 0, 0, BOOKMARK_BUTTON_MAX_WIDTH, height };auto layout = bookmark_button_layout(*button, option, title, max_size_rect);@@ -233,6 +315,11 @@ void BookmarksBar::rebuild()button->setFixedHeight(height);button->installEventFilter(this);++ auto id = ak_string_from_qstring(button->defaultAction() ? button->defaultAction()->property("id").toString() : QString {});+ current_ids.set(id);+ if (animates && !id.is_empty() && !previous_items.contains(id))+ slide_in(*button, layout.preferred_width);};for (auto const& item : WebView::Application::the().bookmarks_menu().items()) {@@ -268,11 +355,26 @@ void BookmarksBar::rebuild()if (auto* button = as_if<QToolButton>(widgetForAction(action))) {button->setPopupMode(QToolButton::InstantPopup);set_button_properties(button, title);+ auto set_menu_open = [button = QPointer { button }](bool open) {+ if (!button)+ return;+ button->setProperty(BOOKMARK_FOLDER_MENU_OPEN_PROPERTY, open);+ button->update();+ };+ QObject::connect(submenu, &QMenu::aboutToShow, button, [set_menu_open] { set_menu_open(true); });+ QObject::connect(submenu, &QMenu::aboutToHide, button, [set_menu_open] { set_menu_open(false); });}},[](WebView::Separator) {});}++ if (animates) {+ for (auto const& [id, item] : previous_items) {+ if (!current_ids.contains(id) && !item.image.isNull())+ slide_out(item.index, item.image);+ }+ }}void BookmarksBar::show_context_menu(QPoint position, Optional<WebView::BookmarkItem const&> item, Optional<String const&> target_folder_id, Optional<String const&> parent_folder_id)@@ -287,8 +389,9 @@ void BookmarksBar::show_context_menu(QPoint position, Optional<WebView::Bookmarkelse if (item->is_folder())execute_context_menu(bookmark_folder_context_menu(), position);} else {+ // NB: Empty space in a folder that about:bookmarks shows adds to that folder, and elsewhere to the bar.m_selected_bookmark_menu_item_id = {};- m_selected_bookmark_menu_target_folder_id = {};+ m_selected_bookmark_menu_target_folder_id = target_folder_id.copy();m_selected_bookmark_menu_parent_folder_id = {};execute_context_menu(bookmarks_bar_context_menu(), position);@@ -304,6 +407,25 @@ bool BookmarksBar::eventFilter(QObject* object, QEvent* event)}}+ // The folders on the bar behave like a menu bar: while one is open, moving over another opens that one instead.+ if (event->type() == QEvent::MouseMove) {+ if (auto* menu = as_if<QMenu>(object)) {+ auto global_position = as<QMouseEvent>(*event).globalPosition().toPoint();+ auto* button = as_if<QToolButton>(childAt(mapFromGlobal(global_position)));+ // NB: A folder's menu is its button's action's.+ auto* folder_menu = button && button->defaultAction() ? button->defaultAction()->menu() : nullptr;+ if (folder_menu && !folder_menu->isVisible()) {+ for (auto* open_menu = menu; open_menu; open_menu = as_if<QMenu>(open_menu->parentWidget()))+ open_menu->close();+ QTimer::singleShot(0, button, [button = QPointer { button }] {+ if (button)+ button->showMenu();+ });+ return true;+ }+ }+ }+if (event->type() == QEvent::MouseButtonPress) {auto& mouse_event = as<QMouseEvent>(*event);diff --git a/UI/Qt/BookmarksBar.h b/UI/Qt/BookmarksBar.hindex 93e00025f80..ae38866ff98 100644--- a/UI/Qt/BookmarksBar.h+++ b/UI/Qt/BookmarksBar.h@@ -46,7 +46,11 @@ private:QMenu& bookmark_context_menu();QMenu& bookmark_folder_context_menu();+ void slide_in(QWidget&, int width);+ void slide_out(int index, QPixmap const& image);+Tab* m_tab { nullptr };+ bool m_has_been_built { false };QMenu* m_bookmarks_bar_context_menu { nullptr };QMenu* m_bookmark_context_menu { nullptr };diff --git a/UI/Qt/BrowserWindow.cpp b/UI/Qt/BrowserWindow.cppindex 83e41c0982b..b2d4aa9662f 100644--- a/UI/Qt/BrowserWindow.cpp+++ b/UI/Qt/BrowserWindow.cpp@@ -22,12 +22,17 @@#include <UI/Qt/ChromeStyle.h>#include <UI/Qt/DevToolsBanner.h>#include <UI/Qt/Icon.h>+#include <UI/Qt/LadybirdButton.h>#include <UI/Qt/Menu.h>+#include <UI/Qt/Motion.h>+#include <UI/Qt/Popover.h>#include <UI/Qt/StringUtils.h>+#include <UI/Qt/SystemAppearance.h>#if defined(AK_OS_MACOS)# include <UI/Qt/MacWindow.h>#endif#include <UI/Qt/TabBar.h>+#include <UI/Qt/Theme.h>#include <UI/Qt/WebContentView.h>#include <UI/Qt/WindowControlButton.h>@@ -38,6 +43,7 @@#include <QGuiApplication>#include <QHBoxLayout>#include <QIcon>+#include <QLabel>#include <QMenuBar>#include <QMouseEvent>#include <QPainter>@@ -59,13 +65,33 @@ namespace Ladybird {static constexpr auto AUDIO_STATE_BUTTON_POSITION = QTabBar::LeftSide;static constexpr auto TAB_CLOSE_BUTTON_POSITION = QTabBar::RightSide;static constexpr auto WINDOW_DRAG_REGION_PROPERTY = "LadybirdWindowDragRegion";+static constexpr int LADYBIRD_MENU_WIDTH = 280;static constexpr int WINDOW_RESIZE_BORDER_WIDTH = 6;static constexpr int WINDOW_RESIZE_CORNER_WIDTH = WINDOW_RESIZE_BORDER_WIDTH * 2;#if defined(AK_OS_MACOS)-static constexpr int NATIVE_WINDOW_CONTROL_X_OFFSET = 6;-static constexpr int NATIVE_WINDOW_CONTROL_Y_OFFSET = 4;+// NB: AppKit puts the traffic lights 10 px in, so they move this far to sit NATIVE_MACOS_WINDOW_CONTROLS_INSET in.+static constexpr int NATIVE_WINDOW_CONTROL_X_OFFSET = NATIVE_MACOS_WINDOW_CONTROLS_INSET - 10;+static constexpr int NATIVE_WINDOW_CONTROL_Y_OFFSET = NATIVE_MACOS_WINDOW_CONTROLS_INSET - 10;#endif+// The widget in a tab that takes the focus when the tab is shown: an address being edited, or else whatever had the focus+// in the tab, or else the page.+static QWidget& focus_widget_for_tab(Tab& tab)+{+ if (auto* location_edit = tab.location_edit_with_parked_editing())+ return *location_edit;+ if (auto* tab_focus_widget = tab.focusWidget(); tab_focus_widget && tab.isAncestorOf(tab_focus_widget))+ return *tab_focus_widget;+ return tab.view();+}++// Whether the focus is in the address field of one of the window's tabs, whose focus ring then shows.+static bool focus_is_in_location_edit_of(QWidget const& window)+{+ auto* focus_widget = QApplication::focusWidget();+ return focus_widget && focus_widget->window() == &window && is<LocationEdit>(*focus_widget);+}+static bool is_empty_window_drag_region(QWidget const& widget, QPoint position){return widget.property(WINDOW_DRAG_REGION_PROPERTY).toBool() && widget.childAt(position) == nullptr;@@ -112,6 +138,8 @@ void FullscreenMode::enter(Tab* tab)void FullscreenMode::entered_fullscreen(){+ if (m_fullscreen_tab && m_window->tab_index(m_fullscreen_tab) != -1)+ m_exit_button->set_host(m_fullscreen_tab->url().host().has_value() ? qstring_from_ak_string(m_fullscreen_tab->url().serialized_host()) : QString {});// Let button float in place for 3 times the time it takes to animate it in place.m_debounce.start(*this, button_animation_time() * 3);m_exit_button->animate_show();@@ -154,17 +182,88 @@ bool FullscreenMode::eventFilter(QObject* obj, QEvent* event)return QObject::eventFilter(obj, event);}+// A toast at the top of the screen says which site went full screen, and how to leave. Clicking it leaves too.+static constexpr int FULLSCREEN_TOAST_HEIGHT = 38;+static constexpr int FULLSCREEN_TOAST_TOP = 28;+static constexpr int FULLSCREEN_TOAST_PADDING = 18;+static constexpr int FULLSCREEN_TOAST_GAP = 10;+static constexpr int FULLSCREEN_TOAST_VISIBLE_MS = 3000;+static constexpr auto FULLSCREEN_TOAST_EXIT_TEXT = "Press Esc to exit"sv;++static QFont fullscreen_toast_font(QFont font, QFont::Weight weight = QFont::Normal)+{+ font.setPixelSize(13);+ font.setWeight(weight);+ return font;+}+ExitFullscreenButton::ExitFullscreenButton(QWidget* parent)- : QPushButton("Exit fullscreen", parent)+ : QPushButton(parent){#if defined(AK_OS_MACOS)// The web content view is a native QRhiWidget on macOS, so this overlay must also be native to remain above it.setAttribute(Qt::WA_NativeWindow);#endif- setStyleSheet("background-color:rgb(55, 99, 129); color: white; padding: 10px; border-radius: 5px;");- adjustSize();+ setAttribute(Qt::WA_TranslucentBackground);+ setAccessibleName("Exit full screen");+ setCursor(Qt::PointingHandCursor);hide();+ cast_floating_shadow(*this, FULLSCREEN_TOAST_HEIGHT / 2.0, FloatingShadowTone::Dark);m_widget_animation = new QPropertyAnimation(this, "pos", this);+ m_hide_timer = new QTimer(this);+ m_hide_timer->setSingleShot(true);+ m_hide_timer->setInterval(FULLSCREEN_TOAST_VISIBLE_MS);+ QObject::connect(m_hide_timer, &QTimer::timeout, this, [this] {+ if (!underMouse())+ hide();+ });+}++void ExitFullscreenButton::set_host(QString host)+{+ m_host = AK::move(host);+ resize(sizeHint());+ update();+}++QSize ExitFullscreenButton::sizeHint() const+{+ auto host_width = m_host.isEmpty() ? 0 : QFontMetrics(fullscreen_toast_font(font(), QFont::DemiBold)).horizontalAdvance(m_host);+ auto message = m_host.isEmpty() ? QStringLiteral("Full screen") : QStringLiteral(" is now full screen");+ auto text_width = host_width + QFontMetrics(fullscreen_toast_font(font())).horizontalAdvance(message);+ auto exit_width = QFontMetrics(fullscreen_toast_font(font())).horizontalAdvance(qstring_from_ak_string(FULLSCREEN_TOAST_EXIT_TEXT));+ return { (2 * FULLSCREEN_TOAST_PADDING) + text_width + (2 * FULLSCREEN_TOAST_GAP) + 1 + exit_width, FULLSCREEN_TOAST_HEIGHT };+}++void ExitFullscreenButton::paintEvent(QPaintEvent*)+{+ QPainter painter(this);+ painter.setRenderHint(QPainter::Antialiasing);++ QRectF pill = QRectF(rect()).adjusted(0.5, 0.5, -0.5, -0.5);+ painter.setPen(QPen(QColor(255, 255, 255, 26), 1));+ painter.setBrush(QColor(28, 28, 30));+ painter.drawRoundedRect(pill, pill.height() / 2, pill.height() / 2);++ auto x = FULLSCREEN_TOAST_PADDING;+ auto draw_text = [&](QString const& text, QFont const& font, QColor const& color) {+ painter.setFont(font);+ painter.setPen(color);+ auto width = QFontMetrics(font).horizontalAdvance(text);+ painter.drawText(QRect(x, 0, width, height()), Qt::AlignVCenter | Qt::AlignLeft, text);+ x += width;+ };+ if (!m_host.isEmpty()) {+ draw_text(m_host, fullscreen_toast_font(font(), QFont::DemiBold), Qt::white);+ draw_text(QStringLiteral(" is now full screen"), fullscreen_toast_font(font()), Qt::white);+ } else {+ draw_text(QStringLiteral("Full screen"), fullscreen_toast_font(font()), Qt::white);+ }++ x += FULLSCREEN_TOAST_GAP;+ painter.fillRect(QRect(x, (height() - 14) / 2, 1, 14), QColor(255, 255, 255, 64));+ x += 1 + FULLSCREEN_TOAST_GAP;+ draw_text(qstring_from_ak_string(FULLSCREEN_TOAST_EXIT_TEXT), fullscreen_toast_font(font()), QColor(0xd0, 0xd0, 0xd6));}void ExitFullscreenButton::animate_show()@@ -172,36 +271,45 @@ void ExitFullscreenButton::animate_show()if (isVisible())return;+ resize(sizeHint());show();raise();+#if defined(AK_OS_MACOS)+ // NB: A native child can't show the page through its corners, so its view is rounded instead.+ round_appkit_view_corners(*this, FULLSCREEN_TOAST_HEIGHT / 2.0, QColor(255, 255, 255, 26));+#endif+ m_hide_timer->start();- auto const container_size = screen() ? screen()->geometry().size() : (parentWidget() ? parentWidget()->size() : QSize {});+ auto const container_size = parentWidget() ? parentWidget()->size() : (screen() ? screen()->geometry().size() : QSize {});int const destination_x = (container_size.width() - width()) / 2;- int const destination_y = static_cast<int>(static_cast<float>(container_size.height()) * 0.05);+ // The toast slides down into place, unless the system asks for less motion.m_widget_animation->stop();- m_widget_animation->setDuration(FullscreenMode::button_animation_time());+ m_widget_animation->setDuration(SystemAppearance::prefers_reduced_motion() ? 0 : Motion::BASE);m_widget_animation->setStartValue(QPoint(destination_x, -height()));- m_widget_animation->setEndValue(QPoint(destination_x, destination_y));- m_widget_animation->setEasingCurve(QEasingCurve::OutBounce);+ m_widget_animation->setEndValue(QPoint(destination_x, FULLSCREEN_TOAST_TOP));+ m_widget_animation->setEasingCurve(Motion::enter_easing());m_widget_animation->start();}-static QIcon const& app_icon()+// Private windows have a dark icon of their own, so they are easy to tell apart in the taskbar.+static QIcon const& app_icon(WebView::IsPrivate is_private){static QIcon icon;- if (icon.isNull()) {+ static QIcon private_icon;+ auto& cached_icon = is_private == WebView::IsPrivate::Yes ? private_icon : icon;+ if (cached_icon.isNull()) {QPixmap pixmap;- pixmap.load(":/Icons/ladybird.png");- icon = QIcon(pixmap);+ pixmap.load(is_private == WebView::IsPrivate::Yes ? ":/Icons/ladybird-private.png" : ":/Icons/ladybird.png");+ cached_icon = QIcon(pixmap);}- return icon;+ return cached_icon;}BrowserWindow::BrowserWindow(Vector<URL::URL> const& initial_urls, IsPopupWindow is_popup_window, WebView::IsPrivate is_private, Tab* parent_tab, Optional<WebView::CanonicalTraversable&> traversable, Optional<WebView::SessionWindowId> restored_session_window_id): m_is_private(is_private), m_session(WebView::Application::session_for_new_view(is_private))- , m_tabs_container(new TabWidget(this))+ , m_tabs_container(new TabWidget(is_private, this)), m_is_popup_window(is_popup_window){auto const& browser_options = WebView::Application::browser_options();@@ -220,7 +328,7 @@ BrowserWindow::BrowserWindow(Vector<URL::URL> const& initial_urls, IsPopupWindowsetWindowFlag(Qt::FramelessWindowHint, uses_client_side_decorations());#endifsetAttribute(Qt::WA_OpaquePaintEvent);- setWindowIcon(app_icon());+ setWindowIcon(app_icon(is_private));qApp->installEventFilter(this);update_window_border();@@ -240,7 +348,7 @@ BrowserWindow::BrowserWindow(Vector<URL::URL> const& initial_urls, IsPopupWindowinitialize_application_actions();initialize_application_menu();- initialize_hamburger_menu();+ initialize_ladybird_menu();initialize_window_context_menu();update_chrome_style();@@ -254,17 +362,17 @@ BrowserWindow::BrowserWindow(Vector<URL::URL> const& initial_urls, IsPopupWindowif (tab)update_window_title(tab->title());+ auto focus_was_in_location_edit = focus_is_in_location_edit_of(*this);set_current_tab(tab);if (tab) {- QWidget* focus_widget = &tab->view();- if (auto* location_edit = tab->location_edit_with_parked_editing())- focus_widget = location_edit;- else if (auto* tab_focus_widget = tab->focusWidget(); tab_focus_widget && tab->isAncestorOf(tab_focus_widget))- focus_widget = tab_focus_widget;+ auto& focus_widget = focus_widget_for_tab(*tab);#if defined(AK_OS_MACOS)- make_appkit_window_first_responder(*focus_widget);+ make_appkit_window_first_responder(focus_widget);#endif- focus_widget->setFocus();+ focus_widget.setFocus();+ // NB: As the focus moves from one tab's address field to another's, their focus ring stays as it is.+ if (auto* location_edit = as_if<LocationEdit>(focus_widget); location_edit && focus_was_in_location_edit)+ location_edit->show_focus_ring_at_once();}fullscreen_mode().exit(FullscreenMode::ExitInitiatedBy::UI);});@@ -302,6 +410,11 @@ BrowserWindow::BrowserWindow(Vector<URL::URL> const& initial_urls, IsPopupWindowsetCentralWidget(main_widget);setContextMenuPolicy(Qt::PreventContextMenu);+ // The first tab was made current before the tabs were in the window, so its focus never reached the window. Without+ // it, the window would give the focus to its first focusable widget once it is activated, rather than to the page.+ if (m_current_tab)+ focus_widget_for_tab(*m_current_tab).setFocus();+if (browser_options.devtools_port.has_value())on_devtools_enabled();}@@ -323,6 +436,8 @@ void BrowserWindow::initialize_application_actions()addAction(application.close_current_tab_action());addAction(application.open_next_tab_action());addAction(application.open_previous_tab_action());+ addAction(application.search_tabs_action());+ addAction(application.move_focus_action());addAction(application.open_file_action());addAction(application.open_settings_action());addAction(application.open_downloads_action());@@ -369,77 +484,108 @@ void BrowserWindow::initialize_application_menu()update_menu_bar_visibility();}-void BrowserWindow::initialize_hamburger_menu()+// The Ladybird menu holds what a window's own button is for: new tabs and windows, history, bookmarks and downloads,+// settings, and Ladybird itself. On macOS the menu bar holds everything else. Elsewhere the menu holds the rest too.+void BrowserWindow::initialize_ladybird_menu(){auto& application = Application::the();- m_hamburger_menu = new QMenu(this);- QObject::connect(m_hamburger_menu, &QMenu::aboutToShow, this, &BrowserWindow::update_hamburger_zoom_label);-- m_hamburger_menu->addAction(application.new_tab_action());- m_hamburger_menu->addAction(application.new_window_action());- m_hamburger_menu->addAction(application.new_private_window_action());- m_hamburger_menu->addAction(application.reopen_recently_closed_tab_action());- m_hamburger_menu->addSeparator();+ m_ladybird_menu = new QMenu(this);+ m_ladybird_menu->setObjectName("LadybirdMenu");+ m_ladybird_menu->setMinimumWidth(LADYBIRD_MENU_WIDTH);+ QObject::connect(m_ladybird_menu, &QMenu::aboutToShow, this, &BrowserWindow::update_ladybird_menu_zoom_level);++ m_ladybird_menu->addAction(application.new_tab_action());+ m_ladybird_menu->addAction(application.new_window_action());+ m_ladybird_menu->addAction(application.new_private_window_action());+ m_ladybird_menu->addAction(application.reopen_recently_closed_tab_action());+ if (m_is_private == WebView::IsPrivate::Yes) {+ auto* restart_private_session_action = m_ladybird_menu->addAction("Start a Fresh Private Session…");+ QObject::connect(restart_private_session_action, &QAction::triggered, this, [this] {+ if (m_current_tab)+ m_current_tab->show_private_session_popover();+ });+ }+ m_ladybird_menu->addSeparator();- m_hamburger_menu->addMenu(application.history_menu());- m_hamburger_menu->addMenu(application.bookmarks_menu());- m_hamburger_menu->addAction(application.open_downloads_action());- m_hamburger_menu->addSeparator();+ m_ladybird_menu->addMenu(application.history_menu());+ m_ladybird_menu->addMenu(application.bookmarks_menu());+ auto* downloads_action = m_ladybird_menu->addAction("Downloads");+ downloads_action->setShortcutVisibleInContextMenu(true);+ // NB: The application's own downloads action owns the shortcut. This item only shows it.+#if defined(AK_OS_MACOS)+ downloads_action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_L));+#else+ downloads_action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_J));+#endif+ downloads_action->setShortcutContext(Qt::WidgetShortcut);+ QObject::connect(downloads_action, &QAction::triggered, this, [this] {+ if (m_current_tab)+ m_current_tab->show_downloads_popover();+ });+ m_ladybird_menu->addSeparator();- m_hamburger_menu->addAction(create_hamburger_zoom_actions());- m_hamburger_menu->addSeparator();+ m_ladybird_menu->addAction(create_ladybird_menu_zoom_row());+ m_ladybird_menu->addAction(application.find_in_page_action());+ m_ladybird_menu->addSeparator();- m_hamburger_menu->addAction(application.find_in_page_action());- m_hamburger_menu->addSeparator();+ m_ladybird_menu->addAction(application.open_settings_action());+ m_ladybird_menu->addMenu(application.inspect_menu());+ m_ladybird_menu->addMenu(application.debug_menu());+ m_ladybird_menu->addSeparator();- m_hamburger_menu->addAction(application.open_settings_action());- m_hamburger_menu->addMenu(application.inspect_menu());- m_hamburger_menu->addMenu(application.debug_menu());- m_hamburger_menu->addSeparator();+ m_ladybird_menu->addMenu(application.help_menu());+ // NB: On macOS, the application menu has Quit.+#if !defined(AK_OS_MACOS)+ m_ladybird_menu->addAction(application.quit_action());+#endif- m_hamburger_menu->addMenu(application.help_menu());- m_hamburger_menu->addAction(application.quit_action());+ m_tabs_container->ladybird_button().setMenu(m_ladybird_menu);}-QAction* BrowserWindow::create_hamburger_zoom_actions()+// The menu's zoom row: its label like an item's, and the page's zoom level between buttons to zoom out and in.+QAction* BrowserWindow::create_ladybird_menu_zoom_row(){auto& application = Application::the();- auto* container = new QWidget(m_hamburger_menu);- container->setObjectName("LadybirdHamburgerZoomActions");-- auto* layout = new QHBoxLayout(container);- layout->setContentsMargins(14, 2, 14, 2);- layout->setSpacing(4);- container->setLayout(layout);-- auto* label = new QLabel("Zoom", container);- layout->addWidget(label);+ auto* row = new QWidget(m_ladybird_menu);+ row->setObjectName("LadybirdMenuZoomRow");+ auto* layout = new QHBoxLayout(row);+ layout->setContentsMargins(10, 3, 10, 3);+ layout->setSpacing(2);+ layout->addWidget(new QLabel("Zoom", row), 1);- auto make_button = [&](QAnyStringView name, QString const& text, QString const& tooltip, QAction* action, int width = 24) {- auto* button = new QPushButton(text, container);- button->setObjectName(name);+ auto add_button = [&](char const* object_name, QString const& tooltip, QAction* action) {+ auto* button = new QPushButton(row);+ button->setObjectName(object_name);button->setToolTip(tooltip);- button->setFixedSize(width, 24);- button->setFlat(true);-+ button->setAccessibleName(tooltip);+ button->setFocusPolicy(Qt::NoFocus);QObject::connect(button, &QPushButton::clicked, action, &QAction::trigger);- QObject::connect(action, &QAction::triggered, this, &BrowserWindow::update_hamburger_zoom_label);-+ QObject::connect(action, &QAction::triggered, this, &BrowserWindow::update_ladybird_menu_zoom_level);layout->addWidget(button);return button;};-- make_button("LadybirdHamburgerZoomOutButton", "-", "Zoom out", application.zoom_out_action());- m_zoom_level = make_button("LadybirdHamburgerResetZoomButton", "100%", "Reset zoom level", application.reset_zoom_action(), 50);- make_button("LadybirdHamburgerZoomInButton", "+", "Zoom in", application.zoom_in_action());-- auto* action = new QWidgetAction(m_hamburger_menu);- action->setDefaultWidget(container);+ add_button("LadybirdMenuZoomButton", "Zoom Out", application.zoom_out_action())->setIcon(create_chrome_icon(ChromeIcon::ZoomOut, Theme::panel().body));+ m_ladybird_menu_zoom_level = add_button("LadybirdMenuZoomLevel", "Reset Zoom", application.reset_zoom_action());+ // NB: The level is drawn in figures of one width, so it doesn't shift as it changes.+ auto level_font = m_ladybird_menu_zoom_level->font();+ level_font.setFeature(QFont::Tag("tnum"), 1);+ m_ladybird_menu_zoom_level->setFont(level_font);+ add_button("LadybirdMenuZoomButton", "Zoom In", application.zoom_in_action())->setIcon(create_chrome_icon(ChromeIcon::NewTab, Theme::panel().body));++ auto* action = new QWidgetAction(m_ladybird_menu);+ action->setDefaultWidget(row);return action;}+void BrowserWindow::update_ladybird_menu_zoom_level()+{+ if (!m_current_tab || !m_ladybird_menu_zoom_level)+ return;+ m_ladybird_menu_zoom_level->setText(qformatted("{}%", round_to<int>(m_current_tab->view().zoom_level() * 100)));+}+void BrowserWindow::initialize_window_context_menu(){m_window_context_menu = new QMenu(this);@@ -479,12 +625,6 @@ void BrowserWindow::show_window_context_menu(QPoint global_position)execute_context_menu(*m_window_context_menu, global_position);}-void BrowserWindow::update_hamburger_zoom_label()-{- auto zoom_level = round_to<int>(m_current_tab->view().zoom_level() * 100);- m_zoom_level->setText(qformatted("{}%", zoom_level));-}-void BrowserWindow::update_tabs_display(){auto const& settings = Application::settings().tab_settings();@@ -521,9 +661,12 @@ Tab& BrowserWindow::new_tab_from_url(URL::URL const& url, Web::HTML::ActivateTabvoid BrowserWindow::open_new_tab(){+ // NB: With the focus already in the selected tab's address field, its focus ring moves to the new tab's field as it+ // is, rather than fading in again.+ auto focus_ring_transition = focus_is_in_location_edit_of(*this) ? Tab::FocusRingTransition::Immediate : Tab::FocusRingTransition::FadeIn;auto& tab = new_tab_from_url(WebView::Application::settings().new_tab_page_url(), Web::HTML::ActivateTab::Yes, TabLocation::end());tab.set_url_is_hidden(true);- tab.focus_location_editor();+ tab.focus_location_editor(focus_ring_transition);}void BrowserWindow::duplicate_tab(Tab& source_tab)@@ -698,10 +841,7 @@ void BrowserWindow::initialize_tab(Tab* tab)QObject::connect(tab, &Tab::favicon_changed, this, &BrowserWindow::tab_favicon_changed);QObject::connect(tab, &Tab::audio_play_state_changed, this, &BrowserWindow::tab_audio_play_state_changed);QObject::connect(tab, &Tab::loading_changed, this, [this] {- m_tabs_container->tab_bar()->update_loading_swirl_animation();- });- QObject::connect(tab, &Tab::loading_finished, this, [this, tab] {- m_tabs_container->tab_bar()->play_load_sheen(*tab);+ m_tabs_container->tab_bar()->update_loading_ring_animation();});if (tab->is_loaded())@@ -826,17 +966,18 @@ void BrowserWindow::move_tab_to_window(int index, BrowserWindow& target_window,close();}-void BrowserWindow::detach_tab_to_new_window(int index, QPoint global_position)+BrowserWindow& BrowserWindow::detach_tab_to_new_window(int index, QPoint global_position, DetachedWindowFollowsPointer follows_pointer){- if (index < 0 || index >= m_tabs_container->count())- return;+ VERIFY(index >= 0 && index < m_tabs_container->count());+ // NB: A window that follows the pointer can't be maximized, so it takes the size this window has when restored.+ auto size = follows_pointer == DetachedWindowFollowsPointer::Yes && isMaximized() ? normalGeometry().size() : this->size();WindowConfiguration configuration {.x = Web::DevicePixels { global_position.x() - 160 },.y = Web::DevicePixels { global_position.y() - 18 },- .width = Web::DevicePixels { width() },- .height = Web::DevicePixels { height() },- .maximized = isMaximized(),+ .width = Web::DevicePixels { size.width() },+ .height = Web::DevicePixels { size.height() },+ .maximized = follows_pointer == DetachedWindowFollowsPointer::No && isMaximized(),};auto& window = Application::the().new_window({}, configuration, IsPopupWindow::No, m_is_private, nullptr, {}, ShowWindow::No);@@ -849,6 +990,22 @@ void BrowserWindow::detach_tab_to_new_window(int index, QPoint global_position)window.activateWindow();window.raise();+ return window;+}++void BrowserWindow::set_failed_download_count(size_t count)+{+ // Failed downloads that are cleared or retried are no longer looked at.+ m_failed_download_count = count;+ m_acknowledged_failed_download_count = min(m_acknowledged_failed_download_count, count);+}++void BrowserWindow::acknowledge_failed_downloads()+{+ m_acknowledged_failed_download_count = m_failed_download_count;+ for_each_tab([](Tab& tab) {+ tab.update_downloads_button();+ });}void BrowserWindow::set_current_tab(Tab* tab)@@ -860,12 +1017,16 @@ void BrowserWindow::set_current_tab(Tab* tab)if (tab)tab->ensure_loaded();- if (m_current_tab)+ // What a tab's toolbar showed belongs to that tab, so it goes away with it however another tab is selected.+ if (m_current_tab) {+ m_current_tab->close_popovers();m_current_tab->view().set_system_visibility_state(Web::HTML::VisibilityState::Hidden);+ }m_current_tab = tab;if (m_current_tab) {+ m_current_tab->clear_attention();m_current_tab->view().set_system_visibility_state(Web::HTML::VisibilityState::Visible);if (auto session_tab_id = m_current_tab->session_tab_id(); session_tab_id.has_value())@@ -893,6 +1054,16 @@ Tab* BrowserWindow::activate_tab_with_url(URL::URL const& url, URL::ExcludeFragm}bool BrowserWindow::definitely_close_tab(int index)+{+ return close_tab(index, WebView::SessionStore::KeepForReopening::Yes);+}++void BrowserWindow::close_tab_without_keeping_it(int index)+{+ (void)close_tab(index, WebView::SessionStore::KeepForReopening::No);+}++bool BrowserWindow::close_tab(int index, WebView::SessionStore::KeepForReopening keep_for_reopening){cancel_window_close_preflight();@@ -907,6 +1078,7 @@ bool BrowserWindow::definitely_close_tab(int index)WebView::SessionStore::TabClosed closed {.tab_id = *session_tab_id,.closed_at = UnixDateTime::now(),+ .keep_for_reopening = keep_for_reopening,};if (auto result = m_session->session_store->tab_closed(AK::move(closed)); result.is_error())dbgln("Unable to record the closed tab in the session store: {}", result.error());@@ -1043,7 +1215,7 @@ int BrowserWindow::tab_index(Tab* tab)void BrowserWindow::update_window_title(QString const& title){char const* format = is_private() == WebView::IsPrivate::Yes- ? "%1 - Ladybird (Private Browsing)"+ ? "%1 - Ladybird (Private)": "%1 - Ladybird";setWindowTitle(QString(format).arg(title));}@@ -1066,15 +1238,15 @@ void BrowserWindow::tab_favicon_changed(int index, QIcon const& icon)void BrowserWindow::update_chrome_style(){- menuBar()->setStyleSheet(ChromeStyle::menu_bar_style_sheet(palette()));- m_hamburger_menu->setStyleSheet(ChromeStyle::hamburger_style_sheet(palette()));+ menuBar()->setStyleSheet(ChromeStyle::menu_bar_style_sheet(Theme::chrome_palette(*this)));}TabBarButton* BrowserWindow::create_tab_close_button(Tab& tab){- auto* close_button = new TabBarButton(create_chrome_icon(ChromeIcon::TabClose, palette()));+ auto* close_button = new TabBarButton(create_chrome_icon(ChromeIcon::TabClose, Theme::chrome_palette(*this)), TabBarButton::Role::Close);close_button->setToolTip("Close Tab");connect(close_button, &QPushButton::clicked, this, [this, tab = &tab]() {+ m_tabs_container->tab_bar()->lock_tab_widths();request_to_close_tab(m_tabs_container->index_of(tab));});return close_button;@@ -1113,7 +1285,7 @@ void BrowserWindow::update_tab_button_icons()for (int index = 0; index < m_tabs_container->count(); ++index) {if (auto* button = m_tabs_container->tab_bar()->tabButton(index, TAB_CLOSE_BUTTON_POSITION)) {if (auto* tab_bar_button = qobject_cast<TabBarButton*>(button))- tab_bar_button->setIcon(create_chrome_icon(ChromeIcon::TabClose, palette()));+ tab_bar_button->setIcon(create_chrome_icon(ChromeIcon::TabClose, Theme::chrome_palette(*this)));}if (auto* button = m_tabs_container->tab_bar()->tabButton(index, AUDIO_STATE_BUTTON_POSITION)) {@@ -1163,10 +1335,10 @@ void BrowserWindow::update_menu_bar_window_control_icons()return;auto is_maximized = this->isMaximized();- m_menu_bar_minimize_window_button->setIcon(create_chrome_icon(ChromeIcon::WindowMinimize, palette()));- m_menu_bar_maximize_window_button->setIcon(create_chrome_icon(is_maximized ? ChromeIcon::WindowRestore : ChromeIcon::WindowMaximize, palette()));+ m_menu_bar_minimize_window_button->setIcon(create_chrome_icon(ChromeIcon::WindowMinimize, Theme::chrome_palette(*this)));+ m_menu_bar_maximize_window_button->setIcon(create_chrome_icon(is_maximized ? ChromeIcon::WindowRestore : ChromeIcon::WindowMaximize, Theme::chrome_palette(*this)));m_menu_bar_maximize_window_button->setToolTip(is_maximized ? "Restore" : "Maximize");- m_menu_bar_close_window_button->setIcon(create_chrome_icon(ChromeIcon::WindowClose, palette()));+ m_menu_bar_close_window_button->setIcon(create_chrome_icon(ChromeIcon::WindowClose, Theme::chrome_palette(*this)));}void BrowserWindow::update_window_decoration_state()@@ -1242,11 +1414,9 @@ void BrowserWindow::tab_audio_play_state_changed(int index, Web::HTML::AudioPlaybreak;case Web::HTML::AudioPlayState::Playing:- auto* button = new TabBarButton(icon_for_page_mute_state(*tab));+ auto* button = new TabBarButton(icon_for_page_mute_state(*tab), TabBarButton::Role::Audio);button->setToolTip(tool_tip_for_page_mute_state(*tab));button->setObjectName("LadybirdAudioState");- // NB: The speaker fills more of its icon than the close button's cross does, so it is drawn a little smaller.- button->set_icon_inset(2);connect(button, &QPushButton::clicked, this, [this, tab]() {tab->view().toggle_page_mute_state();@@ -1275,9 +1445,9 @@ QIcon BrowserWindow::icon_for_page_mute_state(Tab& tab) const{switch (tab.view().page_mute_state()) {case Web::HTML::MuteState::Muted:- return create_chrome_icon(ChromeIcon::VolumeMuted, palette());+ return create_chrome_icon(ChromeIcon::VolumeMuted, Theme::chrome_palette(*this));case Web::HTML::MuteState::Unmuted:- return create_chrome_icon(ChromeIcon::Volume, palette());+ return create_chrome_icon(ChromeIcon::Volume, Theme::chrome_palette(*this));}VERIFY_NOT_REACHED();@@ -1295,6 +1465,21 @@ QString BrowserWindow::tool_tip_for_page_mute_state(Tab& tab) constVERIFY_NOT_REACHED();}+void BrowserWindow::show_all_tabs()+{+ m_tabs_container->show_all_tabs();+}++void BrowserWindow::move_focus_between_chrome_and_page()+{+ if (!m_current_tab)+ return;+ if (m_current_tab->view().hasFocus())+ m_current_tab->focus_location_editor();+ else+ m_current_tab->view().setFocus(Qt::ShortcutFocusReason);+}+void BrowserWindow::open_next_tab(){if (m_tabs_container->count() <= 1)@@ -1682,10 +1867,12 @@ void BrowserWindow::changeEvent(QEvent* event)void BrowserWindow::appearance_changed(){+ SystemAppearance::the().apply_interface_theme(WebView::Application::settings().appearance().interface_theme);update_menu_bar_visibility();for_each_tab([](Tab& tab) {tab.update_bookmarks_bar_visibility();+ tab.view().update_palette();});}@@ -1715,7 +1902,7 @@ void BrowserWindow::paintEvent(QPaintEvent* event)return;QPainter painter(this);- auto color = ChromeStyle::chrome_window_outline(palette());+ auto color = ChromeStyle::chrome_window_outline(Theme::chrome_palette(*this));auto frame = rect();painter.fillRect(QRect(frame.left(), frame.top(), frame.width(), 1), color);painter.fillRect(QRect(frame.left(), frame.bottom(), frame.width(), 1), color);diff --git a/UI/Qt/BrowserWindow.h b/UI/Qt/BrowserWindow.hindex 3d7d58b835b..e986da41841 100644--- a/UI/Qt/BrowserWindow.h+++ b/UI/Qt/BrowserWindow.h@@ -28,6 +28,7 @@class QIcon;class QPropertyAnimation;+class QTimer;class QToolButton;class QWidget;class QWindow;@@ -49,9 +50,17 @@ public:ExitFullscreenButton(QWidget* parent = nullptr);~ExitFullscreenButton() override = default;void animate_show();+ // The site that went full screen, which the toast names.+ void set_host(QString);++ virtual QSize sizeHint() const override;private:+ virtual void paintEvent(QPaintEvent*) override;++ QString m_host;QPropertyAnimation* m_widget_animation;+ QTimer* m_hide_timer { nullptr };};// Handles Qt UI state related to when Ladybird has entered fullscreen,@@ -150,6 +159,9 @@ public:int tab_count() { return m_tabs_container->count(); }int tab_index(Tab*);Tab* tab_at(int index) const { return m_tabs_container->tab(index); }+ TabWidget& tab_widget() const { return *m_tabs_container; }+ // Closes a tab that isn't worth reopening, such as an empty tab that other tabs took the place of.+ void close_tab_without_keeping_it(int index);// Pinned tabs always fill the start of the strip: indices [0, pinned_tab_count()).int pinned_tab_count() const;@@ -177,7 +189,7 @@ public:void on_tab_load_start(Tab&);FullscreenMode& fullscreen_mode();- QMenu& hamburger_menu() const { return *m_hamburger_menu; }+ LadybirdButton& ladybird_button() const { return m_tabs_container->ladybird_button(); }static bool has_chrome_in_titlebar();void show_window_context_menu(QPoint global_position);@@ -196,10 +208,19 @@ public:void update_tabs_display();void rebuild_bookmarks_menu();- void detach_tab_to_new_window(int index, QPoint global_position);+ enum class DetachedWindowFollowsPointer : bool {+ No,+ Yes,+ };+ BrowserWindow& detach_tab_to_new_window(int index, QPoint global_position, DetachedWindowFollowsPointer = DetachedWindowFollowsPointer::No);void move_tab_to_window(int index, BrowserWindow& target_window, int target_index);void adopt_tab(Tab&, int index);+ // A download that failed marks the downloads button until the downloads are looked at.+ void set_failed_download_count(size_t);+ void acknowledge_failed_downloads();+ bool has_unseen_failed_downloads() const { return m_failed_download_count > m_acknowledged_failed_download_count; }+double refresh_rate() const { return m_screen_observer->refresh_rate(); }Optional<u64> display_id() const { return m_screen_observer->display_id(); }@@ -221,12 +242,15 @@ public slots:void request_to_close_current_tab();void open_next_tab();void open_previous_tab();+ void show_all_tabs();+ void move_focus_between_chrome_and_page();void open_file();void show_find_in_page();void enter_fullscreen();void exit_fullscreen();private:+ bool close_tab(int index, WebView::SessionStore::KeepForReopening);virtual bool event(QEvent*) override;virtual bool eventFilter(QObject*, QEvent*) override;virtual void resizeEvent(QResizeEvent*) override;@@ -262,12 +286,11 @@ private:void initialize_application_actions();void initialize_application_menu();- void initialize_hamburger_menu();+ void initialize_ladybird_menu();+ QAction* create_ladybird_menu_zoom_row();+ void update_ladybird_menu_zoom_level();void initialize_window_context_menu();- QAction* create_hamburger_zoom_actions();- void update_hamburger_zoom_label();-void update_chrome_style();int constrain_insertion_index(int index, bool pinned) const;@@ -303,17 +326,19 @@ private:QToolButton* m_menu_bar_maximize_window_button { nullptr };QToolButton* m_menu_bar_close_window_button { nullptr };- QMenu* m_hamburger_menu { nullptr };+ QMenu* m_ladybird_menu { nullptr };+ QPushButton* m_ladybird_menu_zoom_level { nullptr };QMenu* m_window_context_menu { nullptr };QAction* m_reopen_closed_tab_action { nullptr };QAction* m_always_on_top_action { nullptr };QAction* m_toggle_vertical_tabs_action { nullptr };- QPushButton* m_zoom_level { nullptr };IsPopupWindow m_is_popup_window { IsPopupWindow::No };Optional<WebView::SessionWindowId> m_session_window_id;+ size_t m_failed_download_count { 0 };+ size_t m_acknowledged_failed_download_count { 0 };Optional<i64> m_window_close_active_tab_index;QPointer<Tab> m_window_close_original_active_tab;QPointer<Tab> m_window_close_current_preflight_tab;diff --git a/UI/Qt/CMakeLists.txt b/UI/Qt/CMakeLists.txtindex b4f10229235..a0de2b656f4 100644--- a/UI/Qt/CMakeLists.txt+++ b/UI/Qt/CMakeLists.txt@@ -18,19 +18,21 @@ endif()if (LINUX AND NOT ANDROID)find_package(PkgConfig REQUIRED)pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0 gio-unix-2.0)+ # NB: Without the Wayland client library, a tab dragged out of a window does not take a window along with it.+ pkg_check_modules(WAYLAND_CLIENT IMPORTED_TARGET wayland-client)pkg_check_modules(XCB_ICCCM REQUIRED IMPORTED_TARGET xcb-icccm)endif()qt_add_executable(ladybird main.cpp)target_sources(ladybird PRIVATE+ AllTabsPopover.cppApplication.cppAutocomplete.cppBookmarkDialog.cpp+ BookmarkPopover.cppBookmarksBar.cppBrowserWindow.cppChromeStyle.cpp- ContentBlockingButton.cpp- ContentBlockingPopover.cppCrashReportNotifier.cppCrashReportReviewWidget.cppDevToolsBanner.cpp@@ -41,6 +43,7 @@ target_sources(ladybird PRIVATEHiddenPageSizing.cppInputMethodUtils.cppJavaScriptDialog.cpp+ LadybirdButton.cppLocationEdit.cppMenu.cppNativeWindowContainer.cpp@@ -50,12 +53,16 @@ target_sources(ladybird PRIVATEPictureInPictureWindow.cppPopover.cppReportReview.cpp+ RestoreSessionCard.cppScreenshotSelectionOverlay.cppScreenshotViewer.cppSelectDropdown.cpp+ SiteSettingsPopover.cppStringUtils.cpp+ SystemAppearance.cppTab.cppTabBar.cpp+ Theme.cppWebCompatReportReview.cppWebContentView.cppWindowCloseCoordinator.cpp@@ -80,6 +87,11 @@ endif()if (LINUX AND NOT ANDROID)target_sources(ladybird PRIVATE ExternalURLActivationToken.cpp ExternalURLHandler.cpp X11Window.cpp X11Window.h)target_link_libraries(ladybird PRIVATE LibThreading PkgConfig::GIO PkgConfig::XCB_ICCCM Qt::GuiPrivate)+ if (WAYLAND_CLIENT_FOUND)+ target_sources(ladybird PRIVATE WaylandWindow.cpp WaylandWindow.h)+ target_link_libraries(ladybird PRIVATE PkgConfig::WAYLAND_CLIENT)+ target_compile_definitions(ladybird PRIVATE LADYBIRD_HAS_WAYLAND_CLIENT)+ endif()endif()if (APPLE)@@ -95,6 +107,7 @@ if (APPLE)Menu.mmScrollbarPreferencesMac.mmSpellCheckerMac.mm+ SystemAppearanceMac.mmWebContentViewAccessibility.mmWebContentViewMac.mm)@@ -210,7 +223,14 @@ if (BUILD_TESTING)ChromeStyle.cppPerformanceMonitorWidget.cppStringUtils.cpp+ SystemAppearance.cpp+ Theme.cpp)+ if (APPLE)+ target_sources(TestPerformanceMonitorWidget PRIVATE SystemAppearanceMac.mm)+ target_link_libraries(TestPerformanceMonitorWidget PRIVATE "-framework AppKit")+ endif()+ set_target_properties(TestPerformanceMonitorWidget PROPERTIES AUTOMOC ON)target_include_directories(TestPerformanceMonitorWidget PRIVATE ${LADYBIRD_SOURCE_DIR})target_link_libraries(TestPerformanceMonitorWidget PRIVATE Qt6::Widgets LibWebView LibURL AK)qt_import_plugins(TestPerformanceMonitorWidget INCLUDE Qt6::QOffscreenIntegrationPlugin)diff --git a/UI/Qt/ChromeLayout.h b/UI/Qt/ChromeLayout.hindex 53050f074f8..290b2de3dff 100644--- a/UI/Qt/ChromeLayout.h+++ b/UI/Qt/ChromeLayout.h@@ -10,8 +10,15 @@namespace Ladybird {-static constexpr int NATIVE_MACOS_WINDOW_CONTROLS_WIDTH = 62;-static constexpr int NATIVE_MACOS_WINDOW_CONTROLS_GAP = 16;+// The traffic lights sit this far in from the left edge and the top edge of the window, which puts them on the line+// that the window's own items on the tab strip are centered on.+static constexpr int NATIVE_MACOS_WINDOW_CONTROLS_INSET = 12;+// The three traffic lights, with the room after the last one.+static constexpr int NATIVE_MACOS_WINDOW_CONTROLS_WIDTH = 56;+static constexpr int NATIVE_MACOS_WINDOW_CONTROLS_GAP = 14;+// The Ladybird button keeps 28 px clear to the traffic lights before it.+// NB: The traffic lights reach a little past the room kept for them.+static constexpr int LADYBIRD_BUTTON_TRAFFIC_LIGHTS_GAP = 30;static constexpr bool use_native_macos_window_controls(){@@ -31,15 +38,9 @@ struct BrowserChromeLayoutPolicy {static constexpr BrowserChromeLayoutPolicy browser_chrome_layout_policy(){return {- .expanded_sidebar_width = 232,+ .expanded_sidebar_width = 236,.collapsed_sidebar_width = 52,-#ifdef AK_OS_MACOS- // NB: Leaves an even space around the location field, as the rounded web view below it has no border of its own- // to absorb an odd one..toolbar_height = 40,-#else- .toolbar_height = 41,-#endif};}diff --git a/UI/Qt/ChromeStyle.cpp b/UI/Qt/ChromeStyle.cppindex 43017cd5072..a2f04467a33 100644--- a/UI/Qt/ChromeStyle.cpp+++ b/UI/Qt/ChromeStyle.cpp@@ -5,110 +5,32 @@*/#include <AK/Platform.h>-#include <UI/Qt/BrandColors.h>#include <UI/Qt/ChromeStyle.h>#include <UI/Qt/StringUtils.h>+#include <UI/Qt/SystemAppearance.h>+#include <UI/Qt/Theme.h>#include <QAbstractButton>+#include <QApplication>#include <QCursor>#include <QElapsedTimer>#include <QFont>#include <QGuiApplication>#include <QImage>+#include <QMenu>#include <QPainter>#include <QPainterPath>#include <QPalette>+#include <QProxyStyle>#include <QStyleHints>+#include <QStyleOption>#include <QWidget>namespace Ladybird::ChromeStyle {-static bool color_is_dark(QColor const& color)-{- return color.lightness() < 128;-}--static bool palette_is_dark(QPalette const& palette)-{- return color_is_dark(palette.color(QPalette::Window));-}-bool is_dark(QPalette const& palette){- auto color_scheme = QGuiApplication::styleHints()->colorScheme();- if (color_scheme != Qt::ColorScheme::Unknown)- return color_scheme == Qt::ColorScheme::Dark;-- return palette_is_dark(palette);-}--static bool palette_roles_match_color_scheme(QPalette const& palette, bool dark)-{- return color_is_dark(palette.color(QPalette::Window)) == dark- && color_is_dark(palette.color(QPalette::Base)) == dark- && color_is_dark(palette.color(QPalette::Text)) != dark- && color_is_dark(palette.color(QPalette::ButtonText)) != dark;-}--static bool palette_matches_current_color_scheme(QPalette const& palette)-{- auto color_scheme = QGuiApplication::styleHints()->colorScheme();- if (color_scheme == Qt::ColorScheme::Dark)- return palette_roles_match_color_scheme(palette, true);- if (color_scheme == Qt::ColorScheme::Light)- return palette_roles_match_color_scheme(palette, false);- return true;-}--static QColor chrome_window(QPalette const& palette)-{- if (palette_matches_current_color_scheme(palette))- return palette.color(QPalette::Window);-- return is_dark(palette) ? QColor(24, 25, 28) : QColor(245, 245, 246);-}--static QColor chrome_base(QPalette const& palette)-{- if (palette_matches_current_color_scheme(palette))- return palette.color(QPalette::Base);-- return is_dark(palette) ? QColor(22, 23, 26) : QColor(255, 255, 255);-}--struct MaterialColorAnchors {- QColor tab_strip;- QColor background;- QColor surface;- QColor recessed;- QColor hover;- QColor pressed;- QColor border;-};--static MaterialColorAnchors material_color_anchors(bool dark)-{- if (dark) {- return {- .tab_strip = QColor(33, 36, 42),- .background = QColor(13, 15, 18),- .surface = QColor(34, 36, 40),- .recessed = QColor(55, 58, 63),- .hover = QColor(57, 61, 66),- .pressed = QColor(70, 74, 80),- .border = QColor(150, 155, 162),- };- }-- return {- .tab_strip = QColor(195, 197, 204),- .background = QColor(242, 243, 246),- .surface = QColor(255, 255, 255),- .recessed = QColor(150, 150, 152),- .hover = QColor(229, 229, 230),- .pressed = QColor(219, 220, 221),- .border = QColor(95, 96, 98),- };+ return Theme::is_dark(palette);}QColor mix(QColor const& from, QColor const& to, double amount)@@ -124,156 +46,133 @@ QColor mix(QColor const& from, QColor const& to, double amount)};}-// The tab strip is darker than the toolbar below it, whose color the selected tab shares, so the selected tab stands out.+// The opaque color of a translucent color painted over an opaque one.+static QColor over(QColor const& color, QColor const& background)+{+ return mix(background, color, static_cast<double>(color.alphaF()));+}+WindowActivity window_activity(QWidget const& widget){return widget.isActiveWindow() ? WindowActivity::Active : WindowActivity::Inactive;}-QColor chrome_tab_strip_background(QPalette const& palette, WindowActivity activity)+QColor chrome_tab_strip_background(QPalette const& palette){- auto dark = is_dark(palette);- auto color = mix(chrome_window(palette), material_color_anchors(dark).tab_strip, dark ? 0.70 : 0.68);- // An inactive window's tab strip is lifted toward the toolbar, so the window recedes behind the active one.- if (activity == WindowActivity::Inactive)- color = mix(color, chrome_background(palette), 0.4);- return color;+ return Theme::chrome(palette).strip;}-// In dark mode, the chrome is lifted from near black toward a cool slate rather than a plain gray.-static constexpr QColor dark_chrome_base { 17, 20, 25 };-static constexpr QColor dark_chrome_tint { 150, 165, 180 };+// NB: The page never sits right against near-black chrome, so the sidebar beside it is the toolbar's color in the dark+// appearances.+QColor chrome_sidebar_background(QPalette const& palette)+{+ return Theme::chrome(palette).sidebar;+}QColor chrome_background(QPalette const& palette){- auto dark = is_dark(palette);- if (dark)- return mix(mix(chrome_window(palette), dark_chrome_base, 0.70), dark_chrome_tint, 0.27);- return mix(chrome_window(palette), material_color_anchors(dark).background, 0.68);+ return Theme::chrome(palette).toolbar;}-QColor chrome_surface(QPalette const& palette)+QColor chrome_surface(QPalette const&){- auto base = chrome_base(palette);- auto dark = is_dark(palette);- return mix(base, material_color_anchors(dark).surface, dark ? 0.64 : 0.72);+ return Theme::panel().surface;}-QColor chrome_surface_recessed(QPalette const& palette)+QColor chrome_surface_recessed(QPalette const&){- auto dark = is_dark(palette);- if (dark)- return chrome_background(palette).lighter(108);-- return mix(chrome_background(palette), material_color_anchors(dark).recessed, 0.42);+ auto const& panel = Theme::panel();+ return over(panel.control, panel.surface);}-QColor chrome_surface_hover(QPalette const& palette)+QColor chrome_surface_hover(QPalette const&){- auto dark = is_dark(palette);- return mix(chrome_surface(palette), material_color_anchors(dark).hover, dark ? 0.34 : 0.52);+ auto const& panel = Theme::panel();+ return over(panel.control, panel.surface);}-QColor chrome_surface_pressed(QPalette const& palette)+QColor chrome_surface_pressed(QPalette const&){- auto dark = is_dark(palette);- return mix(chrome_surface(palette), material_color_anchors(dark).pressed, dark ? 0.48 : 0.56);+ auto const& panel = Theme::panel();+ return over(panel.pressed, panel.surface);}static QColor chrome_control_surface_hover(QPalette const& palette){- auto dark = is_dark(palette);- return mix(chrome_surface(palette), material_color_anchors(dark).hover, dark ? 0.82 : 0.62);+ return chrome_surface_hover(palette);}static QColor chrome_control_surface_pressed(QPalette const& palette){- auto dark = is_dark(palette);- return mix(chrome_surface(palette), material_color_anchors(dark).pressed, dark ? 0.86 : 0.66);+ return chrome_surface_pressed(palette);}-QColor chrome_control_border(QPalette const& palette)+QColor chrome_control_border(QPalette const&){- auto dark = is_dark(palette);- if (dark)- return mix(chrome_control_surface_hover(palette), material_color_anchors(dark).border, 0.42);-- return mix(chrome_border(palette), material_color_anchors(dark).border, 0.18);+ return Theme::panel().separator;}// The active tab shares the color of the toolbar below it.QColor chrome_active_tab_surface(QPalette const& palette){- return chrome_background(palette);+ return Theme::chrome(palette).toolbar;}QColor chrome_border(QPalette const& palette){- auto dark = is_dark(palette);- return mix(dark ? chrome_surface(palette) : chrome_background(palette), material_color_anchors(dark).border, 0.22);+ return Theme::chrome(palette).divider;}QColor chrome_separator(QPalette const& palette){- return mix(chrome_surface(palette), chrome_border(palette), is_dark(palette) ? 0.42 : 0.54);+ return Theme::chrome(palette).separator;}static QColor chrome_content_separator(QPalette const& palette){- return mix(chrome_background(palette), chrome_border(palette), is_dark(palette) ? 0.44 : 0.58);+ return Theme::chrome(palette).divider;}+// A window without a frame from the desktop has a hairline of its own. It has to hold up against the chrome inside and+// against whatever is behind the window, so it is firmer than the chrome's other lines.QColor chrome_window_outline(QPalette const& palette){- auto dark = is_dark(palette);- if (dark)- return chrome_border(palette);-- // The window outline has to hold up against arbitrary backdrops behind the window, not just our own chrome- // surfaces, so in light mode it is mixed further toward the border anchor than chrome_border().- return mix(chrome_background(palette), material_color_anchors(false).border, 0.5);+ auto const& chrome = Theme::chrome(palette);+ return over(is_dark(palette) ? QColor(255, 255, 255, 56) : QColor(0, 0, 0, 56), chrome.strip);}QColor chrome_accent(){- return BrandColors::Violet100;+ return Theme::accent();}static QColor chrome_text_highlight(){- return BrandColors::SlateBlue900;+ return over(Theme::selection(), Theme::panel().page);}QColor chrome_text(QPalette const& palette){- if (palette_matches_current_color_scheme(palette))- return palette.color(QPalette::Text);-- return is_dark(palette) ? QColor(238, 241, 246) : QColor(24, 29, 36);+ return Theme::chrome(palette).text;}QColor chrome_button_text(QPalette const& palette){- if (palette_matches_current_color_scheme(palette))- return palette.color(QPalette::ButtonText);-- return chrome_text(palette);+ return Theme::chrome(palette).icon;}QColor chrome_muted_text(QPalette const& palette){- if (!palette_matches_current_color_scheme(palette))- return is_dark(palette) ? QColor(154, 163, 176) : QColor(98, 108, 122);-- return palette.color(QPalette::PlaceholderText);+ return Theme::chrome(palette).muted;}-// The titles of tabs and bookmarks share one size.+// The titles of tabs and bookmarks share one size, a point smaller than the application's font, which follows the+// system's interface font.QFont chrome_title_font(QFont font){-#if defined(AK_OS_MACOS)+#if !defined(AK_OS_WINDOWS)// NB: The macOS style gives tab bars and tool buttons small fonts of different sizes when it polishes them, so the- // titles are drawn a point smaller than the application's font rather than in the font of their widget.+ // titles are sized from the application's font rather than from the font of their widget.if (auto application_point_size = QGuiApplication::font().pointSizeF(); application_point_size > 0)font.setPointSizeF(application_point_size - 1);#endif@@ -292,88 +191,50 @@ static QColor chrome_destructive_text()QString style_sheet_color(QColor const& color){+ if (color.alpha() < 255)+ return qformatted("rgba({}, {}, {}, {})", color.red(), color.green(), color.blue(), color.alpha());return qformatted("rgb({}, {}, {})", color.red(), color.green(), color.blue());}-static QString style_sheet_color_with_alpha(QColor const& color)+QString application_style_sheet(QPalette const&){- return qformatted("rgba({}, {}, {}, {})", color.red(), color.green(), color.blue(), color.alpha());-}--QString application_style_sheet(QPalette const& palette)-{- auto surface_color = chrome_surface(palette);- auto text_color = chrome_text(palette);- auto surface = style_sheet_color(surface_color);- auto hover = style_sheet_color(chrome_control_surface_hover(palette));- auto pressed = style_sheet_color(chrome_control_surface_pressed(palette));- auto border = style_sheet_color(chrome_border(palette));- auto separator = style_sheet_color(chrome_separator(palette));- auto text = style_sheet_color(text_color);- auto disabled_text = style_sheet_color(mix(text_color, surface_color, is_dark(palette) ? 0.58 : 0.48));+ auto const& panel = Theme::panel();+ // NB: Menus drawn by Qt are drawn by the application style, so that their rows line up on one right edge, which the+ // style sheet cannot do. Only the widgets put into menus are styled here.return qformatted(R"(-QMenu {{- color: {5};- background: {0};- border: 1px solid {3};- border-radius: 7px;- padding: 5px;-}}--QMenu::item {{- color: {5};+QWidget#LadybirdMenuZoomRow QLabel {{+ color: {0};background: transparent;- border-radius: 5px;- min-height: 20px;- padding: 5px 24px 5px 14px;}}-QMenu::item:selected {{+QWidget#LadybirdMenuZoomRow QPushButton {{+ color: {0};background: {1};+ border: 0;+ border-radius: 6px;+ min-width: 28px;+ max-width: 28px;+ min-height: 22px;+ max-height: 22px;}}-QMenu::item:pressed {{- background: {2};-}}--QMenu::item:disabled {{- color: {6};-}}--QMenu::icon,-QMenu::indicator {{- left: 8px;+QWidget#LadybirdMenuZoomRow QPushButton#LadybirdMenuZoomLevel {{+ background: transparent;+ min-width: 48px;+ max-width: 48px;}}-QMenu::indicator,-QMenu::left-arrow,-QMenu::right-arrow {{- width: 16px;- height: 16px;+QWidget#LadybirdMenuZoomRow QPushButton:hover {{+ background: {2};}}-QMenu::right-arrow {{- right: 8px;-}}-)"-#if defined(AK_OS_MACOS)- R"(-QMenu::right-arrow,-QMenu::left-arrow {{- width: 8px;- height: 8px;-}}-)"-#endif- R"(-QMenu::separator {{- background: {4};- height: 1px;- margin: 5px 8px;+QWidget#LadybirdMenuZoomRow QPushButton:pressed {{+ background: {3};}})",- surface, hover, pressed, border, separator, text, disabled_text);+ style_sheet_color(panel.text), style_sheet_color(panel.control), style_sheet_color(over(panel.control, panel.control)),+ style_sheet_color(panel.pressed));}QString toolbar_container_style_sheet(QPalette const& palette)@@ -384,19 +245,12 @@ QString toolbar_container_style_sheet(QPalette const& palette)auto background = style_sheet_color(background_color);auto surface_hover = style_sheet_color(chrome_control_surface_hover(palette));auto surface_pressed = style_sheet_color(chrome_control_surface_pressed(palette));- // In dark mode, the line under the toolbar is as soft as the one under the tab strip.- auto separator = style_sheet_color(dark ? mix(background_color, chrome_border(palette), 0.44) : chrome_border(palette));+ auto separator = style_sheet_color(chrome_border(palette));auto window_controls_separator = style_sheet_color(mix(chrome_background(palette), chrome_border(palette), dark ? 0.36 : 0.46));auto text = style_sheet_color(chrome_button_text(palette));auto disabled_text = style_sheet_color(chrome_muted_text(palette));auto close_hover = style_sheet_color(chrome_destructive_hover());auto close_text = style_sheet_color(chrome_destructive_text());- auto badge_surface_color = QColor(dark ? BrandColors::Indigo900 : BrandColors::Violet10);- auto badge_border_color = QColor(dark ? BrandColors::Violet50 : BrandColors::Indigo60);- auto badge_surface = style_sheet_color(badge_surface_color);- auto badge_border = style_sheet_color(badge_border_color);- auto badge_surface_hover = style_sheet_color(mix(badge_surface_color, badge_border_color, dark ? 0.28 : 0.22));- auto badge_surface_pressed = style_sheet_color(mix(badge_surface_color, badge_border_color, dark ? 0.45 : 0.38));return qformatted(R"(QWidget#LadybirdToolbarContainer {{@@ -405,21 +259,17 @@ QWidget#LadybirdToolbarContainer {{border-bottom: 1px solid {3};}}-QWidget#LadybirdToolbarContainer[fullWidthToolbar="true"] {{- border-bottom: 0;-}}--QWidget#LadybirdToolbarContainer[hoverBookmarksVisible="true"] {{+QWidget#LadybirdToolbarContainer[bookmarksBarBelow="true"] {{border-bottom-color: transparent;}}QWidget#LadybirdNavigationToolbar QToolButton {{color: {4};background: transparent;- border: 1px solid transparent;- border-radius: 17px;- min-width: 32px;- min-height: 32px;+ border: 0;+ border-radius: 6px;+ min-width: 30px;+ min-height: 28px;padding: 0;}}@@ -444,23 +294,6 @@ QWidget#LadybirdNavigationToolbar QToolButton::menu-indicator {{image: none;}}-QPushButton#LadybirdPrivateBadge {{- color: {4};- background: {9};- border: 1px solid {10};- border-radius: 10px;- padding: 0 10px;- font-weight: 600;-}}--QPushButton#LadybirdPrivateBadge:hover {{- background: {11};-}}--QPushButton#LadybirdPrivateBadge:pressed {{- background: {12};-}}-QWidget#LadybirdToolbarWindowControlsSeparator {{background: {8};}}@@ -471,10 +304,6 @@ QWidget#LadybirdNavigationToolbar QToolButton#LadybirdCloseWindowButton {{background: transparent;border: 0;border-radius: 0;- min-width: 38px;- min-height: 38px;- max-width: 38px;- max-height: 38px;margin: 0;padding: 0;}}@@ -502,17 +331,9 @@ QWidget#LadybirdNavigationToolbar QToolButton#LadybirdCloseWindowButton[pressedOcolor: {4};background: transparent;}}-)"-#if defined(AK_OS_MACOS)- R"(-QWidget#LadybirdToolbarContainer {{- border-bottom: 0;-}}-)"-#endif- ,+)",background, surface_hover, surface_pressed, separator, text, disabled_text, close_hover, close_text,- window_controls_separator, badge_surface, badge_border, badge_surface_hover, badge_surface_pressed);+ window_controls_separator);}QString menu_bar_style_sheet(QPalette const& palette)@@ -568,9 +389,6 @@ QMenuBar#LadybirdMenuBar QToolButton#LadybirdCloseWindowButton {{background: transparent;border: 0;border-radius: 0;- min-width: 40px;- min-height: 30px;- max-height: 30px;padding: 0;}}@@ -601,111 +419,59 @@ QMenuBar#LadybirdMenuBar QToolButton#LadybirdCloseWindowButton[pressedOutside="tbackground, background_bottom, hover, pressed, control_border, text, disabled_text, close_hover, close_text);}-QString hamburger_style_sheet(QPalette const& palette)-{- auto text = style_sheet_color(chrome_button_text(palette));- auto background = style_sheet_color(chrome_background(palette));- auto surface_hover = style_sheet_color(chrome_control_surface_hover(palette));- auto surface_pressed = style_sheet_color(chrome_control_surface_pressed(palette));-- return qformatted(R"(-QWidget#LadybirdHamburgerZoomActions QPushButton#LadybirdHamburgerZoomInButton,-QWidget#LadybirdHamburgerZoomActions QPushButton#LadybirdHamburgerZoomOutButton {{- color: {0};- background: {1};- border-radius: 12px;-}}--QWidget#LadybirdHamburgerZoomActions QPushButton#LadybirdHamburgerResetZoomButton {{- color: {0};- background: transparent;- border-radius: 7px;-}}--QWidget#LadybirdHamburgerZoomActions QPushButton#LadybirdHamburgerZoomInButton:hover,-QWidget#LadybirdHamburgerZoomActions QPushButton#LadybirdHamburgerZoomOutButton:hover,-QWidget#LadybirdHamburgerZoomActions QPushButton#LadybirdHamburgerResetZoomButton:hover {{- background: {2};-}}--QWidget#LadybirdHamburgerZoomActions QPushButton#LadybirdHamburgerZoomInButton:pressed,-QWidget#LadybirdHamburgerZoomActions QPushButton#LadybirdHamburgerZoomOutButton:pressed,-QWidget#LadybirdHamburgerZoomActions QPushButton#LadybirdHamburgerResetZoomButton:pressed {{- background: {3};-}}-)",- text, background, surface_hover, surface_pressed);-}--static QColor autocomplete_surface(QPalette const& palette)-{- if (is_dark(palette))- return mix(chrome_background(palette), material_color_anchors(true).recessed, 0.5);- return chrome_surface(palette);-}-// Hovering a frameless control only lifts it with this soft fill; its ring appears once it is pressed.-static QColor chrome_control_soft_hover(QPalette const& palette)-{- return is_dark(palette) ? QColor(255, 255, 255, 24) : QColor(0, 0, 0, 16);-}-QColor location_edit_border(QPalette const& palette){- return is_dark(palette) ? mix(chrome_background(palette), chrome_border(palette), 0.36) : chrome_border(palette);-}--static QColor location_edit_focus_border(QPalette const& palette)-{- return mix(chrome_border(palette), chrome_accent(), is_dark(palette) ? 0.50 : 0.54);+ return Theme::chrome(palette).divider;}QString location_edit_style_sheet(QPalette const& palette){- auto dark = is_dark(palette);- auto surface_color = chrome_surface(palette);- if (dark)- surface_color = mix(chrome_background(palette), material_color_anchors(true).background, 0.62);- // Hovering the field moves it a little toward the color of the toolbar around it, to show that it can be clicked,- // while it stays set apart from the toolbar.- auto hover_color = mix(surface_color, chrome_background(palette), 0.35);- auto focus_color = dark ? mix(surface_color, QColor(255, 255, 255), 0.035) : surface_color;-- // NB: In dark mode, the field is set apart from the toolbar by its darker fill alone, so its border takes its fill.- auto border_color = dark ? surface_color : location_edit_border(palette);- auto hover_border_color = dark ? hover_color : border_color;- auto focus_border_color = location_edit_focus_border(palette);+ auto const& chrome = Theme::chrome(palette);+ auto const& panel = Theme::panel();++ auto surface_color = over(chrome.field, chrome.toolbar);+ // Hovering the field deepens its fill a little, to show that it can be clicked.+ auto hover_color = over(chrome.hover, surface_color);+ if (chrome.field.alpha() < 255) {+ auto hover_field = chrome.field;+ hover_field.setAlphaF(hover_field.alphaF() + 0.03f);+ hover_color = over(hover_field, chrome.toolbar);+ }+ auto focus_color = chrome.field_focused;+ // The not secure pill deepens a little on hover and press, toward its ink.+ auto warning_hover = mix(chrome.warning_fill, chrome.warning_ink, 0.08);+ auto warning_pressed = mix(chrome.warning_fill, chrome.warning_ink, 0.16);auto surface = style_sheet_color(surface_color);auto hover = style_sheet_color(hover_color);auto focus = style_sheet_color(focus_color);- auto popup_surface = style_sheet_color(autocomplete_surface(palette));- auto border = style_sheet_color(border_color);- auto hover_border = style_sheet_color(hover_border_color);- auto focus_border = style_sheet_color(focus_border_color);- auto text = style_sheet_color(dark ? mix(chrome_text(palette), QColor(255, 255, 255), 0.08) : chrome_text(palette));- auto placeholder = style_sheet_color(mix(chrome_muted_text(palette), surface_color, dark ? 0.20 : 0.34));+ auto border = style_sheet_color(chrome.field_edge.alpha() ? chrome.field_edge : surface_color);+ auto hover_border = style_sheet_color(chrome.field_edge.alpha() ? chrome.field_edge : hover_color);+ // NB: The focus ring is drawn right outside the field's edge, so the focused field's own border keeps to its fill.+ auto focus_border = style_sheet_color(chrome.field_edge.alpha() ? chrome.field_edge : focus_color);+ auto text = style_sheet_color(chrome.text);+ auto placeholder = style_sheet_color(chrome.muted);auto selection = style_sheet_color(chrome_text_highlight());- auto selection_text = style_sheet_color(Qt::white);- auto not_secure_text = style_sheet_color(dark ? QColor(224, 142, 136) : QColor(144, 62, 56));- auto not_secure_background = style_sheet_color(dark ? mix(surface_color, QColor(102, 52, 48), 0.28) : QColor(246, 235, 233));- auto not_secure_hover = style_sheet_color(dark ? mix(surface_color, QColor(104, 55, 51), 0.34) : QColor(242, 226, 223));- auto not_secure_pressed = style_sheet_color(dark ? mix(surface_color, QColor(112, 60, 55), 0.40) : QColor(236, 215, 211));- auto not_secure_border = style_sheet_color(dark ? mix(QColor(92, 48, 45), chrome_border(palette), 0.52) : QColor(224, 203, 199));- auto zoom_text = style_sheet_color(chrome_muted_text(palette));- auto zoom_background = style_sheet_color(dark ? mix(surface_color, chrome_surface_recessed(palette), 0.28) : mix(surface_color, chrome_surface_recessed(palette), 0.14));- auto zoom_hover = style_sheet_color(dark ? mix(surface_color, chrome_surface_recessed(palette), 0.36) : mix(surface_color, chrome_surface_recessed(palette), 0.20));- auto zoom_pressed = style_sheet_color(dark ? mix(surface_color, chrome_surface_recessed(palette), 0.44) : mix(surface_color, chrome_surface_recessed(palette), 0.28));- auto zoom_border = style_sheet_color(dark ? mix(chrome_border(palette), surface_color, 0.38) : mix(chrome_border(palette), surface_color, 0.54));+ auto selection_text = style_sheet_color(chrome.text);+ auto not_secure_text = style_sheet_color(chrome.warning_ink);+ auto not_secure_background = style_sheet_color(chrome.warning_fill);+ auto not_secure_hover = style_sheet_color(warning_hover);+ auto not_secure_pressed = style_sheet_color(warning_pressed);+ auto zoom_text = style_sheet_color(chrome.muted);+ auto zoom_background = style_sheet_color(over(panel.control, surface_color));+ auto zoom_hover = style_sheet_color(over(panel.pressed, surface_color));+ auto zoom_pressed = style_sheet_color(over(panel.pressed, over(panel.control, surface_color)));return qformatted(R"(QLineEdit#LadybirdLocationEdit {{color: {4};background: {0};border: 1px solid {2};- border-radius: {20}px;- min-height: 32px;- padding: 0 16px;+ border-radius: {18}px;+ min-height: 26px;+ max-height: 26px;+ padding: 0 8px;selection-background-color: {6};selection-color: {7};placeholder-text-color: {5};@@ -717,18 +483,10 @@ QLineEdit#LadybirdLocationEdit[fieldHovered="true"] {{}}QLineEdit#LadybirdLocationEdit:focus {{- background: {19};+ background: {17};border-color: {3};}}-QLineEdit#LadybirdLocationEdit[autocompleteOpen="true"] {{- background: {21};- border-bottom-left-radius: 0;- border-bottom-right-radius: 0;- border-bottom: 0;- padding-bottom: 1px;-}}-QLineEdit#LadybirdLocationEdit:disabled {{color: {5};border-color: {2};@@ -737,15 +495,25 @@ QLineEdit#LadybirdLocationEdit:disabled {{QToolButton#LadybirdLocationIcon {{background: transparent;border: 0;+ border-radius: 5px;padding: 0;}}+QToolButton#LadybirdLocationIcon:hover {{+ background: {19};+}}++QToolButton#LadybirdLocationIcon:pressed {{+ background: {20};+}}+QToolButton#LadybirdLocationIcon[notSecure="true"] {{color: {9};background: {10};- border: 1px solid {13};- border-radius: 10px;- padding: 0 7px;+ border: 0;+ border-radius: 5px;+ padding: 0 8px;+ font-size: 12px;font-weight: 500;}}@@ -758,54 +526,58 @@ QToolButton#LadybirdLocationIcon[notSecure="true"]:pressed {{}}QToolButton#LadybirdLocationZoomIndicator {{- color: {14};- background: {15};- border: 1px solid {18};- border-radius: 10px;- padding: 0 7px;- font-weight: 500;+ color: {13};+ background: {14};+ border: 0;+ border-radius: 5px;+ padding: 0 8px;+ font-size: 12px;}}QToolButton#LadybirdLocationZoomIndicator:hover {{- background: {16};+ background: {15};}}QToolButton#LadybirdLocationZoomIndicator:pressed {{- background: {17};+ background: {16};}}QToolButton#LadybirdLocationAction {{background: transparent;border: 0;- margin: 1px;+ margin: 0;padding: 0;}}++/* NB: The buttons in the field keep their own sizes, rather than the toolbar buttons' minimum size. */+QLineEdit#LadybirdLocationEdit QToolButton {{+ min-width: 0;+ min-height: 0;+}})",surface, hover, border, focus_border, text, placeholder, selection, selection_text, hover_border,- not_secure_text, not_secure_background, not_secure_hover, not_secure_pressed, not_secure_border, zoom_text, zoom_background, zoom_hover, zoom_pressed, zoom_border, focus, LOCATION_EDIT_CORNER_RADIUS, popup_surface);+ not_secure_text, not_secure_background, not_secure_hover, not_secure_pressed, zoom_text, zoom_background, zoom_hover, zoom_pressed, focus, LOCATION_EDIT_CORNER_RADIUS,+ style_sheet_color(chrome.hover), style_sheet_color(panel.pressed));}QString bookmarks_bar_style_sheet(QPalette const& palette, int corner_radius){- auto hover = style_sheet_color_with_alpha(chrome_control_soft_hover(palette));- auto pressed = style_sheet_color(chrome_control_surface_pressed(palette));- auto control_border = style_sheet_color(chrome_control_border(palette));- auto text = style_sheet_color(chrome_button_text(palette));+ auto hover = style_sheet_color(Theme::chrome(palette).hover);+ auto pressed = style_sheet_color(Theme::panel().pressed);+ auto control_border = style_sheet_color(Qt::transparent);+ auto text = style_sheet_color(Theme::chrome(palette).text);auto background = style_sheet_color(chrome_background(palette));auto border = style_sheet_color(chrome_content_separator(palette));+ // NB: The bar is 30 px tall, its 24 px bookmarks two points off its top.return qformatted(R"(QToolBar#LadybirdBookmarksBar {{color: {2};background: {4};border: 0;border-bottom: 1px solid {5};- padding: 1px 4px;- spacing: 3px;-}}--QWidget#LadybirdToolbarContainer QToolBar#LadybirdBookmarksBar {{- border-bottom: 0;+ padding: 2px 8px 4px 8px;+ spacing: 2px;}}QToolBar#LadybirdBookmarksBar QToolButton {{@@ -829,160 +601,148 @@ QToolBar#LadybirdBookmarksBar QToolButton:checked {{hover, pressed, text, control_border, background, border, corner_radius);}-QString find_in_page_style_sheet(QPalette const& palette)+QColor find_in_page_unavailable_control_color(){- auto background = style_sheet_color(chrome_background(palette));- auto surface_color = chrome_surface(palette);- auto surface = style_sheet_color(surface_color);- auto hover = style_sheet_color(chrome_control_surface_hover(palette));- auto pressed = style_sheet_color(chrome_control_surface_pressed(palette));- auto border = style_sheet_color(chrome_border(palette));- auto control_border_color = chrome_control_border(palette);- auto control_border = style_sheet_color(control_border_color);- auto accent = style_sheet_color(chrome_accent());- auto selection = style_sheet_color(chrome_text_highlight());- auto selection_text = style_sheet_color(Qt::white);- auto text = style_sheet_color(chrome_text(palette));- auto muted = style_sheet_color(chrome_muted_text(palette));- auto no_results_background = style_sheet_color(mix(surface_color, chrome_destructive_hover(), is_dark(palette) ? 0.34 : 0.18));- auto no_results_border = style_sheet_color(mix(control_border_color, chrome_destructive_hover(), is_dark(palette) ? 0.72 : 0.58));+ return Theme::is_dark() ? QColor(0x5b5b61) : QColor(0xb3b3b9);+}+QString find_in_page_style_sheet(QPalette const&)+{+ auto const& panel = Theme::panel();+ // Without a match, the field is tinted red, and its count says so in red.+ auto no_match_fill = Theme::is_dark() ? QColor(0x3a2225) : QColor(0xfde8e8);+ auto no_match_text = Theme::is_dark() ? QColor(0xff9a8f) : QColor(0xb3261e);return qformatted(R"(-QWidget#LadybirdFindInPageBar {{+QWidget#LadybirdFindInPageField {{background: {0};- border-top: 1px solid {4};+ border-radius: 7px;}}-QWidget#LadybirdFindInPageBar QLineEdit {{- color: {7};- background: {1};- border: 1px solid {4};- border-radius: 8px;- min-height: 26px;- padding: 2px 9px;- selection-background-color: {11};- selection-color: {12};+QWidget#LadybirdFindInPageField QLineEdit {{+ color: {1};+ background: transparent;+ border: 0;+ padding: 0;+ selection-background-color: {6};+ selection-color: {1};+}}++QWidget#LadybirdFindInPageField[noResults="true"] {{+ background: {5};}}-QWidget#LadybirdFindInPageBar QLineEdit:focus {{- border-color: {6};+QLabel#LadybirdFindInPageResult {{+ color: {2};+ font-size: 12px;}}-QWidget#LadybirdFindInPageBar QLineEdit[noResults="true"] {{- background: {9};- border-color: {10};+QLabel#LadybirdFindInPageResult[noResults="true"] {{+ color: {9};}}-QWidget#LadybirdFindInPageBar QPushButton {{- color: {7};+QPushButton#LadybirdFindInPageButton {{+ color: {3};background: transparent;- border: 1px solid transparent;- border-radius: 7px;- min-height: 26px;+ border: 0;+ border-radius: 6px;+ font-size: 12px;+ font-weight: 600;}}-QWidget#LadybirdFindInPageBar QPushButton:hover {{- background: {2};- border-color: {5};+QPushButton#LadybirdFindInPageButton:hover {{+ background: {4};}}-QWidget#LadybirdFindInPageBar QPushButton:pressed {{- background: {3};- border-color: {5};+QPushButton#LadybirdFindInPageButton:checked {{+ color: #ffffff;+ background: {7};}}-QWidget#LadybirdFindInPageBar QCheckBox,-QWidget#LadybirdFindInPageBar QLabel {{- color: {8};+QFrame#LadybirdFindInPageSeparator {{+ background: {8};+ border: 0;}})",- background, surface, hover, pressed, border, control_border, accent, text, muted, no_results_background, no_results_border, selection, selection_text);+ style_sheet_color(panel.page), style_sheet_color(panel.text), style_sheet_color(panel.muted), style_sheet_color(panel.body),+ style_sheet_color(panel.control), style_sheet_color(no_match_fill), style_sheet_color(Theme::selection()), style_sheet_color(Theme::accent()),+ style_sheet_color(panel.separator), style_sheet_color(no_match_text));}-QString javascript_dialog_style_sheet(QPalette const& palette)+QString javascript_dialog_style_sheet(QPalette const&){- auto surface = style_sheet_color(chrome_surface(palette));- auto recessed = style_sheet_color(chrome_surface_recessed(palette));- auto hover = style_sheet_color(chrome_control_surface_hover(palette));- auto pressed = style_sheet_color(chrome_control_surface_pressed(palette));- auto control_border = style_sheet_color(chrome_control_border(palette));- auto accent = style_sheet_color(chrome_accent());- auto selection = style_sheet_color(chrome_text_highlight());- auto selection_text = style_sheet_color(Qt::white);- auto text = style_sheet_color(chrome_text(palette));- auto muted = style_sheet_color(chrome_muted_text(palette));- auto scrim = is_dark(palette) ? QColor(0, 0, 0, 150) : QColor(20, 22, 25, 120);- auto scrim_color = style_sheet_color_with_alpha(scrim);-+ auto const& panel = Theme::panel();+ auto primary = Theme::primary();return qformatted(R"(QWidget#LadybirdJavaScriptDialogOverlay {{- background: {0};+ background: rgba(0, 0, 0, 56);}}QFrame#LadybirdJavaScriptDialogPanel {{- color: {7};+ color: {0};background: {1};- border: 1px solid {5};- border-radius: 12px;+ border: 1px solid {2};+ border-top: 0;+ border-top-left-radius: 0;+ border-top-right-radius: 0;+ border-bottom-left-radius: 12px;+ border-bottom-right-radius: 12px;}}QLabel#LadybirdJavaScriptDialogTitle {{- color: {7};+ color: {3};background: transparent;border: 0;- font-size: 15px;- font-weight: 600;+ font-size: 12px;}}QScrollArea#LadybirdJavaScriptDialogMessageArea,QWidget#LadybirdJavaScriptDialogMessageViewport,QLabel#LadybirdJavaScriptDialogMessage {{- color: {7};+ color: {0};background: transparent;border: 0;+ font-size: 13px;}}QFrame#LadybirdJavaScriptDialogPanel QLineEdit {{- color: {7};- background: {2};- border: 1px solid {5};- border-radius: 8px;- min-height: 26px;- padding: 2px 9px;- selection-background-color: {9};- selection-color: {10};+ color: {0};+ background: {4};+ border: 0;+ border-radius: 7px;+ min-height: 28px;+ padding: 0 9px;+ selection-background-color: {8};+ selection-color: {0};}}-QFrame#LadybirdJavaScriptDialogPanel QLineEdit:focus {{- border-color: {6};+QCheckBox#LadybirdJavaScriptDialogBlockFurtherDialogs {{+ color: {9};+ background: transparent;+ font-size: 12px;+ spacing: 8px;}}QFrame#LadybirdJavaScriptDialogPanel QPushButton {{- color: {7};- background: {2};- border: 1px solid {5};+ color: {0};+ background: {4};+ border: 0;border-radius: 7px;- min-height: 26px;- min-width: 72px;- padding: 2px 12px;-}}--QFrame#LadybirdJavaScriptDialogPanel QPushButton:hover {{- background: {3};- border-color: {5};+ min-height: 28px;+ padding: 0 16px;}}QFrame#LadybirdJavaScriptDialogPanel QPushButton:pressed {{- background: {4};- border-color: {5};+ background: {5};}}QFrame#LadybirdJavaScriptDialogPanel QPushButton:default {{- border-color: {6};+ color: #ffffff;+ background: {6};+ font-weight: 500;}}-QFrame#LadybirdJavaScriptDialogPanel QPushButton:focus {{- border-color: {6};+QFrame#LadybirdJavaScriptDialogPanel QPushButton:default:pressed {{+ background: {7};}}QFrame#LadybirdJavaScriptDialogPanel QScrollBar:vertical {{@@ -991,12 +751,8 @@ QFrame#LadybirdJavaScriptDialogPanel QScrollBar:vertical {{margin: 0;}}-QFrame#LadybirdJavaScriptDialogPanel QScrollBar::groove:vertical {{- background: transparent;-}}-QFrame#LadybirdJavaScriptDialogPanel QScrollBar::handle:vertical {{- background: {8};+ background: {3};border-radius: 4px;min-height: 20px;}}@@ -1011,7 +767,9 @@ QFrame#LadybirdJavaScriptDialogPanel QScrollBar::sub-page:vertical {{background: transparent;}})",- scrim_color, surface, recessed, hover, pressed, control_border, accent, text, muted, selection, selection_text);+ style_sheet_color(panel.text), style_sheet_color(panel.surface), style_sheet_color(over(panel.edge, panel.surface)), style_sheet_color(panel.muted),+ style_sheet_color(panel.control), style_sheet_color(panel.pressed), style_sheet_color(primary), style_sheet_color(primary.darker(115)), style_sheet_color(Theme::selection()),+ style_sheet_color(panel.body));}QString bookmark_dialog_style_sheet(QPalette const& palette)@@ -1023,7 +781,7 @@ QString bookmark_dialog_style_sheet(QPalette const& palette)auto control_border = style_sheet_color(chrome_control_border(palette));auto accent = style_sheet_color(chrome_accent());auto selection = style_sheet_color(chrome_text_highlight());- auto selection_text = style_sheet_color(Qt::white);+ auto selection_text = style_sheet_color(chrome_text(palette));auto text = style_sheet_color(chrome_text(palette));return qformatted(R"(@@ -1042,8 +800,8 @@ QDialog#LadybirdBookmarkDialog QLineEdit,QDialog#LadybirdBookmarkDialog QComboBox {{color: {6};background: {1};- border: 1px solid {4};- border-radius: 8px;+ border: 1px solid transparent;+ border-radius: 7px;min-height: 26px;padding: 2px 9px;selection-background-color: {7};@@ -1126,7 +884,7 @@ QString report_review_style_sheet(QPalette const& palette)auto control_border = style_sheet_color(chrome_control_border(palette));auto accent = style_sheet_color(chrome_accent());auto selection = style_sheet_color(chrome_text_highlight());- auto selection_text = style_sheet_color(Qt::white);+ auto selection_text = style_sheet_color(chrome_text(palette));auto text = style_sheet_color(chrome_text(palette));auto muted = style_sheet_color(chrome_muted_text(palette));@@ -1135,8 +893,8 @@ QWidget#LadybirdReportReview QLineEdit,QWidget#LadybirdReportReview QPlainTextEdit {{color: {3};background: {0};- border: 1px solid {1};- border-radius: 8px;+ border: 1px solid transparent;+ border-radius: 7px;selection-background-color: {5};selection-color: {6};}}@@ -1164,8 +922,22 @@ QWidget#LadybirdReportReview QFrame#ReportDetails {{border: 1px solid {1};border-radius: 8px;}}++QWidget#LadybirdReportReview QPushButton#WebCompatReportShowReportButton {{+ color: {7};+ background: transparent;+ border: 0;+ padding: 0;+}}++QWidget#LadybirdReportReview QFrame#WebCompatReportFooterLine {{+ background: {8};+ border: 0;+ min-height: 1px;+ max-height: 1px;+}})",- recessed, control_border, accent, text, muted, selection, selection_text);+ recessed, control_border, accent, text, muted, selection, selection_text, style_sheet_color(Theme::panel().link), style_sheet_color(Theme::panel().separator_soft));}// Placeholders hint at what to write, so they stay readable rather than taking the platform's faintest text color.@@ -1220,7 +992,6 @@ QString tab_widget_style_sheet(QPalette const& palette)auto dark = is_dark(palette);auto tab_strip_background = chrome_tab_strip_background(palette);auto background = style_sheet_color(tab_strip_background);- auto inactive_background = style_sheet_color(chrome_tab_strip_background(palette, WindowActivity::Inactive));auto hover = style_sheet_color(chrome_control_surface_hover(palette));auto pressed = style_sheet_color(chrome_control_surface_pressed(palette));auto control_border = style_sheet_color(chrome_control_border(palette));@@ -1240,7 +1011,7 @@ QWidget#LadybirdTabStrip {{QWidget#LadybirdVerticalTabBar {{color: {4};- background: {0};+ background: {9};border: 0;border-right: 1px solid {7};}}@@ -1267,11 +1038,6 @@ QToolButton#LadybirdVerticalTabsToggleButton {{padding: 0;}}-QWidget#LadybirdTabStrip[windowInactive="true"],-QWidget#LadybirdVerticalTabBar[windowInactive="true"] {{- background: {9};-}}-QWidget#LadybirdVerticalTabsResizeHandle {{background: transparent;border: 0;@@ -1294,38 +1060,6 @@ QPushButton#LadybirdTabButton {{padding: 0;}}-QToolButton#LadybirdNewTabButton {{- min-width: 30px;- min-height: 30px;- border-radius: 16px;-}}--QPushButton#LadybirdAudioState,-QPushButton#LadybirdTabButton {{- min-width: 20px;- min-height: 20px;- max-width: 20px;- max-height: 20px;-}}--QPushButton#LadybirdAudioState[collapsedVerticalTabButton="true"] {{- min-width: 18px;- min-height: 18px;- max-width: 18px;- max-height: 18px;- border-radius: 9px;-}}--QPushButton#LadybirdTabButton[collapsedVerticalTabButton="true"] {{- min-width: 16px;- min-height: 16px;- max-width: 16px;- max-height: 16px;- background: transparent;- border-color: transparent;- border-radius: 8px;-}}-QToolButton#LadybirdNewTabButton[verticalTabsButton="false"]:hover {{color: {4};background: {1};@@ -1360,8 +1094,6 @@ QToolButton#LadybirdCloseWindowButton {{background: transparent;border: 0;border-radius: 0;- min-width: 40px;- min-height: 40px;padding: 0;}}@@ -1405,51 +1137,33 @@ QWidget#LadybirdVerticalTabsContentSeparator {{)"#endif,- background, hover, pressed, control_border, text, close_hover, close_text, sidebar_separator, sidebar_separator_hover, inactive_background);+ background, hover, pressed, control_border, text, close_hover, close_text, sidebar_separator, sidebar_separator_hover,+ style_sheet_color(chrome_sidebar_background(palette)));}-QString autocomplete_popup_style_sheet(QPalette const& palette)+QString autocomplete_popup_style_sheet(QPalette const&){- auto surface = style_sheet_color(autocomplete_surface(palette));- auto border = style_sheet_color(location_edit_focus_border(palette));- auto text = style_sheet_color(chrome_text(palette));-+ auto const& panel = Theme::panel();return qformatted(R"(-QFrame#LadybirdAutocompletePopup {{- color: {2};- background: {0};- border: 1px solid {1};- border-top: 0;- border-bottom-left-radius: {3}px;- border-bottom-right-radius: {3}px;-}}-QListView#LadybirdAutocompleteList {{- color: {2};- background: {0};+ color: {0};+ background: transparent;border: 0;outline: 0;}})",- surface, border, text, LOCATION_EDIT_CORNER_RADIUS);+ style_sheet_color(panel.text));}-QString downloads_popover_style_sheet(QPalette const& palette)+QString downloads_popover_style_sheet(QPalette const&){- auto surface = ChromeStyle::style_sheet_color(ChromeStyle::chrome_surface(palette));- auto recessed_surface = ChromeStyle::style_sheet_color(ChromeStyle::chrome_surface_recessed(palette));- auto hover_surface = ChromeStyle::style_sheet_color(ChromeStyle::chrome_surface_hover(palette));- auto border = ChromeStyle::style_sheet_color(ChromeStyle::chrome_border(palette));- auto text = ChromeStyle::style_sheet_color(ChromeStyle::chrome_text(palette));- auto muted_text = ChromeStyle::style_sheet_color(ChromeStyle::chrome_muted_text(palette));- auto accent = ChromeStyle::style_sheet_color(ChromeStyle::chrome_accent());-+ auto const& panel = Theme::panel();return qformatted(R"(QFrame#LadybirdDownloadsPopover {{- color: {4};- background: {0};- border: 1px solid {3};- border-radius: 8px;+ color: {0};+ background: {1};+ border: 1px solid {2};+ border-radius: 12px;}}QScrollArea#LadybirdDownloadsPopoverScroll,@@ -1458,29 +1172,37 @@ QWidget#LadybirdDownloadsPopoverRows {{border: 0;}}-QLabel#LadybirdDownloadsPopoverTitle,-QLabel#LadybirdDownloadFileName {{- color: {4};+QLabel#LadybirdDownloadsPopoverTitle {{+ color: {0};font-weight: 600;}}+QLabel#LadybirdDownloadFileName {{+ color: {0};+}}+QLabel#LadybirdDownloadStatus,QLabel#LadybirdDownloadsEmpty {{- color: {5};+ color: {3};+ font-size: 12px;+}}++QLabel#LadybirdDownloadStatus[failed="true"] {{+ color: {6};}}QFrame#LadybirdDownloadRow {{- background: {0};- border: 1px solid {3};+ background: transparent;+ border: 0;border-radius: 6px;}}QFrame#LadybirdDownloadRow:hover {{- background: {2};+ background: {7};}}QProgressBar#LadybirdDownloadProgress {{- background: {1};+ background: {4};border: 0;border-radius: 2px;min-height: 4px;@@ -1488,34 +1210,68 @@ QProgressBar#LadybirdDownloadProgress {{}}QProgressBar#LadybirdDownloadProgress::chunk {{- background: {6};+ background: {8};border-radius: 2px;}}++QFrame#LadybirdPopoverSeparator {{+ background: {4};+ border: 0;+}}++QPushButton#LadybirdPopoverLink {{+ color: {5};+ background: transparent;+ border: 0;+ border-radius: 5px;+ padding: 4px 6px;+ font-size: 12px;+}}++QPushButton#LadybirdPopoverLink:hover,+QPushButton#LadybirdPopoverRow:hover {{+ background: {7};+}}++QPushButton#LadybirdPopoverRow {{+ color: {0};+ background: transparent;+ border: 0;+ border-radius: 6px;+ min-height: 32px;+ padding: 0 10px;+ text-align: left;+}}++QToolButton#LadybirdDownloadAction {{+ background: transparent;+ border: 0;+ border-radius: 7px;+}}++QToolButton#LadybirdDownloadAction:hover {{+ background: {7};+}}++QToolButton#LadybirdDownloadAction:pressed {{+ background: {9};+}})",- surface, recessed_surface, hover_surface, border, text, muted_text, accent);+ style_sheet_color(panel.text), style_sheet_color(panel.surface), style_sheet_color(over(panel.edge, panel.surface)), style_sheet_color(panel.muted),+ style_sheet_color(panel.separator), style_sheet_color(panel.link), style_sheet_color(panel.warning), style_sheet_color(panel.control), style_sheet_color(Theme::accent()),+ style_sheet_color(panel.pressed));}-QString message_popover_style_sheet(QPalette const& palette)+QString message_popover_style_sheet(QPalette const&){- auto text = ChromeStyle::style_sheet_color(ChromeStyle::chrome_text(palette));- auto surface = ChromeStyle::style_sheet_color(ChromeStyle::chrome_surface(palette));- auto border = ChromeStyle::style_sheet_color(ChromeStyle::chrome_border(palette));- auto muted_text = ChromeStyle::style_sheet_color(ChromeStyle::chrome_muted_text(palette));- auto control_border = ChromeStyle::style_sheet_color(ChromeStyle::chrome_control_border(palette));- auto hover_surface = ChromeStyle::style_sheet_color(ChromeStyle::chrome_surface_hover(palette));- auto pressed_surface = ChromeStyle::style_sheet_color(ChromeStyle::chrome_surface_pressed(palette));-- auto accent = ChromeStyle::chrome_accent();- auto accent_color = ChromeStyle::style_sheet_color(accent);- auto accent_hover = style_sheet_color(BrandColors::Violet500);- auto accent_pressed = style_sheet_color(BrandColors::Violet900);-+ auto const& panel = Theme::panel();+ auto primary = Theme::primary();return qformatted(R"(QFrame#LadybirdMessagePopover {{color: {0};background: {1};border: 1px solid {2};- border-radius: 8px;+ border-radius: 12px;}}QLabel#LadybirdMessagePopoverTitle {{@@ -1523,105 +1279,205 @@ QLabel#LadybirdMessagePopoverTitle {{font-weight: 600;}}+QLabel#LadybirdMessagePopoverIcon {{+ background: {9};+ border-radius: 8px;+}}+QLabel#LadybirdMessagePopoverBody {{color: {3};+ font-size: 12px;}}QPushButton#LadybirdMessagePopoverDismissButton {{color: {0};- background: {1};- border: 1px solid {4};- border-radius: 6px;- padding: 5px 12px;+ background: {4};+ border: 0;+ border-radius: 7px;+ min-height: 28px;+ padding: 0 14px;}}-QPushButton#LadybirdMessagePopoverDismissButton:hover {{+QPushButton#LadybirdMessagePopoverDismissButton:hover,+QPushButton#LadybirdMessagePopoverDismissButton:pressed {{background: {5};}}-QPushButton#LadybirdMessagePopoverDismissButton:pressed {{+QPushButton#LadybirdMessagePopoverAcceptButton {{+ color: #ffffff;background: {6};+ border: 0;+ border-radius: 7px;+ min-height: 28px;+ padding: 0 14px;+ font-weight: 500;}}-QPushButton#LadybirdMessagePopoverAcceptButton {{- color: #ffffff;+QPushButton#LadybirdMessagePopoverAcceptButton:hover {{background: {7};- border: 1px solid {7};- border-radius: 6px;- padding: 5px 12px;- font-weight: 600;}}-QPushButton#LadybirdMessagePopoverAcceptButton:hover {{+QPushButton#LadybirdMessagePopoverAcceptButton:pressed {{background: {8};- border-color: {8};}}+)",+ style_sheet_color(panel.text), style_sheet_color(panel.surface), style_sheet_color(over(panel.edge, panel.surface)), style_sheet_color(panel.muted),+ style_sheet_color(panel.control), style_sheet_color(panel.pressed), style_sheet_color(primary), style_sheet_color(primary.darker(110)), style_sheet_color(primary.darker(122)),+ style_sheet_color(panel.information));+}-QPushButton#LadybirdMessagePopoverAcceptButton:pressed {{- background: {9};+QString bookmark_popover_style_sheet(QPalette const&)+{+ auto const& panel = Theme::panel();+ auto primary = Theme::primary();+ return qformatted(R"(+QFrame#LadybirdBookmarkPopover {{+ color: {0};+ background: {1};+ border: 1px solid {2};+ border-radius: 12px;+}}++QFrame#LadybirdBookmarkPopover QLabel {{+ background: transparent;+}}++QLabel#LadybirdBookmarkPopoverTitle {{+ color: {0};+ font-size: 13px;+ font-weight: 600;+}}++QLabel#LadybirdBookmarkPopoverLabel {{+ color: {3};+ font-size: 12px;+}}++QLineEdit#LadybirdBookmarkPopoverName {{+ color: {0};+ background: {4};+ border: 1px solid transparent;+ border-radius: 7px;+ min-height: 28px;+ max-height: 28px;+ padding: 0 8px;+ font-size: 13px;+ selection-background-color: {8};+}}++QLineEdit#LadybirdBookmarkPopoverName:focus {{border-color: {9};}}++QComboBox#LadybirdBookmarkPopoverFolder {{+ color: {0};+ background: {5};+ border: 0;+ border-radius: 7px;+ min-height: 28px;+ max-height: 28px;+ padding: 0 9px;+ font-size: 13px;+}}++QComboBox#LadybirdBookmarkPopoverFolder::drop-down {{+ border: 0;+ width: 24px;+}}++QComboBox#LadybirdBookmarkPopoverFolder::down-arrow {{+ image: none;+}}++QPushButton#LadybirdBookmarkPopoverRemove {{+ color: {0};+ background: {5};+ border: 0;+ border-radius: 7px;+ min-height: 28px;+ padding: 0 12px;+ font-size: 13px;+}}++QPushButton#LadybirdBookmarkPopoverRemove:pressed {{+ background: {10};+}}++QPushButton#LadybirdBookmarkPopoverDone {{+ color: #ffffff;+ background: {6};+ border: 0;+ border-radius: 7px;+ min-height: 28px;+ padding: 0 16px;+ font-size: 13px;+ font-weight: 500;+}}++QPushButton#LadybirdBookmarkPopoverDone:pressed {{+ background: {7};+}})",- text, surface, border, muted_text, control_border, hover_surface, pressed_surface, accent_color, accent_hover, accent_pressed);+ style_sheet_color(panel.text), style_sheet_color(panel.surface), style_sheet_color(over(panel.edge, panel.surface)), style_sheet_color(panel.muted),+ style_sheet_color(panel.page), style_sheet_color(panel.control), style_sheet_color(primary), style_sheet_color(primary.darker(122)),+ style_sheet_color(Theme::selection()), style_sheet_color(Theme::focus_edge()), style_sheet_color(panel.pressed));}// The instructions over a screenshot selection look like a message popover, with every action a secondary one.-QString screenshot_selection_style_sheet(QPalette const& palette)+QString screenshot_selection_style_sheet(QPalette const&){- auto text = style_sheet_color(chrome_text(palette));- auto surface = style_sheet_color(chrome_surface(palette));- auto border = style_sheet_color(chrome_border(palette));- auto control_border = style_sheet_color(chrome_control_border(palette));- auto hover_surface = style_sheet_color(chrome_surface_hover(palette));- auto pressed_surface = style_sheet_color(chrome_surface_pressed(palette));- auto accent = style_sheet_color(chrome_accent());-+ auto const& panel = Theme::panel();return qformatted(R"(QFrame#ScreenshotSelectionInstructions {{color: {0};background: {1};border: 1px solid {2};- border-radius: 8px;+ border-radius: 12px;}}QFrame#ScreenshotSelectionInstructions QLabel {{color: {0};background: transparent;border: none;+ font-size: 13px;}}QFrame#ScreenshotSelectionInstructions QPushButton {{color: {0};- background: {1};- border: 1px solid {3};- border-radius: 6px;- padding: 5px 12px;-}}--QFrame#ScreenshotSelectionInstructions QPushButton:hover {{- background: {4};+ background: {3};+ border: 0;+ border-radius: 7px;+ min-height: 28px;+ max-height: 28px;+ padding: 0 12px;+ font-size: 13px;}}QFrame#ScreenshotSelectionInstructions QPushButton:pressed {{- background: {5};+ background: {4};}}QFrame#ScreenshotSelectionInstructions QPushButton:focus {{- border: 2px solid {6};- padding: 4px 11px;+ border: 2px solid {5};+ padding: 0 10px;}}QFrame#ScreenshotSelectionInstructions QPushButton#ScreenshotSelectionCancelButton {{- border-color: transparent;- padding: 5px;+ background: transparent;+ border: 2px solid transparent;+ padding: 4px;+}}++QFrame#ScreenshotSelectionInstructions QPushButton#ScreenshotSelectionCancelButton:pressed {{+ background: {4};}}QFrame#ScreenshotSelectionInstructions QPushButton#ScreenshotSelectionCancelButton:focus {{- border-color: {6};- padding: 4px;+ border-color: {5};}})",- text, surface, border, control_border, hover_surface, pressed_surface, accent);+ style_sheet_color(panel.text), style_sheet_color(panel.surface), style_sheet_color(over(panel.edge, panel.surface)), style_sheet_color(panel.control),+ style_sheet_color(panel.pressed), style_sheet_color(Theme::focus_ring()));}// The viewer darkens the whole tab whatever the theme, so its controls are light on dark like a photo viewer's.@@ -1654,50 +1510,469 @@ QPushButton#ScreenshotViewerCloseButton:pressed {)");}-QString content_blocking_popover_style_sheet(QPalette const& palette)+QString site_settings_popover_style_sheet(QPalette const&){- auto text = style_sheet_color(chrome_text(palette));- auto surface = style_sheet_color(chrome_surface(palette));- auto border = style_sheet_color(chrome_border(palette));- auto footer_surface_color = chrome_background(palette);- auto muted_text = style_sheet_color(mix(chrome_text(palette), footer_surface_color, 0.4));- auto recessed_surface = style_sheet_color(chrome_surface_recessed(palette));- auto footer_surface = style_sheet_color(footer_surface_color);+ auto const& panel = Theme::panel();+ return qformatted(R"(+QFrame#LadybirdSiteSettingsPopover {{+ color: {0};+ background: {1};+ border: 1px solid {2};+ border-radius: 12px;+}}++QFrame#LadybirdSiteSettingsPopover QLabel {{+ color: {0};+ background: transparent;+}}++QLabel#LadybirdSiteSettingsFavicon {{+ background: #ffffff;+ border: 1px solid #d0d0d6;+ border-radius: 6px;+}}++QLabel#LadybirdSiteSettingsHost {{+ font-weight: 600;+}}++QFrame#LadybirdSiteSettingsPopover QLabel#LadybirdSiteSettingsDetail {{+ color: {3};+ font-size: 12px;+}}++QFrame#LadybirdSiteSettingsPopover QLabel#LadybirdSiteSettingsSecurity {{+ color: {6};+ font-size: 12px;+}}++QFrame#LadybirdPopoverSeparator {{+ background: {4};+ border: 0;+}}++QPushButton#LadybirdPopoverValueButton {{+ color: {0};+ background: {7};+ border: 0;+ border-radius: 6px;+ min-height: 24px;+ max-height: 24px;+ padding: 0 6px 0 9px;+ font-size: 12px;+}}++QPushButton#LadybirdPopoverValueButton:hover,+QPushButton#LadybirdPopoverValueButton:pressed {{+ background: {8};+}}++QPushButton#LadybirdPopoverLink {{+ color: {5};+ background: transparent;+ border: 0;+ border-radius: 5px;+ padding: 6px;+ font-size: 12px;+}}++QPushButton#LadybirdPopoverLink:hover {{+ background: {7};+}}+QPushButton#LadybirdPopoverLink:disabled {{+ color: {3};+}}++QPushButton#LadybirdPopoverRow {{+ background: transparent;+ border: 0;+ border-radius: 6px;+}}++QPushButton#LadybirdPopoverRow:hover,+QToolButton#LadybirdPopoverIconButton:hover {{+ background: {7};+}}++QPushButton#LadybirdPopoverRow:pressed,+QToolButton#LadybirdPopoverIconButton:pressed {{+ background: {8};+}}++QToolButton#LadybirdPopoverIconButton {{+ background: transparent;+ border: 0;+ border-radius: 6px;+}}+)",+ style_sheet_color(panel.text), style_sheet_color(panel.surface), style_sheet_color(over(panel.edge, panel.surface)), style_sheet_color(panel.muted),+ style_sheet_color(panel.separator), style_sheet_color(panel.link), style_sheet_color(panel.warning), style_sheet_color(panel.control), style_sheet_color(panel.pressed));+}++QString all_tabs_popover_style_sheet(QPalette const&)+{+ auto const& panel = Theme::panel();return qformatted(R"(-QFrame#LadybirdContentBlockingPopover {{+QFrame#LadybirdAllTabsPopover {{color: {0};background: {1};border: 1px solid {2};- border-radius: 8px;+ border-radius: 12px;+}}++QLineEdit#LadybirdAllTabsSearch {{+ color: {0};+ background: {3};+ border: 0;+ border-radius: 7px;+ min-height: 28px;+ max-height: 28px;+ padding: 0 6px 0 2px;+ font-size: 13px;+ selection-background-color: {4};+}}++QScrollArea#LadybirdAllTabsList, QScrollArea#LadybirdAllTabsList > QWidget {{+ background: transparent;+}}++QLabel#LadybirdAllTabsHeading {{+ color: {5};+ background: transparent;+ font-size: 12px;+}}++QFrame#LadybirdPopoverSeparator {{+ background: {6};+ border: 0;}}+)",+ style_sheet_color(panel.text), style_sheet_color(panel.surface), style_sheet_color(over(panel.edge, panel.surface)), style_sheet_color(panel.control),+ style_sheet_color(Theme::selection()), style_sheet_color(panel.muted), style_sheet_color(panel.separator));+}-QFrame#LadybirdContentBlockingPopover QLabel,-QFrame#LadybirdContentBlockingPopover QCheckBox {{+QString zoom_popover_style_sheet(QPalette const&)+{+ auto const& panel = Theme::panel();+ return qformatted(R"(+QFrame#LadybirdZoomPopover {{color: {0};+ background: {1};+ border: 1px solid {2};+ border-radius: 12px;}}-QLabel#LadybirdContentBlockingSite,-QLabel#LadybirdContentBlockingCount {{+QLabel#LadybirdZoomLevel {{+ color: {0};+ font-size: 15px;font-weight: 600;}}-QLabel#LadybirdContentBlockingCount {{+QPushButton#LadybirdZoomButton {{+ background: {3};+ border: 0;+ border-radius: 7px;+}}++QPushButton#LadybirdZoomButton:pressed {{background: {4};+}}++QPushButton#LadybirdPopoverLink {{+ color: {5};+ background: transparent;+ border: 0;+ border-radius: 5px;+ padding: 4px 6px;+ font-size: 12px;+}}++QPushButton#LadybirdPopoverLink:hover {{+ background: {3};+}}+)",+ style_sheet_color(panel.text), style_sheet_color(panel.surface), style_sheet_color(over(panel.edge, panel.surface)),+ style_sheet_color(panel.control), style_sheet_color(panel.pressed), style_sheet_color(panel.link));+}++// Tooltips appear after half a second of hover. Once one has shown, the ones next to it appear at once for 1.5 s.+static constexpr int TOOLTIP_DELAY_MS = 500;+static constexpr int TOOLTIP_GRACE_PERIOD_MS = 1500;+// Submenus open after 150 ms of hover, and stay open only while the pointer moves toward them: the first move in another+// direction selects whatever the pointer is over.+static constexpr int SUBMENU_DELAY_MS = 150;++// A menu's rows are 26 px tall, their text inset 10 px from each side of the row. Shortcuts and submenu chevrons end at+// that same inset on the right, so the menu has one right edge.+static constexpr int MENU_PADDING = 6;+static constexpr int MENU_RADIUS = 10;+static constexpr int MENU_ROW_HEIGHT = 26;+static constexpr int MENU_ROW_INSET = 10;+static constexpr int MENU_ROW_RADIUS = 6;+static constexpr int MENU_SEPARATOR_HEIGHT = 11;+static constexpr int MENU_SEPARATOR_INSET = 8;+static constexpr int MENU_ICON_SIZE = 16;+static constexpr int MENU_ICON_GAP = 6;+static constexpr int MENU_SHORTCUT_GAP = 24;+static constexpr int MENU_CHEVRON_SIZE = 12;++static bool menu_item_has_leading_column(QStyleOptionMenuItem const& item)+{+ return item.maxIconWidth > 0 || item.menuHasCheckableItems;+}++static void paint_menu_item(QStyleOptionMenuItem const& item, QPainter& painter, bool underlines_mnemonics)+{+ auto const& panel = Theme::panel();+ auto rect = item.rect;++ if (item.menuItemType == QStyleOptionMenuItem::Separator) {+ auto y = rect.top() + (rect.height() / 2);+ painter.fillRect(QRect(rect.left() + MENU_SEPARATOR_INSET, y, rect.width() - (2 * MENU_SEPARATOR_INSET), 1), panel.separator);+ return;+ }++ auto enabled = item.state.testFlag(QStyle::State_Enabled);+ auto selected = enabled && item.state.testFlag(QStyle::State_Selected);++ painter.save();+ painter.setRenderHint(QPainter::Antialiasing, true);+ if (selected) {+ painter.setPen(Qt::NoPen);+ painter.setBrush(Theme::selected_row());+ painter.drawRoundedRect(QRectF(rect), MENU_ROW_RADIUS, MENU_ROW_RADIUS);+ }++ auto text_color = !enabled ? Theme::chrome().disabled : (selected ? QColor(Qt::white) : panel.text);+ auto secondary_color = !enabled ? Theme::chrome().disabled : (selected ? QColor(Qt::white) : panel.shortcut);++ auto content = rect.adjusted(MENU_ROW_INSET, 0, -MENU_ROW_INSET, 0);++ // A check mark or an icon leads the row, in a column the rows of the menu share.+ if (menu_item_has_leading_column(item)) {+ QRect leading { content.left(), content.top() + ((content.height() - MENU_ICON_SIZE) / 2), MENU_ICON_SIZE, MENU_ICON_SIZE };+ if (item.checkType != QStyleOptionMenuItem::NotCheckable && item.checked) {+ QPainterPath check;+ check.moveTo(3.5, 8.5);+ check.lineTo(6.5, 11.5);+ check.lineTo(12.5, 4.5);+ painter.save();+ painter.translate(leading.topLeft());+ painter.setPen(QPen(text_color, 1.7, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));+ painter.setBrush(Qt::NoBrush);+ painter.drawPath(check);+ painter.restore();+ } else if (!item.icon.isNull()) {+ item.icon.paint(&painter, leading, Qt::AlignCenter, enabled ? (selected ? QIcon::Selected : QIcon::Normal) : QIcon::Disabled);+ }+ content.setLeft(leading.right() + 1 + MENU_ICON_GAP);+ }++ if (item.menuItemType == QStyleOptionMenuItem::SubMenu) {+ QRect chevron { content.right() + 1 - MENU_CHEVRON_SIZE, content.top() + ((content.height() - MENU_CHEVRON_SIZE) / 2), MENU_CHEVRON_SIZE, MENU_CHEVRON_SIZE };+ QPainterPath path;+ path.moveTo(6, 3.5);+ path.lineTo(10.5, 8);+ path.lineTo(6, 12.5);+ painter.save();+ painter.translate(chevron.topLeft());+ painter.scale(MENU_CHEVRON_SIZE / 16.0, MENU_CHEVRON_SIZE / 16.0);+ painter.setPen(QPen(secondary_color, 1.7, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));+ painter.setBrush(Qt::NoBrush);+ painter.drawPath(path);+ painter.restore();+ content.setRight(chevron.left() - MENU_SHORTCUT_GAP);+ }++ auto text_flags = Qt::AlignVCenter | Qt::TextSingleLine | (underlines_mnemonics ? Qt::TextShowMnemonic : Qt::TextHideMnemonic);+ auto label = item.text;+ if (auto tab = label.indexOf(u'\t'); tab >= 0) {+ painter.setPen(secondary_color);+ painter.setFont(item.font);+ painter.drawText(content, text_flags | Qt::AlignRight, label.mid(tab + 1));+ label = label.left(tab);+ }+ painter.setPen(text_color);+ painter.setFont(item.font);+ painter.drawText(content, text_flags | Qt::AlignLeft, label);+ painter.restore();+}++class ApplicationStyle final : public QProxyStyle {+public:+ AK_ALLOC_WITH_KMALLOC;++ // A menu is a rounded card with a hairline edge, which needs a window it can be cut out of.+ virtual void polish(QWidget* widget) override+ {+ QProxyStyle::polish(widget);+ if (qobject_cast<QMenu*>(widget))+ widget->setAttribute(Qt::WA_TranslucentBackground);+ }++ virtual void drawPrimitive(PrimitiveElement element, QStyleOption const* option, QPainter* painter, QWidget const* widget) const override+ {+ if (element == PE_PanelMenu) {+ auto const& panel = Theme::panel();+ painter->save();+ painter->setRenderHint(QPainter::Antialiasing, true);+ painter->setPen(QPen(over(panel.edge, panel.surface), 1));+ painter->setBrush(panel.surface);+ painter->drawRoundedRect(QRectF(option->rect).adjusted(0.5, 0.5, -0.5, -0.5), MENU_RADIUS - 0.5, MENU_RADIUS - 0.5);+ painter->restore();+ return;+ }+ if (element == PE_FrameMenu)+ return;+ QProxyStyle::drawPrimitive(element, option, painter, widget);+ }++ virtual int pixelMetric(PixelMetric metric, QStyleOption const* option, QWidget const* widget) const override+ {+ if (metric == PM_MenuPanelWidth)+ return 1;+ if (metric == PM_MenuHMargin || metric == PM_MenuVMargin)+ return MENU_PADDING - 1;+ return QProxyStyle::pixelMetric(metric, option, widget);+ }++ virtual void drawControl(ControlElement element, QStyleOption const* option, QPainter* painter, QWidget const* widget) const override+ {+ if (element == CE_MenuItem) {+ if (auto const* item = qstyleoption_cast<QStyleOptionMenuItem const*>(option)) {+ paint_menu_item(*item, *painter, styleHint(SH_UnderlineShortcut, option, widget, nullptr) != 0);+ return;+ }+ }+ if (element == CE_MenuEmptyArea)+ return;+ QProxyStyle::drawControl(element, option, painter, widget);+ }++ virtual QSize sizeFromContents(ContentsType type, QStyleOption const* option, QSize const& contents_size, QWidget const* widget) const override+ {+ if (type == CT_MenuItem) {+ if (auto const* item = qstyleoption_cast<QStyleOptionMenuItem const*>(option)) {+ if (item->menuItemType == QStyleOptionMenuItem::Separator)+ return { contents_size.width(), MENU_SEPARATOR_HEIGHT };+ // NB: Qt measures the label and the shortcut column into the contents' width.+ auto width = contents_size.width() + (2 * MENU_ROW_INSET) + MENU_SHORTCUT_GAP;+ if (menu_item_has_leading_column(*item))+ width += MENU_ICON_SIZE + MENU_ICON_GAP;+ if (item->menuItemType == QStyleOptionMenuItem::SubMenu)+ width += MENU_CHEVRON_SIZE + MENU_SHORTCUT_GAP;+ return { width, MENU_ROW_HEIGHT };+ }+ }+ return QProxyStyle::sizeFromContents(type, option, contents_size, widget);+ }++ virtual int styleHint(StyleHint hint, QStyleOption const* option, QWidget const* widget, QStyleHintReturn* return_data) const override+ {+ if (hint == SH_ToolTip_WakeUpDelay)+ return TOOLTIP_DELAY_MS;+ if (hint == SH_ToolTip_FallAsleepDelay)+ return TOOLTIP_GRACE_PERIOD_MS;+ if (hint == SH_Menu_SubMenuPopupDelay || hint == SH_Menu_SubMenuSloppyCloseTimeout)+ return SUBMENU_DELAY_MS;+ if (hint == SH_Menu_SubMenuUniDirection)+ return true;+ if (hint == SH_Menu_SubMenuUniDirectionFailCount)+ return 1;+ return QProxyStyle::styleHint(hint, option, widget, return_data);+ }+};++void install_application_style()+{+ QApplication::setStyle(new ApplicationStyle);+}++QString primary_button_style_sheet()+{+ auto primary = Theme::primary();+ return qformatted(R"(+QPushButton {{+ color: #ffffff;+ background: {0};+ border: 0;+ border-radius: 8px;+ min-height: 32px;+ padding: 0 16px;+ font-weight: 500;+}}++QPushButton:hover {{+ background: {1};+}}++QPushButton:pressed {{+ background: {2};+}}+)",+ style_sheet_color(primary), style_sheet_color(primary.darker(110)), style_sheet_color(primary.darker(122)));+}++QString restore_session_card_style_sheet()+{+ auto const& panel = Theme::panel();+ auto primary = Theme::primary();+ return qformatted(R"(+QFrame#LadybirdRestoreSessionCard {{+ color: {0};+ background: {1};+ border: 0;border-radius: 12px;- padding: 12px 16px;}}-QFrame#LadybirdContentBlockingPopover QLabel#LadybirdContentBlockingNote {{- color: {3};+QFrame#LadybirdRestoreSessionCard QLabel {{+ background: transparent;+ font-size: 13px;+}}++QLabel#LadybirdRestoreSessionTitle {{+ color: {0};+ font-weight: 600;+}}++QLabel#LadybirdRestoreSessionQuestion {{+ color: {2};+}}++QFrame#LadybirdRestoreSessionCard QPushButton {{+ border: 0;+ border-radius: 7px;+ min-height: 28px;+ padding: 0 14px;+ font-size: 13px;+}}++QPushButton#LadybirdRestoreSessionNotNow {{+ color: {0};+ background: {3};+}}++QPushButton#LadybirdRestoreSessionNotNow:pressed {{+ background: {4};+}}++QPushButton#LadybirdRestoreSessionRestore {{+ color: #ffffff;background: {5};- border-top: 1px solid {2};- border-bottom-left-radius: 7px;- border-bottom-right-radius: 7px;- padding: 12px 16px;+ font-weight: 500;+}}++QPushButton#LadybirdRestoreSessionRestore:hover {{+ background: {6};+}}++QPushButton#LadybirdRestoreSessionRestore:pressed {{+ background: {7};}})",- text, surface, border, muted_text, recessed_surface, footer_surface);+ style_sheet_color(panel.text), style_sheet_color(panel.surface), style_sheet_color(panel.muted), style_sheet_color(panel.control), style_sheet_color(panel.pressed),+ style_sheet_color(primary), style_sheet_color(primary.darker(110)), style_sheet_color(primary.darker(122)));}static void paint_circular_control_frame(QPainter& painter, QRect const& rect, qreal device_pixel_ratio, QColor const& background, QColor const& border)@@ -1731,7 +2006,7 @@ static void paint_circular_control_frame(QPainter& painter, QRect const& rect, q}}-Optional<ControlFrameColors> circular_control_frame_colors(QAbstractButton const& button, CircularControlFrameStyle frame_style)+Optional<ControlFrameColors> control_frame_colors(QAbstractButton const& button, ControlFrameStyle frame_style){if (!button.isEnabled())return {};@@ -1741,79 +2016,114 @@ Optional<ControlFrameColors> circular_control_frame_colors(QAbstractButton const// pointer, as when a button is clicked and its toolbar or sidebar changes around it. So also check that the// pointer is actually over the button.auto hovered = button.underMouse() && button.rect().contains(button.mapFromGlobal(QCursor::pos()));- if (!hovered && !pressed && frame_style == CircularControlFrameStyle::InteractionOnly)++ if (frame_style == ControlFrameStyle::InteractionOnly) {+ // A frameless button can sit on the chrome or on a lighter tab, so its fills are translucent and deepen whatever+ // is below.+ if (pressed)+ return ControlFrameColors { Theme::panel().pressed, Qt::transparent };+ if (hovered)+ return ControlFrameColors { Theme::chrome(button.palette()).hover, Qt::transparent };return {};+ }auto const& palette = button.window()->palette();- auto background = frame_style == CircularControlFrameStyle::ActiveTabOverlay- ? chrome_active_tab_surface(palette)- : chrome_control_surface_hover(palette);- auto border = frame_style == CircularControlFrameStyle::ActiveTabOverlay- ? chrome_control_surface_hover(palette)- : chrome_control_border(palette);-- if (hovered && frame_style == CircularControlFrameStyle::InteractionOnly) {- background = chrome_control_soft_hover(palette);- border = Qt::transparent;- } else if (hovered) {+ auto background = chrome_active_tab_surface(palette);+ auto border = chrome_control_surface_hover(palette);+ if (hovered) {background = chrome_control_surface_hover(palette);border = chrome_control_border(palette);}if (pressed) {- // A frameless button can sit on the chrome or on a lighter tab, so pressing it deepens the hover fill rather- // than painting an opaque color that could be darker than what is below.- if (frame_style == CircularControlFrameStyle::InteractionOnly)- background = is_dark(palette) ? QColor(255, 255, 255, 40) : QColor(0, 0, 0, 26);- else- background = chrome_control_surface_pressed(palette);+ background = chrome_control_surface_pressed(palette);border = chrome_control_border(palette);}-return ControlFrameColors { background, border };}-void paint_circular_control_frame(QPainter& painter, QAbstractButton const& button, CircularControlFrameStyle frame_style)+// Keyboard focus is ringed with a fine line of the focus edge color right outside the control, in a wider, fainter halo.+void paint_focus_ring(QPainter& painter, QRectF const& rect, qreal radius){- if (auto colors = circular_control_frame_colors(button, frame_style); colors.has_value())- paint_circular_control_frame(painter, button.rect(), button.devicePixelRatioF(), colors->background, colors->border);+ painter.save();+ painter.setRenderHint(QPainter::Antialiasing, true);+ painter.setBrush(Qt::NoBrush);+ painter.setPen(QPen(Theme::focus_ring(), 2));+ painter.drawRoundedRect(rect.adjusted(-2, -2, 2, 2), radius + 2, radius + 2);+ painter.setPen(QPen(Theme::focus_edge(), 1));+ painter.drawRoundedRect(rect.adjusted(-0.5, -0.5, 0.5, 0.5), radius + 0.5, radius + 0.5);+ painter.restore();}-// A purple gradient with two soft bright spots that moves steadily along a border, to show that something is loading.-// Every swirl follows the same clock, so the swirls on screen move in step.-void paint_loading_swirl(QPainter& painter, QPainterPath const& border)+void paint_control_frame(QPainter& painter, QAbstractButton const& button, ControlFrameStyle frame_style)+{+ auto colors = control_frame_colors(button, frame_style);+ if (!colors.has_value())+ return;++ // Buttons on the chrome are rounded squares. The small buttons that sit over a collapsed sidebar's tabs are circles.+ if (frame_style == ControlFrameStyle::ActiveTabOverlay) {+ // NB: The badge sits on a favicon, so it is ringed with a hairline to keep it apart from what it covers.+ auto ring = colors->border;+ if (!button.isDown() && !button.isChecked() && !(button.underMouse() && button.rect().contains(button.mapFromGlobal(QCursor::pos()))))+ ring = Theme::chrome(button.window()->palette()).separator;+ paint_circular_control_frame(painter, button.rect(), button.devicePixelRatioF(), colors->background, ring);+ return;+ }++ painter.save();+ painter.setRenderHint(QPainter::Antialiasing, true);+ painter.setPen(Qt::NoPen);+ painter.setBrush(colors->background);+ painter.drawRoundedRect(QRectF(button.rect()), CONTROL_FRAME_RADIUS, CONTROL_FRAME_RADIUS);+ painter.restore();+}++// A ring around a favicon, with an arc in the accent color going around it, to show that the page is loading. Every+// ring follows the same clock, so the rings on screen turn in step.+static constexpr qreal LOADING_RING_RADIUS = 10.75;++void paint_progress_ring(QPainter& painter, QPalette const& palette, QPointF center, double progress)+{+ QRectF ring_rect { center.x() - LOADING_RING_RADIUS, center.y() - LOADING_RING_RADIUS, 2 * LOADING_RING_RADIUS, 2 * LOADING_RING_RADIUS };++ painter.save();+ painter.setRenderHint(QPainter::Antialiasing, true);+ painter.setBrush(Qt::NoBrush);+ painter.setPen(QPen(Theme::chrome(palette).separator, 1.5));+ painter.drawEllipse(ring_rect);+ // NB: Qt's angles are in sixteenths of a degree, counterclockwise from three o'clock.+ painter.setPen(QPen(Theme::accent(), 1.5, Qt::SolidLine, Qt::RoundCap));+ painter.drawArc(ring_rect, 90 * 16, -qRound(clamp(progress, 0.0, 1.0) * 360 * 16));+ painter.restore();+}++void paint_loading_ring(QPainter& painter, QPalette const& palette, QPointF center, LoadingPhase loading_phase){static QElapsedTimer clock;if (!clock.isValid())clock.start();- auto phase = static_cast<qreal>(clock.elapsed() % LOADING_SWIRL_PERIOD_MS) / LOADING_SWIRL_PERIOD_MS;+ auto period = loading_phase == LoadingPhase::WaitingForResponse ? LOADING_RING_WAITING_PERIOD_MS : LOADING_RING_PERIOD_MS;+ auto phase = static_cast<qreal>(clock.elapsed() % period) / period;- // The border is drawn in short segments, each colored by where it sits along the border.- static constexpr qreal segment_length = 2.0;- static constexpr qreal bright_spots = 2.0;- // NB: Without caching, every pointAtPercent() call below measures the whole path again.- auto path = border;- path.setCachingEnabled(true);- auto segments = max(1, static_cast<int>(ceil(path.length() / segment_length)));- auto color = chrome_accent();+ QRectF ring_rect { center.x() - LOADING_RING_RADIUS, center.y() - LOADING_RING_RADIUS, 2 * LOADING_RING_RADIUS, 2 * LOADING_RING_RADIUS };painter.save();painter.setRenderHint(QPainter::Antialiasing, true);+ // NB: With reduced motion, the ring pulses its opacity instead of turning, at full strength in both phases.+ if (loading_phase == LoadingPhase::WaitingForResponse && !SystemAppearance::prefers_reduced_motion())+ painter.setOpacity(painter.opacity() * 0.5);painter.setBrush(Qt::NoBrush);-- // NB: pointAtPercent() measures along the path's length, so the swirl moves just as fast around the curves of a- // border as along its straight edges.- auto from_point = path.pointAtPercent(0);- for (int segment = 0; segment < segments; ++segment) {- auto from = static_cast<qreal>(segment) / segments;- auto to = static_cast<qreal>(segment + 1) / segments;- auto to_point = path.pointAtPercent(to);- auto wave = 0.5 + (0.5 * cos(2.0 * M_PI * bright_spots * (((from + to) / 2.0) - phase)));- color.setAlphaF(0.2 + (0.8 * wave * wave));- painter.setPen(QPen(color, 1.5, Qt::SolidLine, Qt::FlatCap));- painter.drawLine(from_point, to_point);- from_point = to_point;- }-+ painter.setPen(QPen(Theme::chrome(palette).separator, 1.5));+ painter.drawEllipse(ring_rect);++ // NB: Qt's angles are in sixteenths of a degree, counterclockwise from three o'clock. The arc is a quarter of the ring+ // and turns clockwise, starting from twelve o'clock. With reduced motion, it stays at twelve o'clock and pulses.+ auto reduce_motion = SystemAppearance::prefers_reduced_motion();+ auto start_angle = reduce_motion ? 90 * 16 : qRound((90.0 - (phase * 360.0)) * 16);+ if (reduce_motion)+ painter.setOpacity(painter.opacity() * (0.35 + (0.65 * (0.5 + (0.5 * qCos(phase * 2 * M_PI))))));+ painter.setPen(QPen(Theme::accent(), 1.5, Qt::SolidLine, Qt::RoundCap));+ painter.drawArc(ring_rect, start_angle, -90 * 16);painter.restore();}diff --git a/UI/Qt/ChromeStyle.h b/UI/Qt/ChromeStyle.hindex 2be27ef6823..6ec8bcacabb 100644--- a/UI/Qt/ChromeStyle.h+++ b/UI/Qt/ChromeStyle.h@@ -14,16 +14,31 @@class QAbstractButton;class QFont;class QPainter;-class QPainterPath;+class QPointF;class QPalette;+class QRectF;class QWidget;namespace Ladybird::ChromeStyle {-constexpr inline int LOCATION_EDIT_CORNER_RADIUS = 16;-constexpr inline int LOADING_SWIRL_PERIOD_MS = 2000;+constexpr inline int LOCATION_EDIT_CORNER_RADIUS = 7;+// One turn of the loading ring.+constexpr inline int LOADING_RING_PERIOD_MS = 900;+// Before the site responds, the ring turns more slowly, at half opacity.+constexpr inline int LOADING_RING_WAITING_PERIOD_MS = 1600;+enum class LoadingPhase : u8 {+ WaitingForResponse,+ Receiving,+};bool is_dark(QPalette const&);++// A QGraphicsDropShadowEffect spreads its blur far less than a CSS shadow with the same blur radius does. Measured against+// the design, a blur radius 2.5 times the CSS one matches its shadows.+constexpr qreal drop_shadow_blur_radius(qreal css_blur_radius)+{+ return css_blur_radius * 2.5;+}QColor mix(QColor const& from, QColor const& to, double amount);QColor chrome_text(QPalette const&);QColor chrome_button_text(QPalette const&);@@ -33,7 +48,8 @@ enum class WindowActivity : u8 {};WindowActivity window_activity(QWidget const&);-QColor chrome_tab_strip_background(QPalette const&, WindowActivity = WindowActivity::Active);+QColor chrome_tab_strip_background(QPalette const&);+QColor chrome_sidebar_background(QPalette const&);QColor chrome_background(QPalette const&);QColor chrome_surface(QPalette const&);QColor chrome_surface_recessed(QPalette const&);@@ -53,10 +69,11 @@ QString style_sheet_color(QColor const&);QString application_style_sheet(QPalette const&);QString toolbar_container_style_sheet(QPalette const&);QString menu_bar_style_sheet(QPalette const&);-QString hamburger_style_sheet(QPalette const&);QString location_edit_style_sheet(QPalette const&);QString bookmarks_bar_style_sheet(QPalette const&, int corner_radius);QString find_in_page_style_sheet(QPalette const&);+// The color of the find bar's previous and next buttons, while there is no match to go to.+QColor find_in_page_unavailable_control_color();QString javascript_dialog_style_sheet(QPalette const&);QString bookmark_dialog_style_sheet(QPalette const&);QString report_review_style_sheet(QPalette const&);@@ -66,11 +83,20 @@ QString tab_widget_style_sheet(QPalette const&);QString autocomplete_popup_style_sheet(QPalette const&);QString downloads_popover_style_sheet(QPalette const&);QString message_popover_style_sheet(QPalette const&);-QString content_blocking_popover_style_sheet(QPalette const&);+QString site_settings_popover_style_sheet(QPalette const&);+QString all_tabs_popover_style_sheet(QPalette const&);+QString bookmark_popover_style_sheet(QPalette const&);+QString zoom_popover_style_sheet(QPalette const&);+// A button filled with the primary blue, for the main action of a page the browser shows.+QString primary_button_style_sheet();++// Installs the application style, which keeps the platform's look but follows the design's timing.+void install_application_style();+QString restore_session_card_style_sheet();QString screenshot_selection_style_sheet(QPalette const&);QString screenshot_viewer_style_sheet();-enum class CircularControlFrameStyle {+enum class ControlFrameStyle {InteractionOnly,ActiveTabOverlay,};@@ -78,10 +104,15 @@ struct ControlFrameColors {QColor background;QColor border;};+// The corner radius of a button's frame on the chrome.+constexpr inline qreal CONTROL_FRAME_RADIUS = 6;// The colors of a button's frame in the button's current state, or nothing while it shows no frame.-Optional<ControlFrameColors> circular_control_frame_colors(QAbstractButton const&, CircularControlFrameStyle = CircularControlFrameStyle::InteractionOnly);-void paint_circular_control_frame(QPainter&, QAbstractButton const&, CircularControlFrameStyle = CircularControlFrameStyle::InteractionOnly);+Optional<ControlFrameColors> control_frame_colors(QAbstractButton const&, ControlFrameStyle = ControlFrameStyle::InteractionOnly);+void paint_control_frame(QPainter&, QAbstractButton const&, ControlFrameStyle = ControlFrameStyle::InteractionOnly);+void paint_focus_ring(QPainter&, QRectF const&, qreal radius);-void paint_loading_swirl(QPainter&, QPainterPath const& border);+void paint_loading_ring(QPainter&, QPalette const&, QPointF center, LoadingPhase = LoadingPhase::Receiving);+// The loading ring's track, with an arc for the progress made, from 0 to 1, clockwise from twelve o'clock.+void paint_progress_ring(QPainter&, QPalette const&, QPointF center, double progress);}diff --git a/UI/Qt/ContentBlockingButton.cpp b/UI/Qt/ContentBlockingButton.cppdeleted file mode 100644index 84ae10b3d2d..00000000000--- a/UI/Qt/ContentBlockingButton.cpp+++ /dev/null@@ -1,102 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <UI/Qt/ChromeStyle.h>-#include <UI/Qt/ContentBlockingButton.h>-#include <UI/Qt/Icon.h>-#include <UI/Qt/StringUtils.h>--#include <QEvent>-#include <QPainter>-#include <QStyleOptionToolButton>-#include <QStylePainter>--namespace Ladybird {--ContentBlockingButton::ContentBlockingButton(QWidget* parent)- : QToolButton(parent)-{- setObjectName("ContentBlockingButton");- setAccessibleName("Ad blocking");- setAutoRaise(true);- setFixedSize(sizeHint());- setFocusPolicy(Qt::StrongFocus);- m_icon = create_chrome_icon(ChromeIcon::ContentBlocking, palette());-}--void ContentBlockingButton::changeEvent(QEvent* event)-{- QToolButton::changeEvent(event);- if (event->type() == QEvent::PaletteChange) {- m_icon = create_chrome_icon(ChromeIcon::ContentBlocking, palette());- update();- }-}--void ContentBlockingButton::set_snapshot(WebView::ContentBlockingSnapshot const& snapshot)-{- m_snapshot = snapshot;- setEnabled(snapshot.state != WebView::ContentBlockingState::Unavailable);- update();-}--void ContentBlockingButton::set_show_count_badge(bool show)-{- if (m_show_count_badge == show)- return;- m_show_count_badge = show;- update();-}--QString ContentBlockingButton::badge_text() const-{- if (!m_show_count_badge || !m_snapshot.enabled() || m_snapshot.blocked_request_count == 0)- return {};- return m_snapshot.blocked_request_count > 99 ? "99+" : qformatted("{}", m_snapshot.blocked_request_count);-}--void ContentBlockingButton::paintEvent(QPaintEvent*)-{- QStyleOptionToolButton option;- initStyleOption(&option);- option.icon = {};-- QStylePainter painter(this);- ChromeStyle::paint_circular_control_frame(painter, *this);- painter.drawComplexControl(QStyle::CC_ToolButton, option);- painter.setRenderHint(QPainter::Antialiasing);- painter.save();-- if (!m_snapshot.enabled())- painter.setOpacity(0.45);-- auto icon_rect = QRect((width() - 20) / 2, (height() - 20) / 2, 20, 20);- m_icon.paint(&painter, icon_rect, Qt::AlignCenter, underMouse() || isDown() ? QIcon::Active : QIcon::Normal);- painter.restore();-- auto badge = badge_text();- if (badge.isEmpty())- return;-- auto badge_font = font();- badge_font.setPointSizeF(7.5);- badge_font.setBold(true);-- painter.setFont(badge_font);-- auto badge_width = painter.fontMetrics().horizontalAdvance(badge) + 6;- auto badge_height = painter.fontMetrics().height() + 2;- auto badge_rect = QRect(width() - badge_width - 1, 1, badge_width, badge_height);-- painter.setPen(Qt::NoPen);- painter.setBrush(ChromeStyle::chrome_accent());- painter.drawRoundedRect(badge_rect, 5, 5);-- painter.setPen(Qt::white);- painter.drawText(badge_rect, Qt::AlignCenter, badge);-}--}diff --git a/UI/Qt/ContentBlockingButton.h b/UI/Qt/ContentBlockingButton.hdeleted file mode 100644index 6c7ef00bbf7..00000000000--- a/UI/Qt/ContentBlockingButton.h+++ /dev/null@@ -1,38 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/kmalloc.h>-#include <LibWebView/ContentBlocking.h>--#include <QIcon>-#include <QToolButton>--namespace Ladybird {--class ContentBlockingButton final : public QToolButton {- AK_ALLOC_WITH_KMALLOC;--public:- explicit ContentBlockingButton(QWidget* parent);-- void set_snapshot(WebView::ContentBlockingSnapshot const&);- void set_show_count_badge(bool);-- QString badge_text() const;--private:- virtual void changeEvent(QEvent*) override;- virtual void paintEvent(QPaintEvent*) override;- virtual QSize sizeHint() const override { return { 34, 34 }; }-- QIcon m_icon;- WebView::ContentBlockingSnapshot m_snapshot;- bool m_show_count_badge { false };-};--}diff --git a/UI/Qt/ContentBlockingPopover.cpp b/UI/Qt/ContentBlockingPopover.cppdeleted file mode 100644index 5c4ff2d1f50..00000000000--- a/UI/Qt/ContentBlockingPopover.cpp+++ /dev/null@@ -1,252 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <UI/Qt/ChromeStyle.h>-#include <UI/Qt/ContentBlockingPopover.h>-#include <UI/Qt/StringUtils.h>--#include <QCheckBox>-#include <QFrame>-#include <QHBoxLayout>-#include <QIcon>-#include <QKeyEvent>-#include <QLabel>-#include <QMouseEvent>-#include <QScreen>-#include <QSignalBlocker>-#include <QStylePainter>-#include <QVBoxLayout>--namespace Ladybird {--class ContentBlockingSwitch final : public QCheckBox {- AK_ALLOC_WITH_KMALLOC;--public:- explicit ContentBlockingSwitch(QWidget* parent)- : QCheckBox("Block ads on this site", parent)- {- setAttribute(Qt::WA_MacShowFocusRect, false);- // NB: The macOS style widens a checkbox past its layout cell to make room for a focus ring. This switch draws- // its own, so keep it inside its cell, where its text lines up with the site name above it.- setAttribute(Qt::WA_LayoutUsesWidgetRect);- setFocusPolicy(Qt::StrongFocus);- }-- virtual QSize sizeHint() const override- {- return { fontMetrics().horizontalAdvance(text()) + 56, qMax(28, fontMetrics().height() + 8) };- }--private:- virtual bool hitButton(QPoint const& position) const override { return rect().contains(position); }-- virtual void paintEvent(QPaintEvent*) override- {- QStylePainter painter(this);- painter.setRenderHint(QPainter::Antialiasing);- auto track = QStyle::visualRect(layoutDirection(), rect(), QRect(width() - 43, (height() - 22) / 2, 40, 22));- // Match the switch colors in Base/res/ladybird/ladybird.css, including disabled states.- auto dark = ChromeStyle::is_dark(palette());- auto track_color = isChecked() ? ChromeStyle::chrome_accent() : QColor(dark ? 0x6b6b6b : 0x8f8f8f);- auto thumb_color = QColor(Qt::white);- if (!isEnabled()) {- track_color = QColor(dark ? 0x353535 : 0xe0e0e0);- thumb_color = QColor(dark ? 0x7a7a7a : 0xfafafa);- }-- painter.setPen(Qt::NoPen);- painter.setBrush(track_color);- painter.drawRoundedRect(track, 11, 11);-- auto thumb_offset = isChecked() != (layoutDirection() == Qt::RightToLeft) ? 21 : 3;- painter.setBrush(thumb_color);- painter.drawEllipse(QRect(track.x() + thumb_offset, track.y() + 3, 16, 16));-- auto text_rect = QStyle::visualRect(layoutDirection(), rect(), QRect(0, 0, width() - 56, height()));- painter.drawItemText(text_rect, Qt::AlignLeading | Qt::AlignVCenter, palette(), isEnabled(), text(), QPalette::WindowText);-- if (hasFocus()) {- painter.setBrush(Qt::NoBrush);- painter.setPen(QPen(ChromeStyle::chrome_accent(), 2));- painter.drawRoundedRect(QRectF(track).adjusted(-2, -2, 2, 2), 13, 13);- }- }-};--ContentBlockingPopover::ContentBlockingPopover(QWidget* parent)- : Popover(parent)-{- setAttribute(Qt::WA_NoMouseReplay);- setFocusPolicy(Qt::StrongFocus);- setAccessibleName("Ad blocking controls");- card().setObjectName("LadybirdContentBlockingPopover");-- auto* card_layout = new QVBoxLayout(&card());- card_layout->setContentsMargins(0, 0, 0, 0);- card_layout->setSpacing(0);-- auto* layout = new QVBoxLayout;- layout->setContentsMargins(16, 14, 16, 14);- layout->setSpacing(12);- card_layout->addLayout(layout);-- auto* heading = new QHBoxLayout;-- m_favicon = new QLabel(&card());- m_favicon->setFixedSize(24, 24);- m_favicon->setAlignment(Qt::AlignCenter);- heading->addWidget(m_favicon, 0, Qt::AlignVCenter);-- m_site = new QLabel(&card());- m_site->setObjectName("LadybirdContentBlockingSite");- m_site->setTextFormat(Qt::PlainText);- m_site->setAlignment(Qt::AlignLeading | Qt::AlignVCenter);- m_site->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);- heading->addWidget(m_site, 1);- layout->addLayout(heading);-- m_switch = new ContentBlockingSwitch(&card());- m_switch->setObjectName("ContentBlockingSiteSwitch");- m_switch->setAccessibleName("Block ads on this site");- m_switch->setFocusPolicy(Qt::StrongFocus);- QObject::connect(m_switch, &QCheckBox::toggled, this, [this](bool enabled) {- if (on_toggle)- on_toggle(enabled);- });- layout->addWidget(m_switch);-- m_count = new QLabel(&card());- m_count->setObjectName("LadybirdContentBlockingCount");- m_count->setTextFormat(Qt::PlainText);- m_count->setAlignment(Qt::AlignCenter);- layout->addWidget(m_count);-- m_error = new QLabel(&card());- m_error->setTextFormat(Qt::PlainText);- m_error->hide();- layout->addWidget(m_error);-- m_note = new QLabel(&card());- m_note->setObjectName("LadybirdContentBlockingNote");- m_note->setTextFormat(Qt::PlainText);- m_note->setAlignment(Qt::AlignCenter);- card_layout->addWidget(m_note);-}--void ContentBlockingPopover::set_favicon(QIcon const& favicon)-{- // Without a favicon, the site name moves over to the edge rather than sitting next to an empty space.- m_favicon->setVisible(!favicon.isNull());- m_favicon->setPixmap(favicon.pixmap(m_favicon->size(), devicePixelRatioF()));-}--void ContentBlockingPopover::set_snapshot(WebView::ContentBlockingSnapshot const& snapshot)-{- auto site = snapshot.site.has_value() ? qstring_from_ak_string(*snapshot.site) : QString("This page");- m_site->setToolTip(site);- m_site->setAccessibleName(site);-- QSignalBlocker blocker(m_switch);- m_switch->setChecked(snapshot.enabled());- m_switch->setEnabled(snapshot.can_toggle());- m_switch->setToolTip(snapshot.state == WebView::ContentBlockingState::Disabled ? "Ad blocking is disabled in Settings." : QString {});-- m_count->setText(qformatted("{} request{} blocked on this page", snapshot.blocked_request_count, snapshot.blocked_request_count == 1 ? ""sv : "s"sv));- m_count->setVisible(snapshot.blocked_request_count > 0);-- m_note->setText("If this site appears broken, try disabling ad block.");- m_error->hide();-- update_size();-}--void ContentBlockingPopover::update_chrome_style(QPalette const& palette)-{- auto active_palette = palette;- active_palette.setCurrentColorGroup(QPalette::Active);- setPalette(active_palette);- setStyleSheet(ChromeStyle::content_blocking_popover_style_sheet(active_palette));- update_size();-}--void ContentBlockingPopover::show_error(QString const& message)-{- m_error->setText(message);- m_error->show();- update_size();-}--void ContentBlockingPopover::focus_switch()-{- if (m_switch->isEnabled())- m_switch->setFocus(Qt::PopupFocusReason);- else- setFocus(Qt::PopupFocusReason);-}--void ContentBlockingPopover::mousePressEvent(QMouseEvent* event)-{- // The transparent shadow margin can overlap the toolbar button. Treat it as outside the card.- if (!card().geometry().contains(event->position().toPoint())) {- close();- event->accept();- return;- }-- Popover::mousePressEvent(event);-}--void ContentBlockingPopover::keyPressEvent(QKeyEvent* event)-{- if (event->key() == Qt::Key_Escape) {- close();- if (on_keyboard_dismiss)- on_keyboard_dismiss();- event->accept();- return;- }-- Popover::keyPressEvent(event);-}--void ContentBlockingPopover::update_size()-{- auto count_font = m_count->font();- count_font.setPixelSize(16);- m_count->setFont(count_font);- m_count->ensurePolished();-- auto available_width = qMax(160, screen()->availableGeometry().width() - 48);- auto count_width = m_count->fontMetrics().horizontalAdvance(m_count->text());- auto count_padding = m_count->contentsMargins().left() + m_count->contentsMargins().right();- auto available_count_width = available_width - 34 - count_padding;- if (count_width > available_count_width) {- // Keep the exact total on one line even on a narrow screen.- count_font.setPixelSize(qMax(10, 16 * available_count_width / (count_width + 1)));- m_count->setFont(count_font);- }-- auto preferred_width = 340;- for (auto* label : { m_count, m_error }) {- if (label->isHidden())- continue;- label->ensurePolished();- preferred_width = qMax(preferred_width, label->sizeHint().width() + 34);- }- m_note->ensurePolished();- preferred_width = qMax(preferred_width, m_note->sizeHint().width() + 2);- card().setFixedWidth(qMin(available_width, preferred_width));-- m_site->setText(m_site->fontMetrics().elidedText(m_site->toolTip(), Qt::ElideRight, card().width() - 80));-- // Refresh the minimum sizes before resizing after rows are hidden or shown.- card().layout()->activate();- layout()->activate();- adjustSize();-}--}diff --git a/UI/Qt/ContentBlockingPopover.h b/UI/Qt/ContentBlockingPopover.hdeleted file mode 100644index 6b0b1f57f83..00000000000--- a/UI/Qt/ContentBlockingPopover.h+++ /dev/null@@ -1,49 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Function.h>-#include <LibWebView/ContentBlocking.h>-#include <UI/Qt/Popover.h>--class QCheckBox;-class QIcon;-class QLabel;-class QKeyEvent;-class QMouseEvent;--namespace Ladybird {--class ContentBlockingPopover final : public Popover {- AK_ALLOC_WITH_KMALLOC;--public:- explicit ContentBlockingPopover(QWidget* parent);-- void set_snapshot(WebView::ContentBlockingSnapshot const&);- void set_favicon(QIcon const&);- void update_chrome_style(QPalette const&);- void show_error(QString const&);- void focus_switch();-- Function<void(bool)> on_toggle;- Function<void()> on_keyboard_dismiss;--private:- virtual void keyPressEvent(QKeyEvent*) override;- virtual void mousePressEvent(QMouseEvent*) override;- void update_size();-- QLabel* m_favicon { nullptr };- QLabel* m_site { nullptr };- QLabel* m_count { nullptr };- QLabel* m_note { nullptr };- QLabel* m_error { nullptr };- QCheckBox* m_switch { nullptr };-};--}diff --git a/UI/Qt/CrashReportNotifier.cpp b/UI/Qt/CrashReportNotifier.cppindex 7f500855d8a..4f0b0f874f1 100644--- a/UI/Qt/CrashReportNotifier.cpp+++ b/UI/Qt/CrashReportNotifier.cpp@@ -8,6 +8,7 @@#include <LibWebView/CrashReportStore.h>#include <UI/Qt/Application.h>#include <UI/Qt/CrashReportNotifier.h>+#include <UI/Qt/LadybirdButton.h>#include <UI/Qt/Tab.h>#include <QApplication>@@ -51,8 +52,8 @@ void CrashReportNotifier::show_pending()if (!m_pending_report_name.has_value() || QGuiApplication::applicationState() != Qt::ApplicationActive)return;- auto* tab = Application::the().active_tab();- auto* anchor = tab ? tab->hamburger_button() : nullptr;+ auto* window = Application::the().active_window_if_any();+ QWidget* anchor = window ? &window->ladybird_button() : nullptr;if (!anchor || !anchor->isVisible() || !window_is_active(*anchor->window()))return;@@ -68,8 +69,8 @@ void CrashReportNotifier::show_pending()m_anchor->installEventFilter(this);auto report_name = m_pending_report_name.release_value();- m_popover = new MessagePopover(anchor, CRASH_REPORT_POPOVER_WIDTH, tr("Ladybird flew off-course!"),- tr("Part of Ladybird stopped unexpectedly. You can send us a crash report to help fix it."), tr("Dismiss"),+ m_popover = new MessagePopover(anchor, CRASH_REPORT_POPOVER_WIDTH, tr("Part of Ladybird stopped unexpectedly"),+ tr("You can send us a crash report to help fix it."), tr("Dismiss"),tr("Review report"));m_popover->setAttribute(Qt::WA_DeleteOnClose);@@ -87,9 +88,9 @@ void CrashReportNotifier::show_pending()// The menu button's palette is transparent, so the popover takes its colors from the window instead.m_popover->update_chrome_style(anchor->window()->palette());m_popover->adjustSize();- move_popover_below(*m_popover, *anchor);+ move_popover_below(*m_popover, *anchor, PopoverAlignment::Leading);m_popover->show();- move_popover_below(*m_popover, *anchor);+ move_popover_below(*m_popover, *anchor, PopoverAlignment::Leading);m_popover->raise();}diff --git a/UI/Qt/DevToolsBanner.cpp b/UI/Qt/DevToolsBanner.cppindex c7c5abbc09f..0ba3af04d59 100644--- a/UI/Qt/DevToolsBanner.cpp+++ b/UI/Qt/DevToolsBanner.cpp@@ -31,7 +31,7 @@ DevToolsBanner::DevToolsBanner(QWidget* parent)layout->addWidget(m_label);layout->addStretch();- auto* launch_client_button = new QPushButton("Open Client", this);+ auto* launch_client_button = new QPushButton("Open client", this);connect(launch_client_button, &QPushButton::clicked, this, &DevToolsBanner::launch_client_requested);layout->addWidget(launch_client_button);diff --git a/UI/Qt/FindInPageWidget.cpp b/UI/Qt/FindInPageWidget.cppindex 7a9d268c955..f464d875c8d 100644--- a/UI/Qt/FindInPageWidget.cpp+++ b/UI/Qt/FindInPageWidget.cpp@@ -7,18 +7,32 @@#include <UI/Qt/ChromeStyle.h>#include <UI/Qt/FindInPageWidget.h>#include <UI/Qt/Icon.h>+#include <UI/Qt/Motion.h>#include <UI/Qt/NativeTextEditingLineEdit.h>+#include <UI/Qt/Popover.h>#include <UI/Qt/StringUtils.h>+#include <UI/Qt/SystemAppearance.h>#include <UI/Qt/Tab.h>+#if defined(AK_OS_MACOS)+# include <UI/Qt/MacWindow.h>+#endif+#include <UI/Qt/Theme.h>+#include <UI/Qt/WebContentView.h>#include <QEvent>+#include <QFrame>+#include <QHBoxLayout>#include <QKeyEvent>+#include <QLabel>+#include <QPainter>#include <QPointer>#include <QStyle>+#include <QVariantAnimation>+#include <QWindow>namespace Ladybird {-static constexpr auto FIND_TEXT_NO_RESULTS_PROPERTY = "noResults";+static constexpr auto NO_MATCHES_PROPERTY = "noResults";static void set_dynamic_property_if_needed(QWidget& widget, char const* property, bool value){@@ -31,84 +45,147 @@ static void set_dynamic_property_if_needed(QWidget& widget, char const* propertywidget.update();}+// The bar floats over the top right corner of the page. It is a native child of the tab, so it stacks above the native+// view the page is presented in, while the keyboard stays within the browser window.+static constexpr int BAR_WIDTH = 430;+static constexpr int BAR_HEIGHT = 40;+static constexpr int BAR_CORNER_RADIUS = 10;+static constexpr int PAGE_EDGE_INSET = 16;+static constexpr int PAGE_TOP_INSET = 8;+FindInPageWidget::FindInPageWidget(Tab* tab, WebContentView* content_view)- : QWidget(static_cast<QWidget*>(tab), Qt::Widget)+ : QWidget(static_cast<QWidget*>(tab)), m_tab(tab), m_content_view(content_view){setObjectName("LadybirdFindInPageBar");- setAttribute(Qt::WA_StyledBackground);+ setAccessibleName("Find in page");+#if defined(AK_OS_MACOS)+ setAttribute(Qt::WA_DontCreateNativeAncestors);+ setAttribute(Qt::WA_NativeWindow);+#endif+ m_shadow = &cast_floating_shadow(*this, BAR_CORNER_RADIUS);setFocusPolicy(Qt::FocusPolicy::StrongFocus);- setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);+ setFixedSize(BAR_WIDTH, BAR_HEIGHT);update_chrome_style();auto* layout = new QHBoxLayout(this);- setLayout(layout);-- layout->setContentsMargins(5, 5, 5, 5);- layout->setAlignment(Qt::AlignmentFlag::AlignLeft);-- m_find_text = new NativeTextEditingLineEdit(this);+ layout->setContentsMargins(4, 5, 6, 5);+ layout->setSpacing(4);++ // The search field holds its icon and the count of matches.+ auto* field = new QWidget(this);+ m_field = field;+ field->setObjectName("LadybirdFindInPageField");+ field->setAttribute(Qt::WA_StyledBackground);+ auto* field_layout = new QHBoxLayout(field);+ field_layout->setContentsMargins(8, 0, 8, 0);+ field_layout->setSpacing(8);+ m_search_icon = new QLabel(field);+ m_search_icon->setFixedSize(14, 14);+ field_layout->addWidget(m_search_icon);++ m_find_text = new NativeTextEditingLineEdit(field);+ m_find_text->setObjectName("LadybirdFindInPageText");m_find_text->setFocusPolicy(Qt::FocusPolicy::StrongFocus);- m_find_text->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Fixed);- m_find_text->setPlaceholderText("Search");- m_find_text->setMinimumWidth(50);- m_find_text->setMaximumWidth(250);+ m_find_text->setPlaceholderText("Find in page");+ m_find_text->setAccessibleName("Find in page");connect(m_find_text, &QLineEdit::textChanged, this, &FindInPageWidget::find_text_changed);+ field_layout->addWidget(m_find_text, 1);- m_previous_button = new QPushButton(this);- m_previous_button->setFixedWidth(30);- m_previous_button->setIcon(create_chrome_icon(ChromeIcon::ChevronUp, palette()));- m_previous_button->setToolTip("Find Previous Match");- m_previous_button->setFlat(true);+ m_result_label = new QLabel(field);+ m_result_label->setObjectName("LadybirdFindInPageResult");+ m_result_label->setVisible(false);+ field_layout->addWidget(m_result_label);+ layout->addWidget(field, 1);++ auto make_button = [&](QString const& tooltip) {+ auto* button = new QPushButton(this);+ button->setObjectName("LadybirdFindInPageButton");+ button->setFixedSize(28, 28);+ button->setAttribute(Qt::WA_LayoutUsesWidgetRect);+ button->setIconSize({ 16, 16 });+ button->setToolTip(tooltip);+ button->setAccessibleName(tooltip);+ button->setFlat(true);+ button->setFocusPolicy(Qt::TabFocus);+ return button;+ };++ m_previous_button = make_button("Previous match");connect(m_previous_button, &QPushButton::clicked, this, [this] {m_content_view->find_in_page_previous_match();});- m_next_button = new QPushButton(this);- m_next_button->setFixedWidth(30);- m_next_button->setIcon(create_chrome_icon(ChromeIcon::ChevronDown, palette()));- m_next_button->setToolTip("Find Next Match");- m_next_button->setFlat(true);+ m_next_button = make_button("Next match");connect(m_next_button, &QPushButton::clicked, this, [this] {m_content_view->find_in_page_next_match();});- m_exit_button = new QPushButton(this);- m_exit_button->setFixedWidth(30);- m_exit_button->setIcon(create_chrome_icon(ChromeIcon::Close, palette()));- m_exit_button->setToolTip("Close Search Bar");- m_exit_button->setFlat(true);- connect(m_exit_button, &QPushButton::clicked, this, [this] {- close_bar();- });-- m_highlight_all = new QCheckBox(this);- m_highlight_all->setText("Highlight &All");- m_highlight_all->setChecked(false);- connect(m_highlight_all, &QCheckBox::checkStateChanged, this, [this] {+ m_match_case = make_button("Match case");+ m_match_case->setText("Aa");+ m_match_case->setCheckable(true);+ connect(m_match_case, &QPushButton::toggled, this, [this] {find_text_changed();});- m_match_case = new QCheckBox(this);- m_match_case->setText("Match &Case");- m_match_case->setChecked(false);- connect(m_match_case, &QCheckBox::checkStateChanged, this, [this] {- find_text_changed();- });+ auto* separator = new QFrame(this);+ separator->setObjectName("LadybirdFindInPageSeparator");+ separator->setFixedSize(1, 16);- m_result_label = new QLabel(this);- m_result_label->setVisible(false);- m_result_label->setStyleSheet("font-weight: bold;");+ m_exit_button = make_button("Close find");+ m_exit_button->setIconSize({ 12, 12 });+ connect(m_exit_button, &QPushButton::clicked, this, [this] {+ close_bar();+ });- layout->addWidget(m_find_text, 1);layout->addWidget(m_previous_button);layout->addWidget(m_next_button);- layout->addWidget(m_highlight_all);layout->addWidget(m_match_case);- layout->addWidget(m_result_label);- layout->addStretch(1);+ layout->addSpacing(2);+ layout->addWidget(separator, 0, Qt::AlignVCenter);+ layout->addSpacing(2);layout->addWidget(m_exit_button);++ update_icons();+}++void FindInPageWidget::update_icons()+{+ auto const& panel = Theme::panel();+ m_search_icon->setPixmap(create_chrome_icon(ChromeIcon::Search, panel.muted).pixmap(QSize(14, 14), devicePixelRatioF()));+ auto navigation_color = m_has_no_matches ? ChromeStyle::find_in_page_unavailable_control_color() : panel.body;+ m_previous_button->setIcon(create_chrome_icon(ChromeIcon::ChevronUp, navigation_color));+ m_next_button->setIcon(create_chrome_icon(ChromeIcon::ChevronDown, navigation_color));+ m_exit_button->setIcon(create_chrome_icon(ChromeIcon::Close, panel.body));+}++void FindInPageWidget::paintEvent(QPaintEvent*)+{+ QPainter painter(this);+ painter.setRenderHint(QPainter::Antialiasing, true);+ auto const& panel = Theme::panel();+#if defined(AK_OS_MACOS)+ // NB: The view's own layer rounds the corners and draws the outline.+ painter.fillRect(rect(), panel.surface);+#else+ painter.setBrush(panel.surface);+ painter.setPen(QPen(panel.edge, 1));+ painter.drawRoundedRect(QRectF(rect()).adjusted(0.5, 0.5, -0.5, -0.5), BAR_CORNER_RADIUS, BAR_CORNER_RADIUS);+#endif+}++void FindInPageWidget::focus_search_field()+{+ setFocus(Qt::ShortcutFocusReason);+}++void FindInPageWidget::reposition()+{+ auto view_top_right = m_content_view->mapTo(m_tab, QPoint(m_content_view->width(), 0));+ auto position = QPoint(view_top_right.x() - PAGE_EDGE_INSET - BAR_WIDTH, view_top_right.y() + PAGE_TOP_INSET + qRound(m_opening_offset));+ if (pos() != position)+ move(position);}FindInPageWidget::~FindInPageWidget() = default;@@ -117,9 +194,7 @@ bool FindInPageWidget::event(QEvent* event){if (event->type() == QEvent::PaletteChange) {update_chrome_style();- m_previous_button->setIcon(create_chrome_icon(ChromeIcon::ChevronUp, palette()));- m_next_button->setIcon(create_chrome_icon(ChromeIcon::ChevronDown, palette()));- m_exit_button->setIcon(create_chrome_icon(ChromeIcon::Close, palette()));+ update_icons();}return QWidget::event(event);@@ -139,10 +214,11 @@ void FindInPageWidget::find_text_changed(){auto query = utf16_string_from_qstring(m_find_text->text());if (query.is_empty())- set_dynamic_property_if_needed(*m_find_text, FIND_TEXT_NO_RESULTS_PROPERTY, false);+ set_has_no_matches(false);auto case_sensitive = m_match_case->isChecked() ? CaseSensitivity::CaseSensitive : CaseSensitivity::CaseInsensitive;- m_content_view->find_in_page(query, case_sensitive, m_highlight_all->isChecked());+ // Every match on the page is highlighted, with the current one standing out.+ m_content_view->find_in_page(query, case_sensitive, true);}void FindInPageWidget::keyPressEvent(QKeyEvent* event)@@ -192,6 +268,34 @@ void FindInPageWidget::focusInEvent(QFocusEvent* event)void FindInPageWidget::showEvent(QShowEvent*){+ // The bar fades in from 4 px above its place, or fades in only if the system asks for less motion.+ auto set_opacity = [this](qreal opacity) {+ set_floating_window_opacity(*this, opacity);+ set_floating_window_opacity(*m_shadow, opacity);+ };+ if (!m_opening_animation) {+ m_opening_animation = new QVariantAnimation(this);+ m_opening_animation->setDuration(Motion::FAST);+ m_opening_animation->setEasingCurve(Motion::enter_easing());+ m_opening_animation->setStartValue(0.0);+ m_opening_animation->setEndValue(1.0);+ QObject::connect(m_opening_animation, &QVariantAnimation::valueChanged, this, [this, set_opacity](QVariant const& value) {+ auto progress = value.toReal();+ m_opening_offset = SystemAppearance::prefers_reduced_motion() ? 0 : -4 * (1 - progress);+ set_opacity(progress);+ reposition();+ });+ }+ m_opening_offset = SystemAppearance::prefers_reduced_motion() ? 0 : -4;+ set_opacity(0);+ m_opening_animation->stop();+ m_opening_animation->start();+ reposition();+ raise();+#if defined(AK_OS_MACOS)+ round_appkit_view_corners(*this, BAR_CORNER_RADIUS, Theme::panel().edge);+#endif+if (m_tab && m_tab->isVisible())m_tab->update_hover_label();}@@ -205,20 +309,33 @@ void FindInPageWidget::hideEvent(QHideEvent*)void FindInPageWidget::update_result_label(size_t current_match_index, Optional<size_t> const& total_match_count){if (total_match_count.has_value()) {- set_dynamic_property_if_needed(*m_find_text, FIND_TEXT_NO_RESULTS_PROPERTY, total_match_count.value() == 0);+ set_has_no_matches(total_match_count.value() == 0);- auto label_text = "Phrase not found"_string;+ auto label_text = "No matches"_string;if (total_match_count.value() > 0)- label_text = MUST(String::formatted("{} of {} matches", current_match_index + 1, total_match_count.value()));+ label_text = MUST(String::formatted("{} of {}", current_match_index + 1, total_match_count.value()));m_result_label->setText(qstring_from_ak_string(label_text));m_result_label->setVisible(true);} else {- set_dynamic_property_if_needed(*m_find_text, FIND_TEXT_NO_RESULTS_PROPERTY, false);+ set_has_no_matches(false);m_result_label->setVisible(false);}}+// Without a match, the field is tinted, and there is no match to go to.+void FindInPageWidget::set_has_no_matches(bool has_no_matches)+{+ if (m_has_no_matches == has_no_matches)+ return;+ m_has_no_matches = has_no_matches;+ set_dynamic_property_if_needed(*m_field, NO_MATCHES_PROPERTY, has_no_matches);+ set_dynamic_property_if_needed(*m_result_label, NO_MATCHES_PROPERTY, has_no_matches);+ m_previous_button->setEnabled(!has_no_matches);+ m_next_button->setEnabled(!has_no_matches);+ update_icons();+}+void FindInPageWidget::find_previous(){m_previous_button->click();diff --git a/UI/Qt/FindInPageWidget.h b/UI/Qt/FindInPageWidget.hindex 0b6883bfcea..35837497e61 100644--- a/UI/Qt/FindInPageWidget.h+++ b/UI/Qt/FindInPageWidget.h@@ -16,6 +16,8 @@#include <QPushButton>#include <QWidget>+class QVariantAnimation;+namespace Ladybird {class Tab;@@ -33,6 +35,8 @@ public:void find_previous();void find_next();+ void reposition();+ void focus_search_field();virtual ~FindInPageWidget() override;@@ -44,10 +48,13 @@ private:virtual void focusInEvent(QFocusEvent*) override;virtual void showEvent(QShowEvent*) override;virtual void hideEvent(QHideEvent*) override;+ virtual void paintEvent(QPaintEvent*) override;void close_bar();void find_text_changed();void update_chrome_style();+ void update_icons();+ void set_has_no_matches(bool);Tab* m_tab { nullptr };WebContentView* m_content_view { nullptr };@@ -56,11 +63,17 @@ private:QPushButton* m_previous_button { nullptr };QPushButton* m_next_button { nullptr };QPushButton* m_exit_button { nullptr };- QCheckBox* m_highlight_all { nullptr };- QCheckBox* m_match_case { nullptr };+ QPushButton* m_match_case { nullptr };+ QWidget* m_field { nullptr };+ QLabel* m_search_icon { nullptr };QLabel* m_result_label { nullptr };bool m_is_updating_chrome_style { false };+ bool m_has_no_matches { false };u64 m_selected_text_request_id { 0 };+ // The bar slides down this far into place as it opens.+ qreal m_opening_offset { 0 };+ QVariantAnimation* m_opening_animation { nullptr };+ QWidget* m_shadow { nullptr };};}diff --git a/UI/Qt/Icon.cpp b/UI/Qt/Icon.cppindex 9c0096b796c..f154f834722 100644--- a/UI/Qt/Icon.cpp+++ b/UI/Qt/Icon.cpp@@ -4,11 +4,14 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/HashMap.h>#include <LibCore/Resource.h>#include <UI/Qt/ChromeStyle.h>#include <UI/Qt/Icon.h>#include <UI/Qt/StringUtils.h>+#include <UI/Qt/Theme.h>+#include <QIconEngine>#include <QPainter>#include <QPainterPath>#include <QPainterPathStroker>@@ -79,422 +82,581 @@ QIcon favicon_with_rounded_corners(QIcon const& favicon, int logical_size)return rounded;}-static QPen chrome_icon_pen(QColor const& color, qreal width)+// Parses the path data of an SVG <path> element. Only the commands used by the icons below are understood: moveto,+// lineto, horizontal and vertical lineto, cubic and quadratic Bézier curves and their smooth forms, elliptical arcs and+// closepath, absolute and relative.+static QPainterPath parse_svg_path(StringView data){- return QPen(color, width, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);-}+ QPainterPath path;+ size_t index = 0;+ char command = 0;+ QPointF current;+ QPointF subpath_start;+ // The second control point of the last cubic curve, which a smooth cubic curve after it reflects.+ Optional<QPointF> last_control;+ // The control point of the last quadratic curve, which a smooth quadratic curve after it reflects.+ Optional<QPointF> last_quadratic_control;++ auto skip_separators = [&] {+ while (index < data.length() && (data[index] == ' ' || data[index] == ','))+ ++index;+ };+ auto at_number = [&] {+ skip_separators();+ if (index >= data.length())+ return false;+ auto c = data[index];+ return c == '-' || c == '.' || (c >= '0' && c <= '9');+ };+ auto read_number = [&] {+ skip_separators();+ auto start = index;+ if (data[index] == '-')+ ++index;+ auto seen_dot = false;+ while (index < data.length()) {+ auto c = data[index];+ if (c == '.') {+ // A second dot starts the next number, as in "1.5.5".+ if (seen_dot)+ break;+ seen_dot = true;+ } else if (c < '0' || c > '9') {+ break;+ }+ ++index;+ }+ return data.substring_view(start, index - start).to_number<double>().value();+ };+ auto read_flag = [&] {+ skip_separators();+ return data[index++] == '1';+ };-static void draw_stroked_icon_path(QPainter& painter, QPainterPath const& path, QColor const& color, qreal width)-{- QPainterPathStroker stroker;- stroker.setWidth(width);- stroker.setCapStyle(Qt::RoundCap);- stroker.setJoinStyle(Qt::RoundJoin);-- auto stroke = stroker.createStroke(path);- stroke.setFillRule(Qt::WindingFill);- painter.fillPath(stroke, color);-}+ // https://www.w3.org/TR/SVG2/implnote.html#ArcConversionEndpointToCenter+ auto arc_to = [&](double rx, double ry, bool large_arc, bool sweep, QPointF end) {+ auto x1p = (current.x() - end.x()) / 2;+ auto y1p = (current.y() - end.y()) / 2;+ auto lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);+ if (lambda > 1) {+ rx *= sqrt(lambda);+ ry *= sqrt(lambda);+ }+ auto numerator = (rx * rx * ry * ry) - (rx * rx * y1p * y1p) - (ry * ry * x1p * x1p);+ auto denominator = (rx * rx * y1p * y1p) + (ry * ry * x1p * x1p);+ auto coefficient = sqrt(max(0.0, numerator / denominator)) * (large_arc == sweep ? -1 : 1);+ auto cxp = coefficient * rx * y1p / ry;+ auto cyp = coefficient * -ry * x1p / rx;+ auto cx = cxp + (current.x() + end.x()) / 2;+ auto cy = cyp + (current.y() + end.y()) / 2;++ auto angle = [](double ux, double uy, double vx, double vy) {+ return atan2((ux * vy) - (uy * vx), (ux * vx) + (uy * vy));+ };+ auto start_angle = angle(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);+ auto sweep_angle = angle((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry);+ if (!sweep && sweep_angle > 0)+ sweep_angle -= 2 * M_PI;+ else if (sweep && sweep_angle < 0)+ sweep_angle += 2 * M_PI;++ // NB: Qt measures angles counterclockwise on screen, where y grows downward, so SVG's angles are negated.+ path.arcTo(QRectF(cx - rx, cy - ry, 2 * rx, 2 * ry), -qRadiansToDegrees(start_angle), -qRadiansToDegrees(sweep_angle));+ current = end;+ };-static void draw_back_icon(QPainter& painter, QColor const& color)-{- QPainterPath path;- path.moveTo(16.7, 10.0);- path.lineTo(3.3, 10.0);- path.moveTo(9.2, 4.7);- path.lineTo(3.3, 10.0);- path.lineTo(9.2, 15.3);- draw_stroked_icon_path(painter, path, color, 2.0);+ while (true) {+ skip_separators();+ if (index >= data.length())+ break;+ if (!at_number())+ command = data[index++];++ auto relative = command >= 'a';+ auto origin = relative ? current : QPointF();+ auto previous_control = exchange(last_control, {});+ auto previous_quadratic_control = exchange(last_quadratic_control, {});+ switch (command) {+ case 'M':+ case 'm': {+ auto x = read_number();+ auto y = read_number();+ current = origin + QPointF(x, y);+ path.moveTo(current);+ subpath_start = current;+ // Further coordinate pairs after a moveto are linetos.+ command = relative ? 'l' : 'L';+ break;+ }+ case 'L':+ case 'l': {+ auto x = read_number();+ auto y = read_number();+ current = origin + QPointF(x, y);+ path.lineTo(current);+ break;+ }+ case 'H':+ case 'h':+ current.setX((relative ? current.x() : 0) + read_number());+ path.lineTo(current);+ break;+ case 'V':+ case 'v':+ current.setY((relative ? current.y() : 0) + read_number());+ path.lineTo(current);+ break;+ case 'C':+ case 'c': {+ QPointF control1 { read_number(), read_number() };+ QPointF control2 { read_number(), read_number() };+ QPointF end { read_number(), read_number() };+ path.cubicTo(origin + control1, origin + control2, origin + end);+ last_control = origin + control2;+ current = origin + end;+ break;+ }+ case 'S':+ case 's': {+ auto control1 = previous_control.has_value() ? (2 * current) - *previous_control : current;+ QPointF control2 { read_number(), read_number() };+ QPointF end { read_number(), read_number() };+ path.cubicTo(control1, origin + control2, origin + end);+ last_control = origin + control2;+ current = origin + end;+ break;+ }+ case 'Q':+ case 'q': {+ QPointF control { read_number(), read_number() };+ QPointF end { read_number(), read_number() };+ path.quadTo(origin + control, origin + end);+ last_quadratic_control = origin + control;+ current = origin + end;+ break;+ }+ case 'T':+ case 't': {+ auto control = previous_quadratic_control.has_value() ? (2 * current) - *previous_quadratic_control : current;+ QPointF end { read_number(), read_number() };+ path.quadTo(control, origin + end);+ last_quadratic_control = control;+ current = origin + end;+ break;+ }+ case 'A':+ case 'a': {+ auto rx = read_number();+ auto ry = read_number();+ (void)read_number(); // NB: None of our icons rotate their ellipses.+ auto large_arc = read_flag();+ auto sweep = read_flag();+ QPointF end { read_number(), read_number() };+ arc_to(rx, ry, large_arc, sweep, origin + end);+ break;+ }+ case 'Z':+ case 'z':+ path.closeSubpath();+ current = subpath_start;+ break;+ default:+ VERIFY_NOT_REACHED();+ }+ }++ return path;}-static void draw_forward_icon(QPainter& painter, QColor const& color)+// The icon set of the chrome: 16 px on a 16 px grid, stroked 1.5 px wide with round caps and joins.+static constexpr auto BACK_ICON_PATH = "M10 3.5L5.5 8l4.5 4.5"sv;+static constexpr auto FORWARD_ICON_PATH = "M6 3.5L10.5 8 6 12.5"sv;+static constexpr auto RELOAD_ICON_PATH = "M12.89 9.04A5 5 0 1 1 8 3c1.4 0 2.74.56 3.74 1.52L13 5.8M13 2.8v3h-2.8"sv;+static constexpr auto STOP_ICON_PATH = "M4 4l8 8M12 4l-8 8"sv;+static constexpr auto SITE_SETTINGS_ICON_PATH = "M2.5 5h6M12.5 5h1M2.5 11h1M7.5 11h6M12.1 5a1.6 1.6 0 1 1-3.2 0a1.6 1.6 0 1 1 3.2 0M7.1 11a1.6 1.6 0 1 1-3.2 0a1.6 1.6 0 1 1 3.2 0"sv;+static constexpr auto MICROPHONE_ICON_PATH = "M8 2.5a2 2 0 0 1 2 2v3.5a2 2 0 0 1-4 0V4.5a2 2 0 0 1 2-2zM4.5 7.5a3.5 3.5 0 0 0 7 0M8 11v2.5"sv;+static constexpr auto SELECT_AREA_ICON_PATH = "M2 5V3a1 1 0 0 1 1-1h2M11 2h2a1 1 0 0 1 1 1v2M14 11v2a1 1 0 0 1-1 1h-2M5 14H3a1 1 0 0 1-1-1v-2"sv;+static constexpr auto CHECK_CIRCLE_ICON_PATH = "M14.5 8a6.5 6.5 0 1 1-13 0a6.5 6.5 0 1 1 13 0M5.2 8.2l2 2 3.8-4.2"sv;+static constexpr auto STAR_ICON_PATH = "M8 2.3l1.75 3.55 3.9.57-2.83 2.75.67 3.88L8 11.22l-3.49 1.83.67-3.88L2.35 6.42l3.9-.57z"sv;+static constexpr auto CONTENT_BLOCKING_ICON_PATH = "M8 1.8l5 1.9v4c0 3.1-2.1 5.3-5 6.5-2.9-1.2-5-3.4-5-6.5v-4z"sv;+static constexpr auto NEW_TAB_ICON_PATH = "M8 3v10M3 8h10"sv;+static constexpr auto CLOSE_ICON_PATH = "M4.5 4.5l7 7M11.5 4.5l-7 7"sv;+static constexpr auto TAB_CLOSE_ICON_PATH = "M4 4l8 8M12 4l-8 8"sv;+static constexpr auto CHEVRON_DOWN_ICON_PATH = "M4.5 6.5L8 10l3.5-3.5"sv;+static constexpr auto CHEVRON_UP_ICON_PATH = "M4.5 9.5L8 6l3.5 3.5"sv;+static constexpr auto SIDEBAR_ICON_PATH = "M4 3h8a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM6 3v10"sv;+static constexpr auto DOWNLOAD_ICON_PATH = "M8 3v6.5M5 6.8L8 9.8l3-3M3.5 12.5h9"sv;+static constexpr auto AUDIO_ICON_PATH = "M2.5 6h2.5L8.5 3v10L5 10H2.5zM11 5.5a3.5 3.5 0 0 1 0 5"sv;+static constexpr auto MUTED_ICON_PATH = "M2.5 6h2.5L8.5 3v10L5 10H2.5zM11 6l3.5 4M14.5 6L11 10"sv;+static constexpr auto PIN_ICON_PATH = "M8 10v4M5 10h6M6.2 2.5h3.6l-.4 4 1.6 3.5H5l1.6-3.5z"sv;+static constexpr auto WARNING_ICON_PATH = "M8 2.5l6 11H2zM8 6.8v3M8 11.7v.1"sv;+static constexpr auto SEARCH_ICON_PATH = "M7 2.5a4.5 4.5 0 1 1 0 9a4.5 4.5 0 1 1 0-9zM10.5 10.5L14 14"sv;+static constexpr auto ZOOM_OUT_ICON_PATH = "M3 8h10"sv;+static constexpr auto PAUSE_ICON_PATH = "M6 4v8M10 4v8"sv;+static constexpr auto MENU_ICON_PATH = "M3 4.5h10M3 8h10M3 11.5h10"sv;+static constexpr auto GLOBE_ICON_PATH = "M8 2.5a5.5 5.5 0 1 1 0 11a5.5 5.5 0 1 1 0-11zM2.5 8h11M8 2.5c-1.6 1.6-2.4 3.4-2.4 5.5s.8 3.9 2.4 5.5M8 2.5c1.6 1.6 2.4 3.4 2.4 5.5s-.8 3.9-2.4 5.5"sv;+static constexpr auto DOCUMENT_ICON_PATH = "M3.5 2.5h6l3 3v8h-9zM9.5 2.5v3h3"sv;+static constexpr auto NETWORK_ICON_PATH = "M2.5 8a5.5 5.5 0 1 0 11 0a5.5 5.5 0 1 0-11 0M2.5 8h11M8 2.5c1.6 1.6 2.4 3.4 2.4 5.5S9.6 11.9 8 13.5M8 2.5C6.4 4.1 5.6 5.9 5.6 8s.8 3.9 2.4 5.5"sv;+static constexpr auto COMPOSITOR_ICON_PATH = "M2.5 4h7v5h-7zM6.5 7h7v5h-7z"sv;+static constexpr auto IMAGE_ICON_PATH = "M2.5 3.5h11v9h-11zM2.5 10.5l3-3 3 3 2-2 3 3M10.5 6.2v.1"sv;+static constexpr auto FOLDER_ICON_PATH = "M2.5 4.5a1 1 0 0 1 1-1h3l1.5 1.5h4.5a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1h-9a1 1 0 0 1-1-1z"sv;++// The window controls of Windows and Linux are drawn on a 10 px box in the middle of the icon.+static constexpr auto WINDOW_MINIMIZE_ICON_PATH = "M3 8.5h10"sv;+static constexpr auto WINDOW_MAXIMIZE_ICON_PATH = "M5 3.5h6a1.5 1.5 0 0 1 1.5 1.5v6a1.5 1.5 0 0 1-1.5 1.5H5A1.5 1.5 0 0 1 3.5 11V5A1.5 1.5 0 0 1 5 3.5z"sv;+static constexpr auto WINDOW_RESTORE_ICON_PATH = "M4.5 6h5a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1h-5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1zM6 3.5h5.5a1 1 0 0 1 1 1V10"sv;+static constexpr auto WINDOW_CLOSE_ICON_PATH = "M3.5 3.5l9 9M12.5 3.5l-9 9"sv;++static constexpr qreal CHROME_ICON_STROKE_WIDTH = 1.5;+static constexpr qreal TOOLBAR_ICON_STROKE_WIDTH = 1.4;++static StringView chrome_icon_path(ChromeIcon icon){- QPainterPath path;- path.moveTo(3.3, 10.0);- path.lineTo(16.7, 10.0);- path.moveTo(10.8, 4.7);- path.lineTo(16.7, 10.0);- path.lineTo(10.8, 15.3);- draw_stroked_icon_path(painter, path, color, 2.0);+ switch (icon) {+ case ChromeIcon::Back:+ return BACK_ICON_PATH;+ case ChromeIcon::Forward:+ return FORWARD_ICON_PATH;+ case ChromeIcon::Reload:+ return RELOAD_ICON_PATH;+ case ChromeIcon::Stop:+ return STOP_ICON_PATH;+ case ChromeIcon::NewTab:+ return NEW_TAB_ICON_PATH;+ case ChromeIcon::Close:+ return CLOSE_ICON_PATH;+ case ChromeIcon::TabClose:+ return TAB_CLOSE_ICON_PATH;+ case ChromeIcon::Menu:+ return MENU_ICON_PATH;+ case ChromeIcon::Star:+ case ChromeIcon::StarFilled:+ return STAR_ICON_PATH;+ case ChromeIcon::Search:+ return SEARCH_ICON_PATH;+ case ChromeIcon::Globe:+ return GLOBE_ICON_PATH;+ case ChromeIcon::Folder:+ return FOLDER_ICON_PATH;+ case ChromeIcon::Document:+ return DOCUMENT_ICON_PATH;+ case ChromeIcon::Network:+ return NETWORK_ICON_PATH;+ case ChromeIcon::Compositor:+ return COMPOSITOR_ICON_PATH;+ case ChromeIcon::Image:+ return IMAGE_ICON_PATH;+ case ChromeIcon::Download:+ return DOWNLOAD_ICON_PATH;+ case ChromeIcon::Volume:+ return AUDIO_ICON_PATH;+ case ChromeIcon::VolumeMuted:+ return MUTED_ICON_PATH;+ case ChromeIcon::ChevronUp:+ return CHEVRON_UP_ICON_PATH;+ case ChromeIcon::ChevronDown:+ return CHEVRON_DOWN_ICON_PATH;+ case ChromeIcon::ContentBlocking:+ return CONTENT_BLOCKING_ICON_PATH;+ case ChromeIcon::SiteSettings:+ return SITE_SETTINGS_ICON_PATH;+ case ChromeIcon::Microphone:+ return MICROPHONE_ICON_PATH;+ case ChromeIcon::SelectArea:+ return SELECT_AREA_ICON_PATH;+ case ChromeIcon::CheckCircle:+ return CHECK_CIRCLE_ICON_PATH;+ case ChromeIcon::Pin:+ return PIN_ICON_PATH;+ case ChromeIcon::Warning:+ return WARNING_ICON_PATH;+ case ChromeIcon::Pause:+ return PAUSE_ICON_PATH;+ case ChromeIcon::ZoomOut:+ return ZOOM_OUT_ICON_PATH;+ case ChromeIcon::Sidebar:+ case ChromeIcon::SidebarRight:+ return SIDEBAR_ICON_PATH;+ case ChromeIcon::WindowMinimize:+ return WINDOW_MINIMIZE_ICON_PATH;+ case ChromeIcon::WindowMaximize:+ return WINDOW_MAXIMIZE_ICON_PATH;+ case ChromeIcon::WindowRestore:+ return WINDOW_RESTORE_ICON_PATH;+ case ChromeIcon::WindowClose:+ return WINDOW_CLOSE_ICON_PATH;+ }+ VERIFY_NOT_REACHED();}-static void draw_reload_icon(QPainter& painter, QColor const& color)+// The right sidebar's icon is the left one's, mirrored.+static QPainterPath mirrored_for_right_sidebar(ChromeIcon icon, QPainterPath path){- QPainterPath shape;- shape.setFillRule(Qt::WindingFill);- shape.arcMoveTo(QRectF(3.0, 3.0, 14.0, 14.0), 58.0);- shape.arcTo(QRectF(3.0, 3.0, 14.0, 14.0), 58.0, 272.0);- shape.arcTo(QRectF(4.9, 4.9, 10.2, 10.2), 330.0, -272.0);- shape.closeSubpath();-- QPainterPath arrow_head;- arrow_head.moveTo(17.1, 7.55);- arrow_head.lineTo(14.65, 2.05);- arrow_head.lineTo(11.35, 7.55);- arrow_head.closeSubpath();- shape.addPath(arrow_head);-- painter.fillPath(shape, color);+ if (icon != ChromeIcon::SidebarRight)+ return path;+ QTransform transform;+ transform.translate(CHROME_ICON_CANVAS_SIZE, 0);+ transform.scale(-1, 1);+ return transform.map(path);}-static void draw_star_icon(QPainter& painter, QColor const& color, bool filled)+static QPainterPath const& chrome_icon_painter_path(ChromeIcon icon){- QPainterPath path;- path.moveTo(10.0, 2.7);- path.lineTo(12.5, 7.6);- path.lineTo(18.0, 8.1);- path.lineTo(13.9, 11.8);- path.lineTo(15.1, 17.3);- path.lineTo(10.0, 14.4);- path.lineTo(4.9, 17.3);- path.lineTo(6.1, 11.8);- path.lineTo(2.0, 8.1);- path.lineTo(7.5, 7.6);- path.closeSubpath();-- painter.setPen(chrome_icon_pen(color, filled ? 1.2 : 1.65));- if (filled)- painter.setBrush(color);- else- painter.setBrush(Qt::NoBrush);- painter.drawPath(path);+ static HashMap<ChromeIcon, QPainterPath> s_paths;+ return s_paths.ensure(icon, [&] {+ return mirrored_for_right_sidebar(icon, parse_svg_path(chrome_icon_path(icon)));+ });}-// A stop sign: an octagon outline with a bar across its middle.-static void draw_content_blocking_icon(QPainter& painter, QColor const& color)+// On a 1x screen a 1.5 px line cannot land on whole pixels and smears, so the small icons of the chrome have a second+// drawing for it: 1 px lines on half pixels, so that their straight edges are crisp, and a 1.25 px line for the diagonals+// of a cross. The drawings are on the same 16 px canvas.+struct PixelSnappedChromeIcon {+ StringView path;+ qreal stroke_width { 1 };+};++// The 1x drawings are used for icons shown within this much of the canvas's size.+static constexpr int PIXEL_SNAPPED_ICON_SIZE_TOLERANCE = 2;++static Optional<PixelSnappedChromeIcon> pixel_snapped_chrome_icon(ChromeIcon icon){- static constexpr qreal center = 10.0;- static constexpr qreal radius = 7.6;-- QPainterPath octagon;- for (int corner = 0; corner < 8; ++corner) {- auto angle = qDegreesToRadians(22.5 + (45.0 * corner));- QPointF point { center + (radius * qCos(angle)), center + (radius * qSin(angle)) };- if (corner == 0)- octagon.moveTo(point);- else- octagon.lineTo(point);+ switch (icon) {+ case ChromeIcon::Close:+ case ChromeIcon::TabClose:+ return PixelSnappedChromeIcon { "M4 4L12 12M12 4L4 12"sv, 1.25 };+ case ChromeIcon::NewTab:+ return PixelSnappedChromeIcon { "M7.5 2.5v10M2.5 7.5h10"sv };+ case ChromeIcon::Volume:+ return PixelSnappedChromeIcon { "M2.5 5.5H5l3.5-3v11L5 10.5H2.5zM10.9 5.3Q12.6 6.4 12.6 8T10.9 10.7"sv };+ case ChromeIcon::VolumeMuted:+ return PixelSnappedChromeIcon { "M2.5 5.5H5l3.5-3v11L5 10.5H2.5zM10 6l4 4M14 6l-4 4"sv };+ case ChromeIcon::Sidebar:+ case ChromeIcon::SidebarRight:+ return PixelSnappedChromeIcon { "M3.5 3.5h9a1 1 0 0 1 1 1v7a1 1 0 0 1-1 1h-9a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1zM6.5 3.5v9"sv };+ case ChromeIcon::Download:+ return PixelSnappedChromeIcon { "M7.5 2v7.5M4.5 6.5l3 3 3-3M2.5 12.5h10"sv };+ default:+ return {};}- octagon.closeSubpath();+}- // Same stroke as the hamburger icon next to it.- painter.setBrush(Qt::NoBrush);- painter.setPen(chrome_icon_pen(color, 1.55));- painter.drawPath(octagon);- painter.drawLine(QPointF(7.4, center), QPointF(12.6, center));+static QPainterPath const* chrome_icon_pixel_snapped_painter_path(ChromeIcon icon)+{+ static HashMap<ChromeIcon, Optional<QPainterPath>> s_paths;+ auto const& path = s_paths.ensure(icon, [&]() -> Optional<QPainterPath> {+ auto snapped = pixel_snapped_chrome_icon(icon);+ if (!snapped.has_value())+ return {};+ return mirrored_for_right_sidebar(icon, parse_svg_path(snapped->path));+ });+ return path.has_value() ? &path.value() : nullptr;}-static QPainterPath horizontally_flipped_path(QPainterPath const& path)+static QPixmap create_transparent_icon_pixmap(QSize logical_size, qreal device_pixel_ratio){- QTransform transform;- transform.translate(20.0, 0.0);- transform.scale(-1.0, 1.0);- return transform.map(path);+ QPixmap pixmap(physical_size_for_device_pixel_ratio(logical_size, device_pixel_ratio));+ pixmap.setDevicePixelRatio(device_pixel_ratio);+ pixmap.fill(Qt::transparent);+ return pixmap;}-// The expanded sidebar's button shows the sidebar with an arrow into it. The collapsed sidebar's button is a double-// chevron pointing away from the sidebar's edge of the window.-static void draw_vertical_tab_bar_icon(QPainter& painter, QColor const& color, bool expanded, bool right_side)+// The icon is drawn from its vector at the size and device pixel ratio it is shown at, never scaled from a picture of it.+// NB: The size the icon was made for sets its line: the toolbar's larger icons are drawn with a finer line on their+// canvas, so that they keep about the weight of the smaller ones.+static QPixmap create_chrome_icon_pixmap(ChromeIcon icon, QPainterPath const& path, QColor color, qreal device_pixel_ratio, int logical_size, int design_size){- if (!expanded) {- QPainterPath chevrons;- chevrons.moveTo(6.0, 6.3);- chevrons.lineTo(9.7, 10.0);- chevrons.lineTo(6.0, 13.7);- chevrons.moveTo(10.6, 6.3);- chevrons.lineTo(14.3, 10.0);- chevrons.lineTo(10.6, 13.7);- if (right_side)- chevrons = horizontally_flipped_path(chevrons);- draw_stroked_icon_path(painter, chevrons, color, 1.7);- return;- }+ auto pixmap = create_transparent_icon_pixmap({ logical_size, logical_size }, device_pixel_ratio);- QPainterPath tab_bar;- tab_bar.addRoundedRect(QRectF(3.8, 4.2, 12.4, 11.6), 1.6, 1.6);- tab_bar.moveTo(7.8, 4.6);- tab_bar.lineTo(7.8, 15.4);+ QPainter painter(&pixmap);+ painter.setRenderHint(QPainter::Antialiasing, true);- QPainterPath arrow;- arrow.moveTo(13.1, 7.8);- arrow.lineTo(10.3, 10.0);- arrow.lineTo(13.1, 12.2);+ // An icon is drawn in one opaque color, then made as translucent as its color as a whole, so that where its lines+ // cross they don't add up to a brighter spot.+ auto opaque_color = color;+ opaque_color.setAlpha(255);++ // NB: The 1x drawing keeps the size of the 16 px canvas, so it is only used for icons shown at about that size. A+ // smaller icon, such as a badge's, is scaled from its vector.+ auto has_pixel_snapped_size = device_pixel_ratio == 1 && abs(logical_size - CHROME_ICON_CANVAS_SIZE) <= PIXEL_SNAPPED_ICON_SIZE_TOLERANCE;+ auto const* pixel_snapped_path = has_pixel_snapped_size ? chrome_icon_pixel_snapped_painter_path(icon) : nullptr;+ if (pixel_snapped_path) {+ // NB: The 1x drawing keeps its own pixels, so it is centered on whole pixels rather than scaled.+ auto offset = (logical_size - CHROME_ICON_CANVAS_SIZE) / 2;+ painter.translate(offset, offset);+ painter.setPen(QPen(opaque_color, pixel_snapped_chrome_icon(icon)->stroke_width, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));+ painter.setBrush(Qt::NoBrush);+ painter.drawPath(*pixel_snapped_path);+ } else {+ painter.scale(static_cast<qreal>(logical_size) / CHROME_ICON_CANVAS_SIZE, static_cast<qreal>(logical_size) / CHROME_ICON_CANVAS_SIZE);++ auto stroke_width = CHROME_ICON_STROKE_WIDTH;+ // NB: The window controls of Windows are drawn with hairlines, as the system draws its own.+ if (icon == ChromeIcon::WindowMinimize || icon == ChromeIcon::WindowMaximize || icon == ChromeIcon::WindowRestore || icon == ChromeIcon::WindowClose)+ stroke_width = 1.0;+ else if (design_size == TOOLBAR_ICON_SIZE)+ stroke_width = TOOLBAR_ICON_STROKE_WIDTH;++ painter.setPen(QPen(opaque_color, stroke_width, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));+ painter.setBrush(icon == ChromeIcon::StarFilled ? QBrush(opaque_color) : QBrush(Qt::NoBrush));+ painter.drawPath(path);+ }- if (right_side) {- tab_bar = horizontally_flipped_path(tab_bar);- arrow = horizontally_flipped_path(arrow);+ if (color.alpha() != 255) {+ painter.resetTransform();+ painter.setCompositionMode(QPainter::CompositionMode_DestinationIn);+ painter.fillRect(QRect(QPoint(), pixmap.size()), QColor(0, 0, 0, color.alpha()));}- draw_stroked_icon_path(painter, tab_bar, color, 1.55);- draw_stroked_icon_path(painter, arrow, color, 1.85);+ return pixmap;}-static void draw_globe_icon(QPainter& painter, QColor const& color)-{- auto outline_rect = QRectF(3.5, 3.5, 13, 13);- QRectF meridian_rect(7.5, outline_rect.top() + 0.25, 5.0, outline_rect.height() - 0.5);+// Draws a chrome icon from its vector for each size and device pixel ratio it is asked for.+class ChromeIconEngine final : public QIconEngine {+public:+ AK_ALLOC_WITH_KMALLOC;- QPainterPath path;- path.addEllipse(outline_rect);- path.moveTo(QPointF(outline_rect.left() + 1.3, 10));- path.lineTo(QPointF(outline_rect.right() - 1.3, 10));- path.arcMoveTo(meridian_rect, 90);- path.arcTo(meridian_rect, 90, 180);- path.arcMoveTo(meridian_rect, 270);- path.arcTo(meridian_rect, 270, 180);-- draw_stroked_icon_path(painter, path, color, 1.55);-}+ struct Colors {+ QColor normal;+ QColor active;+ QColor disabled;+ QColor selected;+ };-static void draw_volume_icon(QPainter& painter, QColor const& color, bool muted)-{- QPainterPath speaker;- speaker.setFillRule(Qt::WindingFill);-- speaker.moveTo(0.55, 14);- speaker.lineTo(4.55, 14);- speaker.lineTo(10.55, 19);- speaker.lineTo(10.55, 1);- speaker.lineTo(4.55, 6);- speaker.lineTo(0.55, 6);- speaker.closeSubpath();- painter.fillPath(speaker, color);-- if (muted) {- painter.drawLine(QPointF(1.5, 1.0), QPointF(18.5, 19.0));- return;+ ChromeIconEngine(ChromeIcon icon, QPainterPath path, Colors colors, int design_size)+ : m_icon(icon)+ , m_path(AK::move(path))+ , m_colors(AK::move(colors))+ , m_design_size(design_size)+ {}- QPainterPath inner_wave;- inner_wave.moveTo(12.55, 6);- inner_wave.lineTo(12.55, 14);- inner_wave.cubicTo(14.15, 14, 15.45, 12.21, 15.45, 10);- inner_wave.cubicTo(15.45, 7.79, 14.15, 6, 12.55, 6);- inner_wave.closeSubpath();- painter.fillPath(inner_wave, color);+ virtual QIconEngine* clone() const override { return new ChromeIconEngine(m_icon, m_path, m_colors, m_design_size); }- painter.setBrush(Qt::NoBrush);- painter.setPen(chrome_icon_pen(color, 1.6));- painter.drawArc(QRectF(7.85, 2.4, 10.8, 15.2), 90 * 16, -180 * 16);-}+ virtual QSize actualSize(QSize const& size, QIcon::Mode, QIcon::State) override+ {+ auto side = min(size.width(), size.height());+ return { side, side };+ }-static QPixmap create_transparent_icon_pixmap(QSize logical_size, qreal device_pixel_ratio)-{- QPixmap pixmap(physical_size_for_device_pixel_ratio(logical_size, device_pixel_ratio));- pixmap.setDevicePixelRatio(device_pixel_ratio);- pixmap.fill(Qt::transparent);- return pixmap;-}+ virtual QList<QSize> availableSizes(QIcon::Mode, QIcon::State) override { return { QSize(m_design_size, m_design_size) }; }++ virtual QPixmap pixmap(QSize const& size, QIcon::Mode mode, QIcon::State state) override+ {+ return scaledPixmap(size, mode, state, 1);+ }++ virtual QPixmap scaledPixmap(QSize const& size, QIcon::Mode mode, QIcon::State, qreal scale) override+ {+ auto side = min(size.width(), size.height());+ if (side <= 0)+ return {};+ return create_chrome_icon_pixmap(m_icon, m_path, color_for_mode(mode), scale, side, m_design_size);+ }++ virtual void paint(QPainter* painter, QRect const& rect, QIcon::Mode mode, QIcon::State state) override+ {+ auto side = min(rect.width(), rect.height());+ auto device_pixel_ratio = painter->device() ? painter->device()->devicePixelRatio() : 1;+ auto pixmap = scaledPixmap(QSize(side, side), mode, state, device_pixel_ratio);+ auto position = rect.topLeft() + QPoint((rect.width() - side) / 2, (rect.height() - side) / 2);+ painter->drawPixmap(position, pixmap);+ }++private:+ QColor color_for_mode(QIcon::Mode mode) const+ {+ switch (mode) {+ case QIcon::Active:+ return m_colors.active;+ case QIcon::Disabled:+ return m_colors.disabled;+ case QIcon::Selected:+ return m_colors.selected;+ case QIcon::Normal:+ break;+ }+ return m_colors.normal;+ }++ ChromeIcon m_icon;+ QPainterPath m_path;+ Colors m_colors;+ int m_design_size { CHROME_ICON_CANVAS_SIZE };+};QPixmap create_chrome_icon_pixmap(ChromeIcon icon, QColor color, qreal device_pixel_ratio){- auto pixmap = create_transparent_icon_pixmap({ CHROME_ICON_CANVAS_SIZE, CHROME_ICON_CANVAS_SIZE }, device_pixel_ratio);+ return create_chrome_icon_pixmap(icon, chrome_icon_painter_path(icon), color, device_pixel_ratio, CHROME_ICON_CANVAS_SIZE, CHROME_ICON_CANVAS_SIZE);+}- QPainter painter(&pixmap);- painter.setRenderHint(QPainter::Antialiasing, true);- painter.setPen(chrome_icon_pen(color, 1.7));+static QIcon create_chrome_icon(ChromeIcon icon, QPainterPath const& path, QPalette const& palette, ChromeStyle::WindowActivity activity, int logical_size)+{+ auto const& chrome = Theme::chrome(palette);+ // Toolbar buttons take the icon color. The controls inside the address field and the tabs are quieter.+ auto normal = chrome.icon;switch (icon) {- case ChromeIcon::Back:- draw_back_icon(painter, color);- break;- case ChromeIcon::Forward:- draw_forward_icon(painter, color);- break;- case ChromeIcon::Reload:- draw_reload_icon(painter, color);- break;- case ChromeIcon::Stop:- painter.setPen(chrome_icon_pen(color, 2.0));- painter.drawLine(QPointF(4.5, 4.5), QPointF(15.5, 15.5));- painter.drawLine(QPointF(15.5, 4.5), QPointF(4.5, 15.5));- break;- case ChromeIcon::NewTab:- painter.setPen(chrome_icon_pen(color, 1.9));- painter.drawLine(QPointF(10.0, 4.3), QPointF(10.0, 15.7));- painter.drawLine(QPointF(4.3, 10.0), QPointF(15.7, 10.0));- break;case ChromeIcon::Close:case ChromeIcon::TabClose:- painter.setPen(chrome_icon_pen(color, 1.9));- painter.drawLine(QPointF(5.5, 5.25), QPointF(14.5, 14.75));- painter.drawLine(QPointF(14.5, 5.25), QPointF(5.5, 14.75));- break;- case ChromeIcon::Menu:- painter.setPen(chrome_icon_pen(color, 1.55));- painter.drawLine(QPointF(4.1, 6.2), QPointF(15.9, 6.2));- painter.drawLine(QPointF(4.1, 10.0), QPointF(15.9, 10.0));- painter.drawLine(QPointF(4.1, 13.8), QPointF(15.9, 13.8));- break;+ case ChromeIcon::ContentBlocking:case ChromeIcon::Star:- draw_star_icon(painter, color, false);- break;case ChromeIcon::StarFilled:- draw_star_icon(painter, color, true);- break;+ case ChromeIcon::SiteSettings:case ChromeIcon::Search:- painter.setPen(chrome_icon_pen(color, 1.55));- painter.drawEllipse(QRectF(4.1, 4.0, 9.7, 9.7));- painter.drawLine(QPointF(12.0, 12.1), QPointF(15.9, 16.0));- break;case ChromeIcon::Globe:- draw_globe_icon(painter, color);- break;- case ChromeIcon::Folder: {- painter.setPen(chrome_icon_pen(color, 1.6));- QPainterPath path;- path.moveTo(2.8, 5.1);- path.lineTo(7.6, 5.1);- path.lineTo(9.2, 7.0);- path.lineTo(17.2, 7.0);- path.quadTo(18.0, 7.0, 18.0, 7.8);- path.lineTo(18.0, 14.1);- path.quadTo(18.0, 14.9, 17.2, 14.9);- path.lineTo(2.8, 14.9);- path.quadTo(2.0, 14.9, 2.0, 14.1);- path.lineTo(2.0, 5.9);- path.quadTo(2.0, 5.1, 2.8, 5.1);- path.closeSubpath();- painter.drawPath(path);- break;- }- case ChromeIcon::Download:- case ChromeIcon::DownloadActive: {- painter.setPen(chrome_icon_pen(color, 1.75));- painter.drawLine(QPointF(10.0, 3.4), QPointF(10.0, 12.0));- painter.drawLine(QPointF(6.6, 8.7), QPointF(10.0, 12.1));- painter.drawLine(QPointF(13.4, 8.7), QPointF(10.0, 12.1));-- QPainterPath tray;- tray.moveTo(4.0, 13.4);- tray.lineTo(4.0, 15.7);- tray.quadTo(4.0, 16.6, 4.9, 16.6);- tray.lineTo(15.1, 16.6);- tray.quadTo(16.0, 16.6, 16.0, 15.7);- tray.lineTo(16.0, 13.4);- painter.drawPath(tray);- break;- }case ChromeIcon::Volume:- draw_volume_icon(painter, color, false);- break;case ChromeIcon::VolumeMuted:- draw_volume_icon(painter, color, true);- break;- case ChromeIcon::ChevronUp:- painter.setPen(chrome_icon_pen(color, 1.85));- painter.drawLine(QPointF(5.0, 12.5), QPointF(10.0, 7.5));- painter.drawLine(QPointF(10.0, 7.5), QPointF(15.0, 12.5));- break;- case ChromeIcon::ContentBlocking:- draw_content_blocking_icon(painter, color);- break;- case ChromeIcon::ChevronDown:- painter.setPen(chrome_icon_pen(color, 1.85));- painter.drawLine(QPointF(5.0, 7.5), QPointF(10.0, 12.5));- painter.drawLine(QPointF(10.0, 12.5), QPointF(15.0, 7.5));- break;- case ChromeIcon::VerticalTabBarCollapse:- draw_vertical_tab_bar_icon(painter, color, true, false);- break;- case ChromeIcon::VerticalTabBarCollapseRight:- draw_vertical_tab_bar_icon(painter, color, true, true);- break;- case ChromeIcon::VerticalTabBarExpand:- draw_vertical_tab_bar_icon(painter, color, false, false);+ normal = chrome.muted;break;- case ChromeIcon::VerticalTabBarExpandRight:- draw_vertical_tab_bar_icon(painter, color, false, true);- break;- case ChromeIcon::WindowMinimize:- painter.setPen(chrome_icon_pen(color, 1.65));- painter.drawLine(QPointF(5.2, 10.0), QPointF(14.8, 10.0));- break;- case ChromeIcon::WindowMaximize:- painter.setPen(chrome_icon_pen(color, 1.55));- painter.drawRoundedRect(QRectF(5.0, 5.0, 10.0, 10.0), 1.4, 1.4);- break;- case ChromeIcon::WindowRestore:- painter.setPen(chrome_icon_pen(color, 1.55));- painter.drawRoundedRect(QRectF(5.1, 7.0, 7.9, 7.9), 1.2, 1.2);- painter.drawLine(QPointF(7.2, 5.1), QPointF(14.9, 5.1));- painter.drawLine(QPointF(14.9, 5.1), QPointF(14.9, 12.9));- break;- case ChromeIcon::WindowClose:- painter.setPen(chrome_icon_pen(color, 1.65));- painter.drawLine(QPointF(5.5, 5.5), QPointF(14.5, 14.5));- painter.drawLine(QPointF(14.5, 5.5), QPointF(5.5, 14.5));+ default:break;}+ if (icon == ChromeIcon::StarFilled)+ normal = chrome.icon;+ // An inactive window's chrome icons drop to the muted color.+ if (activity == ChromeStyle::WindowActivity::Inactive)+ normal = chrome.muted;- return pixmap;+ return QIcon(new ChromeIconEngine(icon, path, { normal, chrome.icon, chrome.disabled, chrome.icon }, logical_size));}-QIcon create_chrome_icon(ChromeIcon icon, QPalette const& palette)+QIcon create_chrome_icon(ChromeIcon icon, QPalette const& palette, ChromeStyle::WindowActivity activity, int logical_size){- auto normal = ChromeStyle::chrome_button_text(palette);- auto normal_alpha = 216;- if (icon == ChromeIcon::DownloadActive) {- normal = ChromeStyle::chrome_accent();- normal_alpha = 244;- } else if (icon == ChromeIcon::Close || icon == ChromeIcon::TabClose)- normal_alpha = 172;- else if (icon == ChromeIcon::Star)- normal_alpha = 204;- else if (icon == ChromeIcon::Globe || icon == ChromeIcon::Search || icon == ChromeIcon::Menu || icon == ChromeIcon::ContentBlocking)- normal_alpha = 188;- normal.setAlpha(normal_alpha);-- auto active = ChromeStyle::chrome_button_text(palette);- active.setAlpha(icon == ChromeIcon::Close || icon == ChromeIcon::TabClose ? 220 : 236);-- auto disabled = ChromeStyle::chrome_muted_text(palette);- disabled.setAlpha(icon == ChromeIcon::Close || icon == ChromeIcon::TabClose ? 78 : 82);-- QIcon qicon;-- for (auto device_pixel_ratio : ICON_DEVICE_PIXEL_RATIOS) {- qicon.addPixmap(create_chrome_icon_pixmap(icon, normal, device_pixel_ratio), QIcon::Normal);- qicon.addPixmap(create_chrome_icon_pixmap(icon, active, device_pixel_ratio), QIcon::Active);- qicon.addPixmap(create_chrome_icon_pixmap(icon, disabled, device_pixel_ratio), QIcon::Disabled);- qicon.addPixmap(create_chrome_icon_pixmap(icon, active, device_pixel_ratio), QIcon::Selected);- }-- return qicon;+ return create_chrome_icon(icon, chrome_icon_painter_path(icon), palette, activity, logical_size);}-static QPixmap create_loading_spinner_icon_pixmap(QPalette const& palette, int frame, int device_pixel_ratio)+// The icon is two lines, each with a knob on it, the top one to the right and the bottom one to the left. The knobs+// slide past each other as the travel goes from 0 to 1, and each line breaks around its knob.+QIcon create_site_settings_icon(QPalette const& palette, qreal knob_travel){- static constexpr int icon_size = 16;- static constexpr int segment_count = 12;+ static constexpr qreal LINE_START = 2.5;+ static constexpr qreal LINE_END = 13.5;+ static constexpr qreal KNOB_RADIUS = 1.6;+ static constexpr qreal KNOB_GAP = 2;+ static constexpr qreal KNOB_TRAVEL = 5;- auto pixmap = create_transparent_icon_pixmap({ icon_size, icon_size }, device_pixel_ratio);-- QPainter painter(&pixmap);- painter.setRenderHint(QPainter::Antialiasing);- painter.translate(icon_size / 2.0, icon_size / 2.0);-- auto color = ChromeStyle::chrome_text(palette);- for (int segment = 0; segment < segment_count; ++segment) {- auto segment_color = color;- segment_color.setAlpha(((segment - frame + segment_count) % segment_count + 1) * 255 / segment_count);-- painter.save();- painter.rotate(segment * 360.0 / segment_count);- painter.setPen(QPen(segment_color, 1.5, Qt::SolidLine, Qt::RoundCap));- painter.drawLine(QPointF(0, -4), QPointF(0, -7));- painter.restore();- }+ QPainterPath path;+ auto add_line_with_knob = [&](qreal y, qreal knob_x) {+ if (knob_x - KNOB_GAP > LINE_START) {+ path.moveTo(LINE_START, y);+ path.lineTo(knob_x - KNOB_GAP, y);+ }+ if (knob_x + KNOB_GAP < LINE_END) {+ path.moveTo(knob_x + KNOB_GAP, y);+ path.lineTo(LINE_END, y);+ }+ path.addEllipse(QPointF(knob_x, y), KNOB_RADIUS, KNOB_RADIUS);+ };+ add_line_with_knob(5, 10.5 - (KNOB_TRAVEL * knob_travel));+ add_line_with_knob(11, 5.5 + (KNOB_TRAVEL * knob_travel));- return pixmap;+ return create_chrome_icon(ChromeIcon::SiteSettings, path, palette, ChromeStyle::WindowActivity::Active, CHROME_ICON_CANVAS_SIZE);}-QIcon loading_spinner_icon(QPalette const& palette, int frame)+QIcon create_chrome_icon(ChromeIcon icon, QColor const& color){- QIcon icon;- for (auto device_pixel_ratio : ICON_DEVICE_PIXEL_RATIOS)- icon.addPixmap(create_loading_spinner_icon_pixmap(palette, frame, device_pixel_ratio));- return icon;+ return QIcon(new ChromeIconEngine(icon, chrome_icon_painter_path(icon), { color, color, color, color }, CHROME_ICON_CANVAS_SIZE));}QSize physical_size_for_device_pixel_ratio(QSize size, qreal device_pixel_ratio)@@ -505,4 +667,26 @@ QSize physical_size_for_device_pixel_ratio(QSize size, qreal device_pixel_ratio)};}+// The logomark traces x = sin 2t, y = sin 3t, scaled 179 : 145, on a box of 22 by 18.4 around its middle.+static constexpr auto LOGOMARK_PATH = "M0 0 L1.39 1.68 L2.76 3.29 L4.07 4.76 L5.30 6.02 L6.43 7.02 L7.43 7.70 L8.29 8.06 L8.99 8.06 L9.51 7.70 L9.85 7.02 L9.99 6.02 L9.95 4.76 L9.70 3.29 L9.27 1.68 L8.66 0 L7.88 -1.68 L6.95 -3.29 L5.88 -4.76 L4.69 -6.02 L3.42 -7.02 L2.08 -7.70 L0.70 -8.06 L-0.70 -8.06 L-2.08 -7.70 L-3.42 -7.02 L-4.69 -6.02 L-5.88 -4.76 L-6.95 -3.29 L-7.88 -1.68 L-8.66 0 L-9.27 1.68 L-9.70 3.29 L-9.95 4.76 L-9.99 6.02 L-9.85 7.02 L-9.51 7.70 L-8.99 8.06 L-8.29 8.06 L-7.43 7.70 L-6.43 7.02 L-5.30 6.02 L-4.07 4.76 L-2.76 3.29 L-1.39 1.68 L0 0 L1.39 -1.68 L2.76 -3.29 L4.07 -4.76 L5.30 -6.02 L6.43 -7.02 L7.43 -7.70 L8.29 -8.06 L8.99 -8.06 L9.51 -7.70 L9.85 -7.02 L9.99 -6.02 L9.95 -4.76 L9.70 -3.29 L9.27 -1.68 L8.66 0 L7.88 1.68 L6.95 3.29 L5.88 4.76 L4.69 6.02 L3.42 7.02 L2.08 7.70 L0.70 8.06 L-0.70 8.06 L-2.08 7.70 L-3.42 7.02 L-4.69 6.02 L-5.88 4.76 L-6.95 3.29 L-7.88 1.68 L-8.66 0 L-9.27 -1.68 L-9.70 -3.29 L-9.95 -4.76 L-9.99 -6.02 L-9.85 -7.02 L-9.51 -7.70 L-8.99 -8.06 L-8.29 -8.06 L-7.43 -7.70 L-6.43 -7.02 L-5.30 -6.02 L-4.07 -4.76 L-2.76 -3.29 L-1.39 -1.68 Z"sv;+static constexpr QRectF LOGOMARK_BOUNDS { -11, -9.2, 22, 18.4 };++void paint_logomark(QPainter& painter, QRectF const& rect, QColor const& color, qreal stroke_width)+{+ static auto const path = parse_svg_path(LOGOMARK_PATH);++ // NB: The stroke width is given on the logomark's own box, as the design gives it, so it scales along with the path.+ auto scale = min(rect.width() / LOGOMARK_BOUNDS.width(), rect.height() / LOGOMARK_BOUNDS.height());++ painter.save();+ painter.setRenderHint(QPainter::Antialiasing, true);+ painter.translate(rect.center());+ painter.scale(scale, scale);+ painter.translate(-LOGOMARK_BOUNDS.center());+ painter.setBrush(Qt::NoBrush);+ painter.setPen(QPen(color, stroke_width, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));+ painter.drawPath(path);+ painter.restore();+}+}diff --git a/UI/Qt/Icon.h b/UI/Qt/Icon.hindex 3822a21cb48..f81d314569f 100644--- a/UI/Qt/Icon.h+++ b/UI/Qt/Icon.h@@ -9,13 +9,16 @@#include <AK/Array.h>#include <AK/Span.h>#include <AK/StringView.h>+#include <UI/Qt/ChromeStyle.h>#include <QColor>#include <QIcon>#include <QPixmap>#include <QSize>+class QPainter;class QPalette;+class QRectF;namespace Ladybird {@@ -34,16 +37,25 @@ enum class ChromeIcon {Globe,Folder,Download,- DownloadActive,Volume,VolumeMuted,ChevronUp,ChevronDown,ContentBlocking,- VerticalTabBarCollapse,- VerticalTabBarCollapseRight,- VerticalTabBarExpand,- VerticalTabBarExpandRight,+ SiteSettings,+ Microphone,+ SelectArea,+ CheckCircle,+ Document,+ Network,+ Compositor,+ Image,+ Pin,+ Warning,+ Pause,+ ZoomOut,+ Sidebar,+ SidebarRight,WindowMinimize,WindowMaximize,WindowRestore,@@ -51,17 +63,26 @@ enum class ChromeIcon {};constexpr inline auto ICON_DEVICE_PIXEL_RATIOS = to_array({ 1, 2, 3 });-// Chrome icons are drawn on a canvas of this size, with room around their shapes.-constexpr inline int CHROME_ICON_CANVAS_SIZE = 20;+// Chrome icons are drawn on a canvas of this size.+constexpr inline int CHROME_ICON_CANVAS_SIZE = 16;+// The toolbar's buttons show their icons larger than the controls inside the address field.+constexpr inline int TOOLBAR_ICON_SIZE = 18;QIcon load_icon_from_uri(StringView);QIcon icon_from_png(ReadonlyBytes, int logical_size);QPixmap favicon_with_rounded_corners(QPixmap const&);QIcon favicon_with_rounded_corners(QIcon const&, int logical_size);-QIcon create_chrome_icon(ChromeIcon, QPalette const&);+QIcon create_chrome_icon(ChromeIcon, QPalette const&, ChromeStyle::WindowActivity = ChromeStyle::WindowActivity::Active, int logical_size = CHROME_ICON_CANVAS_SIZE);+// The site settings icon with its two knobs moved toward each other's place, by a travel from 0 to 1.+QIcon create_site_settings_icon(QPalette const&, qreal knob_travel);+// The icon in one color, whatever its state.+QIcon create_chrome_icon(ChromeIcon, QColor const&);QPixmap create_chrome_icon_pixmap(ChromeIcon, QColor, qreal device_pixel_ratio);-QIcon loading_spinner_icon(QPalette const& palette, int frame);QSize physical_size_for_device_pixel_ratio(QSize size, qreal device_pixel_ratio);+// Strokes Ladybird's logomark, a Lissajous figure, to fill the given rect. The stroke width is on the logomark's own+// 22 by 18.4 box.+void paint_logomark(QPainter&, QRectF const&, QColor const&, qreal stroke_width);+}diff --git a/UI/Qt/JavaScriptDialog.cpp b/UI/Qt/JavaScriptDialog.cppindex d85e75684b7..19e4f8c7f7f 100644--- a/UI/Qt/JavaScriptDialog.cpp+++ b/UI/Qt/JavaScriptDialog.cpp@@ -5,16 +5,29 @@*/#include <UI/Qt/ChromeStyle.h>+#include <UI/Qt/Icon.h>#include <UI/Qt/JavaScriptDialog.h>+#include <UI/Qt/Motion.h>#include <UI/Qt/NativeTextEditingLineEdit.h>+#include <UI/Qt/Popover.h>+#include <UI/Qt/SystemAppearance.h>+#include <UI/Qt/Theme.h>+#if defined(AK_OS_MACOS)+# include <UI/Qt/MacWindow.h>+#endif#include <AK/Platform.h>#include <AK/StdLibExtras.h>#include <QApplication>+#include <QCheckBox>#include <QDialogButtonBox>#include <QEvent>#include <QFocusEvent>#include <QFrame>+#include <QGraphicsDropShadowEffect>+#include <QGraphicsOpacityEffect>+#include <QHBoxLayout>+#include <QIcon>#include <QKeyEvent>#include <QLabel>#include <QLineEdit>@@ -24,14 +37,19 @@#include <QShortcut>#include <QShowEvent>#include <QVBoxLayout>+#include <QVariantAnimation>namespace Ladybird {-static constexpr int DIALOG_MAX_WIDTH = 520;-static constexpr int DIALOG_MIN_WIDTH = 320;+// The dialog is a sheet that hangs from the top of the page, over a dimmed page.+static constexpr int DIALOG_WIDTH = 440;static constexpr int DIALOG_MAX_MESSAGE_HEIGHT = 240;static constexpr int DIALOG_MARGIN = 24;static constexpr int PANEL_HORIZONTAL_PADDING = 20;+#if defined(AK_OS_MACOS)+static constexpr int PANEL_CORNER_RADIUS = 12;+#endif+static constexpr int OPENING_SLIDE_DISTANCE = 12;JavaScriptDialog::JavaScriptDialog(QWidget* parent): QWidget(parent)@@ -39,7 +57,11 @@ JavaScriptDialog::JavaScriptDialog(QWidget* parent)setObjectName("LadybirdJavaScriptDialogOverlay");setCursor(Qt::ArrowCursor);setAttribute(Qt::WA_StyledBackground);-#if defined(AK_OS_MACOS) || defined(USE_DIRECTX) || defined(USE_VULKAN_DMABUF_IMAGES)+#if defined(AK_OS_MACOS)+ // NB: The page is presented above anything Qt paints over it, and a native view over it cannot let it show through.+ // So only the sheet is a native view, with its shadow cast by another, and the page view dims the page itself.+ // This overlay only takes the input meant for the page.+#elif defined(USE_DIRECTX) || defined(USE_VULKAN_DMABUF_IMAGES)// Native rendering surfaces stack above ordinary child widgets. Match their native stacking level so the dialog// remains above the page.setAttribute(Qt::WA_DontCreateNativeAncestors);@@ -53,21 +75,37 @@ JavaScriptDialog::JavaScriptDialog(QWidget* parent)QApplication::instance()->installEventFilter(this);auto* overlay_layout = new QVBoxLayout(this);- overlay_layout->setContentsMargins(DIALOG_MARGIN, DIALOG_MARGIN, DIALOG_MARGIN, DIALOG_MARGIN);- overlay_layout->addStretch();+ overlay_layout->setContentsMargins(DIALOG_MARGIN, 0, DIALOG_MARGIN, DIALOG_MARGIN);m_panel = new QFrame(this);m_panel->setObjectName("LadybirdJavaScriptDialogPanel");m_panel->setAttribute(Qt::WA_StyledBackground);m_panel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);+#if defined(AK_OS_MACOS)+ m_panel->setAttribute(Qt::WA_DontCreateNativeAncestors);+ m_panel->setAttribute(Qt::WA_NativeWindow);+ m_panel_floating_shadow = &cast_floating_shadow(*m_panel, PANEL_CORNER_RADIUS, FloatingShadowTone::FollowTheme, FloatingShadowKind::Sheet);+#else+ m_panel_shadow = new QGraphicsDropShadowEffect(m_panel);+ m_panel_shadow->setBlurRadius(ChromeStyle::drop_shadow_blur_radius(40));+ m_panel_shadow->setOffset(0, 18);+ m_panel->setGraphicsEffect(m_panel_shadow);+#endifauto* panel_layout = new QVBoxLayout(m_panel);- panel_layout->setContentsMargins(PANEL_HORIZONTAL_PADDING, 18, PANEL_HORIZONTAL_PADDING, 18);+ panel_layout->setContentsMargins(PANEL_HORIZONTAL_PADDING, 18, PANEL_HORIZONTAL_PADDING, 16);panel_layout->setSpacing(12);+ // The site's icon, then who is asking.+ auto* title_layout = new QHBoxLayout;+ title_layout->setSpacing(8);+ m_title_icon = new QLabel(m_panel);+ m_title_icon->setFixedSize(16, 16);+ title_layout->addWidget(m_title_icon);m_title_label = new QLabel(m_panel);m_title_label->setObjectName("LadybirdJavaScriptDialogTitle");- panel_layout->addWidget(m_title_label);+ title_layout->addWidget(m_title_label, 1);+ panel_layout->addLayout(title_layout);m_message_scroll_area = new QScrollArea(m_panel);m_message_scroll_area->setObjectName("LadybirdJavaScriptDialogMessageArea");@@ -91,11 +129,15 @@ JavaScriptDialog::JavaScriptDialog(QWidget* parent)m_prompt_text->setObjectName("LadybirdJavaScriptDialogPrompt");panel_layout->addWidget(m_prompt_text);+ m_block_further_dialogs = new PopoverCheckBox("Don't let this site show more dialogs", m_panel);+ m_block_further_dialogs->setObjectName("LadybirdJavaScriptDialogBlockFurtherDialogs");+ panel_layout->addWidget(m_block_further_dialogs);+m_button_box = new QDialogButtonBox(m_panel);m_button_box->setObjectName("LadybirdJavaScriptDialogButtons");panel_layout->addWidget(m_button_box);- overlay_layout->addWidget(m_panel, 0, Qt::AlignHCenter);+ overlay_layout->addWidget(m_panel, 0, Qt::AlignHCenter | Qt::AlignTop);overlay_layout->addStretch();QObject::connect(m_button_box, &QDialogButtonBox::accepted, this, [this] {@@ -114,9 +156,9 @@ JavaScriptDialog::JavaScriptDialog(QWidget* parent)hide();}-void JavaScriptDialog::show_alert(QString const& title, QString const& message)+void JavaScriptDialog::show_alert(QString const& title, QString const& message, OfferToBlockFurtherDialogs offer_to_block_further_dialogs){- open(Type::Alert, title, message);+ open(Type::Alert, title, message, {}, offer_to_block_further_dialogs);}void JavaScriptDialog::show_before_unload(QString const& title)@@ -124,17 +166,29 @@ void JavaScriptDialog::show_before_unload(QString const& title)open(Type::BeforeUnload, title, "Leave this page? Your changes may not be saved.");}-void JavaScriptDialog::show_confirm(QString const& title, QString const& message)+void JavaScriptDialog::show_confirm(QString const& title, QString const& message, OfferToBlockFurtherDialogs offer_to_block_further_dialogs)+{+ open(Type::Confirm, title, message, {}, offer_to_block_further_dialogs);+}++void JavaScriptDialog::show_prompt(QString const& title, QString const& message, QString const& default_text, OfferToBlockFurtherDialogs offer_to_block_further_dialogs){- open(Type::Confirm, title, message);+ open(Type::Prompt, title, message, default_text, offer_to_block_further_dialogs);}-void JavaScriptDialog::show_prompt(QString const& title, QString const& message, QString const& default_text)+void JavaScriptDialog::set_title_icon(QIcon const& icon){- open(Type::Prompt, title, message, default_text);+ // Like the tab strip, a site without an icon gets the globe.+ auto const& shown_icon = icon.isNull() ? create_chrome_icon(ChromeIcon::Globe, Theme::panel().muted) : icon;+ m_title_icon->setPixmap(shown_icon.pixmap(QSize(16, 16), devicePixelRatioF()));}-void JavaScriptDialog::open(Type type, QString const& title, QString const& message, QString const& default_text)+bool JavaScriptDialog::blocks_further_dialogs() const+{+ return !m_block_further_dialogs->isHidden() && m_block_further_dialogs->isChecked();+}++void JavaScriptDialog::open(Type type, QString const& title, QString const& message, QString const& default_text, OfferToBlockFurtherDialogs offer_to_block_further_dialogs){if (m_type.has_value())return;@@ -148,6 +202,8 @@ void JavaScriptDialog::open(Type type, QString const& title, QString const& messm_message_label->setText(message);m_prompt_text->setVisible(type == Type::Prompt);m_prompt_text->setText(default_text);+ m_block_further_dialogs->setChecked(false);+ m_block_further_dialogs->setVisible(offer_to_block_further_dialogs == OfferToBlockFurtherDialogs::Yes);QDialogButtonBox::StandardButtons buttons { QDialogButtonBox::Ok };if (type != Type::Alert)@@ -232,13 +288,19 @@ void JavaScriptDialog::restore_focus_after_close(){auto* focus_widget = QApplication::focusWidget();auto dialog_had_focus = focus_widget == this || isAncestorOf(focus_widget);- hide();restore_parent_focus_policy();auto previous_focus_widget = m_previous_focus_widget;m_previous_focus_widget = nullptr;- if (dialog_had_focus && previous_focus_widget && previous_focus_widget->isVisible())- previous_focus_widget->setFocus();+ // NB: The focus moves before the dialog hides, since hiding it would hand the focus to the next widget in the chain.+ // Without a widget to return to, the page the dialog came from takes the focus.+ if (dialog_had_focus) {+ if (previous_focus_widget && previous_focus_widget->isVisible())+ previous_focus_widget->setFocus();+ else if (parentWidget()->focusPolicy() != Qt::NoFocus)+ parentWidget()->setFocus();+ }+ hide();}bool JavaScriptDialog::event(QEvent* event)@@ -361,11 +423,67 @@ void JavaScriptDialog::resizeEvent(QResizeEvent* event)void JavaScriptDialog::showEvent(QShowEvent* event){QWidget::showEvent(event);++#if defined(AK_OS_MACOS)+ round_appkit_view_bottom_corners(*m_panel, PANEL_CORNER_RADIUS);+#endif++ // The sheet slides 12 px down from the toolbar as it fades in, over the page as it dims. It only fades in if the+ // system asks for less motion.+ if (!m_opening_animation) {+ m_opening_animation = new QVariantAnimation(this);+ m_opening_animation->setDuration(Motion::BASE);+ m_opening_animation->setEasingCurve(Motion::enter_easing());+ m_opening_animation->setStartValue(0.0);+ m_opening_animation->setEndValue(1.0);+ QObject::connect(m_opening_animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ set_opening_progress(value.toReal());+ });+ }+update_geometry_constraints();raise();+ set_opening_progress(0);+ m_opening_animation->stop();+ m_opening_animation->start();focus_dialog();}+void JavaScriptDialog::hideEvent(QHideEvent* event)+{+ QWidget::hideEvent(event);+ if (m_opening_animation)+ m_opening_animation->stop();+ if (on_page_dim_change)+ on_page_dim_change(0);+}++void JavaScriptDialog::set_opening_progress(qreal progress)+{+ // NB: The sheet is placed by the layout, and slides from there.+ layout()->activate();+ auto offset = SystemAppearance::prefers_reduced_motion() ? 0 : qRound(-OPENING_SLIDE_DISTANCE * (1 - progress));+ m_panel->move(m_panel->x(), layout()->contentsMargins().top() + offset);++#if defined(AK_OS_MACOS)+ set_appkit_view_opacity(*m_panel, progress);+ set_floating_window_opacity(*m_panel_floating_shadow, progress);+ if (on_page_dim_change)+ on_page_dim_change(progress);+#else+ if (progress >= 1.0) {+ setGraphicsEffect(nullptr);+ } else {+ auto* effect = qobject_cast<QGraphicsOpacityEffect*>(graphicsEffect());+ if (!effect) {+ effect = new QGraphicsOpacityEffect(this);+ setGraphicsEffect(effect);+ }+ effect->setOpacity(progress);+ }+#endif+}+void JavaScriptDialog::focus_dialog(){if (!m_type.has_value())@@ -388,17 +506,20 @@ void JavaScriptDialog::update_chrome_style()m_is_updating_chrome_style = true;setStyleSheet(ChromeStyle::javascript_dialog_style_sheet(palette()));+#if !defined(AK_OS_MACOS)+ if (m_panel_shadow)+ m_panel_shadow->setColor(QColor(0, 0, 0, Theme::is_dark() ? 140 : 56));+#endifm_is_updating_chrome_style = false;}void JavaScriptDialog::update_geometry_constraints(){- auto available_width = max(0, width() - DIALOG_MARGIN * 2);- m_panel->setMinimumWidth(min(DIALOG_MIN_WIDTH, available_width));- m_panel->setMaximumWidth(min(DIALOG_MAX_WIDTH, available_width));+ // The panel is as wide as the design's, unless the view is too narrow for it.+ auto panel_width = min(DIALOG_WIDTH, max(0, width() - DIALOG_MARGIN * 2));+ m_panel->setFixedWidth(panel_width);- auto maximum_message_width = max(1, available_width - PANEL_HORIZONTAL_PADDING * 2);- auto message_width = max(1, min(m_message_scroll_area->width(), maximum_message_width));+ auto message_width = max(1, panel_width - PANEL_HORIZONTAL_PADDING * 2);auto desired_message_height = max(0, m_message_label->heightForWidth(message_width));m_message_label->setMinimumHeight(desired_message_height);diff --git a/UI/Qt/JavaScriptDialog.h b/UI/Qt/JavaScriptDialog.hindex 9714e48ff1f..1d9a3b8c3e4 100644--- a/UI/Qt/JavaScriptDialog.h+++ b/UI/Qt/JavaScriptDialog.h@@ -13,11 +13,15 @@#include <QPointer>#include <QWidget>+class QCheckBox;class QDialogButtonBox;class QFrame;+class QGraphicsDropShadowEffect;+class QIcon;class QLabel;class QLineEdit;class QScrollArea;+class QVariantAnimation;namespace Ladybird {@@ -32,21 +36,33 @@ public:Prompt,};+ // From a page's second dialog on, the dialog offers to stop the page from showing more.+ enum class OfferToBlockFurtherDialogs : bool {+ No,+ Yes,+ };+explicit JavaScriptDialog(QWidget* parent);bool is_open() const { return m_type.has_value(); }Optional<Type> type() const { return m_type; }- void show_alert(QString const& title, QString const& message);+ void show_alert(QString const& title, QString const& message, OfferToBlockFurtherDialogs = OfferToBlockFurtherDialogs::No);void show_before_unload(QString const& title);- void show_confirm(QString const& title, QString const& message);- void show_prompt(QString const& title, QString const& message, QString const& default_text);+ void show_confirm(QString const& title, QString const& message, OfferToBlockFurtherDialogs = OfferToBlockFurtherDialogs::No);+ void show_prompt(QString const& title, QString const& message, QString const& default_text, OfferToBlockFurtherDialogs = OfferToBlockFurtherDialogs::No);void set_prompt_text(QString const& text);+ // The icon of the site the dialogs come from, shown before the title.+ void set_title_icon(QIcon const&);+ // Whether the user asked, in the dialog that is open or that just closed, to block the page's further dialogs.+ bool blocks_further_dialogs() const;void accept();void dismiss();void reset();Function<void(Type, bool accepted, QString const& prompt_text)> on_complete;+ // Dims the page under the dialog, from 0 for not at all to 1 for fully.+ Function<void(qreal)> on_page_dim_change;protected:virtual bool event(QEvent*) override;@@ -54,11 +70,12 @@ protected:virtual bool focusNextPrevChild(bool next) override;virtual void resizeEvent(QResizeEvent*) override;virtual void showEvent(QShowEvent*) override;+ virtual void hideEvent(QHideEvent*) override;private:bool is_dialog_widget(QWidget const&) const;bool is_blocked_content_widget(QWidget const&) const;- void open(Type, QString const& title, QString const& message, QString const& default_text = {});+ void open(Type, QString const& title, QString const& message, QString const& default_text = {}, OfferToBlockFurtherDialogs = OfferToBlockFurtherDialogs::No);void complete(bool accepted);void focus_dialog();void restore_focus_after_close();@@ -68,14 +85,23 @@ private:Optional<Type> m_type;QFrame* m_panel { nullptr };+#if defined(AK_OS_MACOS)+ QWidget* m_panel_floating_shadow { nullptr };+#else+ QGraphicsDropShadowEffect* m_panel_shadow { nullptr };+#endif+ QLabel* m_title_icon { nullptr };QLabel* m_title_label { nullptr };QLabel* m_message_label { nullptr };QScrollArea* m_message_scroll_area { nullptr };QLineEdit* m_prompt_text { nullptr };+ QCheckBox* m_block_further_dialogs { nullptr };QDialogButtonBox* m_button_box { nullptr };QPointer<QWidget> m_previous_focus_widget;Optional<Qt::FocusPolicy> m_parent_focus_policy;bool m_is_updating_chrome_style { false };+ QVariantAnimation* m_opening_animation { nullptr };+ void set_opening_progress(qreal);};}diff --git a/UI/Qt/LadybirdButton.cpp b/UI/Qt/LadybirdButton.cppnew file mode 100644index 00000000000..f69cfde4b12--- /dev/null+++ b/UI/Qt/LadybirdButton.cpp@@ -0,0 +1,261 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/GenericShorthands.h>+#include <LibWebView/Application.h>+#include <UI/Qt/ChromeStyle.h>+#include <UI/Qt/Icon.h>+#include <UI/Qt/LadybirdButton.h>+#include <UI/Qt/Motion.h>+#include <UI/Qt/SystemAppearance.h>+#include <UI/Qt/Theme.h>++#include <QFocusEvent>+#include <QKeyEvent>+#include <QMenu>+#include <QMouseEvent>+#include <QPainter>+#include <QPainterPath>+#include <QVariantAnimation>++namespace Ladybird {++static constexpr int TILE_HEIGHT = 26;+static constexpr qreal TILE_RADIUS = 7;+// NB: The button is as tall as the tab row it sits in on the strip.+static constexpr int TILE_VERTICAL_MARGIN = 4;+// The tile holds the mark and a menu chevron, padded a little more before the mark than after the chevron.+static constexpr qreal TILE_LEADING_PADDING = 7;+static constexpr qreal TILE_TRAILING_PADDING = 6;+static constexpr qreal MARK_CHEVRON_GAP = 3;+static constexpr QSizeF LOGOMARK_SIZE { 20, 16.7 };+static constexpr qreal LOGOMARK_STROKE_WIDTH = 1.55;+static constexpr qreal PRIVATE_GLYPH_SIZE = 20;+static constexpr qreal CHEVRON_SIZE = 10;+// How deep the tile's fill is under the pointer, and while pressed or while the menu is open. At rest it has none, only+// its hairline, so it doesn't read as stuck in a hover.+static constexpr qreal HOVERED_FILL = 0.75;+static constexpr qreal PRESSED_FILL = 1;++static qreal mark_width(WebView::IsPrivate is_private)+{+ return is_private == WebView::IsPrivate::Yes ? PRIVATE_GLYPH_SIZE : LOGOMARK_SIZE.width();+}++static QSize tile_size(WebView::IsPrivate is_private)+{+ auto width = TILE_LEADING_PADDING + mark_width(is_private) + MARK_CHEVRON_GAP + CHEVRON_SIZE + TILE_TRAILING_PADDING;+ return { static_cast<int>(ceil(width)), TILE_HEIGHT };+}++// The menu chevron points down, drawn in a 16 px box scaled to its size.+static void paint_chevron(QPainter& painter, QPointF center, QColor const& color)+{+ QPainterPath chevron;+ chevron.moveTo(4, 6.5);+ chevron.lineTo(8, 10.5);+ chevron.lineTo(12, 6.5);++ painter.save();+ painter.translate(center - QPointF(CHEVRON_SIZE / 2, CHEVRON_SIZE / 2));+ painter.scale(CHEVRON_SIZE / 16, CHEVRON_SIZE / 16);+ painter.setBrush(Qt::NoBrush);+ painter.setPen(QPen(color, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));+ painter.drawPath(chevron);+ painter.restore();+}++// The private glyph is a domino mask with its eye holes cut out, drawn in a 16 px box scaled to its size.+static void paint_private_glyph(QPainter& painter, QPointF center, QColor const& color)+{+ QPainterPath glyph;+ glyph.setFillRule(Qt::OddEvenFill);+ glyph.moveTo(8, 5.3);+ glyph.cubicTo(9.7, 4.5, 12, 4.1, 13.9, 4.4);+ glyph.cubicTo(14.8, 4.6, 15.1, 5.4, 15, 6.6);+ glyph.cubicTo(14.8, 9.6, 13.5, 11.8, 11.2, 11.8);+ glyph.cubicTo(9.8, 11.8, 8.9, 10.9, 8, 9.9);+ glyph.cubicTo(7.1, 10.9, 6.2, 11.8, 4.8, 11.8);+ glyph.cubicTo(2.5, 11.8, 1.2, 9.6, 1, 6.6);+ glyph.cubicTo(0.9, 5.4, 1.2, 4.6, 2.1, 4.4);+ glyph.cubicTo(4, 4.1, 6.3, 4.5, 8, 5.3);+ glyph.closeSubpath();+ glyph.moveTo(3.1, 7.3);+ glyph.cubicTo(3.5, 8.7, 5.7, 9.1, 6.7, 7.9);+ glyph.cubicTo(6.5, 6.6, 4.1, 6.2, 3.1, 7.3);+ glyph.closeSubpath();+ glyph.moveTo(12.9, 7.3);+ glyph.cubicTo(12.5, 8.7, 10.3, 9.1, 9.3, 7.9);+ glyph.cubicTo(9.5, 6.6, 11.9, 6.2, 12.9, 7.3);+ glyph.closeSubpath();++ painter.save();+ painter.translate(center - QPointF(PRIVATE_GLYPH_SIZE / 2, PRIVATE_GLYPH_SIZE / 2));+ painter.scale(PRIVATE_GLYPH_SIZE / 16, PRIVATE_GLYPH_SIZE / 16);+ painter.setPen(Qt::NoPen);+ painter.setBrush(color);+ painter.drawPath(glyph);+ painter.restore();+}++LadybirdButton::LadybirdButton(WebView::IsPrivate is_private, QWidget* parent)+ : QToolButton(parent)+ , m_is_private(is_private)+{+ setObjectName("LadybirdButton");+ setAccessibleName(is_private == WebView::IsPrivate::Yes ? "Ladybird menu, private window" : "Ladybird menu");+ setToolTip(is_private == WebView::IsPrivate::Yes ? "Ladybird menu, private window" : "Ladybird menu");+ setFocusPolicy(Qt::TabFocus);+ setPopupMode(QToolButton::InstantPopup);+ setFixedSize(sizeHint());++ // The tile fills in under the pointer, and a little more while pressed or while the menu is open.+ m_fill_animation = new QVariantAnimation(this);+ m_fill_animation->setDuration(Motion::FAST);+ connect(m_fill_animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ m_fill = value.toReal();+ update();+ });+}++void LadybirdButton::animate_fill(qreal fill)+{+ m_fill_animation->stop();+ if (SystemAppearance::prefers_reduced_motion()) {+ m_fill = fill;+ update();+ return;+ }+ m_fill_animation->setStartValue(m_fill);+ m_fill_animation->setEndValue(fill);+ m_fill_animation->start();+}++QSize LadybirdButton::sizeHint() const+{+ auto tile = tile_size(m_is_private);+ return { tile.width(), tile.height() + (2 * TILE_VERTICAL_MARGIN) };+}++QRect LadybirdButton::tile_rect() const+{+ auto tile = tile_size(m_is_private);+ return { QPoint((width() - tile.width()) / 2, ((height() - tile.height()) / 2) + m_tile_vertical_offset), tile };+}++// NB: On the tab strip, the button sits on the same line as the tabs, a little below the middle of its own height.+void LadybirdButton::set_tile_vertical_offset(int offset)+{+ if (m_tile_vertical_offset == offset)+ return;+ m_tile_vertical_offset = offset;+ update();+}++void LadybirdButton::paintEvent(QPaintEvent*)+{+ QPainter painter(this);+ painter.setRenderHint(QPainter::Antialiasing, true);+ // The button fades back in an inactive window.+ painter.setOpacity(ChromeStyle::window_activity(*this) == ChromeStyle::WindowActivity::Inactive ? 0.55 : 1.0);++ // The tile is a hairline outline, with a neutral fill only under the pointer or while pressed. The mark is in the+ // profile's color, which is the only brand color in the chrome, and doesn't change with the tile's state. A private+ // window shows its glyph in place of the logomark.+ auto is_private = m_is_private == WebView::IsPrivate::Yes;+ auto dark = is_private || Theme::is_dark(*this);+ auto fill_color = dark ? QColor(255, 255, 255) : QColor(0, 0, 0);+ fill_color.setAlphaF((dark ? 0.16 : 0.12) * m_fill);+ auto hairline_color = fill_color;+ hairline_color.setAlphaF(Theme::has_increased_contrast() ? 0.45 : (dark ? 0.16 : 0.14));+ auto mark_color = is_private ? QColor(0xd8c8ff) : (dark ? QColor(0xa684ff) : QColor(0x4b22ad));++ QRectF tile_rect { this->tile_rect() };+ painter.setPen(Qt::NoPen);+ painter.setBrush(fill_color);+ painter.drawRoundedRect(tile_rect, TILE_RADIUS, TILE_RADIUS);+ painter.setPen(QPen(hairline_color, 1));+ painter.setBrush(Qt::NoBrush);+ painter.drawRoundedRect(tile_rect.adjusted(0.5, 0.5, -0.5, -0.5), TILE_RADIUS - 0.5, TILE_RADIUS - 0.5);++ auto mark_center = QPointF(tile_rect.left() + TILE_LEADING_PADDING + (mark_width(m_is_private) / 2), tile_rect.center().y());+ if (is_private) {+ paint_private_glyph(painter, mark_center, mark_color);+ } else {+ QRectF logomark_rect { QPointF(), LOGOMARK_SIZE };+ logomark_rect.moveCenter(mark_center);+ paint_logomark(painter, logomark_rect, mark_color, LOGOMARK_STROKE_WIDTH);+ }+ auto chevron_center = QPointF(tile_rect.right() - TILE_TRAILING_PADDING - (CHEVRON_SIZE / 2), tile_rect.center().y());+ paint_chevron(painter, chevron_center, mark_color);++ // Focus is ringed only when it came from the keyboard.+ if (hasFocus() && m_has_keyboard_focus) {+ painter.setOpacity(1);+ ChromeStyle::paint_focus_ring(painter, tile_rect, TILE_RADIUS);+ }+}++// The fill deepens as the pointer comes over the button, and is gone at once as it leaves.+void LadybirdButton::enterEvent(QEnterEvent* event)+{+ QToolButton::enterEvent(event);+ if (!isDown())+ animate_fill(HOVERED_FILL);+}++void LadybirdButton::leaveEvent(QEvent* event)+{+ QToolButton::leaveEvent(event);+ if (isDown())+ return;+ m_fill_animation->stop();+ m_fill = 0;+ update();+}++void LadybirdButton::focusInEvent(QFocusEvent* event)+{+ m_has_keyboard_focus = first_is_one_of(event->reason(), Qt::TabFocusReason, Qt::BacktabFocusReason, Qt::ShortcutFocusReason);+ QToolButton::focusInEvent(event);+}++// Menus open as the button is pressed, so pressing, dragging to an item and releasing chooses it.+void LadybirdButton::mousePressEvent(QMouseEvent* event)+{+ if (event->button() == Qt::LeftButton) {+ show_menu();+ return;+ }+ QToolButton::mousePressEvent(event);+}++void LadybirdButton::keyPressEvent(QKeyEvent* event)+{+ if (first_is_one_of(event->key(), Qt::Key_Select, Qt::Key_Space, Qt::Key_Return, Qt::Key_Enter, Qt::Key_Down)) {+ show_menu();+ return;+ }+ QToolButton::keyPressEvent(event);+}++void LadybirdButton::show_menu()+{+ auto* menu = this->menu();+ if (!menu)+ return;++ setDown(true);+ animate_fill(PRESSED_FILL);+ // The menu hangs from the tile's bottom left corner, a few points below it.+ auto tile = tile_size(m_is_private);+ auto tile_bottom_left = QPoint((width() - tile.width()) / 2, (height() + tile.height()) / 2 + 4);+ menu->exec(mapToGlobal(tile_bottom_left));+ setDown(false);+ animate_fill(underMouse() ? HOVERED_FILL : 0);+}++}diff --git a/UI/Qt/LadybirdButton.h b/UI/Qt/LadybirdButton.hnew file mode 100644index 00000000000..f54e6411c8b--- /dev/null+++ b/UI/Qt/LadybirdButton.h@@ -0,0 +1,51 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/kmalloc.h>+#include <LibWebView/BrowsingSession.h>++#include <QToolButton>++class QVariantAnimation;++namespace Ladybird {++// The Ladybird button opens the browser's menu. It shows the logomark in the profile's color and a menu chevron, on a soft+// fill that deepens under the pointer and while the menu is open.+class LadybirdButton final : public QToolButton {+public:+ AK_ALLOC_WITH_KMALLOC;++ LadybirdButton(WebView::IsPrivate, QWidget* parent);++ virtual QSize sizeHint() const override;++ // The part of the button its tile covers, which popovers hang from.+ QRect tile_rect() const;+ void set_tile_vertical_offset(int);++private:+ virtual void paintEvent(QPaintEvent*) override;+ virtual void mousePressEvent(QMouseEvent*) override;+ virtual void keyPressEvent(QKeyEvent*) override;+ virtual void focusInEvent(QFocusEvent*) override;+ virtual void enterEvent(QEnterEvent*) override;+ virtual void leaveEvent(QEvent*) override;++ void show_menu();+ void animate_fill(qreal);++ WebView::IsPrivate m_is_private;+ bool m_has_keyboard_focus { false };+ int m_tile_vertical_offset { 0 };+ // How deep the tile's fill is, from 0 at rest to 1 while pressed.+ qreal m_fill { 0 };+ QVariantAnimation* m_fill_animation { nullptr };+};++}diff --git a/UI/Qt/LocationEdit.cpp b/UI/Qt/LocationEdit.cppindex b4e51b9d6de..a26e066105a 100644--- a/UI/Qt/LocationEdit.cpp+++ b/UI/Qt/LocationEdit.cpp@@ -15,15 +15,19 @@#include <UI/Qt/Icon.h>#include <UI/Qt/LocationEdit.h>#include <UI/Qt/Menu.h>+#include <UI/Qt/Motion.h>#include <UI/Qt/StringUtils.h>+#include <UI/Qt/SystemAppearance.h>+#include <UI/Qt/Theme.h>#include <QAction>#include <QApplication>#include <QClipboard>#include <QEasingCurve>-#include <QGraphicsDropShadowEffect>+#include <QGraphicsEffect>#include <QGuiApplication>#include <QKeyEvent>+#include <QLabel>#include <QMenu>#include <QMouseEvent>#include <QPainter>@@ -38,6 +42,9 @@namespace Ladybird {+static constexpr qreal LOCATION_BUTTON_RADIUS = 5;+static constexpr int SITE_SETTINGS_KNOB_SLIDE_DURATION_MS = 240;+class LocationActionButton final : public QToolButton {public:AK_ALLOC_WITH_KMALLOC;@@ -45,26 +52,35 @@ public:explicit LocationActionButton(QWidget* parent): QToolButton(parent){+ QObject::connect(&m_motion_animation, &QVariantAnimation::valueChanged, this, [this] { update(); });+ }++ void play_motion(LocationEdit::TrailingActionMotion motion, QIcon previous_icon)+ {+ m_motion = motion;+ m_previous_icon = AK::move(previous_icon);+ m_motion_animation.stop();+ m_motion_animation.setStartValue(0.0);+ m_motion_animation.setEndValue(1.0);+ m_motion_animation.setDuration(motion == LocationEdit::TrailingActionMotion::Pop ? POP_DURATION_MS : FADE_DURATION_MS);+ m_motion_animation.start();}private:+ static constexpr int POP_DURATION_MS = 220;+ static constexpr qreal POP_SCALE = 0.12;+ static constexpr qreal POP_PEAK_AT = 0.45;+ static constexpr int FADE_DURATION_MS = 160;+virtual void paintEvent(QPaintEvent*) override{- static constexpr int hover_size = 23;- static constexpr qreal hover_y_offset = 1.0;-QPainter painter(this);painter.setRenderHint(QPainter::Antialiasing, true);if (isDown() || underMouse()) {- auto background = isDown()- ? ChromeStyle::mix(ChromeStyle::chrome_surface_pressed(palette()), ChromeStyle::chrome_button_text(palette()), 0.04)- : ChromeStyle::mix(ChromeStyle::chrome_surface_hover(palette()), ChromeStyle::chrome_button_text(palette()), 0.04);painter.setPen(Qt::NoPen);- painter.setBrush(background);- auto hover_rect = QRectF(0, 0, hover_size, hover_size);- hover_rect.moveCenter(QPointF(rect().center().x(), rect().center().y() + hover_y_offset));- painter.drawRoundedRect(hover_rect, 10, 10);+ painter.setBrush(isDown() ? Theme::panel().pressed : Theme::chrome(*this).hover);+ painter.drawRoundedRect(QRectF(rect()), LOCATION_BUTTON_RADIUS, LOCATION_BUTTON_RADIUS);}auto icon_rect = QRect(@@ -72,16 +88,84 @@ private:(height() - iconSize().height()) / 2,iconSize().width(),iconSize().height());- icon().paint(&painter, icon_rect, Qt::AlignCenter, isEnabled() ? QIcon::Normal : QIcon::Disabled, isDown() ? QIcon::On : QIcon::Off);+ auto mode = isEnabled() ? QIcon::Normal : QIcon::Disabled;+ auto state = isDown() ? QIcon::On : QIcon::Off;++ if (m_motion_animation.state() == QAbstractAnimation::Running) {+ auto progress = m_motion_animation.currentValue().toReal();+ if (m_motion == LocationEdit::TrailingActionMotion::Fade) {+ painter.setOpacity(1 - progress);+ m_previous_icon.paint(&painter, icon_rect, Qt::AlignCenter, mode, state);+ painter.setOpacity(progress);+ } else {+ painter.setRenderHint(QPainter::SmoothPixmapTransform, true);+ auto scale = 1 + (POP_SCALE * Motion::there_and_back(progress, POP_PEAK_AT));+ auto center = QRectF(icon_rect).center();+ painter.translate(center);+ painter.scale(scale, scale);+ painter.translate(-center);+ }+ }+ icon().paint(&painter, icon_rect, Qt::AlignCenter, mode, state);}++ LocationEdit::TrailingActionMotion m_motion { LocationEdit::TrailingActionMotion::Pop };+ QIcon m_previous_icon;+ QVariantAnimation m_motion_animation;};-static QColor location_focus_glow_color(int alpha)-{- auto color = ChromeStyle::chrome_accent();- color.setAlpha(alpha);- return color;-}+// The focused field is ringed in the accent color: a crisp line right outside its edge, inside a wider, softer ring.+// The effect draws outside the field's bounds, where a style sheet cannot.+class FocusRingEffect final : public QGraphicsEffect {+public:+ AK_ALLOC_WITH_KMALLOC;++ using QGraphicsEffect::QGraphicsEffect;++ void set_opacity(qreal opacity)+ {+ m_opacity = opacity;+ // NB: An enabled effect renders the field offscreen on every repaint, even when the ring is invisible.+ setEnabled(opacity > 0);+ update();+ }++private:+ static constexpr qreal OUTER_RING_WIDTH = 2;++ virtual QRectF boundingRectFor(QRectF const& rect) const override+ {+ auto outset = 1 + OUTER_RING_WIDTH;+ return rect.adjusted(-outset, -outset, outset, outset);+ }++ virtual void draw(QPainter* painter) override+ {+ QPoint offset;+ auto source = sourcePixmap(Qt::LogicalCoordinates, &offset);+ painter->drawPixmap(offset, source);++ auto field_rect = sourceBoundingRect(Qt::LogicalCoordinates);+ auto radius = static_cast<qreal>(ChromeStyle::LOCATION_EDIT_CORNER_RADIUS);++ painter->save();+ painter->setRenderHint(QPainter::Antialiasing, true);+ painter->setOpacity(m_opacity);+ painter->setBrush(Qt::NoBrush);++ auto outer_rect = field_rect.adjusted(-1 - (OUTER_RING_WIDTH / 2), -1 - (OUTER_RING_WIDTH / 2), 1 + (OUTER_RING_WIDTH / 2), 1 + (OUTER_RING_WIDTH / 2));+ auto outer_radius = radius + 1 + (OUTER_RING_WIDTH / 2);+ painter->setPen(QPen(Theme::focus_ring(), OUTER_RING_WIDTH));+ painter->drawRoundedRect(outer_rect, outer_radius, outer_radius);++ auto inner_rect = field_rect.adjusted(-0.5, -0.5, 0.5, 0.5);+ painter->setPen(QPen(Theme::focus_edge(), 1));+ painter->drawRoundedRect(inner_rect, radius + 0.5, radius + 0.5);+ painter->restore();+ }++ qreal m_opacity { 0 };+};static int qstring_offset_for_byte_offset(String const& text, size_t byte_offset){@@ -89,13 +173,21 @@ static int qstring_offset_for_byte_offset(String const& text, size_t byte_offsetreturn static_cast<int>(qstring_from_ak_string(prefix).length());}-static constexpr int LOCATION_TRAILING_EDGE_MARGIN = 12;-static constexpr int LOCATION_TRAILING_TEXT_GAP = 4;+// The field's content is inset more on its leading side than on its trailing side.+static constexpr int LOCATION_LEADING_EDGE_MARGIN = 2;+static constexpr int LOCATION_TRAILING_EDGE_MARGIN = 3;+// The text starts this far in when nothing comes before it. The style sheet pads the field by as much.+static constexpr int LOCATION_TEXT_PADDING = 8;static constexpr int LOCATION_TRAILING_ITEM_GAP = 6;+static constexpr int LOCATION_LEADING_ITEM_GAP = 6;static constexpr int LOCATION_TRAILING_ACTION_WIDTH = 24;-static constexpr int LOCATION_TRAILING_ACTION_HEIGHT = 23;+static constexpr int LOCATION_SITE_SETTINGS_BUTTON_WIDTH = 26;+static constexpr int LOCATION_TRAILING_ACTION_HEIGHT = 22;static constexpr int LOCATION_PILL_HEIGHT = 22;-static constexpr int LOCATION_PILL_HORIZONTAL_PADDING = 18;+static constexpr int LOCATION_PILL_HORIZONTAL_PADDING = 16;+// The zoom chip is at least wide enough for any zoom level up to 999%, so it keeps its width as the level changes.+static constexpr int LOCATION_ZOOM_CHIP_MIN_WIDTH = 54;+static constexpr int LOCATION_ZOOM_CHIP_GAP = 3;LocationEdit::LocationEdit(QWidget* parent, WebView::IsPrivate is_private): NativeTextEditingLineEdit(parent)@@ -103,41 +195,52 @@ LocationEdit::LocationEdit(QWidget* parent, WebView::IsPrivate is_private), m_autocomplete(new Autocomplete(this)){setObjectName("LadybirdLocationEdit");- setMinimumHeight(30);+ setMinimumHeight(28);update_chrome_style();- m_focus_glow_effect = new QGraphicsDropShadowEffect(this);- m_focus_glow_effect->setBlurRadius(10);- m_focus_glow_effect->setOffset(0, 0);- update_focus_glow(0);- setGraphicsEffect(m_focus_glow_effect);-- m_focus_glow_animation = new QVariantAnimation(this);- m_focus_glow_animation->setDuration(130);- m_focus_glow_animation->setEasingCurve(QEasingCurve::OutCubic);- connect(m_focus_glow_animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {- update_focus_glow(value.toInt());+ m_focus_ring_effect = new FocusRingEffect(this);+ setGraphicsEffect(m_focus_ring_effect);+ update_focus_ring(0);++ m_focus_ring_animation = new QVariantAnimation(this);+ m_focus_ring_animation->setDuration(Motion::FAST);+ m_focus_ring_animation->setEasingCurve(Motion::enter_easing());+ connect(m_focus_ring_animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ update_focus_ring(value.toReal());});m_leading_icon_button = new QToolButton(this);m_leading_icon_button->setObjectName("LadybirdLocationIcon");- m_leading_icon_button->setIconSize({ 18, 18 });- m_leading_icon_button->setFixedSize(22, 22);+ m_leading_icon_button->setIconSize({ 16, 16 });+ m_leading_icon_button->setFixedSize(LOCATION_SITE_SETTINGS_BUTTON_WIDTH, LOCATION_PILL_HEIGHT);m_leading_icon_button->setAutoRaise(true);m_leading_icon_button->setFocusPolicy(Qt::NoFocus);m_leading_icon_button->setCursor(Qt::ArrowCursor);m_leading_icon_button->hide();+ connect(m_leading_icon_button, &QToolButton::clicked, this, [this] {+ if (on_site_settings_requested)+ on_site_settings_requested();+ });m_trailing_action_button = new LocationActionButton(this);m_trailing_action_button->setObjectName("LadybirdLocationAction");m_trailing_action_button->setToolButtonStyle(Qt::ToolButtonIconOnly);- m_trailing_action_button->setIconSize({ 17, 17 });+ m_trailing_action_button->setIconSize({ 16, 16 });m_trailing_action_button->setFixedSize(LOCATION_TRAILING_ACTION_WIDTH, LOCATION_TRAILING_ACTION_HEIGHT);m_trailing_action_button->setAutoRaise(true);m_trailing_action_button->setFocusPolicy(Qt::NoFocus);m_trailing_action_button->setCursor(Qt::ArrowCursor);m_trailing_action_button->hide();+ // While the text is inline completed to a page, the page's title stands where the bookmark star does.+ m_completion_title = new QLabel(this);+ m_completion_title->setObjectName("LadybirdLocationCompletionTitle");+ m_completion_title->setAttribute(Qt::WA_TransparentForMouseEvents);+ auto completion_title_font = m_completion_title->font();+ completion_title_font.setPointSizeF(12);+ m_completion_title->setFont(completion_title_font);+ m_completion_title->hide();+m_zoom_indicator_button = new QToolButton(this);m_zoom_indicator_button->setObjectName("LadybirdLocationZoomIndicator");m_zoom_indicator_button->setToolButtonStyle(Qt::ToolButtonTextOnly);@@ -146,16 +249,31 @@ LocationEdit::LocationEdit(QWidget* parent, WebView::IsPrivate is_private)m_zoom_indicator_button->setFocusPolicy(Qt::NoFocus);m_zoom_indicator_button->setCursor(Qt::ArrowCursor);m_zoom_indicator_button->hide();+ m_zoom_indicator_opacity = new QGraphicsOpacityEffect(m_zoom_indicator_button);+ m_zoom_indicator_button->setGraphicsEffect(m_zoom_indicator_opacity);+ m_zoom_indicator_fade = new QVariantAnimation(this);+ m_zoom_indicator_fade->setDuration(Motion::FAST);+ m_zoom_indicator_fade->setEndValue(1.0);+ connect(m_zoom_indicator_fade, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ m_zoom_indicator_opacity->setOpacity(value.toReal());+ });+ connect(m_zoom_indicator_fade, &QVariantAnimation::finished, this, [this] {+ if (m_zoom_indicator_opacity->opacity() > 0)+ return;+ m_zoom_indicator_button->hide();+ update_text_margins();+ update_trailing_item_positions();+ });connect(m_zoom_indicator_button, &QToolButton::clicked, this, [this] {- if (m_zoom_action)- m_zoom_action->trigger();+ if (on_zoom_requested)+ on_zoom_requested();});for (auto* button : { m_leading_icon_button, m_trailing_action_button, m_zoom_indicator_button })button->installEventFilter(this);update_text_margins();- update_placeholder();+ setPlaceholderText("Search or enter address");update_location_icon();m_omnibox.on_display_change = [this](WebView::Omnibox::Display const& display) {@@ -172,9 +290,11 @@ LocationEdit::LocationEdit(QWidget* parent, WebView::IsPrivate is_private)deselect();setCursorPosition(static_cast<int>(display_text.length()));}+ update_completion_title();};m_omnibox.on_suggestions_change = [this] {+ update_completion_title();if (!m_omnibox.is_popup_visible()) {m_autocomplete->close();return;@@ -221,6 +341,7 @@ LocationEdit::LocationEdit(QWidget* parent, WebView::IsPrivate is_private)bool cursor_at_end = !hasSelectedText() && cursorPosition() == text().length();m_omnibox.text_edited(ak_string_from_qstring(text()), cursor_at_end);+ update_completion_title();});connect(this, &QLineEdit::textChanged, this, [this] {@@ -241,10 +362,84 @@ LocationEdit::LocationEdit(QWidget* parent, WebView::IsPrivate is_private)});}+QWidget& LocationEdit::trailing_action_button() const+{+ return *m_trailing_action_button;+}++QWidget& LocationEdit::site_settings_button() const+{+ return *m_leading_icon_button;+}+void LocationEdit::set_trailing_action(QAction* action){m_trailing_action_button->setDefaultAction(action);- m_trailing_action_button->setVisible(action != nullptr);+ update_trailing_action_visibility();+}++void LocationEdit::animate_trailing_action_change(TrailingActionMotion motion, Function<void()> const& change)+{+ auto previous_icon = m_trailing_action_button->icon();+ change();+ // NB: The action's icon is replaced as the change takes effect, and the button takes it up at once.+ if (SystemAppearance::prefers_reduced_motion() || m_trailing_action_button->icon().cacheKey() == previous_icon.cacheKey())+ return;+ static_cast<LocationActionButton*>(m_trailing_action_button)->play_motion(motion, AK::move(previous_icon));+}++void LocationEdit::follow_site_settings_popover(QWidget& popover)+{+ if (m_site_settings_popover == &popover)+ return;+ m_site_settings_popover = &popover;+ popover.installEventFilter(this);+}++void LocationEdit::slide_site_settings_knobs(qreal travel)+{+ if (!m_site_settings_knob_animation) {+ m_site_settings_knob_animation = new QVariantAnimation(this);+ m_site_settings_knob_animation->setDuration(SITE_SETTINGS_KNOB_SLIDE_DURATION_MS);+ m_site_settings_knob_animation->setEasingCurve(Motion::move_easing());+ QObject::connect(m_site_settings_knob_animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ m_site_settings_knob_travel = value.toReal();+ if (m_shows_site_settings_button)+ m_leading_icon_button->setIcon(create_site_settings_icon(Theme::chrome_palette(*this), m_site_settings_knob_travel));+ });+ }++ m_site_settings_knob_animation->stop();+ if (SystemAppearance::prefers_reduced_motion()) {+ m_site_settings_knob_travel = travel;+ update_location_icon();+ return;+ }+ m_site_settings_knob_animation->setStartValue(m_site_settings_knob_travel);+ m_site_settings_knob_animation->setEndValue(travel);+ m_site_settings_knob_animation->start();+}++// The bookmark star is about the page, so it stands aside while the text is being edited, and for a new tab, which has+// no page yet.+void LocationEdit::update_trailing_action_visibility()+{+ m_trailing_action_button->setVisible(m_trailing_action_button->defaultAction() && !m_is_editing_location && !m_url_is_hidden);+ update_text_margins();+ update_trailing_item_positions();+}++void LocationEdit::update_completion_title()+{+ auto title = m_is_editing_location ? m_omnibox.completion_title() : OptionalNone {};+ if (title.has_value()) {+ // NB: The field's style sheet would color the title as the text it follows.+ m_completion_title->setStyleSheet(qformatted("color: {}; background: transparent;", ChromeStyle::style_sheet_color(Theme::chrome(*this).muted)));+ auto maximum_width = width() / 3;+ m_completion_title->setText(m_completion_title->fontMetrics().elidedText(qstring_from_ak_string(*title), Qt::ElideRight, maximum_width));+ m_completion_title->adjustSize();+ }+ m_completion_title->setVisible(title.has_value());update_text_margins();update_trailing_item_positions();}@@ -280,6 +475,7 @@ void LocationEdit::set_url_is_hidden(bool url_is_hidden)if (m_url_is_hidden)set_text_and_restart_editing({});+ update_trailing_action_visibility();}void LocationEdit::show_autocomplete()@@ -293,6 +489,16 @@ void LocationEdit::show_autocomplete()void LocationEdit::changeEvent(QEvent* event){QLineEdit::changeEvent(event);+ if (event->type() == QEvent::ActivationChange) {+ highlight_location();+ // The focus ring only shows in the active window, though the field keeps its focus and its editing session.+ if (m_focus_ring_animation)+ m_focus_ring_animation->stop();+ if (!isActiveWindow())+ update_focus_ring(0);+ else if (m_is_editing_location && hasFocus())+ update_focus_ring(1);+ }// NB: Repolishing for the hover look changes our palette to the hovered colors, which needs no new style.if (event->type() == QEvent::PaletteChange && m_is_updating_field_hover)return;@@ -312,11 +518,25 @@ bool LocationEdit::event(QEvent* event)bool LocationEdit::eventFilter(QObject* watched, QEvent* event){+ if (watched == m_site_settings_popover) {+ if (event->type() == QEvent::Show)+ slide_site_settings_knobs(1);+ else if (event->type() == QEvent::Hide)+ slide_site_settings_knobs(0);+ return QLineEdit::eventFilter(watched, event);+ }+// The buttons inside the field have their own hover look, so the field itself does not look hovered under them.- if (event->type() == QEvent::Enter)+ // NB: Clicking a button that takes no focus gives the focus to the nearest widget around it that does, which is the+ // field. A click on a button opens something about the page, rather than editing its address, so the field+ // takes no focus from clicks while the mouse is over a button.+ if (event->type() == QEvent::Enter) {set_field_hovered(false);- else if (event->type() == QEvent::Leave)+ setFocusPolicy(Qt::TabFocus);+ } else if (event->type() == QEvent::Leave || event->type() == QEvent::Hide) {set_field_hovered(underMouse());+ setFocusPolicy(Qt::StrongFocus);+ }return QLineEdit::eventFilter(watched, event);}@@ -350,7 +570,7 @@ void LocationEdit::contextMenuEvent(QContextMenuEvent* event)bool clipboard_holds_url = !has_search_engine || (!clipboard_text.is_empty() && WebView::location_looks_like_url(clipboard_text));auto paste_and_go_icon = clipboard_holds_url- ? create_chrome_icon(ChromeIcon::Forward, palette())+ ? create_chrome_icon(ChromeIcon::Forward, Theme::chrome_palette(*this)): QIcon::fromTheme(QIcon::ThemeIcon::SystemSearch);auto* paste_and_go_action = new QAction(paste_and_go_icon, qstring_from_ak_string(paste_and_go_text), menu);@@ -416,7 +636,7 @@ void LocationEdit::focusInEvent(QFocusEvent* event)}if (m_omnibox.is_popup_visible())m_autocomplete->show_with_suggestions(m_omnibox.suggestions(), m_omnibox.selected_suggestion());- animate_focus_glow(58);+ show_focus_ring();return;}@@ -440,7 +660,7 @@ void LocationEdit::focusInEvent(QFocusEvent* event)m_omnibox.begin_editing(ak_string_from_qstring(text()));highlight_location();- animate_focus_glow(58);+ show_focus_ring();if (!should_defer_full_url) {QTimer::singleShot(0, this, [this] {@@ -464,14 +684,13 @@ void LocationEdit::focusOutEvent(QFocusEvent* event)return;}- animate_focus_glow(0);+ hide_focus_ring();m_omnibox.end_editing();m_should_show_full_url_on_mouse_release = false;if (m_url_is_hidden) {- m_url_is_hidden = false;- m_has_user_edited_hidden_url = false;+ set_url_is_hidden(false);if (text().isEmpty() && m_url.has_value())setText(display_url());} else if (m_url.has_value() && text() == serialized_url()) {@@ -483,25 +702,46 @@ void LocationEdit::focusOutEvent(QFocusEvent* event)highlight_location();}-void LocationEdit::update_focus_glow(int alpha)+void LocationEdit::update_focus_ring(qreal opacity)+{+ m_focus_ring_opacity = opacity;+ if (m_focus_ring_effect)+ static_cast<FocusRingEffect*>(m_focus_ring_effect)->set_opacity(opacity);+}++// The ring fades in when the field gets focus, and disappears at once when it loses it.+void LocationEdit::show_focus_ring(){- m_focus_glow_alpha = alpha;- if (!m_focus_glow_effect)+ m_is_editing_location = true;+ update_trailing_action_visibility();++ if (!m_focus_ring_animation)return;- m_focus_glow_effect->setColor(location_focus_glow_color(alpha));- // NB: An enabled effect renders the edit offscreen and blurs it on every repaint, even when the glow is invisible.- m_focus_glow_effect->setEnabled(alpha > 0);++ m_focus_ring_animation->stop();+ m_focus_ring_animation->setStartValue(m_focus_ring_opacity);+ m_focus_ring_animation->setEndValue(1.0);+ m_focus_ring_animation->start();}-void LocationEdit::animate_focus_glow(int target_alpha)+void LocationEdit::show_focus_ring_at_once(){- if (!m_focus_glow_animation)+ if (!hasFocus() || !isActiveWindow())return;+ if (m_focus_ring_animation)+ m_focus_ring_animation->stop();+ update_focus_ring(1);+}- m_focus_glow_animation->stop();- m_focus_glow_animation->setStartValue(m_focus_glow_alpha);- m_focus_glow_animation->setEndValue(target_alpha);- m_focus_glow_animation->start();+void LocationEdit::hide_focus_ring()+{+ m_is_editing_location = false;+ update_trailing_action_visibility();+ update_completion_title();++ if (m_focus_ring_animation)+ m_focus_ring_animation->stop();+ update_focus_ring(0);}void LocationEdit::native_text_editing_command_will_execute(Web::TextEditingCommand const& command)@@ -595,27 +835,39 @@ void LocationEdit::resizeEvent(QResizeEvent* event)update_trailing_item_positions();}+// The "Not secure" pill is inset as far from the field's leading edge as from its top and bottom.+static int leading_indicator_inset(QWidget const& field, QWidget const& indicator)+{+ if (indicator.property("notSecure").toBool())+ return (field.height() - indicator.height()) / 2;+ return LOCATION_LEADING_EDGE_MARGIN;+}+void LocationEdit::update_trailing_item_positions(){auto button_size = m_leading_icon_button->size();- auto y = (height() - button_size.height()) / 2 + (m_leading_icon_button->property("notSecure").toBool() ? 0 : 1);- m_leading_icon_button->move(12, y);+ m_leading_icon_button->move(leading_indicator_inset(*this, *m_leading_icon_button), (height() - button_size.height()) / 2);auto trailing_button_size = m_trailing_action_button->size();auto trailing_x = width() - trailing_button_size.width() - LOCATION_TRAILING_EDGE_MARGIN;auto trailing_y = (height() - trailing_button_size.height()) / 2;m_trailing_action_button->move(trailing_x, trailing_y);+ // NB: The items before the star are placed from the star's place, whether it shows or not.+ auto items_x = trailing_x;++ auto completion_title_size = m_completion_title->size();+ m_completion_title->move(width() - LOCATION_TRAILING_EDGE_MARGIN - LOCATION_TEXT_PADDING - completion_title_size.width(), (height() - completion_title_size.height()) / 2);+auto zoom_button_size = m_zoom_indicator_button->size();auto zoom_y = (height() - zoom_button_size.height()) / 2;- m_zoom_indicator_button->move(trailing_x - LOCATION_TRAILING_ITEM_GAP - zoom_button_size.width(), zoom_y);+ m_zoom_indicator_button->move(items_x - LOCATION_ZOOM_CHIP_GAP - zoom_button_size.width(), zoom_y);m_zoom_indicator_button->raise();m_trailing_action_button->raise();}void LocationEdit::search_engine_settings_changed(){- update_placeholder();update_location_icon();}@@ -626,10 +878,12 @@ void LocationEdit::update_text_margins()int LocationEdit::trailing_text_margin() const{- auto margin = LOCATION_TRAILING_EDGE_MARGIN + LOCATION_TRAILING_ACTION_WIDTH + LOCATION_TRAILING_TEXT_GAP;+ auto margin = LOCATION_TRAILING_EDGE_MARGIN + LOCATION_TRAILING_ACTION_WIDTH + LOCATION_TRAILING_ITEM_GAP - LOCATION_TEXT_PADDING;+ if (m_completion_title && !m_completion_title->isHidden())+ margin = max(margin, LOCATION_TRAILING_EDGE_MARGIN + m_completion_title->width() + LOCATION_TRAILING_ITEM_GAP);if (m_zoom_indicator_button && !m_zoom_indicator_button->isHidden())- margin += m_zoom_indicator_button->width() + LOCATION_TRAILING_ITEM_GAP;+ margin += m_zoom_indicator_button->width() + LOCATION_ZOOM_CHIP_GAP;return margin;}@@ -641,7 +895,7 @@ void LocationEdit::update_chrome_style()m_is_updating_chrome_style = true;// Match the popup's palette without feeding our styled background into the next style update.- setStyleSheet(ChromeStyle::location_edit_style_sheet(QApplication::palette()));+ setStyleSheet(ChromeStyle::location_edit_style_sheet(Theme::chrome_palette(*this)));m_is_updating_chrome_style = false;update_zoom_indicator();}@@ -655,7 +909,7 @@ void LocationEdit::schedule_chrome_style_update()QTimer::singleShot(0, this, [this] {update_chrome_style();m_autocomplete->schedule_chrome_style_update();- update_focus_glow(m_focus_glow_alpha);+ update_focus_ring(m_focus_ring_opacity);update_location_icon();update_zoom_indicator();highlight_location();@@ -664,16 +918,8 @@ void LocationEdit::schedule_chrome_style_update()});}-void LocationEdit::update_placeholder()-{- if (auto const& search_engine = WebView::Application::settings().search_engine_settings().engine; search_engine.has_value()) {- auto prompt = MUST(String::formatted("Search with {} or enter web address", search_engine->name));- setPlaceholderText(qstring_from_ak_string(prompt));- } else {- setPlaceholderText("Enter web address");- }-}-+// Before the address, the field shows a button for the site's information, or a warning when the connection is not+// secure. While the address is being edited, nothing comes before the text.void LocationEdit::update_location_icon(){if (!m_leading_icon_button)@@ -688,12 +934,16 @@ void LocationEdit::update_location_icon()m_leading_icon_button->style()->polish(m_leading_icon_button);};- auto position_indicator = [this](int y_offset) {- auto button_size = m_leading_icon_button->size();- auto y = (height() - button_size.height()) / 2 + y_offset;- m_leading_icon_button->move(12, y);+ auto show_indicator = [&](int width) {+ m_leading_icon_button->show();+ auto inset = leading_indicator_inset(*this, *m_leading_icon_button);+ m_leading_icon_button->move(inset, (height() - m_leading_icon_button->height()) / 2);+ m_text_leading_margin = inset + width + LOCATION_LEADING_ITEM_GAP - LOCATION_TEXT_PADDING;+ update_text_margins();};+ m_shows_site_settings_button = false;+auto hide_indicator = [&] {update_indicator_style(false);m_leading_icon_button->hide();@@ -704,59 +954,50 @@ void LocationEdit::update_location_icon()update_text_margins();};- auto show_icon = [&](ChromeIcon icon, QString const& tooltip) {+ auto show_site_settings_button = [&] {update_indicator_style(false);m_leading_icon_button->setToolButtonStyle(Qt::ToolButtonIconOnly);m_leading_icon_button->setText({});- m_leading_icon_button->setIcon(create_chrome_icon(icon, palette()));- m_leading_icon_button->setIconSize({ 18, 18 });- m_leading_icon_button->setFixedSize(22, 22);- m_leading_icon_button->setToolTip(tooltip);- m_leading_icon_button->show();- position_indicator(1);- m_text_leading_margin = 22;- update_text_margins();+ m_leading_icon_button->setIcon(create_site_settings_icon(Theme::chrome_palette(*this), m_site_settings_knob_travel));+ m_shows_site_settings_button = true;+ m_leading_icon_button->setIconSize({ 16, 16 });+ m_leading_icon_button->setFixedSize(LOCATION_SITE_SETTINGS_BUTTON_WIDTH, LOCATION_PILL_HEIGHT);+ m_leading_icon_button->setToolTip("Site settings");+ show_indicator(LOCATION_SITE_SETTINGS_BUTTON_WIDTH);};auto show_not_secure_indicator = [&] {update_indicator_style(true);- m_leading_icon_button->setToolButtonStyle(Qt::ToolButtonTextOnly);- m_leading_icon_button->setIcon({});+ m_leading_icon_button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);+ m_leading_icon_button->setIcon(create_chrome_icon(ChromeIcon::Warning, Theme::chrome(*this).warning_ink));+ m_leading_icon_button->setIconSize({ 14, 14 });m_leading_icon_button->setText("Not secure");- auto width = m_leading_icon_button->fontMetrics().horizontalAdvance("Not secure") + 18;- m_leading_icon_button->setFixedSize(width, 22);- m_leading_icon_button->setToolTip("Not secure");- m_leading_icon_button->show();- position_indicator(0);- m_text_leading_margin = width;- update_text_margins();+ auto font = m_leading_icon_button->font();+ font.setPixelSize(12);+ font.setWeight(QFont::Medium);+ auto width = QFontMetrics(font).horizontalAdvance("Not secure") + 14 + 5 + LOCATION_PILL_HORIZONTAL_PADDING;+ m_leading_icon_button->setFixedSize(width, LOCATION_PILL_HEIGHT);+ m_leading_icon_button->setToolTip("The connection to this site is not secure");+ show_indicator(width);};auto is_showing_current_url_for_display = !hasFocus()&& m_url.has_value()&& text() == display_url();- if (text_matches_current_url() || is_showing_current_url_for_display) {+ if (is_showing_current_url_for_display) {auto scheme = m_url->scheme();if (scheme == "http"sv)show_not_secure_indicator();+ else if (scheme == "https"sv)+ show_site_settings_button();elsehide_indicator();return;}- auto query = ak_string_from_qstring(current_query());- auto query_view = query.bytes_as_string_view().trim_whitespace();- if (query_view.is_empty()) {- hide_indicator();- } else if (WebView::location_looks_like_url(query_view)) {- show_icon(ChromeIcon::Globe, "Go to address");- } else if (WebView::Application::settings().search_engine_settings().engine.has_value()) {- show_icon(ChromeIcon::Search, "Search");- } else {- hide_indicator();- }+ hide_indicator();}void LocationEdit::update_zoom_indicator()@@ -764,20 +1005,43 @@ void LocationEdit::update_zoom_indicator()if (!m_zoom_indicator_button)return;+ // The chip fades in when the page is zoomed and out when the zoom is reset. Its number changes in place.+ auto fade_to = [this](qreal opacity) {+ if (SystemAppearance::prefers_reduced_motion()) {+ m_zoom_indicator_fade->stop();+ m_zoom_indicator_opacity->setOpacity(opacity);+ if (opacity == 0) {+ m_zoom_indicator_button->hide();+ update_text_margins();+ update_trailing_item_positions();+ }+ return;+ }+ m_zoom_indicator_fade->stop();+ m_zoom_indicator_fade->setEasingCurve(opacity > 0 ? Motion::enter_easing() : Motion::exit_easing());+ m_zoom_indicator_fade->setStartValue(m_zoom_indicator_opacity->opacity());+ m_zoom_indicator_fade->setEndValue(opacity);+ m_zoom_indicator_fade->start();+ };+auto visible = m_zoom_action && m_zoom_action->isVisible() && !m_zoom_action->text().isEmpty();if (!visible) {- m_zoom_indicator_button->hide();- update_text_margins();- update_trailing_item_positions();+ if (!m_zoom_indicator_button->isHidden())+ fade_to(0);return;}m_zoom_indicator_button->setText(m_zoom_action->text());m_zoom_indicator_button->setToolTip(m_zoom_action->toolTip());- auto width = m_zoom_indicator_button->fontMetrics().horizontalAdvance(m_zoom_indicator_button->text()) + LOCATION_PILL_HORIZONTAL_PADDING;+ auto width = max(LOCATION_ZOOM_CHIP_MIN_WIDTH, m_zoom_indicator_button->fontMetrics().horizontalAdvance(m_zoom_indicator_button->text()) + LOCATION_PILL_HORIZONTAL_PADDING);m_zoom_indicator_button->setFixedSize(width, LOCATION_PILL_HEIGHT);- m_zoom_indicator_button->show();+ if (m_zoom_indicator_button->isHidden() || m_zoom_indicator_fade->endValue().toReal() == 0) {+ if (m_zoom_indicator_button->isHidden())+ m_zoom_indicator_opacity->setOpacity(0);+ m_zoom_indicator_button->show();+ fade_to(1);+ }update_text_margins();update_trailing_item_positions();@@ -788,15 +1052,19 @@ void LocationEdit::highlight_location()auto url = ak_string_from_qstring(text());QList<QInputMethodEvent::Attribute> attributes;- // The parts of the URL around the domain are secondary, but should not look disabled.- auto darkened_text_color = ChromeStyle::chrome_text(palette());- darkened_text_color.setAlpha(ChromeStyle::is_dark(palette()) ? 178 : 148);+ // The parts of the URL around the domain are secondary, but should not look disabled. In an inactive window, the+ // whole address drops to the muted color.+ auto is_inactive = ChromeStyle::window_activity(*this) == ChromeStyle::WindowActivity::Inactive;+ auto text_color = is_inactive ? Theme::chrome(*this).muted : ChromeStyle::chrome_text(Theme::chrome_palette(*this));+ auto darkened_text_color = text_color;+ if (!is_inactive)+ darkened_text_color.setAlpha(ChromeStyle::is_dark(Theme::chrome_palette(*this)) ? 178 : 148);QTextCharFormat dark_attributes;dark_attributes.setForeground(darkened_text_color);QTextCharFormat highlight_attributes;- highlight_attributes.setForeground(ChromeStyle::chrome_text(palette()));+ highlight_attributes.setForeground(text_color);auto append_attributes = [&](StringView scheme_and_subdomain, StringView effective_tld_plus_one, StringView remainder) {attributes.append({diff --git a/UI/Qt/LocationEdit.h b/UI/Qt/LocationEdit.hindex 4b5ed886254..e4b9482277d 100644--- a/UI/Qt/LocationEdit.h+++ b/UI/Qt/LocationEdit.h@@ -13,12 +13,15 @@#include <LibWebView/Omnibox.h>#include <LibWebView/Settings.h>+#include <QPointer>#include <QString>#include <UI/Qt/NativeTextEditingLineEdit.h>class QAction;class QEvent;-class QGraphicsDropShadowEffect;+class QGraphicsEffect;+class QGraphicsOpacityEffect;+class QLabel;class QMouseEvent;class QResizeEvent;class QToolButton;@@ -39,7 +42,17 @@ public:LocationEdit(QWidget*, WebView::IsPrivate);void set_trailing_action(QAction*);+ // The content blocker's button stands in the field, before the bookmark star.QAction* trailing_action() const;+ // The star pops as the page is bookmarked, and its fill fades as the bookmark is removed. It moves only for a change+ // the user makes, rather than as another page is shown, so such a change is made through here.+ enum class TrailingActionMotion : u8 {+ Pop,+ Fade,+ };+ void animate_trailing_action_change(TrailingActionMotion, Function<void()> const& change);+ // The knobs of the site settings icon slide past each other while the given popover is open.+ void follow_site_settings_popover(QWidget&);void set_zoom_action(QAction*);Optional<URL::URL const&> url() const { return m_url; }@@ -49,7 +62,16 @@ public:void show_autocomplete();void park_editing_session();bool has_parked_editing_session() const { return m_parked_editing_session.has_value(); }-+ // Shows the focus ring of a focused field at once, rather than fading it in, as the focus moves to it from another+ // tab's field, whose ring was showing.+ void show_focus_ring_at_once();++ // Asks for the site settings of the page whose address is shown.+ Function<void()> on_site_settings_requested;+ // Asks for the page's zoom controls, shown when the zoom level in the field is clicked.+ Function<void()> on_zoom_requested;+ QWidget& trailing_action_button() const;+ QWidget& site_settings_button() const;Function<void(String, Optional<URL::URL>, WebView::OmniboxDestinationKind)> on_navigation;signals:@@ -74,14 +96,17 @@ private:void update_text_margins();int trailing_text_margin() const;void update_trailing_item_positions();- void update_placeholder();void update_chrome_style();void update_location_icon();void update_zoom_indicator();- void update_focus_glow(int alpha);+ void update_focus_ring(qreal opacity);void set_field_hovered(bool);void schedule_chrome_style_update();- void animate_focus_glow(int target_alpha);+ void show_focus_ring();+ void hide_focus_ring();+ void update_trailing_action_visibility();+ void slide_site_settings_knobs(qreal travel);+ void update_completion_title();void highlight_location();bool text_matches_current_url() const;QString serialized_url() const;@@ -92,14 +117,22 @@ private:WebView::Omnibox m_omnibox;Autocomplete* m_autocomplete { nullptr };QToolButton* m_leading_icon_button { nullptr };+ bool m_shows_site_settings_button { false };+ QPointer<QWidget> m_site_settings_popover;+ QVariantAnimation* m_site_settings_knob_animation { nullptr };+ qreal m_site_settings_knob_travel { 0 };QToolButton* m_trailing_action_button { nullptr };QToolButton* m_zoom_indicator_button { nullptr };- QVariantAnimation* m_focus_glow_animation { nullptr };- QGraphicsDropShadowEffect* m_focus_glow_effect { nullptr };+ QGraphicsOpacityEffect* m_zoom_indicator_opacity { nullptr };+ QVariantAnimation* m_zoom_indicator_fade { nullptr };+ QLabel* m_completion_title { nullptr };+ QVariantAnimation* m_focus_ring_animation { nullptr };+ QGraphicsEffect* m_focus_ring_effect { nullptr };QAction* m_zoom_action { nullptr };Optional<URL::URL> m_url;bool m_url_is_hidden { false };+ bool m_is_editing_location { false };struct ParkedEditingSession {int cursor_position { 0 };@@ -113,7 +146,7 @@ private:bool m_has_pending_chrome_style_update { false };bool m_should_show_full_url_on_mouse_release { false };int m_text_leading_margin { 0 };- int m_focus_glow_alpha { 0 };+ qreal m_focus_ring_opacity { 0 };};}diff --git a/UI/Qt/MacWindow.h b/UI/Qt/MacWindow.hindex 93d8e199441..b0e2896e004 100644--- a/UI/Qt/MacWindow.h+++ b/UI/Qt/MacWindow.h@@ -14,6 +14,7 @@#include <Qt>+class QColor;class QDrag;class QWidget;@@ -25,6 +26,8 @@ Optional<u64> appkit_display_id_for_window(QWidget&);void hide_appkit_window_title(QWidget&);void make_appkit_window_resizable(QWidget&);void keep_appkit_window_visible_while_inactive(QWidget&);+// For windows that animate their own showing and hiding.+void disable_appkit_window_animations(QWidget&);void ensure_appkit_window_is_exposed(QWidget&);void set_appkit_window_content_aspect_ratio(QWidget&, Gfx::IntSize);void offset_appkit_window_controls(QWidget&, int x_offset, int y_offset);@@ -33,6 +36,14 @@ void offset_appkit_window_controls(QWidget&, int x_offset, int y_offset);void reapply_appkit_window_control_offsets(QWidget&);void install_appkit_event_capture();void make_appkit_window_first_responder(QWidget&);+// Rounds the corners of a native child widget's view, which shows what is below it through them, and outlines it.+void round_appkit_view_corners(QWidget&, qreal radius, QColor const& border_color);+// Puts the native view of the first widget right below the second one's, among the views of the second one's superview.+void stack_appkit_view_below(QWidget&, QWidget& sibling);+// The opacity of a native view embedded in another window, which has no window opacity of its own.+void set_appkit_view_opacity(QWidget&, qreal opacity);+// Clips a native view to rounded bottom corners, for a sheet that hangs from what is above it.+void round_appkit_view_bottom_corners(QWidget&, qreal radius);bool start_appkit_window_drag(QWidget&);Qt::DropAction execute_appkit_tab_drag(QWidget&, QDrag&);void show_appkit_dictionary_lookup(QWidget&, WebView::DictionaryLookup const&, Gfx::IntPoint);diff --git a/UI/Qt/MacWindow.mm b/UI/Qt/MacWindow.mmindex a625d4953c9..3d6eee37444 100644--- a/UI/Qt/MacWindow.mm+++ b/UI/Qt/MacWindow.mm@@ -402,6 +402,14 @@ void keep_appkit_window_visible_while_inactive(QWidget& widget)view.window.hidesOnDeactivate = NO;}+void disable_appkit_window_animations(QWidget& widget)+{+ auto* view = reinterpret_cast<NSView*>(widget.winId());+ if (!view || !view.window)+ return;+ view.window.animationBehavior = NSWindowAnimationBehaviorNone;+}+void ensure_appkit_window_is_exposed(QWidget& widget){auto* window = widget.windowHandle();@@ -519,4 +527,51 @@ void show_appkit_dictionary_lookup(QWidget& widget, WebView::DictionaryLookup coshow_dictionary_lookup(view, lookup, widget_position_to_ns_point(widget, position));}+void round_appkit_view_corners(QWidget& widget, qreal radius, QColor const& border_color)+{+ auto* view = reinterpret_cast<NSView*>(widget.winId());+ if (!view)+ return;+ view.wantsLayer = YES;+ auto* layer = view.layer;+ layer.cornerRadius = radius;+ layer.cornerCurve = kCACornerCurveContinuous;+ layer.masksToBounds = YES;+ layer.borderWidth = 1;+ auto* color = CGColorCreateSRGB(border_color.redF(), border_color.greenF(), border_color.blueF(), border_color.alphaF());+ layer.borderColor = color;+ CGColorRelease(color);+}++void stack_appkit_view_below(QWidget& widget, QWidget& sibling)+{+ auto* view = reinterpret_cast<NSView*>(widget.winId());+ auto* sibling_view = reinterpret_cast<NSView*>(sibling.winId());+ if (!view || !sibling_view || !sibling_view.superview)+ return;+ [sibling_view.superview addSubview:view positioned:NSWindowBelow relativeTo:sibling_view];+}++void round_appkit_view_bottom_corners(QWidget& widget, qreal radius)+{+ auto* view = reinterpret_cast<NSView*>(widget.winId());+ if (!view)+ return;+ view.wantsLayer = YES;+ auto* layer = view.layer;+ layer.cornerRadius = radius;+ layer.cornerCurve = kCACornerCurveContinuous;+ // NB: Qt's views are flipped, so the bottom of the view is at its layer's largest y.+ layer.maskedCorners = view.isFlipped ? (kCALayerMinXMaxYCorner | kCALayerMaxXMaxYCorner) : (kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner);+ layer.masksToBounds = YES;+}++void set_appkit_view_opacity(QWidget& widget, qreal opacity)+{+ auto* view = reinterpret_cast<NSView*>(widget.winId());+ if (!view)+ return;+ view.alphaValue = opacity;+}+}diff --git a/UI/Qt/Menu.cpp b/UI/Qt/Menu.cppindex c41295f503d..93def432c7b 100644--- a/UI/Qt/Menu.cpp+++ b/UI/Qt/Menu.cpp@@ -74,15 +74,14 @@ public:case WebView::ActionID::ToggleVerticalTabsExpanded:if (auto* parent = as_if<QWidget>(m_action->parent())) {auto const& tab_settings = WebView::Application::settings().tab_settings();- auto icon = tab_settings.vertical_tabs_position == WebView::VerticalTabsPosition::Right- ? (action.engaged() ? ChromeIcon::VerticalTabBarCollapseRight : ChromeIcon::VerticalTabBarExpandRight)- : (action.engaged() ? ChromeIcon::VerticalTabBarCollapse : ChromeIcon::VerticalTabBarExpand);+ auto icon = tab_settings.vertical_tabs_position == WebView::VerticalTabsPosition::Right ? ChromeIcon::SidebarRight : ChromeIcon::Sidebar;m_action->setIcon(create_chrome_icon(icon, parent->palette()));}break;case WebView::ActionID::ToggleBookmark:case WebView::ActionID::ToggleBookmarkViaToolbar:+ // A bookmarked page's star is filled in.if (auto* parent = as_if<QWidget>(m_action->parent())) {auto icon = action.engaged() ? ChromeIcon::StarFilled : ChromeIcon::Star;m_action->setIcon(create_chrome_icon(icon, parent->palette()));@@ -156,7 +155,7 @@ static void add_properties(QObject& object, T& menu_or_action)object.setProperty(key.to_byte_string().characters(), qstring_from_ak_string(value));}-static void initialize_native_control(WebView::Action& action, QAction& qaction, QPalette const& palette, IncludeActionIcon include_action_icon, IncludeActionShortcut include_action_shortcut)+static void initialize_native_control(WebView::Action& action, QAction& qaction, QPalette const& palette, IncludeActionIcon include_action_icon){static constexpr int const MENU_ICON_SIZE = 16;@@ -186,7 +185,11 @@ static void initialize_native_control(WebView::Action& action, QAction& qaction,case WebView::ActionID::ViewDownloads:if (include_action_icon == IncludeActionIcon::Yes)qaction.setIcon(create_chrome_icon(ChromeIcon::Download, palette));+#if defined(AK_OS_MACOS)+ qaction.setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_L));+#elseqaction.setShortcut(QKeySequence(Qt::CTRL | Qt::Key_J));+#endifbreak;case WebView::ActionID::Undo:@@ -220,6 +223,13 @@ static void initialize_native_control(WebView::Action& action, QAction& qaction,case WebView::ActionID::ToggleBookmarksBar:qaction.setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_B));break;+ case WebView::ActionID::ToggleVerticalTabsExpanded:+#if defined(AK_OS_MACOS)+ qaction.setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_S));+#else+ qaction.setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_S));+#endif+ break;case WebView::ActionID::AddBookmarkAllTabs:qaction.setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_D));break;@@ -235,6 +245,13 @@ static void initialize_native_control(WebView::Action& action, QAction& qaction,qaction.setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Y));#elseqaction.setShortcut(QKeySequence(Qt::CTRL | Qt::Key_H));+#endif+ break;+ case WebView::ActionID::ManageBookmarks:+#if defined(AK_OS_MACOS)+ qaction.setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_B));+#else+ qaction.setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_O));#endifbreak;case WebView::ActionID::ClearBrowsingData:@@ -262,7 +279,11 @@ static void initialize_native_control(WebView::Action& action, QAction& qaction,});break;case WebView::ActionID::ViewSource:+#if defined(AK_OS_MACOS)+ qaction.setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_U));+#elseqaction.setShortcut(QKeySequence(Qt::CTRL | Qt::Key_U));+#endifbreak;case WebView::ActionID::ZoomIn: {@@ -286,7 +307,7 @@ static void initialize_native_control(WebView::Action& action, QAction& qaction,break;}- qaction.setShortcutVisibleInContextMenu(include_action_shortcut == IncludeActionShortcut::Yes);+ qaction.setShortcutVisibleInContextMenu(true);if (action.is_checkable())qaction.setCheckable(true);@@ -295,7 +316,7 @@ static void initialize_native_control(WebView::Action& action, QAction& qaction,add_properties(qaction, action);}-static void add_items_to_menu(QMenu& qmenu, QWidget& parent, WebView::Menu& menu, IncludeActionShortcut include_action_shortcut)+static void add_items_to_menu(QMenu& qmenu, QWidget& parent, WebView::Menu& menu){menu.add_observer(MenuObserver::create(qmenu));add_properties(qmenu, menu);@@ -303,12 +324,12 @@ static void add_items_to_menu(QMenu& qmenu, QWidget& parent, WebView::Menu& menufor (auto& menu_item : menu.items()) {menu_item.visit([&](NonnullRefPtr<WebView::Action>& action) {- auto* qaction = create_application_action(parent, action, IncludeActionIcon::No, include_action_shortcut);+ auto* qaction = create_application_action(parent, action, IncludeActionIcon::No);qmenu.addAction(qaction);},[&](NonnullRefPtr<WebView::Menu> const& submenu) {auto* qsubmenu = new QMenu(qstring_from_ak_string(submenu->title()), &qmenu);- add_items_to_menu(*qsubmenu, parent, submenu, include_action_shortcut);+ add_items_to_menu(*qsubmenu, parent, submenu);if (submenu->render_group_icon())qsubmenu->setIcon(create_chrome_icon(ChromeIcon::Folder, parent.palette()));@@ -364,17 +385,17 @@ void populate_session_history_traversal_menu(QMenu& menu, WebContentView& view,append_session_history_traversal_menu_items(menu, view, direction);}-QMenu* create_application_menu(QWidget& parent, WebView::Menu& menu, IncludeActionShortcut include_action_shortcut)+QMenu* create_application_menu(QWidget& parent, WebView::Menu& menu){auto* application_menu = new QMenu(qstring_from_ak_string(menu.title()), &parent);- add_items_to_menu(*application_menu, parent, menu, include_action_shortcut);+ add_items_to_menu(*application_menu, parent, menu);return application_menu;}-void repopulate_application_menu(QMenu& menu, QWidget& parent, WebView::Menu& source, IncludeActionShortcut include_action_shortcut)+void repopulate_application_menu(QMenu& menu, QWidget& parent, WebView::Menu& source){menu.clear();- add_items_to_menu(menu, parent, source, include_action_shortcut);+ add_items_to_menu(menu, parent, source);}static void insert_dynamic_history_action(QMenu& menu, QAction* before, QAction& action)@@ -458,7 +479,7 @@ void update_history_menu(QMenu& menu, WebContentView* view)QMenu* create_context_menu(QWidget& parent, WebContentView& view, WebView::Menu& menu){- auto* application_menu = create_application_menu(parent, menu, IncludeActionShortcut::No);+ auto* application_menu = create_application_menu(parent, menu);menu.on_activation = [view = QPointer { &view }, application_menu = QPointer { application_menu }](Gfx::IntPoint position) {if (view && application_menu)@@ -468,10 +489,10 @@ QMenu* create_context_menu(QWidget& parent, WebContentView& view, WebView::Menu&return application_menu;}-QAction* create_application_action(QWidget& parent, WebView::Action& action, IncludeActionIcon include_action_icon, IncludeActionShortcut include_action_shortcut)+QAction* create_application_action(QWidget& parent, WebView::Action& action, IncludeActionIcon include_action_icon){auto* qaction = new QAction(&parent);- initialize_native_control(action, *qaction, parent.palette(), include_action_icon, include_action_shortcut);+ initialize_native_control(action, *qaction, parent.palette(), include_action_icon);return qaction;}diff --git a/UI/Qt/Menu.h b/UI/Qt/Menu.hindex deba966a5ef..c19f221f612 100644--- a/UI/Qt/Menu.h+++ b/UI/Qt/Menu.h@@ -23,18 +23,13 @@ enum class IncludeActionIcon : u8 {Yes,};-enum class IncludeActionShortcut : u8 {- No,- Yes,-};--QMenu* create_application_menu(QWidget& parent, WebView::Menu&, IncludeActionShortcut = IncludeActionShortcut::Yes);-void repopulate_application_menu(QMenu& menu, QWidget& parent, WebView::Menu& source, IncludeActionShortcut = IncludeActionShortcut::Yes);+QMenu* create_application_menu(QWidget& parent, WebView::Menu&);+void repopulate_application_menu(QMenu& menu, QWidget& parent, WebView::Menu& source);void update_history_menu(QMenu& menu, WebContentView*);void populate_session_history_traversal_menu(QMenu& menu, WebContentView&, int direction);QMenu* create_context_menu(QWidget& parent, WebContentView&, WebView::Menu&);-QAction* create_application_action(QWidget& parent, WebView::Action&, IncludeActionIcon = IncludeActionIcon::Yes, IncludeActionShortcut = IncludeActionShortcut::Yes);+QAction* create_application_action(QWidget& parent, WebView::Action&, IncludeActionIcon = IncludeActionIcon::Yes);#if defined(AK_OS_MACOS)void enable_menu_icons(QMenu&);diff --git a/UI/Qt/Menu.mm b/UI/Qt/Menu.mmindex 6ddb0e25741..9bc1436479f 100644--- a/UI/Qt/Menu.mm+++ b/UI/Qt/Menu.mm@@ -39,17 +39,23 @@ static void hide_native_context_menu_shortcuts(QMenu& menu)return;menu.setProperty(property, true);- // Qt ignores QAction::isShortcutVisibleInContextMenu() for native menus. Run after Qt's aboutToShow handling,- // which can update the native items.+ // Qt ignores QAction::isShortcutVisibleInContextMenu() for native menus, so the shortcuts of the actions that+ // don't show theirs are removed from the native items. Run after Qt's aboutToShow handling, which can update the+ // native items.QObject::connect(menu.platformMenu(), &QPlatformMenu::aboutToShow, &menu, [&menu] {- for (auto* action : menu.actions()) {+ auto actions = menu.actions();+ for (auto* action : actions) {if (auto* submenu = action->menu())hide_native_context_menu_shortcuts(*submenu);}- for (NSMenuItem* item in menu.toNSMenu().itemArray) {- item.keyEquivalent = @"";- item.keyEquivalentModifierMask = 0;+ // NB: The native menu has an item for each action, separators included, in the same order.+ NSArray<NSMenuItem*>* items = menu.toNSMenu().itemArray;+ for (NSUInteger index = 0; index < items.count; ++index) {+ if (index < static_cast<NSUInteger>(actions.size()) && actions[index]->isShortcutVisibleInContextMenu())+ continue;+ items[index].keyEquivalent = @"";+ items[index].keyEquivalentModifierMask = 0;}});}diff --git a/UI/Qt/Motion.h b/UI/Qt/Motion.hnew file mode 100644index 00000000000..256307b8de3--- /dev/null+++ b/UI/Qt/Motion.h@@ -0,0 +1,50 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <QEasingCurve>+#include <QPointF>++namespace Ladybird::Motion {++// The durations of the chrome's motion, in milliseconds.+// Hover out, and any state that must feel immediate.+constexpr inline int INSTANT = 0;+// Hover in, focus, menus, the active tab.+constexpr inline int FAST = 100;+// Tabs opening, closing and reordering.+constexpr inline int BASE = 160;+// The sidebar, and anything else that moves far.+constexpr inline int SLOW = 220;+// The way a menu or popover disappears.+constexpr inline int EXIT = 80;++inline QEasingCurve cubic_bezier(qreal x1, qreal y1, qreal x2, qreal y2)+{+ QEasingCurve curve(QEasingCurve::BezierSpline);+ curve.addCubicBezierSegment({ x1, y1 }, { x2, y2 }, { 1, 1 });+ return curve;+}++// For things that appear: fast at first, settling gently.+inline QEasingCurve enter_easing() { return cubic_bezier(0.2, 0, 0, 1); }+// For things that leave: slow at first, then gone.+inline QEasingCurve exit_easing() { return cubic_bezier(0.4, 0, 1, 1); }+// For things that move from one place to another.+inline QEasingCurve move_easing() { return cubic_bezier(0.3, 0, 0.2, 1); }++// How far along a motion that goes from rest to a peak and back is, from 0 at rest to 1 at the peak. Each half is eased+// as things that appear are.+inline qreal there_and_back(qreal progress, qreal peak_at)+{+ static auto const easing = enter_easing();+ if (progress < peak_at)+ return easing.valueForProgress(progress / peak_at);+ return 1 - easing.valueForProgress((progress - peak_at) / (1 - peak_at));+}++}diff --git a/UI/Qt/PictureInPictureWindow.cpp b/UI/Qt/PictureInPictureWindow.cppindex 0c5d24af88c..431ca572623 100644--- a/UI/Qt/PictureInPictureWindow.cpp+++ b/UI/Qt/PictureInPictureWindow.cpp@@ -64,6 +64,10 @@ public:setScreen(screen);setAttribute(Qt::WA_ShowWithoutActivating);+#if defined(AK_OS_MACOS)+ // NB: The window is clear outside its rounded corners.+ setAttribute(Qt::WA_TranslucentBackground);+#endif#if defined(AK_OS_MACOS)// A tool window otherwise hides whenever Ladybird is inactive. Qt's WA_MacAlwaysShowToolWindow would also make// it order every window to the front whenever Ladybird is activated, bringing browser windows forward too.@@ -125,6 +129,8 @@ public:#if defined(AK_OS_MACOS)// A frameless window cannot be resized from its edges on macOS unless AppKit is told it is resizable.make_appkit_window_resizable(*this);+ // The window has the rounded corners and the faint edge of a floating video.+ round_appkit_view_corners(*this, 12, QColor(255, 255, 255, 20));#endifset_size_limits(video_size);lock_aspect_ratio();diff --git a/UI/Qt/Popover.cpp b/UI/Qt/Popover.cppindex 88a4dba3b7a..ef51075b321 100644--- a/UI/Qt/Popover.cpp+++ b/UI/Qt/Popover.cpp@@ -5,24 +5,41 @@*/#include <AK/StdLibExtras.h>+#include <AK/TemporaryChange.h>#include <UI/Qt/ChromeStyle.h>+#include <UI/Qt/Motion.h>#include <UI/Qt/Popover.h>+#include <UI/Qt/SystemAppearance.h>+#include <UI/Qt/Theme.h>+#include <QCloseEvent>+#include <QFocusEvent>#include <QFrame>#include <QGraphicsDropShadowEffect>+#include <QGraphicsOpacityEffect>#include <QGuiApplication>#include <QHBoxLayout>#include <QHideEvent>#include <QLabel>+#include <QMouseEvent>+#include <QPainter>+#include <QPixmap>#include <QPushButton>#include <QScreen>#include <QShowEvent>#include <QVBoxLayout>+#include <QVariantAnimation>+#include <QWindow>++#if defined(AK_OS_MACOS)+# include <UI/Qt/MacWindow.h>+#endifnamespace Ladybird {static constexpr int POPOVER_ANCHOR_GAP = 4;-static constexpr int POPOVER_SHADOW_MARGIN = 24;+// NB: The popovers' shadow falls downward, so it needs less room above the card.+static constexpr QMargins POPOVER_SHADOW_MARGINS { 60, 36, 60, 90 };// The window is transparent around a card that casts its own shadow. The window has no shadow of its own, which would// not follow the card's rounded corners.@@ -35,7 +52,7 @@ Popover::Popover(QWidget* parent)setAttribute(Qt::WA_TranslucentBackground);auto* layout = new QVBoxLayout(this);- layout->setContentsMargins(POPOVER_SHADOW_MARGIN, POPOVER_SHADOW_MARGIN, POPOVER_SHADOW_MARGIN, POPOVER_SHADOW_MARGIN);+ layout->setContentsMargins(POPOVER_SHADOW_MARGINS);layout->setSpacing(0);m_card = new QFrame(this);@@ -45,42 +62,354 @@ Popover::Popover(QWidget* parent)cast_popover_shadow(*m_card);}+// An opening popover grows to its full size from a little smaller.+static constexpr qreal OPENING_POPOVER_STARTING_SCALE = 0.97;++#if defined(AK_OS_MACOS)+// A picture of a popover that is opening, which grows out of the popover's anchor as it fades in. The popover itself+// is shown at once, transparent, so it takes the keyboard and the pointer as a popup does, and appears when the picture+// has grown.+class OpeningPopoverSnapshot final : public QWidget {+public:+ AK_ALLOC_WITH_KMALLOC;++ OpeningPopoverSnapshot(QWidget& popover, QPixmap snapshot, QPointF origin, Function<void()> on_finished)+ : QWidget(nullptr, Qt::ToolTip | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint | Qt::WindowTransparentForInput)+ , m_snapshot(AK::move(snapshot))+ , m_origin(origin)+ {+ setAttribute(Qt::WA_TranslucentBackground);+ setAttribute(Qt::WA_ShowWithoutActivating);+ setAttribute(Qt::WA_TransparentForMouseEvents);+ setAttribute(Qt::WA_DeleteOnClose);+ setGeometry(popover.geometry());+ show();++ auto* animation = new QVariantAnimation(this);+ animation->setDuration(Motion::FAST);+ animation->setEasingCurve(Motion::enter_easing());+ animation->setStartValue(0.0);+ animation->setEndValue(1.0);+ QObject::connect(animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ m_progress = value.toReal();+ update();+ });+ QObject::connect(animation, &QVariantAnimation::finished, this, [this, on_finished = AK::move(on_finished)] {+ on_finished();+ close();+ });+ animation->start(QAbstractAnimation::DeleteWhenStopped);+ }++private:+ virtual void paintEvent(QPaintEvent*) override+ {+ auto scale = OPENING_POPOVER_STARTING_SCALE + ((1.0 - OPENING_POPOVER_STARTING_SCALE) * m_progress);++ QPainter painter(this);+ painter.setRenderHint(QPainter::SmoothPixmapTransform);+ painter.setOpacity(m_progress);+ painter.translate(m_origin);+ painter.scale(scale, scale);+ painter.translate(-m_origin);+ painter.drawPixmap(0, 0, m_snapshot);+ }++ QPixmap m_snapshot;+ QPointF m_origin;+ qreal m_progress { 0 };+};+#endif++// A popover fades in quickly as it opens, growing out of its anchor.void Popover::showEvent(QShowEvent* event){QWidget::showEvent(event);++ Optional<QPointF> origin;+ if (!SystemAppearance::prefers_reduced_motion() && m_anchor_point.has_value())+ origin = QPointF(mapFromGlobal(*m_anchor_point));++#if defined(AK_OS_MACOS)+ // NB: AppKit would fade the window out as it hides, under the picture that fades out in its place.+ disable_appkit_window_animations(*this);++ if (!origin.has_value()) {+ auto* animation = new QVariantAnimation(this);+ animation->setDuration(Motion::FAST);+ animation->setEasingCurve(Motion::enter_easing());+ animation->setStartValue(0.0);+ animation->setEndValue(1.0);+ QObject::connect(animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ setWindowOpacity(value.toReal());+ });+ setWindowOpacity(0);+ animation->start(QAbstractAnimation::DeleteWhenStopped);+ } else {+ auto snapshot = grab();+ setWindowOpacity(0);+ m_opening_snapshot = new OpeningPopoverSnapshot(*this, AK::move(snapshot), *origin, [popover = QPointer { this }] {+ if (popover)+ popover->setWindowOpacity(1);+ });+ }+#else+ fade_in(origin);+#endif+if (on_visibility_change)on_visibility_change(true);}+#if defined(AK_OS_MACOS)+// A picture of a popover that has just closed, which fades out where it was. The popover itself closes at once, so+// that it lets go of the keyboard and the pointer as a popup does.+class ClosingPopoverSnapshot final : public QWidget {+public:+ AK_ALLOC_WITH_KMALLOC;++ ClosingPopoverSnapshot(QPixmap snapshot, QRect geometry)+ : QWidget(nullptr, Qt::ToolTip | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint | Qt::WindowTransparentForInput)+ , m_snapshot(AK::move(snapshot))+ {+ setAttribute(Qt::WA_TranslucentBackground);+ setAttribute(Qt::WA_ShowWithoutActivating);+ setAttribute(Qt::WA_TransparentForMouseEvents);+ setAttribute(Qt::WA_DeleteOnClose);+ setGeometry(geometry);+ show();++ auto* animation = new QVariantAnimation(this);+ animation->setDuration(Motion::EXIT);+ animation->setEasingCurve(Motion::exit_easing());+ animation->setStartValue(1.0);+ animation->setEndValue(0.0);+ QObject::connect(animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ m_opacity = value.toReal();+ update();+ });+ QObject::connect(animation, &QVariantAnimation::finished, this, &QWidget::close);+ animation->start(QAbstractAnimation::DeleteWhenStopped);+ }++private:+ virtual void paintEvent(QPaintEvent*) override+ {+ QPainter painter(this);+ painter.setOpacity(m_opacity);+ painter.drawPixmap(0, 0, m_snapshot);+ }++ QPixmap m_snapshot;+ qreal m_opacity { 1 };+};+#endif++#if !defined(AK_OS_MACOS)+void Popover::stop_fading()+{+ if (!m_fading_animation)+ return;+ // NB: The animation deletes itself once stopped.+ m_fading_animation->stop();+ m_fading_animation = nullptr;+ m_is_fading_out = false;+ m_fading_picture = {};+ m_fading_origin = {};+ m_card->show();+ layout()->setEnabled(true);+}++void Popover::paintEvent(QPaintEvent* event)+{+ if (!m_fading_picture.has_value()) {+ QWidget::paintEvent(event);+ return;+ }+ QPainter painter(this);+ painter.setOpacity(m_fading_progress);+ if (m_fading_origin.has_value()) {+ auto scale = OPENING_POPOVER_STARTING_SCALE + ((1.0 - OPENING_POPOVER_STARTING_SCALE) * m_fading_progress);+ painter.setRenderHint(QPainter::SmoothPixmapTransform);+ painter.translate(*m_fading_origin);+ painter.scale(scale, scale);+ painter.translate(-*m_fading_origin);+ }+ painter.drawPixmap(0, 0, *m_fading_picture);+}+#endif++void Popover::setVisible(bool visible)+{+#if defined(AK_OS_MACOS)+ // The picture a closing popover fades out with is taken while it is still shown, as it looked, with the focus that+ // it loses once hidden.+ if (!visible && isVisible() && !size().isEmpty())+ m_closing_picture = grab();+#else+ if (visible) {+ stop_fading();+ } else if (isVisible() && !m_is_finishing_close) {+ fade_out(AfterFadingOut::Hide);+ return;+ }+#endif+ QWidget::setVisible(visible);+}++#if !defined(AK_OS_MACOS)+// NB: A window of its own first appears a frame or more after it is shown on Wayland, so a picture of the popover in a+// window of its own would leave a frame with neither. The popover fades out a picture of itself in its own window+// instead, and hides or closes once it has faded. One the compositor closed itself, such as a popup dismissed by a+// click outside it, is already gone.+void Popover::closeEvent(QCloseEvent* event)+{+ if (!event->spontaneous() && isVisible() && !m_is_finishing_close) {+ event->ignore();+ fade_out(AfterFadingOut::Close);+ return;+ }+ QWidget::closeEvent(event);+}++// NB: The card is hidden behind its picture, with the layout set aside so the window keeps its size.+void Popover::show_fading_picture()+{+ m_fading_picture = grab();+ layout()->setEnabled(false);+ m_card->hide();+}++// NB: As it fades out, the popover fades in a picture of itself in its own window, for the same reason.+void Popover::fade_in(Optional<QPointF> origin)+{+ stop_fading();+ show_fading_picture();+ m_fading_origin = origin;+ m_fading_progress = 0;+ m_fading_animation = new QVariantAnimation(this);+ m_fading_animation->setDuration(Motion::FAST);+ m_fading_animation->setEasingCurve(Motion::enter_easing());+ m_fading_animation->setStartValue(0.0);+ m_fading_animation->setEndValue(1.0);+ QObject::connect(m_fading_animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ m_fading_progress = value.toReal();+ update();+ });+ QObject::connect(m_fading_animation, &QVariantAnimation::finished, this, [this] {+ m_fading_animation = nullptr;+ m_fading_picture = {};+ m_fading_origin = {};+ m_card->show();+ layout()->setEnabled(true);+ });+ m_fading_animation->start(QAbstractAnimation::DeleteWhenStopped);+}++void Popover::fade_out(AfterFadingOut after_fading_out)+{+ if (m_is_fading_out)+ return;+ stop_fading();+ show_fading_picture();+ m_is_fading_out = true;+ m_fading_progress = 1;+ m_fading_animation = new QVariantAnimation(this);+ m_fading_animation->setDuration(Motion::EXIT);+ m_fading_animation->setEasingCurve(Motion::exit_easing());+ m_fading_animation->setStartValue(1.0);+ m_fading_animation->setEndValue(0.0);+ QObject::connect(m_fading_animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ m_fading_progress = value.toReal();+ update();+ });+ QObject::connect(m_fading_animation, &QVariantAnimation::finished, this, [this, after_fading_out] {+ TemporaryChange finishing_close { m_is_finishing_close, true };+ if (after_fading_out == AfterFadingOut::Close)+ close();+ else+ hide();+ });+ m_fading_animation->start(QAbstractAnimation::DeleteWhenStopped);+}+#endif++// The window reaches well past the card, to make room for its shadow. A press there is outside the popover as far as+// anyone can see, so it closes the popover like a press anywhere else outside it.+void Popover::mousePressEvent(QMouseEvent* event)+{+#if !defined(AK_OS_MACOS)+ // A popover that is fading out has closed, and takes no more presses.+ if (m_is_fading_out) {+ event->accept();+ return;+ }+#endif+ if (!m_card->geometry().contains(event->position().toPoint())) {+ close();+ event->accept();+ return;+ }+ QWidget::mousePressEvent(event);+}++// A popover fades out quickly as it closes.void Popover::hideEvent(QHideEvent* event){QWidget::hideEvent(event);++#if defined(AK_OS_MACOS)+ if (m_opening_snapshot)+ m_opening_snapshot->close();+ setWindowOpacity(1);+ if (auto picture = exchange(m_closing_picture, {}); picture.has_value() && !event->spontaneous())+ new ClosingPopoverSnapshot(picture.release_value(), geometry());+#else+ stop_fading();+#endif+if (on_visibility_change)on_visibility_change(false);}// A message that asks whether to act on it. Leaving the popover in any other way than accepting it, such as by clicking// outside it, dismisses the message.-MessagePopover::MessagePopover(QWidget* parent, int width, QString const& title, QString const& body, QString const& dismiss_text, QString const& accept_text)+MessagePopover::MessagePopover(QWidget* parent, int width, QString const& title, QString const& body, QString const& dismiss_text, QString const& accept_text, QIcon const& icon): Popover(parent){card().setObjectName("LadybirdMessagePopover");card().setFixedWidth(width);auto* layout = new QVBoxLayout(&card());- layout->setContentsMargins(16, 14, 16, 14);- layout->setSpacing(10);+ layout->setContentsMargins(16, 16, 16, 16);+ layout->setSpacing(6);auto* title_label = new QLabel(title, &card());title_label->setObjectName("LadybirdMessagePopoverTitle");title_label->setWordWrap(true);- layout->addWidget(title_label);+ if (icon.isNull()) {+ layout->addWidget(title_label);+ } else {+ auto* header = new QHBoxLayout;+ header->setSpacing(12);+ auto* icon_tile = new QLabel(&card());+ icon_tile->setObjectName("LadybirdMessagePopoverIcon");+ icon_tile->setFixedSize(32, 32);+ icon_tile->setAlignment(Qt::AlignCenter);+ icon_tile->setPixmap(icon.pixmap(QSize(18, 18), devicePixelRatioF()));+ header->addWidget(icon_tile, 0, Qt::AlignTop);+ header->addWidget(title_label, 1);+ layout->addLayout(header);+ }- auto* body_label = new QLabel(body, &card());- body_label->setObjectName("LadybirdMessagePopoverBody");- body_label->setWordWrap(true);- layout->addWidget(body_label);+ if (!body.isEmpty()) {+ auto* body_label = new QLabel(body, &card());+ body_label->setObjectName("LadybirdMessagePopoverBody");+ body_label->setWordWrap(true);+ layout->addWidget(body_label);+ }+ layout->addSpacing(8);auto* button_layout = new QHBoxLayout;button_layout->setSpacing(8);button_layout->addStretch();@@ -88,12 +417,16 @@ MessagePopover::MessagePopover(QWidget* parent, int width, QString const& title,auto* dismiss_button = new QPushButton(dismiss_text, &card());dismiss_button->setObjectName("LadybirdMessagePopoverDismissButton");+ // NB: The platform style lays out a push button by a frame of its own rather than by the button, which would+ // make it overlap its neighbors.+ dismiss_button->setAttribute(Qt::WA_LayoutUsesWidgetRect);dismiss_button->setFocusPolicy(Qt::NoFocus);QObject::connect(dismiss_button, &QPushButton::clicked, this, [this] { close(); });button_layout->addWidget(dismiss_button);auto* accept_button = new QPushButton(accept_text, &card());accept_button->setObjectName("LadybirdMessagePopoverAcceptButton");+ accept_button->setAttribute(Qt::WA_LayoutUsesWidgetRect);accept_button->setDefault(true);QObject::connect(accept_button, &QPushButton::clicked, this, [this] {m_is_accepted = true;@@ -117,13 +450,15 @@ void MessagePopover::hideEvent(QHideEvent* event)on_dismiss();}-// Places the popover's card below the anchor with their right edges aligned, kept on the anchor's screen, and above the-// anchor when there is no room below it. Only the shadow around the card may reach past the edge of the screen.-void move_popover_below(Popover& popover, QWidget& anchor)+// Places the popover's card below the anchor with their left or right edges aligned, kept on the anchor's screen, and+// above the anchor when there is no room below it. Only the shadow around the card may reach past the edge of the screen.+void move_popover_below(Popover& popover, QWidget& anchor, PopoverAlignment alignment, Optional<QRect> anchor_rect){- auto card_size = popover.size().shrunkBy({ POPOVER_SHADOW_MARGIN, POPOVER_SHADOW_MARGIN, POPOVER_SHADOW_MARGIN, POPOVER_SHADOW_MARGIN });- auto anchor_position = anchor.mapToGlobal(anchor.rect().bottomRight());- auto card_position = QPoint(anchor_position.x() - card_size.width(), anchor_position.y() + POPOVER_ANCHOR_GAP);+ auto rect = anchor_rect.value_or(anchor.rect());+ auto card_size = popover.size().shrunkBy(POPOVER_SHADOW_MARGINS);+ auto anchor_position = anchor.mapToGlobal(rect.bottomRight());+ auto card_x = alignment == PopoverAlignment::Leading ? anchor.mapToGlobal(rect.topLeft()).x() : anchor_position.x() - card_size.width();+ auto card_position = QPoint(card_x, anchor_position.y() + POPOVER_ANCHOR_GAP);if (auto* screen = QGuiApplication::screenAt(anchor_position)) {auto available_geometry = screen->availableGeometry();@@ -132,22 +467,305 @@ void move_popover_below(Popover& popover, QWidget& anchor)if (card_position.x() + card_size.width() > available_geometry.right())card_position.setX(available_geometry.right() - card_size.width() + 1);if (card_position.y() + card_size.height() > available_geometry.bottom())- card_position.setY(anchor.mapToGlobal(anchor.rect().topRight()).y() - card_size.height() - POPOVER_ANCHOR_GAP);+ card_position.setY(anchor.mapToGlobal(rect.topRight()).y() - card_size.height() - POPOVER_ANCHOR_GAP);if (card_position.y() < available_geometry.top())card_position.setY(available_geometry.top());}- popover.move(card_position - QPoint(POPOVER_SHADOW_MARGIN, POPOVER_SHADOW_MARGIN));+ popover.move(card_position - QPoint(POPOVER_SHADOW_MARGINS.left(), POPOVER_SHADOW_MARGINS.top()));++ // The popover grows out of the corner of its card nearest the anchor.+ auto anchor_x = alignment == PopoverAlignment::Leading ? card_position.x() : card_position.x() + card_size.width();+ popover.set_anchor_point(QPoint(anchor_x, card_position.y()));}// Cards that float over other content cast the same shadow as popovers, whether they are windows of their own or not.void cast_popover_shadow(QWidget& card){auto* shadow = new QGraphicsDropShadowEffect(&card);- shadow->setBlurRadius(24);- shadow->setOffset(0, 4);- shadow->setColor(QColor(0, 0, 0, 72));+ shadow->setBlurRadius(ChromeStyle::drop_shadow_blur_radius(36));+ shadow->setOffset(0, 14);+ shadow->setColor(QColor(0, 0, 0, Theme::is_dark() ? 115 : 41));card.setGraphicsEffect(shadow);}+static constexpr int SHEET_SHADOW_MARGIN = 100;++// The shape that casts the shadow. It lies under the surface, so only the shadow around it shows.+class FloatingShadowCaster final : public QWidget {+public:+ AK_ALLOC_WITH_KMALLOC;++ FloatingShadowCaster(QWidget& parent, qreal corner_radius, FloatingShadowTone tone, FloatingShadowKind kind)+ : QWidget(&parent)+ , m_corner_radius(corner_radius)+ , m_tone(tone)+ {+ auto is_dark = tone == FloatingShadowTone::Dark || Theme::is_dark();+ auto* shadow = new QGraphicsDropShadowEffect(this);+ if (kind == FloatingShadowKind::Sheet) {+ shadow->setBlurRadius(ChromeStyle::drop_shadow_blur_radius(40));+ shadow->setOffset(0, 18);+ shadow->setColor(QColor(0, 0, 0, is_dark ? 140 : 56));+ } else {+ shadow->setBlurRadius(ChromeStyle::drop_shadow_blur_radius(36));+ shadow->setOffset(0, 14);+ shadow->setColor(QColor(0, 0, 0, is_dark ? 115 : 41));+ }+ setGraphicsEffect(shadow);+ }++private:+ virtual void paintEvent(QPaintEvent*) override+ {+ QPainter painter(this);+ painter.setRenderHint(QPainter::Antialiasing);+ painter.setPen(Qt::NoPen);+ painter.setBrush(m_tone == FloatingShadowTone::Dark ? QColor(28, 28, 30) : Theme::panel().surface);+ painter.drawRoundedRect(QRectF(rect()), m_corner_radius, m_corner_radius);+ }++ qreal m_corner_radius { 0 };+ FloatingShadowTone m_tone { FloatingShadowTone::FollowTheme };+};++class FloatingShadow final : public QWidget {+public:+ AK_ALLOC_WITH_KMALLOC;++ // NB: On macOS, like the suggestions under the address field, the shadow is a window of its own embedded in the+ // browser window, so it stacks above the page's native view, while letting the mouse through to it. Elsewhere+ // the page and the surface are drawn in the window itself, so the shadow is a widget beside the surface.+ FloatingShadow(QWidget& surface, qreal corner_radius, FloatingShadowTone tone, FloatingShadowKind kind)+#if defined(AK_OS_MACOS)+ : QWidget(surface.window(), Qt::Tool | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint | Qt::WindowTransparentForInput)+#else+ : QWidget(surface.parentWidget())+#endif+ , m_surface(&surface)+ , m_margins(kind == FloatingShadowKind::Sheet+ ? QMargins(SHEET_SHADOW_MARGIN, 0, SHEET_SHADOW_MARGIN, SHEET_SHADOW_MARGIN)+ : POPOVER_SHADOW_MARGINS)+ {+ setAttribute(Qt::WA_TranslucentBackground);+ setAttribute(Qt::WA_ShowWithoutActivating);+ setAttribute(Qt::WA_TransparentForMouseEvents);+#if defined(AK_OS_MACOS)+ setAttribute(Qt::WA_NativeWindow);+#endif+ auto* layout = new QVBoxLayout(this);+ layout->setContentsMargins(m_margins);+ layout->addWidget(new FloatingShadowCaster(*this, corner_radius, tone, kind));++ watch_surface_and_its_ancestors();+ connect(&surface, &QObject::destroyed, this, &QObject::deleteLater);+ hide();+ follow_surface();+ }++private:+ virtual bool eventFilter(QObject*, QEvent* event) override+ {+ switch (event->type()) {+ case QEvent::Move:+ case QEvent::Resize:+ case QEvent::Show:+ case QEvent::Hide:+ case QEvent::ZOrderChange:+ follow_surface();+ break;+ case QEvent::ParentChange:+ // NB: The surface can move to another window with its tab, so the shadow watches the widgets it now lies in.+ watch_surface_and_its_ancestors();+ follow_surface();+ break;+ default:+ break;+ }+ return false;+ }++ // The surface moves in the window when it or any widget it lies in moves.+ void watch_surface_and_its_ancestors()+ {+ if (!m_surface)+ return;+ for (QWidget* widget = m_surface; widget; widget = widget->isWindow() ? nullptr : widget->parentWidget())+ widget->installEventFilter(this);+ }++ void follow_surface()+ {+ // NB: The shadow is deleted only after its surface, and may still hear from the surface's window until then.+ if (m_is_following || !m_surface)+ return;+ TemporaryChange following { m_is_following, true };++ if (!m_surface->isVisible()) {+ hide();+ return;+ }++#if defined(AK_OS_MACOS)+ // NB: The shadow belongs to the surface's window, so it is not deleted with a window the surface has left.+ if (parentWidget() != m_surface->window())+ setParent(m_surface->window(), windowFlags());++ // NB: The shadow is stacked right below the surface's native view, among the views of the surface's native+ // parent, so it is placed in that parent's coordinates.+ auto* host = m_surface->nativeParentWidget();+ if (!host)+ host = m_surface->window();+ (void)winId();+ windowHandle()->setParent(host->windowHandle());+ auto surface_rect = QRect(m_surface->mapTo(host, QPoint()), m_surface->size());+ setGeometry(surface_rect.marginsAdded(m_margins));+ show();+ stack_appkit_view_below(*this, *m_surface);+#else+ if (parentWidget() != m_surface->parentWidget())+ setParent(m_surface->parentWidget());+ setGeometry(m_surface->geometry().marginsAdded(m_margins));+ show();+ stackUnder(m_surface);+#endif+ }++ QPointer<QWidget> m_surface;+ QMargins m_margins;+ bool m_is_following { false };+};++QWidget& cast_floating_shadow(QWidget& surface, qreal corner_radius, FloatingShadowTone tone, FloatingShadowKind kind)+{+ return *new FloatingShadow(surface, corner_radius, tone, kind);+}++void set_floating_window_opacity(QWidget& window, qreal opacity)+{+#if defined(AK_OS_MACOS)+ set_appkit_view_opacity(window, opacity);+#else+ // NB: Wayland has no window opacity, and a widget in a window has none either, so those fade by an effect instead.+ static auto const has_window_opacity = !QGuiApplication::platformName().startsWith(QStringLiteral("wayland"));+ if (window.isWindow() && has_window_opacity) {+ window.setWindowOpacity(opacity);+ return;+ }+ auto* effect = qobject_cast<QGraphicsOpacityEffect*>(window.graphicsEffect());+ if (opacity >= 1.0) {+ if (effect)+ window.setGraphicsEffect(nullptr);+ return;+ }+ if (!effect) {+ // NB: A widget has only one effect, and one it casts its shadow with is left alone.+ if (window.graphicsEffect())+ return;+ effect = new QGraphicsOpacityEffect(&window);+ window.setGraphicsEffect(effect);+ }+ effect->setOpacity(opacity);+#endif+}++PopoverSwitch::PopoverSwitch(QWidget* parent)+ : QCheckBox(parent)+{+ setAttribute(Qt::WA_MacShowFocusRect, false);+ setAttribute(Qt::WA_LayoutUsesWidgetRect);+ setFocusPolicy(Qt::StrongFocus);+ setFixedSize(sizeHint());+}++static constexpr int CHECK_BOX_SIZE = 16;+static constexpr int CHECK_BOX_TEXT_GAP = 8;++PopoverCheckBox::PopoverCheckBox(QString const& text, QWidget* parent)+ : QCheckBox(text, parent)+{+ setAttribute(Qt::WA_MacShowFocusRect, false);+}++// Focus that came from a click isn't ringed.+static bool is_keyboard_focus_reason(Qt::FocusReason reason)+{+ return reason == Qt::TabFocusReason || reason == Qt::BacktabFocusReason || reason == Qt::ShortcutFocusReason;+}++void PopoverSwitch::focusInEvent(QFocusEvent* event)+{+ m_has_keyboard_focus = is_keyboard_focus_reason(event->reason());+ QCheckBox::focusInEvent(event);+}++void PopoverCheckBox::focusInEvent(QFocusEvent* event)+{+ m_has_keyboard_focus = is_keyboard_focus_reason(event->reason());+ QCheckBox::focusInEvent(event);+}++QSize PopoverCheckBox::sizeHint() const+{+ auto metrics = fontMetrics();+ return { CHECK_BOX_SIZE + CHECK_BOX_TEXT_GAP + metrics.horizontalAdvance(text()), max(CHECK_BOX_SIZE, metrics.height()) };+}++void PopoverCheckBox::paintEvent(QPaintEvent*)+{+ QPainter painter(this);+ painter.setRenderHint(QPainter::Antialiasing);+ QRectF box { 0, (height() - CHECK_BOX_SIZE) / 2.0, CHECK_BOX_SIZE, CHECK_BOX_SIZE };+ auto const& panel = Theme::panel();+ if (isChecked()) {+ painter.setPen(Qt::NoPen);+ painter.setBrush(Theme::accent());+ painter.drawRoundedRect(box, 4, 4);+ // The check is drawn on a 16 px grid, scaled into the middle of the box.+ painter.save();+ painter.translate(box.center());+ painter.scale(11.0 / 16, 11.0 / 16);+ painter.translate(-8, -8);+ painter.setPen(QPen(Qt::white, 2.4, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));+ QPointF check[] { { 3.5, 8.5 }, { 6.5, 11.5 }, { 12.5, 4.5 } };+ painter.drawPolyline(check, 3);+ painter.restore();+ } else {+ painter.setPen(QPen(panel.shortcut, 1.5));+ painter.setBrush(panel.page);+ painter.drawRoundedRect(box.adjusted(0.75, 0.75, -0.75, -0.75), 3.25, 3.25);+ }+ if (hasFocus() && m_has_keyboard_focus)+ ChromeStyle::paint_focus_ring(painter, box, 4);++ painter.setPen(palette().color(foregroundRole()));+ painter.drawText(QRectF(CHECK_BOX_SIZE + CHECK_BOX_TEXT_GAP, 0, width() - CHECK_BOX_SIZE - CHECK_BOX_TEXT_GAP, height()), Qt::AlignLeft | Qt::AlignVCenter, text());+}++void PopoverSwitch::paintEvent(QPaintEvent*)+{+ QPainter painter(this);+ painter.setRenderHint(QPainter::Antialiasing);+ QRectF track { (width() - 32) / 2.0, (height() - 18) / 2.0, 32, 18 };+ auto track_color = isChecked() ? Theme::accent() : (Theme::is_dark() ? QColor(0x48484e) : QColor(0xbcbcc2));+ // A switch that can't be turned fades, knob and all, so it doesn't look as though it could.+ if (!isEnabled())+ painter.setOpacity(0.4);++ painter.setPen(Qt::NoPen);+ painter.setBrush(track_color);+ painter.drawRoundedRect(track, 9, 9);++ auto knob_x = isChecked() != (layoutDirection() == Qt::RightToLeft) ? track.right() - 16 : track.left() + 2;+ painter.setBrush(QColor(0, 0, 0, 40));+ painter.drawEllipse(QRectF(knob_x, track.top() + 3, 14, 14));+ painter.setBrush(Qt::white);+ painter.drawEllipse(QRectF(knob_x, track.top() + 2, 14, 14));++ if (hasFocus() && m_has_keyboard_focus) {+ painter.setOpacity(1);+ ChromeStyle::paint_focus_ring(painter, track, 9);+ }+}+}diff --git a/UI/Qt/Popover.h b/UI/Qt/Popover.hindex 54191f6a957..714c561e97a 100644--- a/UI/Qt/Popover.h+++ b/UI/Qt/Popover.h@@ -7,13 +7,22 @@#pragma once#include <AK/Function.h>+#include <AK/Optional.h>+#include <AK/Platform.h>+#include <AK/Types.h>#include <AK/kmalloc.h>+#include <QCheckBox>+#include <QIcon>+#include <QPointer>#include <QWidget>class QFrame;+class QCloseEvent;class QHideEvent;+class QMouseEvent;class QShowEvent;+class QVariantAnimation;namespace Ladybird {@@ -25,21 +34,52 @@ public:Function<void(bool)> on_visibility_change;+ // The point the popover hangs from, which it grows out of as it opens.+ void set_anchor_point(Optional<QPoint> point) { m_anchor_point = point; }++ virtual void setVisible(bool) override;+protected:explicit Popover(QWidget* parent);virtual void showEvent(QShowEvent*) override;virtual void hideEvent(QHideEvent*) override;+ virtual void mousePressEvent(QMouseEvent*) override;+#if !defined(AK_OS_MACOS)+ virtual void closeEvent(QCloseEvent*) override;+ virtual void paintEvent(QPaintEvent*) override;+#endifprivate:QFrame* m_card { nullptr };+ Optional<QPoint> m_anchor_point;+#if defined(AK_OS_MACOS)+ QPointer<QWidget> m_opening_snapshot;+ Optional<QPixmap> m_closing_picture;+#else+ enum class AfterFadingOut {+ Hide,+ Close,+ };+ void fade_in(Optional<QPointF> origin);+ void fade_out(AfterFadingOut);+ void show_fading_picture();+ void stop_fading();+ QPointer<QVariantAnimation> m_fading_animation;+ bool m_is_fading_out { false };+ Optional<QPixmap> m_fading_picture;+ Optional<QPointF> m_fading_origin;+ qreal m_fading_progress { 1 };+ bool m_is_finishing_close { false };+#endif};class MessagePopover final : public Popover {public:AK_ALLOC_WITH_KMALLOC;- MessagePopover(QWidget* parent, int width, QString const& title, QString const& body, QString const& dismiss_text, QString const& accept_text);+ // With an icon, the icon stands in a tile before the title.+ MessagePopover(QWidget* parent, int width, QString const& title, QString const& body, QString const& dismiss_text, QString const& accept_text, QIcon const& icon = {});void update_chrome_style(QPalette const&);@@ -52,7 +92,65 @@ private:bool m_is_accepted { false };};-void move_popover_below(Popover&, QWidget& anchor);+// A small switch in the style of the system's, for settings in popovers.+class PopoverSwitch final : public QCheckBox {+public:+ AK_ALLOC_WITH_KMALLOC;++ explicit PopoverSwitch(QWidget* parent);++ virtual QSize sizeHint() const override { return { 36, 22 }; }++private:+ virtual bool hitButton(QPoint const& position) const override { return rect().contains(position); }+ virtual void paintEvent(QPaintEvent*) override;+ virtual void focusInEvent(QFocusEvent*) override;++ bool m_has_keyboard_focus { false };+};++// A checkbox: a rounded box, ringed when unchecked, filled with a white check when checked.+class PopoverCheckBox final : public QCheckBox {+public:+ AK_ALLOC_WITH_KMALLOC;++ PopoverCheckBox(QString const& text, QWidget* parent);++ virtual QSize sizeHint() const override;++private:+ virtual bool hitButton(QPoint const& position) const override { return rect().contains(position); }+ virtual void paintEvent(QPaintEvent*) override;+ virtual void focusInEvent(QFocusEvent*) override;++ bool m_has_keyboard_focus { false };+};++// Which edges of the popover's card and its anchor line up.+enum class PopoverAlignment : u8 {+ Leading,+ Trailing,+};+// The popover hangs from the anchor's rect, or from the given part of it where the anchor draws less than all of it.+void move_popover_below(Popover&, QWidget& anchor, PopoverAlignment = PopoverAlignment::Trailing, Optional<QRect> anchor_rect = {});void cast_popover_shadow(QWidget&);+// A surface that is a native view of its own, floating over the page, cannot draw a shadow outside itself. This gives it+// the popovers' shadow, cast by a native view behind it that follows it around and lets the mouse through.+enum class FloatingShadowTone : u8 {+ FollowTheme,+ // For surfaces that are dark in both themes.+ Dark,+};+enum class FloatingShadowKind : u8 {+ Popover,+ // A sheet hangs from the top of the page, and casts the deeper shadow of a dialog below it only.+ Sheet,+};+QWidget& cast_floating_shadow(QWidget& surface, qreal corner_radius, FloatingShadowTone = FloatingShadowTone::FollowTheme, FloatingShadowKind = FloatingShadowKind::Popover);++// Floating surfaces and their shadows are native views embedded in the browser window on macOS, which have no window+// opacity of their own.+void set_floating_window_opacity(QWidget&, qreal opacity);+}diff --git a/UI/Qt/ProcessManagerWindow.cpp b/UI/Qt/ProcessManagerWindow.cppindex 036a1557edc..978e7214328 100644--- a/UI/Qt/ProcessManagerWindow.cpp+++ b/UI/Qt/ProcessManagerWindow.cpp@@ -5,21 +5,23 @@*/#include <AK/HashMap.h>+#include <AK/QuickSort.h>#include <AK/kmalloc.h>#include <LibURL/InternalURLs.h>#include <LibWebView/ProcessManager.h>#include <LibWebView/ProcessSnapshot.h>-#include <UI/Qt/BrandColors.h>#include <UI/Qt/ChromeStyle.h>#include <UI/Qt/Icon.h>#include <UI/Qt/ProcessManagerWindow.h>#include <UI/Qt/StringUtils.h>+#include <UI/Qt/Theme.h>#include <QAction>#include <QApplication>#include <QClipboard>#include <QContextMenuEvent>#include <QEvent>+#include <QHBoxLayout>#include <QHeaderView>#include <QLabel>#include <QLineEdit>@@ -60,14 +62,43 @@ namespace {enum Column {Name,- PID,CPU,Memory,+ PID,+};++enum class RowKind {+ Process,+ Site,+ Group,+ Tab,};-// Rows are identified by the process's child ID, which, unlike its PID, never comes to name another process.+// Process rows are identified by the process's child ID, which, unlike its PID, never comes to name another process.+// Site rows are identified by their site.constexpr int ChildIDRole = Qt::UserRole + 1;+constexpr int KindRole = Qt::UserRole + 2;+constexpr int SiteRole = Qt::UserRole + 3;+// What a site row says after the site's name, such as how many tabs show it.+constexpr int NoteRole = Qt::UserRole + 4;++constexpr int TITLE_BAR_HEIGHT = 52;+constexpr int FOOTER_HEIGHT = 52;+constexpr int ROW_HEIGHT = 30;+constexpr qreal SELECTION_RADIUS = 6;+#if defined(AK_OS_MACOS)+// NB: The traffic lights sit in the title bar, and the title comes after them.+constexpr int TITLE_LEADING_MARGIN = 86;+#else+constexpr int TITLE_LEADING_MARGIN = 14;+#endif++RowKind row_kind(QTreeWidgetItem const* item)+{+ return static_cast<RowKind>(item->data(Name, KindRole).toInt());+}+// The column the rows are sorted by is drawn in the text color and weight, with the order beside it.class ProcessHeader final : public QHeaderView {public:AK_ALLOC_WITH_KMALLOC;@@ -83,32 +114,42 @@ private:QStyleOptionHeader option;initStyleOption(&option);initStyleOptionForIndex(&option, section);- option.rect = rect;auto text = option.text;- option.text.clear();- option.sortIndicator = QStyleOptionHeader::None;+ auto is_sorted = isSortIndicatorShown() && sortIndicatorSection() == section;+painter->save();painter->setClipRect(rect);- style()->drawControl(QStyle::CE_Header, &option, painter, this);- auto text_rect = rect.adjusted(8, 0, -8, 0);- if (isSortIndicatorShown() && sortIndicatorSection() == section) {- auto arrow_right = text_rect.right();- auto center_y = rect.center().y();- auto color = option.palette.color(QPalette::Text);- color.setAlphaF(0.65);- painter->setPen(QPen(color, 1));+ painter->fillRect(rect, Theme::panel().page);+ painter->fillRect(QRect(rect.left(), rect.bottom(), rect.width(), 1), Theme::panel().separator_soft);++ auto font = this->font();+ font.setPixelSize(12);+ font.setWeight(is_sorted ? QFont::DemiBold : QFont::Normal);+ painter->setFont(font);+ painter->setPen(is_sorted ? Theme::panel().text : Theme::panel().muted);++ auto text_rect = rect.adjusted(12, 0, -12, 0);+ auto alignment = section == Name ? Qt::AlignLeft : Qt::AlignRight;+ if (is_sorted) {+ // The order is shown by a small chevron after the name, pointing down for the largest first.+ static constexpr int chevron_size = 10;+ auto text_width = QFontMetrics(font).horizontalAdvance(text);+ auto chevron_left = alignment == Qt::AlignLeft ? text_rect.left() + text_width + 4 : text_rect.right() - chevron_size;+ if (alignment == Qt::AlignRight)+ text_rect.setRight(chevron_left - 4);+ auto center_y = rect.center().y() + 0.5;+ auto direction = sortIndicatorOrder() == Qt::DescendingOrder ? 1.0 : -1.0;painter->setRenderHint(QPainter::Antialiasing);- auto direction = sortIndicatorOrder() == Qt::AscendingOrder ? 1 : -1;+ painter->setPen(QPen(Theme::panel().text, 1.4, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));QPointF points[] {- { static_cast<qreal>(arrow_right - 6), center_y + direction * 1.5 },- { static_cast<qreal>(arrow_right - 3), center_y - direction * 1.5 },- { static_cast<qreal>(arrow_right), center_y + direction * 1.5 },+ { chevron_left + 2.5, center_y - direction * 2 },+ { chevron_left + 5.0, center_y + direction * 0.5 },+ { chevron_left + 7.5, center_y - direction * 2 },};painter->drawPolyline(points, 3);- text_rect.setRight(arrow_right - 10);+ painter->setPen(Theme::panel().text);}- painter->setPen(option.palette.color(QPalette::Text));- painter->drawText(text_rect, option.textAlignment | Qt::AlignVCenter, fontMetrics().elidedText(text, Qt::ElideRight, text_rect.width()));+ painter->drawText(text_rect, alignment | Qt::AlignVCenter, QFontMetrics(font).elidedText(text, Qt::ElideRight, text_rect.width()));painter->restore();}};@@ -135,6 +176,43 @@ private:}event->accept();}++ // The selected row is filled across all its columns with rounded ends.+ virtual void drawRow(QPainter* painter, QStyleOptionViewItem const& option, QModelIndex const& index) const override+ {+ if (selectionModel()->isSelected(index)) {+ painter->save();+ painter->setRenderHint(QPainter::Antialiasing);+ painter->setPen(Qt::NoPen);+ painter->setBrush(Theme::primary());+ // NB: The row's rectangle leaves out the branch area before it, which the fill covers too.+ QRectF row_rect(0, option.rect.top(), viewport()->width(), option.rect.height() - 1);+ painter->drawRoundedRect(row_rect, SELECTION_RADIUS, SELECTION_RADIUS);+ painter->restore();+ }+ QTreeWidget::drawRow(painter, option, index);+ }++ // The rows draw their own selection, so only the expand indicator of a site is drawn in the branch area. A process+ // always shows its tabs.+ virtual void drawBranches(QPainter* painter, QRect const& rect, QModelIndex const& index) const override+ {+ if (!model()->hasChildren(index) || static_cast<RowKind>(index.siblingAtColumn(Name).data(KindRole).toInt()) != RowKind::Site)+ return;+ auto selected = selectionModel()->isSelected(index);+ painter->save();+ painter->setRenderHint(QPainter::Antialiasing);+ painter->setPen(QPen(selected ? QColor(255, 255, 255, 199) : Theme::panel().muted, 1.6, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));+ auto center = QRectF(rect.right() - 16, rect.top(), 12, rect.height()).center();+ if (isExpanded(index)) {+ QPointF points[] { center + QPointF(-3, -1.5), center + QPointF(0, 1.5), center + QPointF(3, -1.5) };+ painter->drawPolyline(points, 3);+ } else {+ QPointF points[] { center + QPointF(-1.5, -3), center + QPointF(1.5, 0), center + QPointF(-1.5, 3) };+ painter->drawPolyline(points, 3);+ }+ painter->restore();+ }};class ProcessDelegate final : public QStyledItemDelegate {@@ -149,49 +227,68 @@ public:virtual QSize sizeHint(QStyleOptionViewItem const& option, QModelIndex const& index) const override{auto size = QStyledItemDelegate::sizeHint(option, index);- size.setHeight(qMax(size.height(), 27));+ size.setHeight(ROW_HEIGHT);return size;}-};--class ProcessItem final : public QTreeWidgetItem {-public:- AK_ALLOC_WITH_KMALLOC;- void update_page_icon(WebView::ProcessPageSnapshot const* page, QIcon const& fallback)+ virtual void paint(QPainter* painter, QStyleOptionViewItem const& option, QModelIndex const& index) const override{- auto view_id = page ? Optional<u64> { page->view_id } : Optional<u64> {};- auto favicon_hash = page ? page->favicon_hash : Optional<String> {};- auto url = page ? Optional<URL::URL> { page->url } : Optional<URL::URL> {};- if (view_id != m_view_id || favicon_hash != m_favicon_hash || url != m_url) {- m_view_id = view_id;- m_favicon_hash = favicon_hash;- m_url = url;- m_favicon = {};- if (page) {- if (auto png = WebView::favicon_png_for_page(*page); png.has_value())- m_favicon = icon_from_png(png->bytes(), 16);- }+ auto adjusted_option = option;+ auto selected = option.state.testFlag(QStyle::State_Selected);+ // The row's fill is drawn by the tree, so the cell draws none of its own.+ adjusted_option.state &= ~QStyle::State_Selected;+ adjusted_option.state &= ~QStyle::State_HasFocus;+ if (selected) {+ adjusted_option.palette.setColor(QPalette::Text, Qt::white);+ adjusted_option.palette.setColor(QPalette::WindowText, Qt::white);}- setIcon(Name, m_favicon.isNull() ? fallback : m_favicon);+ initStyleOption(&adjusted_option, index);+ if (selected)+ adjusted_option.palette.setColor(QPalette::Text, Qt::white);+ auto* widget = option.widget;+ auto* style = widget ? widget->style() : QApplication::style();+ if (selected && index.column() != Name)+ adjusted_option.palette.setBrush(QPalette::Text, QColor(255, 255, 255, 199));+ style->drawControl(QStyle::CE_ItemViewItem, &adjusted_option, painter, widget);++ auto note = index.data(NoteRole).toString();+ if (note.isEmpty())+ return;+ auto text_rect = style->subElementRect(QStyle::SE_ItemViewItemText, &adjusted_option, widget);+ auto name_width = QFontMetrics(adjusted_option.font).horizontalAdvance(adjusted_option.text);+ auto note_font = adjusted_option.font;+ note_font.setWeight(QFont::Normal);+ note_font.setPixelSize(12);+ auto note_rect = text_rect.adjusted(name_width + 8, 0, 0, 0);+ if (note_rect.width() <= 0)+ return;+ painter->save();+ painter->setFont(note_font);+ painter->setPen(selected ? QColor(255, 255, 255, 199) : Theme::panel().muted);+ painter->drawText(note_rect, Qt::AlignLeft | Qt::AlignVCenter, QFontMetrics(note_font).elidedText(note, Qt::ElideRight, note_rect.width()));+ painter->restore();}+};- virtual bool operator<(QTreeWidgetItem const& other) const override- {- auto column = treeWidget()->sortColumn();+// What a row is sorted by in a column.+QVariant sort_key(QTreeWidgetItem const* item, int column)+{+ if (column == Name)+ return item->text(Name);+ return item->data(column, Qt::UserRole);+}++bool sorts_before(QTreeWidgetItem const* a, QTreeWidgetItem const* b, int column, Qt::SortOrder order)+{+ auto less = [&](QTreeWidgetItem const* left, QTreeWidgetItem const* right) {if (column == Name)- return QString::localeAwareCompare(text(column), other.text(column)) < 0;+ return QString::localeAwareCompare(left->text(Name), right->text(Name)) < 0;if (column == CPU)- return data(column, Qt::UserRole).toDouble() < other.data(column, Qt::UserRole).toDouble();- return data(column, Qt::UserRole).toULongLong() < other.data(column, Qt::UserRole).toULongLong();- }--private:- Optional<u64> m_view_id;- Optional<String> m_favicon_hash;- Optional<URL::URL> m_url;- QIcon m_favicon;-};+ return sort_key(left, column).toDouble() < sort_key(right, column).toDouble();+ return sort_key(left, column).toULongLong() < sort_key(right, column).toULongLong();+ };+ return order == Qt::AscendingOrder ? less(a, b) : less(b, a);+}}@@ -199,76 +296,116 @@ ProcessManagerWindow::ProcessManagerWindow(WebView::ProcessManager& process_mana: m_process_manager(process_manager){setWindowFlags(Qt::Window);+#if defined(AK_OS_MACOS)+ // The title bar is the window's own, with the traffic lights, the title and the filter in it.+ setWindowFlag(Qt::ExpandedClientAreaHint);+ setWindowFlag(Qt::NoTitleBarBackgroundHint);+ setAttribute(Qt::WA_ContentsMarginsRespectsSafeArea, false);+#endifsetWindowTitle(tr("Task Manager"));setAttribute(Qt::WA_QuitOnClose, false);- resize(760, 360);- setMinimumSize(560, 260);-- auto* layout = new QVBoxLayout(this);- layout->setContentsMargins(16, 8, 16, 4);- layout->setSpacing(8);-- auto* toolbar = new QHBoxLayout;- toolbar->setSpacing(24);- m_process_count = new QLabel(tr("Processes"), this);- toolbar->addWidget(m_process_count);- toolbar->addStretch();- m_search = new QLineEdit(this);+ resize(820, 620);+ setMinimumSize(560, 300);++ auto* window_layout = new QVBoxLayout(this);+ window_layout->setContentsMargins(0, 0, 0, 0);+ window_layout->setSpacing(0);+ auto* content = new QWidget(this);+ content->setObjectName("LadybirdTaskManager");+ window_layout->addWidget(content);+ auto* layout = new QVBoxLayout(content);+ layout->setContentsMargins(0, 0, 0, 0);+ layout->setSpacing(0);++ m_title_bar = new QWidget(content);+ m_title_bar->setObjectName("LadybirdTaskManagerTitleBar");+ m_title_bar->setFixedHeight(TITLE_BAR_HEIGHT);+ auto* title_bar_layout = new QHBoxLayout(m_title_bar);+ title_bar_layout->setContentsMargins(TITLE_LEADING_MARGIN, 0, 12, 0);+ m_title = new QLabel(tr("Task Manager"), m_title_bar);+ m_title->setObjectName("LadybirdTaskManagerTitle");+ title_bar_layout->addWidget(m_title);+ title_bar_layout->addStretch();+ m_search = new QLineEdit(m_title_bar);+ m_search->setObjectName("LadybirdTaskManagerFilter");m_search->setPlaceholderText(tr("Search processes"));m_search->setAccessibleName(tr("Search processes"));m_search->setClearButtonEnabled(true);- m_search->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);- m_search->setMinimumWidth(180);- m_search->setMaximumWidth(240);- m_search->addAction(create_chrome_icon(ChromeIcon::Search, palette()), QLineEdit::LeadingPosition);- toolbar->addWidget(m_search);- layout->addLayout(toolbar);-- auto* process_tree = new ProcessTree(this);+ m_search->setFixedSize(220, 28);+ title_bar_layout->addWidget(m_search);+ layout->addWidget(m_title_bar);++ auto* list = new QWidget(content);+ auto* list_layout = new QVBoxLayout(list);+ list_layout->setContentsMargins(8, 0, 8, 6);+ auto* process_tree = new ProcessTree(list);process_tree->on_context_menu = [this](auto const& position) { show_context_menu(position); };m_processes = process_tree;m_processes->setHeader(new ProcessHeader(m_processes));- m_processes->setHeaderLabels({ tr("Process"), tr("PID"), tr("CPU"), tr("Memory") });+ m_processes->setHeaderLabels({ tr("Name"), tr("CPU"), tr("Memory"), tr("PID") });m_processes->headerItem()->setTextAlignment(Name, Qt::AlignLeft | Qt::AlignVCenter);m_processes->setIconSize(QSize(16, 16));m_processes->setAccessibleName(tr("Processes"));m_processes->setFrameShape(QFrame::NoFrame);- m_processes->setUniformRowHeights(true);m_processes->setItemDelegate(new ProcessDelegate(m_processes));m_processes->setSelectionMode(QAbstractItemView::SingleSelection);- m_processes->setSortingEnabled(true);- m_processes->sortByColumn(PID, Qt::AscendingOrder);- m_processes->setIndentation(14);+ m_processes->setIndentation(24);+ m_processes->setRootIsDecorated(true);+ m_processes->setFocusPolicy(Qt::StrongFocus);+ // NB: The rows are sorted within their sections, which the tree's own sorting would mix together.+ m_processes->header()->setSortIndicatorShown(true);+ m_processes->header()->setSectionsClickable(true);+ m_processes->header()->setSortIndicator(Memory, Qt::DescendingOrder);+ m_processes->header()->setFixedHeight(30);m_processes->header()->setStretchLastSection(false);m_processes->header()->setSectionResizeMode(Name, QHeaderView::Stretch);- for (auto column : { PID, CPU, Memory }) {+ for (auto column : { CPU, Memory, PID }) {m_processes->header()->setSectionResizeMode(column, QHeaderView::Interactive);- m_processes->setColumnWidth(column, column == Memory ? 130 : 100);+ m_processes->setColumnWidth(column, column == Memory ? 122 : 102);m_processes->headerItem()->setTextAlignment(column, Qt::AlignRight | Qt::AlignVCenter);}- layout->addWidget(m_processes, 1);+ connect(m_processes->header(), &QHeaderView::sortIndicatorChanged, this, [this] { refresh(); });+ list_layout->addWidget(m_processes);+ layout->addWidget(list, 1);connect(m_search, &QLineEdit::textChanged, this, &ProcessManagerWindow::apply_filter);-- auto* summary_layout = new QHBoxLayout;- summary_layout->setContentsMargins(0, 4, 0, 8);- m_end_process_action = new QAction(tr("End Process"), this);- m_end_process_action->setEnabled(false);- connect(m_end_process_action, &QAction::triggered, this, &ProcessManagerWindow::end_selected_process);- m_end_process_button = new QPushButton(m_end_process_action->text(), this);- m_end_process_button->setAutoDefault(false);- m_end_process_button->setEnabled(false);- connect(m_end_process_button, &QPushButton::clicked, m_end_process_action, &QAction::trigger);- connect(m_end_process_action, &QAction::changed, this, [this] {- m_end_process_button->setEnabled(m_end_process_action->isEnabled());+ connect(m_processes, &QTreeWidget::itemExpanded, this, [this](QTreeWidgetItem* item) {+ if (row_kind(item) == RowKind::Site)+ m_expanded_sites.set(ak_string_from_qstring(item->data(Name, SiteRole).toString()));});- summary_layout->addWidget(m_end_process_button);- summary_layout->addStretch();- m_summary = new QLabel(this);- m_summary->setAttribute(Qt::WA_MacSmallSize);- m_summary->setAlignment(Qt::AlignRight);+ connect(m_processes, &QTreeWidget::itemCollapsed, this, [this](QTreeWidgetItem* item) {+ if (row_kind(item) == RowKind::Process)+ item->setExpanded(true);+ if (row_kind(item) == RowKind::Site)+ m_expanded_sites.remove(ak_string_from_qstring(item->data(Name, SiteRole).toString()));+ });++ m_footer = new QWidget(content);+ m_footer->setObjectName("LadybirdTaskManagerFooter");+ m_footer->setFixedHeight(FOOTER_HEIGHT);+ auto* footer_layout = new QHBoxLayout(m_footer);+ footer_layout->setContentsMargins(20, 0, 12, 0);+ m_summary = new QLabel(m_footer);+ m_summary->setObjectName("LadybirdTaskManagerSummary");+ m_summary->setTextFormat(Qt::RichText);m_summary->setToolTip(tr("Total CPU and memory for all Ladybird processes. Updates every second."));- summary_layout->addWidget(m_summary);- layout->addLayout(summary_layout);+ footer_layout->addWidget(m_summary);+ footer_layout->addStretch();+ m_end_action = new QAction(tr("End Process"), this);+ m_end_action->setEnabled(false);+ connect(m_end_action, &QAction::triggered, this, &ProcessManagerWindow::end_selection);+ m_end_button = new QPushButton(m_end_action->text(), m_footer);+ m_end_button->setObjectName("LadybirdTaskManagerEndButton");+ m_end_button->setAutoDefault(false);+ m_end_button->setEnabled(false);+ m_end_button->setFixedHeight(28);+ m_end_button->setAttribute(Qt::WA_LayoutUsesWidgetRect);+ connect(m_end_button, &QPushButton::clicked, m_end_action, &QAction::trigger);+ connect(m_end_action, &QAction::changed, this, [this] {+ m_end_button->setEnabled(m_end_action->isEnabled());+ m_end_button->setText(m_end_action->text());+ });+ footer_layout->addWidget(m_end_button);+ layout->addWidget(m_footer);m_copy_pid_action = new QAction(tr("Copy PID"), this);m_copy_pid_action->setShortcut(QKeySequence::Copy);@@ -291,6 +428,14 @@ ProcessManagerWindow::ProcessManagerWindow(WebView::ProcessManager& process_manaupdate_style();}+bool ProcessManagerWindow::event(QEvent* event)+{+ // NB: Qt sends the show event before the native window appears, so it never shows with its controls unmoved.+ if ((event->type() == QEvent::Show || event->type() == QEvent::WindowTitleChange) && on_title_bar_change)+ on_title_bar_change();+ return QDialog::event(event);+}+void ProcessManagerWindow::changeEvent(QEvent* event){QDialog::changeEvent(event);@@ -304,50 +449,86 @@ void ProcessManagerWindow::update_style()return;m_is_updating_style = true;- auto text = ChromeStyle::chrome_text(palette());- auto background = ChromeStyle::chrome_background(palette());- auto surface = ChromeStyle::style_sheet_color(ChromeStyle::is_dark(palette())- ? ChromeStyle::chrome_surface_recessed(palette())- : ChromeStyle::chrome_surface(palette()));- auto border = ChromeStyle::style_sheet_color(ChromeStyle::mix(background, text, 0.12));- auto foreground = ChromeStyle::style_sheet_color(text);- auto secondary_foreground = ChromeStyle::style_sheet_color(ChromeStyle::chrome_muted_text(palette()));- auto search_surface_color = ChromeStyle::chrome_surface(palette());- auto search_surface = ChromeStyle::style_sheet_color(search_surface_color);- auto search_border = ChromeStyle::style_sheet_color(ChromeStyle::chrome_border(palette()));- auto accent = ChromeStyle::style_sheet_color(ChromeStyle::chrome_accent());- auto selection = ChromeStyle::style_sheet_color(BrandColors::SlateBlue900);- auto placeholder = ChromeStyle::style_sheet_color(ChromeStyle::mix(text, search_surface_color, 0.4));-- m_process_count->setStyleSheet(QStringLiteral("color: %1;").arg(secondary_foreground));- m_summary->setStyleSheet(QStringLiteral("color: %1;").arg(secondary_foreground));- m_search->setStyleSheet(QStringLiteral(- "QLineEdit { color: %1; background: %2; border: 1px solid %3; border-radius: 8px;"- " min-height: 26px; padding: 2px 9px; selection-background-color: %5; selection-color: white;"- " placeholder-text-color: %6; }"- "QLineEdit:focus { border-color: %4; }")- .arg(foreground, search_surface, search_border, accent, selection, placeholder));- m_processes->setStyleSheet(QStringLiteral(- "QTreeWidget { background: %1; color: %2; border: none;"- " selection-background-color: %3; selection-color: white; }"- "QTreeWidget::item { padding: 0px 8px; }"- "QTreeWidget::item:selected { background: %3; color: white; }")- .arg(surface, foreground, selection));- m_processes->header()->setStyleSheet(QStringLiteral(- "QHeaderView::section { background: %1; color: %2; border: none; border-bottom: 1px solid %3;"- " padding: 5px 8px; }")- .arg(surface, foreground, border));+ auto const& panel = Theme::panel();+ auto color = [](QColor const& color) { return ChromeStyle::style_sheet_color(color); };+ auto* content = m_title_bar->parentWidget();+ content->setStyleSheet(qformatted(R"(+QWidget#LadybirdTaskManager {{+ background: {0};+}}+QWidget#LadybirdTaskManagerTitleBar {{+ background: {1};+ border-bottom: 1px solid {2};+}}+QLabel#LadybirdTaskManagerTitle {{+ color: {3};+ font-weight: 600;+}}+QLineEdit#LadybirdTaskManagerFilter {{+ color: {3};+ background: {4};+ border: none;+ border-radius: 7px;+ padding: 0 8px;+ selection-background-color: {5};+}}+QWidget#LadybirdTaskManagerFooter {{+ background: {0};+ border-top: 1px solid {2};+}}+QLabel#LadybirdTaskManagerSummary {{+ color: {6};+}}+QPushButton#LadybirdTaskManagerEndButton {{+ color: {3};+ background: {4};+ border: none;+ border-radius: 7px;+ padding: 0 14px;+}}+QPushButton#LadybirdTaskManagerEndButton:pressed {{+ background: {7};+}}+QPushButton#LadybirdTaskManagerEndButton:disabled {{+ color: {6};+}}+QTreeWidget {{+ background: {0};+ color: {3};+ border: none;+ outline: none;+}}+QTreeWidget::item {{+ padding: 0px 4px;+}}+)",+ color(panel.page), color(Theme::chrome().toolbar), color(panel.separator), color(panel.text), color(panel.control),+ color(Theme::selection()), color(panel.muted), color(panel.pressed)));++ // NB: The tree draws the selected row's fill itself, so the style's highlight under the branch area is left clear.+ auto tree_palette = m_processes->palette();+ tree_palette.setColor(QPalette::Highlight, Qt::transparent);+ m_processes->setPalette(tree_palette);++ auto summary_font = m_summary->font();+ summary_font.setPixelSize(12);+ m_summary->setFont(summary_font);+m_browser_icon = load_icon_from_uri("resource://icons/48x48/app-browser.png"sv);- m_web_content_icon = create_chrome_icon(ChromeIcon::Globe, palette());- auto muted_palette = palette();- auto muted_color = ChromeStyle::chrome_muted_text(palette());- muted_palette.setColor(QPalette::Text, muted_color);- muted_palette.setColor(QPalette::WindowText, muted_color);- muted_palette.setColor(QPalette::ButtonText, muted_color);- m_service_icon = create_chrome_icon(ChromeIcon::WindowRestore, muted_palette);- m_spare_icon = create_chrome_icon(ChromeIcon::WindowMaximize, muted_palette);+ m_document_icon = create_chrome_icon(ChromeIcon::Document, panel.body);+ m_network_icon = create_chrome_icon(ChromeIcon::Network, panel.body);+ m_compositor_icon = create_chrome_icon(ChromeIcon::Compositor, panel.body);+ m_image_icon = create_chrome_icon(ChromeIcon::Image, panel.body);+ m_service_icon = create_chrome_icon(ChromeIcon::WindowRestore, panel.body);+ auto search_icon = create_chrome_icon(ChromeIcon::Search, panel.muted);+ if (m_search_icon)+ m_search_icon->setIcon(search_icon);+ else+ m_search_icon = m_search->addAction(search_icon, QLineEdit::LeadingPosition);+ m_favicons.clear();m_is_updating_style = false;+ refresh();}void ProcessManagerWindow::showEvent(QShowEvent* event)@@ -363,136 +544,320 @@ void ProcessManagerWindow::hideEvent(QHideEvent* event)QDialog::hideEvent(event);}+QIcon ProcessManagerWindow::favicon_for(WebView::ProcessPageSnapshot const& page)+{+ if (!page.favicon_hash.has_value())+ return create_chrome_icon(ChromeIcon::Globe, Theme::panel().body);+ if (auto icon = m_favicons.get(*page.favicon_hash); icon.has_value())+ return *icon;+ QIcon icon;+ if (auto png = WebView::favicon_png_for_page(page); png.has_value())+ icon = favicon_with_rounded_corners(icon_from_png(png->bytes(), 16), 16);+ if (icon.isNull())+ icon = create_chrome_icon(ChromeIcon::Globe, Theme::panel().body);+ m_favicons.set(*page.favicon_hash, icon);+ return icon;+}+void ProcessManagerWindow::refresh(){+ if (m_is_updating_style)+ return;+auto processes = WebView::process_snapshots(m_process_manager);+ QLocale locale;- auto scroll_position = m_processes->verticalScrollBar()->value();- auto selected_child_id = m_processes->currentItem() && m_processes->currentItem()->isSelected() ? m_processes->currentItem()->data(PID, ChildIDRole) : QVariant {};- QSignalBlocker selection_blocker(m_processes);- HashMap<u64, QTreeWidgetItem*> items;- HashMap<u64, bool> expanded;- m_processes->setUpdatesEnabled(false);- m_processes->setSortingEnabled(false);- auto detach_items = [&](auto& self, QTreeWidgetItem* parent) -> void {- while (parent->childCount()) {- auto* item = parent->child(0);- auto child_id = item->data(PID, ChildIDRole).toULongLong();- expanded.set(child_id, item->isExpanded());- self(self, item);- parent->takeChild(0);- items.set(child_id, item);+ HashMap<u64, WebView::ProcessSnapshot const*> processes_by_child_id;+ for (auto const& process : processes)+ processes_by_child_id.set(process.child_id, &process);++ // Each process is listed with the browser's own processes, with a site, or with the spare processes. A process+ // that works for another, such as a page's image decoder, is listed with it.+ auto is_spare = [](WebView::ProcessSnapshot const& process) {+ return process.type == WebView::ProcessType::WebContent && process.title.has_value() && *process.title == "(spare)"_utf16;+ };+ // NB: A page's process, and a request server bound to a site, belong to that site.+ auto site_of = [](WebView::ProcessSnapshot const& process) -> QString {+ if (!first_is_one_of(process.type, WebView::ProcessType::WebContent, WebView::ProcessType::RequestServer) || !process.site_url.has_value())+ return {};+ return task_manager_site_label(*process.site_url);+ };+ auto section_process = [&](WebView::ProcessSnapshot const& process) -> WebView::ProcessSnapshot const& {+ if (process.owner_child_id.has_value()) {+ if (auto owner = processes_by_child_id.get(*process.owner_child_id); owner.has_value())+ return **owner;}+ return process;};- detach_items(detach_items, m_processes->invisibleRootItem());- HashMap<u64, QTreeWidgetItem*> live_items;- QTreeWidgetItem* browser_item = nullptr;+ struct Site {+ QString name;+ Vector<WebView::ProcessSnapshot const*> processes;+ size_t tab_count { 0 };+ size_t frame_count { 0 };+ WebView::ProcessPageSnapshot const* page { nullptr };+ double cpu { 0 };+ u64 memory { 0 };+ };+ Vector<WebView::ProcessSnapshot const*> own_processes;+ Vector<WebView::ProcessSnapshot const*> spare_processes;+ Vector<Site> sites;double total_cpu = 0;u64 total_memory = 0;- QLocale locale;-- HashMap<u64, WebView::ProcessSnapshot const*> processes_by_child_id;- for (auto const& process : processes)- processes_by_child_id.set(process.child_id, &process);for (auto const& process : processes) {- auto* item = static_cast<ProcessItem*>(items.take(process.child_id).value_or_lazy_evaluated([] { return new ProcessItem; }));- auto name = qstring_from_ak_string(WebView::process_name_from_type(process.type));- if (first_is_one_of(process.type, WebView::ProcessType::WebContent, WebView::ProcessType::ImageDecoder, WebView::ProcessType::RequestServer)) {- auto const* label_process = &process;- if (process.type == WebView::ProcessType::ImageDecoder && process.owner_child_id.has_value()) {- if (auto owner = processes_by_child_id.get(*process.owner_child_id); owner.has_value())- label_process = *owner;- }-- auto const& page = label_process->page;- auto const& site_url = label_process->site_url;-- bool is_spare = label_process->title.has_value() && *label_process->title == "(spare)"_utf16;- if (site_url.has_value()) {- auto site = task_manager_site_label(*site_url);- if (!site.isEmpty())- name += QStringLiteral(" — ") + site;- } else if (label_process->title.has_value()) {- name += QStringLiteral(" — ") + qstring_from_utf16_string(*label_process->title);- }-- if (process.type == WebView::ProcessType::WebContent)- item->update_page_icon(page.has_value() && page->url != URL::about_blank() ? &*page : nullptr, is_spare ? m_spare_icon : m_web_content_icon);- else- item->setIcon(Name, m_service_icon);- } else {- if (process.title.has_value())- name += QStringLiteral(" — ") + qstring_from_utf16_string(*process.title);- if (process.type == WebView::ProcessType::Browser) {- browser_item = item;- item->setIcon(Name, m_browser_icon);- } else {- item->setIcon(Name, m_service_icon);- }+ total_cpu += process.cpu_percent;+ total_memory += process.memory_usage_bytes;+ auto const& section = section_process(process);+ if (is_spare(section)) {+ spare_processes.append(&process);+ continue;}+ auto site_name = site_of(section);+ if (site_name.isEmpty()) {+ own_processes.append(&process);+ continue;+ }+ auto site = sites.find_if([&](auto const& site) { return site.name == site_name; });+ if (site == sites.end()) {+ Site new_site;+ new_site.name = site_name;+ sites.append(AK::move(new_site));+ site = sites.end() - 1;+ }+ site->processes.append(&process);+ site->tab_count += process.tabs.size();+ site->frame_count += process.frame_count;+ if (process.page.has_value() && (!site->page || (process.page->kind == WebView::ProcessPageKind::TopLevel && site->page->kind != WebView::ProcessPageKind::TopLevel)))+ site->page = &*process.page;+ site->cpu += process.cpu_percent;+ site->memory += process.memory_usage_bytes;+ }++ auto selected = m_processes->currentItem() && m_processes->currentItem()->isSelected() ? m_processes->currentItem() : nullptr;+ auto selected_child_id = selected && row_kind(selected) == RowKind::Process ? selected->data(PID, ChildIDRole) : QVariant {};+ auto selected_site = selected && row_kind(selected) == RowKind::Site ? selected->data(Name, SiteRole) : QVariant {};+ auto scroll_position = m_processes->verticalScrollBar()->value();++ QSignalBlocker selection_blocker(m_processes);+ m_processes->setUpdatesEnabled(false);+ m_processes->clear();++ auto sort_column = m_processes->header()->sortIndicatorSection();+ auto sort_order = m_processes->header()->sortIndicatorOrder();+ auto sort_items = [&](Vector<QTreeWidgetItem*>& items) {+ quick_sort(items, [&](auto* a, auto* b) { return sorts_before(a, b, sort_column, sort_order); });+ };++ auto set_numbers = [&](QTreeWidgetItem& item, double cpu, u64 memory) {+ item.setText(CPU, locale.toString(cpu, 'f', 1) + '%');+ item.setText(Memory, locale.formattedDataSize(memory, 1, QLocale::DataSizeTraditionalFormat));+ item.setData(CPU, Qt::UserRole, cpu);+ item.setData(Memory, Qt::UserRole, static_cast<qulonglong>(memory));+ for (auto column : { CPU, Memory, PID })+ item.setTextAlignment(column, Qt::AlignRight | Qt::AlignVCenter);+ };++ auto make_process_item = [&](WebView::ProcessSnapshot const& process, bool shows_title) {+ auto* item = new QTreeWidgetItem;+ item->setData(Name, KindRole, static_cast<int>(RowKind::Process));+ auto name = qstring_from_ak_string(WebView::process_name_from_type(process.type));+ if (shows_title && process.title.has_value() && process.type != WebView::ProcessType::WebContent)+ name += QStringLiteral(" — ") + qstring_from_utf16_string(*process.title);item->setText(Name, name);item->setToolTip(Name, name);+ switch (process.type) {+ case WebView::ProcessType::Browser: {+ item->setIcon(Name, m_browser_icon);+ auto font = item->font(Name);+ font.setWeight(QFont::DemiBold);+ item->setFont(Name, font);+ break;+ }+ case WebView::ProcessType::WebContent:+ item->setIcon(Name, m_document_icon);+ break;+ case WebView::ProcessType::RequestServer:+ item->setIcon(Name, m_network_icon);+ break;+ case WebView::ProcessType::Compositor:+ item->setIcon(Name, m_compositor_icon);+ break;+ case WebView::ProcessType::ImageDecoder:+ item->setIcon(Name, m_image_icon);+ break;+ default:+ item->setIcon(Name, m_service_icon);+ break;+ }item->setText(PID, QString::number(process.pid));- item->setText(CPU, locale.toString(process.cpu_percent, 'f', 2) + '%');- item->setText(Memory, locale.formattedDataSize(process.memory_usage_bytes, 2));item->setData(PID, Qt::UserRole, static_cast<qlonglong>(process.pid));item->setData(PID, ChildIDRole, static_cast<qulonglong>(process.child_id));- item->setData(CPU, Qt::UserRole, process.cpu_percent);- item->setData(Memory, Qt::UserRole, static_cast<qulonglong>(process.memory_usage_bytes));- for (auto column : { PID, CPU, Memory })- item->setTextAlignment(column, Qt::AlignRight | Qt::AlignVCenter);- live_items.set(process.child_id, item);- total_cpu += process.cpu_percent;- total_memory += process.memory_usage_bytes;+ set_numbers(*item, process.cpu_percent, process.memory_usage_bytes);+ for (auto const& tab : process.tabs) {+ auto title = tab.title.is_empty() ? tr("Untitled") : qstring_from_utf16_string(tab.title);+ auto* tab_item = new QTreeWidgetItem(item, { title });+ tab_item->setData(Name, KindRole, static_cast<int>(RowKind::Tab));+ tab_item->setFlags(Qt::ItemIsEnabled);+ tab_item->setToolTip(Name, title);+ tab_item->setIcon(Name, favicon_for(tab.page));+ }+ return item;+ };++ auto add_group = [&](QString const& name) {+ auto* item = new QTreeWidgetItem(m_processes, { name });+ item->setData(Name, KindRole, static_cast<int>(RowKind::Group));+ item->setFlags(Qt::ItemIsEnabled);+ auto font = item->font(Name);+ font.setPixelSize(12);+ font.setWeight(QFont::DemiBold);+ item->setFont(Name, font);+ item->setForeground(Name, Theme::panel().muted);+ item->setFirstColumnSpanned(true);+ };++ QTreeWidgetItem* item_to_select = nullptr;+ auto add_items = [&](QTreeWidgetItem* parent, Vector<QTreeWidgetItem*>& items) {+ sort_items(items);+ for (auto* item : items) {+ if (parent)+ parent->addChild(item);+ else+ m_processes->addTopLevelItem(item);+ if (selected_child_id.isValid() && item->data(PID, ChildIDRole) == selected_child_id)+ item_to_select = item;+ }+ };++ // The browser comes first among its own processes, whatever the order.+ Vector<QTreeWidgetItem*> own_items;+ QTreeWidgetItem* browser_item = nullptr;+ for (auto const* process : own_processes) {+ auto* item = make_process_item(*process, true);+ if (process->type == WebView::ProcessType::Browser)+ browser_item = item;+ else+ own_items.append(item);}- for (auto& entry : items)- delete entry.value;- for (auto& entry : live_items) {- auto* parent = browser_item && entry.value != browser_item ? browser_item : m_processes->invisibleRootItem();- parent->addChild(entry.value);+ if (browser_item) {+ m_processes->addTopLevelItem(browser_item);+ if (selected_child_id.isValid() && browser_item->data(PID, ChildIDRole) == selected_child_id)+ item_to_select = browser_item;}- m_processes->setCurrentItem(nullptr);- for (auto& entry : live_items) {- entry.value->setExpanded(expanded.get(entry.key).value_or(true));- if (entry.value->data(PID, ChildIDRole) == selected_child_id)- m_processes->setCurrentItem(entry.value);+ add_items(nullptr, own_items);++ if (!sites.is_empty()) {+ add_group(tr("Sites"));+ Vector<QTreeWidgetItem*> site_items;+ for (auto& site : sites) {+ auto* item = new QTreeWidgetItem;+ item->setData(Name, KindRole, static_cast<int>(RowKind::Site));+ item->setData(Name, SiteRole, site.name);+ item->setText(Name, site.name);+ item->setToolTip(Name, site.name);+ auto font = item->font(Name);+ font.setWeight(QFont::DemiBold);+ item->setFont(Name, font);+ if (site.page)+ item->setIcon(Name, favicon_for(*site.page));+ QStringList note;+ if (site.tab_count > 0)+ note.append(site.tab_count == 1 ? tr("1 tab") : tr("%1 tabs").arg(site.tab_count));+ if (site.frame_count > 0)+ note.append(site.frame_count == 1 ? tr("1 embedded frame") : tr("%1 embedded frames").arg(site.frame_count));+ item->setData(Name, NoteRole, note.join(QStringLiteral(" · ")));+ set_numbers(*item, site.cpu, site.memory);+ site_items.append(item);++ Vector<QTreeWidgetItem*> process_items;+ for (auto const* process : site.processes)+ process_items.append(make_process_item(*process, false));+ add_items(item, process_items);+ if (selected_site.isValid() && selected_site.toString() == site.name)+ item_to_select = item;+ }+ add_items(nullptr, site_items);+ for (auto* item : site_items) {+ item->setExpanded(m_expanded_sites.contains(ak_string_from_qstring(item->data(Name, SiteRole).toString())));+ for (int i = 0; i < item->childCount(); ++i)+ item->child(i)->setExpanded(true);+ }+ }++ if (!spare_processes.is_empty()) {+ add_group(tr("Spare"));+ Vector<QTreeWidgetItem*> spare_items;+ for (auto const* process : spare_processes) {+ auto* item = make_process_item(*process, false);+ for (int column = 0; column < m_processes->columnCount(); ++column)+ item->setForeground(column, Theme::panel().muted);+ spare_items.append(item);+ }+ add_items(nullptr, spare_items);}- m_processes->setSortingEnabled(true);++ if (item_to_select)+ m_processes->setCurrentItem(item_to_select);m_processes->verticalScrollBar()->setValue(scroll_position);m_processes->setUpdatesEnabled(true);apply_filter();update_actions();- m_summary->setText(tr("CPU: %1% Memory: %2")- .arg(locale.toString(total_cpu, 'f', 2))- .arg(locale.formattedDataSize(total_memory, 2)));++ auto value = [&](QString const& text) {+ return QStringLiteral("<span style=\"color: %1\">%2</span>").arg(ChromeStyle::style_sheet_color(Theme::panel().text), text.toHtmlEscaped());+ };+ m_summary->setText(tr("CPU %1 Memory %2 %3 · %4")+ .arg(value(locale.toString(total_cpu, 'f', 1) + '%'))+ .arg(value(locale.formattedDataSize(total_memory, 1, QLocale::DataSizeTraditionalFormat)))+ .arg(sites.size() == 1 ? tr("1 site") : tr("%1 sites").arg(sites.size()))+ .arg(processes.size() == 1 ? tr("1 process") : tr("%1 processes").arg(processes.size())));}void ProcessManagerWindow::apply_filter(){auto query = m_search->text().trimmed();- size_t visible_count = 0;- size_t total_count = 0;+ auto matches = [&](QTreeWidgetItem* item) {+ return item->text(Name).contains(query, Qt::CaseInsensitive) || item->text(PID).contains(query);+ };auto filter = [&](auto& self, QTreeWidgetItem* item) -> bool {- ++total_count;- bool visible = item->text(Name).contains(query, Qt::CaseInsensitive) || item->text(PID).contains(query);+ auto kind = row_kind(item);+ if (kind == RowKind::Group)+ return false;+ bool visible = matches(item);bool has_visible_child = false;for (int i = 0; i < item->childCount(); ++i)has_visible_child |= self(self, item->child(i));+ // A site shows all it holds when its name matches.+ if (kind == RowKind::Site && visible) {+ for (int i = 0; i < item->childCount(); ++i)+ item->child(i)->setHidden(false);+ }visible |= has_visible_child;item->setHidden(!visible);if (has_visible_child && !query.isEmpty())item->setExpanded(true);- if (visible)- ++visible_count;return visible;};- for (int i = 0; i < m_processes->topLevelItemCount(); ++i)- filter(filter, m_processes->topLevelItem(i));- m_process_count->setText(visible_count == total_count- ? tr("%1 processes").arg(total_count)- : tr("%1 of %2 processes").arg(visible_count).arg(total_count));++ // A group shows while any of its rows do.+ QTreeWidgetItem* group = nullptr;+ bool group_has_visible_row = false;+ auto finish_group = [&] {+ if (group)+ group->setHidden(!group_has_visible_row);+ };+ for (int i = 0; i < m_processes->topLevelItemCount(); ++i) {+ auto* item = m_processes->topLevelItem(i);+ if (row_kind(item) == RowKind::Group) {+ finish_group();+ group = item;+ group_has_visible_row = false;+ continue;+ }+ group_has_visible_row |= filter(filter, item);+ }+ finish_group();update_actions();}@@ -500,26 +865,55 @@ void ProcessManagerWindow::update_actions(){auto* item = m_processes->currentItem();bool has_selection = item && item->isSelected() && !item->isHidden();- m_copy_pid_action->setEnabled(has_selection);- if (!has_selection) {- m_end_process_action->setEnabled(false);+ auto kind = has_selection ? row_kind(item) : RowKind::Group;+ m_end_action->setText(tr("End Process"));+ m_copy_pid_action->setEnabled(false);+ // Ending a site ends the processes that show it, so the button says how many.+ if (kind == RowKind::Site) {+ int process_count = 0;+ for (int i = 0; i < item->childCount(); ++i) {+ if (row_kind(item->child(i)) == RowKind::Process)+ ++process_count;+ }+ if (process_count > 1)+ m_end_action->setText(tr("End %1 processes").arg(process_count));+ m_end_action->setEnabled(process_count > 0);+ return;+ }+ if (kind != RowKind::Process) {+ m_end_action->setEnabled(false);return;}auto process = m_process_manager.find_child(item->data(PID, ChildIDRole).toULongLong());m_copy_pid_action->setEnabled(process.has_value());- m_end_process_action->setEnabled(process.has_value() && process->type() != WebView::ProcessType::Browser);+ m_end_action->setEnabled(process.has_value() && process->type() != WebView::ProcessType::Browser);}-void ProcessManagerWindow::end_selected_process()+void ProcessManagerWindow::end_selection(){update_actions();- if (!m_end_process_action->isEnabled())+ if (!m_end_action->isEnabled())return;- auto pid = static_cast<pid_t>(m_processes->currentItem()->data(PID, Qt::UserRole).toLongLong());- auto child_id = m_processes->currentItem()->data(PID, ChildIDRole).toULongLong();- if (auto result = m_process_manager.terminate_child(child_id, Core::Process::TerminationMode::Forceful); result.is_error()) {- if (!result.error().is_errno() || result.error().code() != ESRCH)- QMessageBox::warning(this, tr("Unable to end process"), qformatted("Could not end process {}: {}", pid, result.error()));++ // Ending a site ends the processes that show it.+ Vector<QTreeWidgetItem*> items;+ auto* selected = m_processes->currentItem();+ if (row_kind(selected) == RowKind::Site) {+ for (int i = 0; i < selected->childCount(); ++i) {+ if (row_kind(selected->child(i)) == RowKind::Process)+ items.append(selected->child(i));+ }+ } else {+ items.append(selected);+ }++ for (auto* item : items) {+ auto pid = static_cast<pid_t>(item->data(PID, Qt::UserRole).toLongLong());+ auto child_id = item->data(PID, ChildIDRole).toULongLong();+ if (auto result = m_process_manager.terminate_child(child_id, Core::Process::TerminationMode::Forceful); result.is_error()) {+ if (!result.error().is_errno() || result.error().code() != ESRCH)+ QMessageBox::warning(this, tr("Unable to end process"), qformatted("Could not end process {}: {}", pid, result.error()));+ }}m_processes->clearSelection();refresh();@@ -528,14 +922,17 @@ void ProcessManagerWindow::end_selected_process()void ProcessManagerWindow::show_context_menu(QPoint const& position){auto* item = m_processes->itemAt(position);- if (!item)+ if (!item || (row_kind(item) != RowKind::Process && row_kind(item) != RowKind::Site))return;m_processes->setCurrentItem(item);update_actions();QMenu menu(this);- if (m_end_process_action->isEnabled())- menu.addAction(m_end_process_action);- menu.addAction(m_copy_pid_action);+ if (m_end_action->isEnabled())+ menu.addAction(m_end_action);+ if (row_kind(item) == RowKind::Process)+ menu.addAction(m_copy_pid_action);+ if (menu.isEmpty())+ return;menu.exec(m_processes->viewport()->mapToGlobal(position));}diff --git a/UI/Qt/ProcessManagerWindow.h b/UI/Qt/ProcessManagerWindow.hindex b6e5a1db1f0..201a88b7349 100644--- a/UI/Qt/ProcessManagerWindow.h+++ b/UI/Qt/ProcessManagerWindow.h@@ -6,6 +6,11 @@#pragma once+#include <AK/Function.h>+#include <AK/HashMap.h>+#include <AK/HashTable.h>+#include <AK/Optional.h>+#include <AK/String.h>#include <AK/kmalloc.h>#include <LibURL/Forward.h>#include <LibWebView/Forward.h>@@ -19,18 +24,32 @@ class QPushButton;class QLineEdit;class QTimer;class QTreeWidget;+class QTreeWidgetItem;++namespace WebView {++struct ProcessPageSnapshot;++}namespace Ladybird {QString task_manager_site_label(URL::URL const&);+// The Task Manager lists the browser's own processes, then each site with the processes that show it, then the spare+// processes kept ready for the next site.class ProcessManagerWindow final : public QDialog {public:AK_ALLOC_WITH_KMALLOC;explicit ProcessManagerWindow(WebView::ProcessManager&);+ // Called as the window is shown, and as its title changes, so the platform can hide the title and place the window+ // controls in the window's title bar.+ Function<void()> on_title_bar_change;+private:+ virtual bool event(QEvent*) override;virtual void showEvent(QShowEvent*) override;virtual void hideEvent(QHideEvent*) override;virtual void changeEvent(QEvent*) override;@@ -38,23 +57,31 @@ private:void refresh();void apply_filter();void update_actions();- void end_selected_process();+ void end_selection();void show_context_menu(QPoint const&);+ QIcon favicon_for(WebView::ProcessPageSnapshot const&);WebView::ProcessManager& m_process_manager;- QAction* m_end_process_action { nullptr };+ QAction* m_end_action { nullptr };QAction* m_copy_pid_action { nullptr };- QPushButton* m_end_process_button { nullptr };+ QPushButton* m_end_button { nullptr };bool m_is_updating_style { false };QTreeWidget* m_processes { nullptr };QLineEdit* m_search { nullptr };- QLabel* m_process_count { nullptr };+ QAction* m_search_icon { nullptr };QLabel* m_summary { nullptr };QTimer* m_timer { nullptr };+ QWidget* m_title_bar { nullptr };+ QLabel* m_title { nullptr };+ QWidget* m_footer { nullptr };QIcon m_browser_icon;- QIcon m_web_content_icon;+ QIcon m_document_icon;+ QIcon m_network_icon;+ QIcon m_compositor_icon;+ QIcon m_image_icon;QIcon m_service_icon;- QIcon m_spare_icon;+ HashMap<String, QIcon> m_favicons;+ HashTable<String> m_expanded_sites;};}diff --git a/UI/Qt/ReportReview.cpp b/UI/Qt/ReportReview.cppindex 148c9171cfa..fca0d6bf6de 100644--- a/UI/Qt/ReportReview.cpp+++ b/UI/Qt/ReportReview.cpp@@ -42,7 +42,12 @@ QLabel* create_heading(QString const& text, qreal scale, QWidget* parent)QLabel* create_title(QString const& text, QWidget* parent){- return create_heading(text, 1.5, parent);+ auto* label = create_label(text, parent);+ auto font = label->font();+ font.setPixelSize(22);+ font.setWeight(QFont::DemiBold);+ label->setFont(font);+ return label;}// A button that shows or hides the content below it, which starts out hidden. It is drawn as plain text, flush with thediff --git a/UI/Qt/RestoreSessionCard.cpp b/UI/Qt/RestoreSessionCard.cppnew file mode 100644index 00000000000..dc806885f9c--- /dev/null+++ b/UI/Qt/RestoreSessionCard.cpp@@ -0,0 +1,108 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <UI/Qt/ChromeStyle.h>+#include <UI/Qt/Popover.h>+#include <UI/Qt/RestoreSessionCard.h>+#include <UI/Qt/StringUtils.h>+#include <UI/Qt/Theme.h>++#include <QEvent>+#include <QHBoxLayout>+#include <QLabel>+#include <QPushButton>+#include <QVBoxLayout>++#if defined(AK_OS_MACOS)+# include <UI/Qt/MacWindow.h>+#endif++namespace Ladybird {++// The card is a native child of the tab, so it stacks above the native view the page is presented in.+static constexpr int CARD_WIDTH = 580;+static constexpr int CARD_CORNER_RADIUS = 12;+static constexpr int PAGE_TOP_INSET = 22;++RestoreSessionCard::RestoreSessionCard(QWidget& parent, QWidget& page, size_t tab_count)+ : QFrame(&parent)+ , m_page(page)+{+ setObjectName("LadybirdRestoreSessionCard");+ setAccessibleName("Ladybird quit unexpectedly");+#if defined(AK_OS_MACOS)+ setAttribute(Qt::WA_DontCreateNativeAncestors);+ setAttribute(Qt::WA_NativeWindow);+#endif+ setFixedWidth(CARD_WIDTH);+ cast_floating_shadow(*this, CARD_CORNER_RADIUS);++ auto* layout = new QHBoxLayout(this);+ layout->setContentsMargins(18, 14, 14, 14);+ layout->setSpacing(14);++ auto* text = new QVBoxLayout;+ text->setSpacing(3);+ auto* title = new QLabel("Ladybird quit unexpectedly", this);+ title->setObjectName("LadybirdRestoreSessionTitle");+ text->addWidget(title);+ auto* question = new QLabel(tab_count == 1 ? QStringLiteral("Restore the tab you had open?") : qformatted("Restore the {} tabs you had open?", tab_count), this);+ question->setObjectName("LadybirdRestoreSessionQuestion");+ text->addWidget(question);+ layout->addLayout(text, 1);++ auto* not_now_button = new QPushButton("Not now", this);+ not_now_button->setObjectName("LadybirdRestoreSessionNotNow");+ QObject::connect(not_now_button, &QPushButton::clicked, this, [this] { deleteLater(); });+ layout->addWidget(not_now_button);++ auto* restore_button = new QPushButton("Restore tabs", this);+ restore_button->setObjectName("LadybirdRestoreSessionRestore");+ restore_button->setDefault(true);+ QObject::connect(restore_button, &QPushButton::clicked, this, [this] {+ if (on_restore)+ on_restore();+ deleteLater();+ });+ layout->addWidget(restore_button);++ update_chrome_style();+ adjustSize();+}++void RestoreSessionCard::reposition()+{+ auto page_top_left = m_page.mapTo(parentWidget(), QPoint(0, 0));+ auto position = QPoint(page_top_left.x() + ((m_page.width() - width()) / 2), page_top_left.y() + PAGE_TOP_INSET);+ if (pos() != position)+ move(position);+}++bool RestoreSessionCard::event(QEvent* event)+{+ if (event->type() == QEvent::PaletteChange)+ update_chrome_style();+ return QFrame::event(event);+}++void RestoreSessionCard::showEvent(QShowEvent* event)+{+ QFrame::showEvent(event);+ reposition();+ raise();+#if defined(AK_OS_MACOS)+ round_appkit_view_corners(*this, CARD_CORNER_RADIUS, Theme::panel().edge);+#endif+}++void RestoreSessionCard::update_chrome_style()+{+ // NB: Setting a style sheet changes the palette, so it is only set when it changed, or it would set itself forever.+ if (auto style_sheet = ChromeStyle::restore_session_card_style_sheet(); styleSheet() != style_sheet)+ setStyleSheet(style_sheet);+}++}diff --git a/UI/Qt/RestoreSessionCard.h b/UI/Qt/RestoreSessionCard.hnew file mode 100644index 00000000000..93e7e75f549--- /dev/null+++ b/UI/Qt/RestoreSessionCard.h@@ -0,0 +1,38 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Function.h>+#include <AK/kmalloc.h>++#include <QFrame>++class QLabel;++namespace Ladybird {++// After Ladybird quit unexpectedly, a card over the top of the page offers to restore the tabs that were open.+class RestoreSessionCard final : public QFrame {+public:+ AK_ALLOC_WITH_KMALLOC;++ RestoreSessionCard(QWidget& parent, QWidget& page, size_t tab_count);++ void reposition();++ Function<void()> on_restore;++private:+ virtual bool event(QEvent*) override;+ virtual void showEvent(QShowEvent*) override;++ void update_chrome_style();++ QWidget& m_page;+};++}diff --git a/UI/Qt/SiteSettingsPopover.cpp b/UI/Qt/SiteSettingsPopover.cppnew file mode 100644index 00000000000..ad0d8de0228--- /dev/null+++ b/UI/Qt/SiteSettingsPopover.cpp@@ -0,0 +1,383 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibWebView/Application.h>+#include <UI/Qt/ChromeStyle.h>+#include <UI/Qt/Icon.h>+#include <UI/Qt/SiteSettingsPopover.h>+#include <UI/Qt/StringUtils.h>+#include <UI/Qt/Theme.h>++#include <QFrame>+#include <QHBoxLayout>+#include <QLabel>+#include <QMenu>+#include <QPushButton>+#include <QSignalBlocker>+#include <QToolButton>+#include <QVBoxLayout>++namespace Ladybird {++static constexpr int POPOVER_WIDTH = 344;+static constexpr int ROW_HEIGHT = 36;+static constexpr int BLOCKED_RESOURCE_ROW_HEIGHT = 26;++static void add_separator(QWidget& parent, QVBoxLayout& layout, int top_margin, int bottom_margin)+{+ layout.addSpacing(top_margin);+ auto* separator = new QFrame(&parent);+ separator->setObjectName("LadybirdPopoverSeparator");+ separator->setFixedHeight(1);+ auto* row = new QHBoxLayout;+ row->setContentsMargins(10, 0, 10, 0);+ row->addWidget(separator);+ layout.addLayout(row);+ layout.addSpacing(bottom_margin);+}++static QLabel* create_icon(QWidget& parent)+{+ auto* label = new QLabel(&parent);+ label->setFixedSize(16, 16);+ return label;+}++static QPushButton* create_link(QWidget& parent, QString const& text)+{+ auto* link = new QPushButton(text, &parent);+ link->setObjectName("LadybirdPopoverLink");+ link->setCursor(Qt::PointingHandCursor);+ // NB: The platform style lays out a push button by a frame of its own rather than by the button, which would+ // make it overlap its neighbors.+ link->setAttribute(Qt::WA_LayoutUsesWidgetRect);+ return link;+}++// The popover shows the site, and the settings that apply to it. Its content blocking leads on to what was blocked on+// the page, shown in place of the site until the popover goes back to it.+static QString autoplay_policy_name(Web::HTML::AutoplayPolicy policy)+{+ switch (policy) {+ case Web::HTML::AutoplayPolicy::AllowAudioAndVideo:+ return QStringLiteral("Allow");+ case Web::HTML::AutoplayPolicy::BlockAudio:+ return QStringLiteral("Block audio");+ case Web::HTML::AutoplayPolicy::BlockAudioAndVideo:+ return QStringLiteral("Block");+ }+ VERIFY_NOT_REACHED();+}++SiteSettingsPopover::SiteSettingsPopover(QWidget* parent)+ : Popover(parent)+{+ setAccessibleName("Site settings");+ card().setObjectName("LadybirdSiteSettingsPopover");+ card().setFixedWidth(POPOVER_WIDTH);++ auto* pages = new QVBoxLayout(&card());+ pages->setContentsMargins(0, 0, 0, 0);+ pages->setSpacing(0);++ // The site.+ m_site_page = new QWidget(&card());+ auto* layout = new QVBoxLayout(m_site_page);+ layout->setContentsMargins(6, 14, 6, 8);+ layout->setSpacing(0);++ auto* heading = new QHBoxLayout;+ heading->setContentsMargins(10, 0, 10, 0);+ heading->setSpacing(10);+ m_favicon = new QLabel(m_site_page);+ m_favicon->setFixedSize(28, 28);+ m_favicon->setAlignment(Qt::AlignCenter);+ m_favicon->setObjectName("LadybirdSiteSettingsFavicon");+ heading->addWidget(m_favicon);+ auto* heading_text = new QVBoxLayout;+ heading_text->setSpacing(2);+ m_host_label = new QLabel(m_site_page);+ m_host_label->setObjectName("LadybirdSiteSettingsHost");+ m_host_label->setTextFormat(Qt::PlainText);+ heading_text->addWidget(m_host_label);+ m_security_label = new QLabel(m_site_page);+ m_security_label->setObjectName("LadybirdSiteSettingsSecurity");+ m_security_label->setTextFormat(Qt::PlainText);+ heading_text->addWidget(m_security_label);+ heading->addLayout(heading_text, 1);+ layout->addLayout(heading);++ add_separator(*m_site_page, *layout, 12, 6);++ // Whether media may play on its own.+ auto* autoplay_row = new QHBoxLayout;+ autoplay_row->setContentsMargins(10, 0, 10, 0);+ autoplay_row->setSpacing(10);+ m_autoplay_icon = create_icon(*m_site_page);+ autoplay_row->addWidget(m_autoplay_icon);+ auto* autoplay_label = new QLabel("Autoplay", m_site_page);+ autoplay_label->setFixedHeight(ROW_HEIGHT);+ autoplay_row->addWidget(autoplay_label, 1);+ m_autoplay_button = new QPushButton(m_site_page);+ m_autoplay_button->setObjectName("LadybirdPopoverValueButton");+ m_autoplay_button->setCursor(Qt::PointingHandCursor);+ m_autoplay_button->setAttribute(Qt::WA_LayoutUsesWidgetRect);+ // NB: The chevron follows the value.+ m_autoplay_button->setLayoutDirection(Qt::RightToLeft);+ m_autoplay_button->setIconSize({ 12, 12 });+ QObject::connect(m_autoplay_button, &QPushButton::clicked, this, [this] {+ // A site is either allowed to autoplay, or follows the default, which the menu names so that the choice it shows+ // on the button is always one of those in the menu.+ auto const& autoplay = WebView::Application::settings().autoplay_settings();+ auto is_allowed_on_site = autoplay.site_filters.contains(m_host);+ QMenu menu(this);+ auto* allow = menu.addAction("Allow");+ allow->setCheckable(true);+ allow->setChecked(is_allowed_on_site);+ auto* use_default = menu.addAction(qformatted("Default ({})", autoplay_policy_name(autoplay.policy)));+ use_default->setCheckable(true);+ use_default->setChecked(!is_allowed_on_site);+ auto* chosen = menu.exec(m_autoplay_button->mapToGlobal(QPoint(0, m_autoplay_button->height())));+ if (chosen == allow)+ WebView::Application::settings().add_autoplay_site_filter(m_host);+ else if (chosen == use_default)+ WebView::Application::settings().remove_autoplay_site_filter(m_host);+ update_autoplay();+ });+ autoplay_row->addWidget(m_autoplay_button);+ layout->addLayout(autoplay_row);++ add_separator(*m_site_page, *layout, 6, 6);++ // Whether content blocking is on for the site, and what it blocked on the page.+ auto* blocking_row = new QHBoxLayout;+ blocking_row->setContentsMargins(10, 0, 10, 0);+ blocking_row->setSpacing(10);+ m_content_blocking_icon = create_icon(*m_site_page);+ blocking_row->addWidget(m_content_blocking_icon);+ auto* blocking_label = new QLabel("Content blocking", m_site_page);+ blocking_label->setFixedHeight(ROW_HEIGHT);+ blocking_row->addWidget(blocking_label, 1);+ m_content_blocking_switch = new PopoverSwitch(m_site_page);+ m_content_blocking_switch->setAccessibleName("Content blocking on this site");+ QObject::connect(m_content_blocking_switch, &QCheckBox::toggled, this, [this](bool enabled) {+ if (on_content_blocking_toggle)+ on_content_blocking_toggle(enabled);+ });+ blocking_row->addWidget(m_content_blocking_switch);+ layout->addLayout(blocking_row);++ m_blocked_row = new QPushButton(m_site_page);+ m_blocked_row->setObjectName("LadybirdPopoverRow");+ m_blocked_row->setAccessibleName("Blocked on this page");+ m_blocked_row->setFixedHeight(ROW_HEIGHT);+ m_blocked_row->setAttribute(Qt::WA_LayoutUsesWidgetRect);+ auto* blocked_row_layout = new QHBoxLayout(m_blocked_row);+ blocked_row_layout->setContentsMargins(10, 0, 10, 0);+ blocked_row_layout->setSpacing(10);+ // NB: A box layout puts no spacing after a spacer, so this spacer covers the icon and its spacing in the rows above.+ blocked_row_layout->addSpacing(26);+ auto* blocked_label = new QLabel("Blocked on this page", m_blocked_row);+ blocked_label->setAttribute(Qt::WA_TransparentForMouseEvents);+ blocked_row_layout->addWidget(blocked_label, 1);+ m_blocked_count = new QLabel(m_blocked_row);+ m_blocked_count->setObjectName("LadybirdSiteSettingsDetail");+ m_blocked_count->setAttribute(Qt::WA_TransparentForMouseEvents);+ blocked_row_layout->addWidget(m_blocked_count);+ m_blocked_row_chevron = new QLabel(m_blocked_row);+ m_blocked_row_chevron->setFixedSize(12, 12);+ m_blocked_row_chevron->setAttribute(Qt::WA_TransparentForMouseEvents);+ blocked_row_layout->addWidget(m_blocked_row_chevron);+ QObject::connect(m_blocked_row, &QPushButton::clicked, this, [this] { show_blocked_resources(true); });+ layout->addWidget(m_blocked_row);++ add_separator(*m_site_page, *layout, 6, 2);++ auto* links = new QHBoxLayout;+ links->setContentsMargins(4, 0, 4, 0);+ // What can be set for the site is reset to the defaults.+ m_reset_permissions_link = create_link(*m_site_page, "Reset permissions");+ QObject::connect(m_reset_permissions_link, &QPushButton::clicked, this, [this] {+ WebView::Application::settings().remove_autoplay_site_filter(m_host);+ update_autoplay();+ });+ links->addWidget(m_reset_permissions_link);+ links->addStretch(1);+ auto* site_settings_link = create_link(*m_site_page, "All site settings");+ QObject::connect(site_settings_link, &QPushButton::clicked, this, [this] {+ close();+ if (on_open_all_site_settings)+ on_open_all_site_settings();+ });+ links->addWidget(site_settings_link);+ layout->addLayout(links);+ pages->addWidget(m_site_page);++ // What was blocked on the page.+ m_blocked_page = new QWidget(&card());+ auto* blocked_layout = new QVBoxLayout(m_blocked_page);+ blocked_layout->setContentsMargins(6, 8, 6, 8);+ blocked_layout->setSpacing(0);++ auto* blocked_heading = new QHBoxLayout;+ blocked_heading->setContentsMargins(4, 0, 10, 0);+ blocked_heading->setSpacing(4);+ m_back_button = new QToolButton(m_blocked_page);+ m_back_button->setObjectName("LadybirdPopoverIconButton");+ m_back_button->setAccessibleName("Back to site settings");+ m_back_button->setFixedSize(28, 28);+ m_back_button->setIconSize({ 14, 14 });+ QObject::connect(m_back_button, &QToolButton::clicked, this, [this] { show_blocked_resources(false); });+ blocked_heading->addWidget(m_back_button);+ auto* blocked_title = new QLabel("Blocked on this page", m_blocked_page);+ blocked_title->setObjectName("LadybirdSiteSettingsHost");+ blocked_title->setFixedHeight(32);+ blocked_heading->addWidget(blocked_title, 1);+ m_blocked_page_count = new QLabel(m_blocked_page);+ m_blocked_page_count->setObjectName("LadybirdSiteSettingsDetail");+ blocked_heading->addWidget(m_blocked_page_count);+ blocked_layout->addLayout(blocked_heading);+ blocked_layout->addSpacing(6);++ add_separator(*m_blocked_page, *blocked_layout, 0, 6);++ m_blocked_list = new QVBoxLayout;+ m_blocked_list->setContentsMargins(10, 0, 10, 0);+ m_blocked_list->setSpacing(0);+ blocked_layout->addLayout(m_blocked_list);++ add_separator(*m_blocked_page, *blocked_layout, 8, 6);++ auto* blocked_links = new QHBoxLayout;+ blocked_links->setContentsMargins(4, 2, 4, 0);+ auto* report_link = create_link(*m_blocked_page, "Report a broken site");+ QObject::connect(report_link, &QPushButton::clicked, this, [this] {+ close();+ if (on_report_broken_site)+ on_report_broken_site();+ });+ blocked_links->addWidget(report_link);+ blocked_links->addStretch(1);+ auto* filter_lists_link = create_link(*m_blocked_page, "Filter lists");+ QObject::connect(filter_lists_link, &QPushButton::clicked, this, [this] {+ close();+ if (on_open_filter_lists)+ on_open_filter_lists();+ });+ blocked_links->addWidget(filter_lists_link);+ blocked_layout->addLayout(blocked_links);+ pages->addWidget(m_blocked_page);+ m_blocked_page->hide();++ update_icons();+}++void SiteSettingsPopover::set_site(Site site)+{+ m_host = AK::move(site.host);+ m_host_label->setText(qstring_from_ak_string(m_host));+ // A secure connection is the norm, so only an insecure one is mentioned.+ m_security_label->setText("Connection is not secure");+ m_security_label->setVisible(!site.is_secure);++ m_favicon->setPixmap(site.favicon.isNull() ? create_chrome_icon(ChromeIcon::Globe, Theme::panel().muted).pixmap(QSize(16, 16), devicePixelRatioF()) : site.favicon.pixmap(QSize(16, 16), devicePixelRatioF()));++ update_autoplay();+ show_blocked_resources(false);+ set_content_blocking(site.content_blocking);+}++void SiteSettingsPopover::set_content_blocking(WebView::ContentBlockingSnapshot const& blocking)+{+ QSignalBlocker blocker(m_content_blocking_switch);+ m_content_blocking_switch->setChecked(blocking.enabled());+ m_content_blocking_switch->setEnabled(blocking.can_toggle());++ // What was blocked is only listed while content blocking is on.+ auto count = qformatted("{}", blocking.blocked_resources.size());+ m_blocked_count->setText(count);+ m_blocked_page_count->setText(count);+ m_blocked_row->setVisible(blocking.enabled());+ if (!blocking.enabled())+ show_blocked_resources(false);++ while (auto* item = m_blocked_list->takeAt(0)) {+ delete item->widget();+ delete item;+ }+ if (blocking.blocked_resources.is_empty()) {+ auto* empty = new QLabel("Nothing has been blocked on this page.", m_blocked_page);+ empty->setObjectName("LadybirdSiteSettingsDetail");+ empty->setFixedHeight(BLOCKED_RESOURCE_ROW_HEIGHT);+ m_blocked_list->addWidget(empty);+ }+ for (auto const& resource : blocking.blocked_resources) {+ auto* row = new QWidget(m_blocked_page);+ row->setFixedHeight(BLOCKED_RESOURCE_ROW_HEIGHT);+ auto* row_layout = new QHBoxLayout(row);+ row_layout->setContentsMargins(0, 0, 0, 0);+ row_layout->setSpacing(10);+ auto* host = new QLabel(row);+ host->setTextFormat(Qt::PlainText);+ host->setText(host->fontMetrics().elidedText(qstring_from_ak_string(resource.host), Qt::ElideRight, POPOVER_WIDTH - 120));+ row_layout->addWidget(host, 1);+ auto* kind = new QLabel(qstring_from_ak_string(resource.kind), row);+ kind->setObjectName("LadybirdSiteSettingsDetail");+ row_layout->addWidget(kind);+ m_blocked_list->addWidget(row);+ }+ fit_to_page();+}++void SiteSettingsPopover::show_blocked_resources(bool show)+{+ // NB: The page shown before is hidden first, so that the popover never has to fit both pages at once.+ (show ? m_site_page : m_blocked_page)->hide();+ (show ? m_blocked_page : m_site_page)->show();+ fit_to_page();+}++void SiteSettingsPopover::fit_to_page()+{+ // NB: The page's and the card's layouts take in a row that shows or hides only once they are activated, so they are+ // activated before the popover's own, which would otherwise keep the card at its old height.+ for (auto* page : { m_site_page, m_blocked_page }) {+ if (!page->isHidden())+ page->layout()->activate();+ }+ card().layout()->activate();+ layout()->activate();+ adjustSize();+}++void SiteSettingsPopover::update_autoplay()+{+ auto const& autoplay = WebView::Application::settings().autoplay_settings();+ auto name = autoplay.site_filters.contains(m_host) ? QStringLiteral("Allow") : autoplay_policy_name(autoplay.policy);+ m_autoplay_button->setText(name);+ m_autoplay_button->setIcon(create_chrome_icon(ChromeIcon::ChevronDown, Theme::panel().muted));+ if (m_reset_permissions_link)+ m_reset_permissions_link->setEnabled(autoplay.site_filters.contains(m_host));+}++void SiteSettingsPopover::update_chrome_style(QPalette const& palette)+{+ setPalette(palette);+ setStyleSheet(ChromeStyle::site_settings_popover_style_sheet(palette));+ // NB: The popover is kept for its tab, so its icons are drawn again in the colors of the current theme.+ update_icons();+}++void SiteSettingsPopover::update_icons()+{+ auto const& panel = Theme::panel();+ m_autoplay_icon->setPixmap(create_chrome_icon(ChromeIcon::Volume, panel.body).pixmap(QSize(16, 16), devicePixelRatioF()));+ m_content_blocking_icon->setPixmap(create_chrome_icon(ChromeIcon::ContentBlocking, panel.body).pixmap(QSize(16, 16), devicePixelRatioF()));+ m_blocked_row_chevron->setPixmap(create_chrome_icon(ChromeIcon::Forward, panel.muted).pixmap(QSize(12, 12), devicePixelRatioF()));+ m_back_button->setIcon(create_chrome_icon(ChromeIcon::Back, panel.body));+}++}diff --git a/UI/Qt/SiteSettingsPopover.h b/UI/Qt/SiteSettingsPopover.hnew file mode 100644index 00000000000..20f307e6383--- /dev/null+++ b/UI/Qt/SiteSettingsPopover.h@@ -0,0 +1,68 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Function.h>+#include <AK/String.h>+#include <LibWebView/ContentBlocking.h>+#include <UI/Qt/Popover.h>++class QLabel;+class QPushButton;+class QToolButton;+class QVBoxLayout;++namespace Ladybird {++// What Ladybird knows about the site a page is from, and the settings that apply to it.+class SiteSettingsPopover final : public Popover {+public:+ AK_ALLOC_WITH_KMALLOC;++ explicit SiteSettingsPopover(QWidget* parent);++ struct Site {+ String host;+ bool is_secure { false };+ QIcon favicon;+ WebView::ContentBlockingSnapshot content_blocking;+ };+ void set_site(Site);+ void set_content_blocking(WebView::ContentBlockingSnapshot const&);+ void update_chrome_style(QPalette const&);++ Function<void(bool)> on_content_blocking_toggle;+ Function<void()> on_open_all_site_settings;+ Function<void()> on_report_broken_site;+ Function<void()> on_open_filter_lists;++private:+ void update_autoplay();+ void update_icons();+ void show_blocked_resources(bool);+ void fit_to_page();++ String m_host;+ QWidget* m_site_page { nullptr };+ QWidget* m_blocked_page { nullptr };+ QLabel* m_favicon { nullptr };+ QLabel* m_host_label { nullptr };+ QLabel* m_security_label { nullptr };+ QLabel* m_autoplay_icon { nullptr };+ QPushButton* m_autoplay_button { nullptr };+ QPushButton* m_reset_permissions_link { nullptr };+ QLabel* m_content_blocking_icon { nullptr };+ PopoverSwitch* m_content_blocking_switch { nullptr };+ QPushButton* m_blocked_row { nullptr };+ QLabel* m_blocked_row_chevron { nullptr };+ QToolButton* m_back_button { nullptr };+ QLabel* m_blocked_count { nullptr };+ QLabel* m_blocked_page_count { nullptr };+ QVBoxLayout* m_blocked_list { nullptr };+};++}diff --git a/UI/Qt/SystemAppearance.cpp b/UI/Qt/SystemAppearance.cppnew file mode 100644index 00000000000..c0812f44f85--- /dev/null+++ b/UI/Qt/SystemAppearance.cpp@@ -0,0 +1,93 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Platform.h>+#include <UI/Qt/SystemAppearance.h>++#include <QAccessibilityHints>+#include <QApplication>+#include <QStyleHints>+#include <QWidget>++namespace Ladybird {++SystemAppearance& SystemAppearance::the()+{+ static auto* appearance = new SystemAppearance;+ return *appearance;+}++SystemAppearance::SystemAppearance()+{+ m_prefers_dark = query_system_prefers_dark();++ QObject::connect(QGuiApplication::styleHints(), &QStyleHints::colorSchemeChanged, this, [this] {+ update();+ });+ // The chrome's colors depend on the contrast preference, but changing it does not change the application palette.+ // Widgets restyle themselves on palette changes, so tell them about one.+ QObject::connect(QGuiApplication::styleHints()->accessibility(), &QAccessibilityHints::contrastPreferenceChanged, this, [] {+ QEvent application_event(QEvent::ApplicationPaletteChange);+ QCoreApplication::sendEvent(qApp, &application_event);+ for (auto* widget : QApplication::allWidgets()) {+ QEvent event(QEvent::PaletteChange);+ QCoreApplication::sendEvent(widget, &event);+ }+ });+ observe_platform_changes();+}++void SystemAppearance::update()+{+ auto prefers_dark = query_system_prefers_dark();+ if (prefers_dark == m_prefers_dark)+ return;++ m_prefers_dark = prefers_dark;+ emit changed();+}++void SystemAppearance::apply_interface_theme(WebView::ThemePreference theme)+{+ if (theme == m_interface_theme)+ return;+ m_interface_theme = theme;++ switch (theme) {+ case WebView::ThemePreference::System:+ QGuiApplication::styleHints()->unsetColorScheme();+ break;+ case WebView::ThemePreference::Light:+ QGuiApplication::styleHints()->setColorScheme(Qt::ColorScheme::Light);+ break;+ case WebView::ThemePreference::Dark:+ QGuiApplication::styleHints()->setColorScheme(Qt::ColorScheme::Dark);+ break;+ }+}++#if !defined(AK_OS_MACOS)+bool SystemAppearance::query_system_prefers_dark() const+{+ // FIXME: Ask the platform directly. While the interface theme overrides Qt's color scheme, Qt reports the override,+ // so we keep the appearance we last saw from the system.+ if (m_interface_theme != WebView::ThemePreference::System)+ return m_prefers_dark;+ return QGuiApplication::styleHints()->colorScheme() == Qt::ColorScheme::Dark;+}++void SystemAppearance::observe_platform_changes()+{+}++bool SystemAppearance::prefers_reduced_motion()+{+ // FIXME: Ask the platform.+ return false;+}+#endif++}diff --git a/UI/Qt/SystemAppearance.h b/UI/Qt/SystemAppearance.hnew file mode 100644index 00000000000..4a8092a11dd--- /dev/null+++ b/UI/Qt/SystemAppearance.h@@ -0,0 +1,46 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <LibWebView/Settings.h>++#include <QObject>++namespace Ladybird {++// The light or dark appearance chosen in the system's settings. The interface theme setting overrides the appearance+// of our own windows, so this tracks the system separately: websites follow it while their color scheme setting is+// left on System.+class SystemAppearance final : public QObject {+ Q_OBJECT++public:+ AK_ALLOC_WITH_KMALLOC;++ static SystemAppearance& the();++ bool prefers_dark() const { return m_prefers_dark; }+ // Whether the system asks for less motion. The chrome then moves nothing, though it still fades.+ static bool prefers_reduced_motion();++ void apply_interface_theme(WebView::ThemePreference);++signals:+ void changed();++private:+ SystemAppearance();++ void update();+ bool query_system_prefers_dark() const;+ void observe_platform_changes();++ bool m_prefers_dark { false };+ WebView::ThemePreference m_interface_theme { WebView::ThemePreference::System };+};++}diff --git a/UI/Qt/SystemAppearanceMac.mm b/UI/Qt/SystemAppearanceMac.mmnew file mode 100644index 00000000000..b2730b7fe51--- /dev/null+++ b/UI/Qt/SystemAppearanceMac.mm@@ -0,0 +1,40 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <UI/Qt/SystemAppearance.h>++#import <AppKit/AppKit.h>+#import <Foundation/Foundation.h>++#include <QMetaObject>++namespace Ladybird {++// NB: The application's own appearance follows the interface theme, so the system's choice is read from the global+// defaults instead. The key only exists while the system is dark, including while Auto has made it dark.+bool SystemAppearance::query_system_prefers_dark() const+{+ auto* style = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];+ return [style isEqualToString:@"Dark"];+}++bool SystemAppearance::prefers_reduced_motion()+{+ return [[NSWorkspace sharedWorkspace] accessibilityDisplayShouldReduceMotion];+}++void SystemAppearance::observe_platform_changes()+{+ [[NSDistributedNotificationCenter defaultCenter] addObserverForName:@"AppleInterfaceThemeChangedNotification"+ object:nil+ queue:[NSOperationQueue mainQueue]+ usingBlock:^(NSNotification*) {+ // The defaults are updated after the notification is posted.+ QMetaObject::invokeMethod(this, [this] { update(); }, Qt::QueuedConnection);+ }];+}++}diff --git a/UI/Qt/Tab.cpp b/UI/Qt/Tab.cppindex ae521fd534c..64e8724295d 100644--- a/UI/Qt/Tab.cpp+++ b/UI/Qt/Tab.cpp@@ -9,6 +9,7 @@#include <AK/kmalloc.h>#include <LibCore/EventLoop.h>#include <LibCore/Promise.h>+#include <LibURL/Parser.h>#include <LibURL/URL.h>#include <LibWakeLock/DisplaySleepInhibitor.h>#include <LibWebCommon/HTML/SelectedFile.h>@@ -18,23 +19,29 @@#include <LibWebView/Utilities.h>#include <LibWebView/WebContentClient.h>#include <UI/Qt/Application.h>+#include <UI/Qt/BookmarkPopover.h>#include <UI/Qt/BrowserWindow.h>#include <UI/Qt/ChromeLayout.h>#include <UI/Qt/ChromeStyle.h>-#include <UI/Qt/ContentBlockingButton.h>-#include <UI/Qt/ContentBlockingPopover.h>#include <UI/Qt/Icon.h>#include <UI/Qt/JavaScriptDialog.h>+#include <UI/Qt/LadybirdButton.h>#if defined(AK_OS_MACOS)# include <UI/Qt/MacWindow.h>#endif#include <UI/Qt/Menu.h>+#include <UI/Qt/Motion.h>#include <UI/Qt/Popover.h>+#include <UI/Qt/RestoreSessionCard.h>+#include <UI/Qt/SiteSettingsPopover.h>#include <UI/Qt/StringUtils.h>+#include <UI/Qt/SystemAppearance.h>+#include <UI/Qt/Theme.h>#include <UI/Qt/WindowControlButton.h>#include <LibWebView/TabPerformanceMonitor.h>#include <QApplication>+#include <QClipboard>#include <QColorDialog>#include <QCursor>#include <QDynamicPropertyChangeEvent>@@ -70,18 +77,102 @@ class ToolbarButton : public QToolButton {public:AK_ALLOC_WITH_KMALLOC;- using QToolButton::QToolButton;+ explicit ToolbarButton(QWidget* parent)+ : QToolButton(parent)+ {+ QObject::connect(&m_icon_motion_animation, &QVariantAnimation::valueChanged, this, [this] { update(); });+ QObject::connect(&m_icon_motion_animation, &QVariantAnimation::finished, this, [this] { update(); });+ }Function<void()> on_middle_click;+ // A click or a change of state moves the icon a little: back and forward nudge their way, and the downloads arrow+ // drops into place as the button appears and bobs once as a download finishes.+ enum class IconMotion : u8 {+ NudgeLeft,+ NudgeRight,+ DropIn,+ Bob,+ };++ void play_icon_motion(IconMotion motion)+ {+ if (SystemAppearance::prefers_reduced_motion())+ return;+ m_icon_motion = motion;+ // NB: A click can disable its button, as going back to the first page does with the back button. The motion+ // plays out as the button looked when it started.+ m_icon_motion_is_hovered = underMouse();+ m_icon_motion_animation.stop();+ m_icon_motion_animation.setStartValue(0.0);+ m_icon_motion_animation.setEndValue(1.0);+ switch (motion) {+ case IconMotion::NudgeLeft:+ case IconMotion::NudgeRight:+ m_icon_motion_animation.setDuration(NUDGE_DURATION_MS);+ break;+ case IconMotion::DropIn:+ m_icon_motion_animation.setDuration(DROP_IN_DURATION_MS);+ break;+ case IconMotion::Bob:+ m_icon_motion_animation.setDuration(BOB_DURATION_MS);+ break;+ }+ m_icon_motion_animation.start();+ }+protected:+ QRect icon_rect() const+ {+ return QRect(QPoint((width() - iconSize().width()) / 2, (height() - iconSize().height()) / 2), iconSize());+ }++ QIcon::Mode icon_mode() const+ {+ return isEnabled() ? (underMouse() ? QIcon::Active : QIcon::Normal) : QIcon::Disabled;+ }+virtual void paintEvent(QPaintEvent*) override{+ if (m_icon_motion_animation.state() == QAbstractAnimation::Running) {+ QPainter painter(this);+ if (isEnabled()) {+ ChromeStyle::paint_control_frame(painter, *this);+ } else if (m_icon_motion_is_hovered && underMouse()) {+ painter.setRenderHint(QPainter::Antialiasing, true);+ painter.setPen(Qt::NoPen);+ painter.setBrush(Theme::chrome(palette()).hover);+ painter.drawRoundedRect(QRectF(rect()), ChromeStyle::CONTROL_FRAME_RADIUS, ChromeStyle::CONTROL_FRAME_RADIUS);+ painter.setRenderHint(QPainter::Antialiasing, false);+ }+ auto mode = isEnabled() ? icon_mode() : (m_icon_motion_is_hovered && underMouse() ? QIcon::Active : QIcon::Normal);+ auto progress = m_icon_motion_animation.currentValue().toReal();+ switch (m_icon_motion) {+ case IconMotion::NudgeLeft:+ painter.translate(-NUDGE_DISTANCE * Motion::there_and_back(progress, NUDGE_PEAK_AT), 0);+ break;+ case IconMotion::NudgeRight:+ painter.translate(NUDGE_DISTANCE * Motion::there_and_back(progress, NUDGE_PEAK_AT), 0);+ break;+ case IconMotion::DropIn: {+ auto eased = Motion::enter_easing().valueForProgress(progress);+ painter.translate(0, -DROP_IN_DISTANCE * (1 - eased));+ painter.setOpacity(eased);+ break;+ }+ case IconMotion::Bob:+ painter.translate(0, BOB_DISTANCE * Motion::there_and_back(progress, BOB_PEAK_AT));+ break;+ }+ icon().paint(&painter, icon_rect(), Qt::AlignCenter, mode);+ return;+ }+QStyleOptionToolButton option;initStyleOption(&option);QStylePainter painter(this);- ChromeStyle::paint_circular_control_frame(painter, *this);+ ChromeStyle::paint_control_frame(painter, *this);painter.drawComplexControl(QStyle::CC_ToolButton, option);}@@ -104,13 +195,26 @@ protected:QToolButton::mouseReleaseEvent(event);}}++private:+ static constexpr int NUDGE_DURATION_MS = 180;+ static constexpr qreal NUDGE_DISTANCE = 2;+ static constexpr qreal NUDGE_PEAK_AT = 0.4;+ static constexpr int DROP_IN_DURATION_MS = 220;+ static constexpr qreal DROP_IN_DISTANCE = 4;+ static constexpr int BOB_DURATION_MS = 260;+ static constexpr qreal BOB_DISTANCE = 2;+ static constexpr qreal BOB_PEAK_AT = 0.45;++ IconMotion m_icon_motion { IconMotion::NudgeLeft };+ bool m_icon_motion_is_hovered { false };+ QVariantAnimation m_icon_motion_animation;};// The reload button becomes a stop button while the page loads. So that one click does not do what the user did not aim-// at, the button does not change at the wrong moment while under the pointer: a stop button stays until the pointer-// leaves or a short delay passes, and a reload click does not become a stop button until the double-click interval-// passes, so a double-click does not stop the reload it started. The reload action stays attached to the button while-// it shows stop, so its shortcuts still work during a load.+// at, a stop button under the pointer stays until the pointer leaves or a short delay passes, and a click on stop within+// the double-click interval of a reload click is ignored, so a double-click does not stop the reload it started. The+// reload action stays attached to the button while it shows stop, so its shortcuts still work during a load.class ReloadButton final : public ToolbarButton {public:AK_ALLOC_WITH_KMALLOC;@@ -118,11 +222,12 @@ public:explicit ReloadButton(QWidget* parent): ToolbarButton(parent){+ m_icon_fade.setStartValue(0.0);+ m_icon_fade.setEndValue(1.0);+ QObject::connect(&m_icon_fade, &QVariantAnimation::valueChanged, this, [this] { update(); });+m_double_click_timer.setSingleShot(true);m_double_click_timer.setInterval(QApplication::doubleClickInterval());- QObject::connect(&m_double_click_timer, &QTimer::timeout, this, [this] {- change_mode(m_intended_mode, ForceChange::No);- });m_stop_to_reload_timer.setSingleShot(true);m_stop_to_reload_timer.setInterval(STOP_TO_RELOAD_DELAY_MS);@@ -165,6 +270,8 @@ protected:// any other click there does. QToolButton triggers its default action from here, once a click has completed.virtual void nextCheckState() override{+ if (m_visible_mode == Mode::Stop && m_double_click_timer.isActive())+ return;if (m_visible_mode == Mode::Reload && QApplication::keyboardModifiers().testFlag(Qt::ShiftModifier)) {m_reload_bypassing_cache_action->trigger();return;@@ -174,6 +281,13 @@ protected:private:static constexpr int STOP_TO_RELOAD_DELAY_MS = 1000;+ static constexpr int ARROW_TURN_DURATION_MS = 340;+ static constexpr int TURN_CROSS_FADE_DELAY_MS = 200;+ static constexpr int TURN_CROSS_FADE_DURATION_MS = 140;+ static constexpr int STOP_TURN_DELAY_MS = 180;+ static constexpr int STOP_TURN_DURATION_MS = 200;+ static constexpr int RELOAD_TO_STOP_DURATION_MS = STOP_TURN_DELAY_MS + STOP_TURN_DURATION_MS;+ static constexpr int ICON_CROSS_FADE_DURATION_MS = 160;enum class Mode {Reload,@@ -189,10 +303,18 @@ private:{m_intended_mode = mode;- auto change_is_safe = mode == Mode::Stop ? !m_double_click_timer.isActive() : m_visible_mode != Mode::Stop;+ auto change_is_safe = mode == Mode::Stop || m_visible_mode != Mode::Stop;if (force_change == ForceChange::Yes || !underMouse() || change_is_safe) {- m_double_click_timer.stop();m_stop_to_reload_timer.stop();+ if (m_visible_mode != mode && defaultAction() && !SystemAppearance::prefers_reduced_motion()) {+ m_previous_icon = defaultAction()->icon();+ // NB: The arrow turns into the stop icon only as the reload button is clicked. A load started otherwise+ // cross-fades it, as does the end of a load.+ m_turns_icon = mode == Mode::Stop && m_double_click_timer.isActive();+ m_icon_fade.stop();+ m_icon_fade.setDuration(m_turns_icon ? RELOAD_TO_STOP_DURATION_MS : ICON_CROSS_FADE_DURATION_MS);+ m_icon_fade.start();+ }m_visible_mode = mode;setDefaultAction(mode == Mode::Stop ? m_stop_action : m_reload_action);return;@@ -202,125 +324,181 @@ private:m_stop_to_reload_timer.start();}+ // As a click on it starts a load, the reload arrow turns half a turn, and over its second half cross-fades into the+ // stop icon, which turns into place. Otherwise, as when the load ends, the two icons only cross-fade.+ virtual void paintEvent(QPaintEvent* event) override+ {+ if (m_icon_fade.state() != QAbstractAnimation::Running) {+ ToolbarButton::paintEvent(event);+ return;+ }++ QPainter painter(this);+ painter.setRenderHint(QPainter::SmoothPixmapTransform, true);+ ChromeStyle::paint_control_frame(painter, *this);+ auto elapsed = m_icon_fade.currentValue().toReal() * m_icon_fade.duration();+ auto part = [&](qreal delay, qreal duration) { return clamp((elapsed - delay) / duration, 0.0, 1.0); };+ auto center = QRectF(icon_rect()).center();+ auto paint_turned = [&](QIcon const& icon, qreal opacity, qreal degrees) {+ painter.save();+ painter.setOpacity(opacity);+ painter.translate(center);+ painter.rotate(degrees);+ painter.translate(-center);+ icon.paint(&painter, icon_rect(), Qt::AlignCenter, icon_mode());+ painter.restore();+ };+ if (!m_turns_icon) {+ auto fade = part(0, ICON_CROSS_FADE_DURATION_MS);+ paint_turned(m_previous_icon, 1 - fade, 0);+ paint_turned(icon(), fade, 0);+ return;+ }+ static auto const easing = Motion::enter_easing();+ auto fade = part(TURN_CROSS_FADE_DELAY_MS, TURN_CROSS_FADE_DURATION_MS);+ paint_turned(m_previous_icon, 1 - fade, 180 * easing.valueForProgress(part(0, ARROW_TURN_DURATION_MS)));+ paint_turned(icon(), fade, -90 * (1 - easing.valueForProgress(part(STOP_TURN_DELAY_MS, STOP_TURN_DURATION_MS))));+ }+QAction* m_reload_action { nullptr };QAction* m_reload_bypassing_cache_action { nullptr };QAction* m_stop_action { nullptr };+ QIcon m_previous_icon;+ QVariantAnimation m_icon_fade;+ bool m_turns_icon { false };Mode m_visible_mode { Mode::Reload };Mode m_intended_mode { Mode::Reload };QTimer m_double_click_timer;QTimer m_stop_to_reload_timer;};-class HamburgerButton final : public ToolbarButton {-public:- AK_ALLOC_WITH_KMALLOC;-- using ToolbarButton::ToolbarButton;--protected:- virtual void mousePressEvent(QMouseEvent* event) override- {- if (event->button() == Qt::LeftButton)- show_menu();- else- QToolButton::mousePressEvent(event);- }-- virtual void keyPressEvent(QKeyEvent* event) override- {- if (first_is_one_of(event->key(), Qt::Key_Select, Qt::Key_Space))- show_menu();- else- QToolButton::keyPressEvent(event);- }--private:- void show_menu()- {- auto* menu = this->menu();- VERIFY(menu);-- auto bottom_right = mapToGlobal(rect().bottomRight());- auto menu_width = menu->sizeHint().width();-- menu->popup(QPoint { bottom_right.x() - menu_width, bottom_right.y() });- }-};+static constexpr QSize TOOLBAR_BUTTON_SIZE { 32, 28 };+// The downloads button appears at the end of the toolbar once there are downloads, and opens the list of them. While+// they are under way, a ring around it fills as they progress, or turns while their progress is not known. A failed+// download marks it with a dot until the list is looked at.class DownloadsButton final : public ToolbarButton {public:AK_ALLOC_WITH_KMALLOC;- using ToolbarButton::ToolbarButton;-- void set_progress(Optional<double> progress)+ explicit DownloadsButton(QWidget* parent)+ : ToolbarButton(parent){- auto normalized_progress = progress.map([](auto value) {- if (value < 0.0)- return 0.0;- if (value > 1.0)- return 1.0;- return value;+ setObjectName("LadybirdDownloadsButton");+ setAccessibleName("Downloads");+ // NB: The button stays checked while the list of downloads is open.+ setCheckable(true);+ setAutoRaise(true);+ setFocusPolicy(Qt::NoFocus);+ setIconSize({ TOOLBAR_ICON_SIZE, TOOLBAR_ICON_SIZE });+ setFixedSize(TOOLBAR_BUTTON_SIZE);+ setAttribute(Qt::WA_LayoutUsesWidgetRect);+ hide();++ m_ring_animation.setDuration(ChromeStyle::LOADING_RING_PERIOD_MS);+ m_ring_animation.setStartValue(0.0);+ m_ring_animation.setEndValue(1.0);+ m_ring_animation.setLoopCount(-1);+ QObject::connect(&m_ring_animation, &QVariantAnimation::valueChanged, this, [this] { update(); });++ m_ring_fade.setDuration(RING_FADE_DURATION_MS);+ QObject::connect(&m_ring_fade, &QVariantAnimation::valueChanged, this, [this] { update(); });++ m_progress_animation.setDuration(PROGRESS_GLIDE_DURATION_MS);+ QObject::connect(&m_progress_animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ m_shown_progress = value.toReal();+ update();});+ }- if (m_progress.has_value() == normalized_progress.has_value()) {- if (!normalized_progress.has_value())- return;- if (AK::abs(*m_progress - *normalized_progress) < 0.005)- return;+ void set_progress(bool downloading, Optional<double> progress)+ {+ if (m_downloading == downloading && m_progress == progress)+ return;+ // The ring fades in as downloads start, and out as they end, showing how far they had got.+ if (m_downloading != downloading) {+ m_ring_fade.stop();+ if (!SystemAppearance::prefers_reduced_motion() && isVisible()) {+ m_ring_fade.setStartValue(downloading ? 0.0 : 1.0);+ m_ring_fade.setEndValue(downloading ? 1.0 : 0.0);+ m_ring_fade.start();+ }}-- m_progress = AK::move(normalized_progress);+ if (m_downloading && !downloading)+ m_progress_at_end = m_shown_progress;+ // The ring glides to each new amount rather than jumping to it.+ m_progress_animation.stop();+ if (progress.has_value() && downloading) {+ if (!m_downloading || !m_progress.has_value() || SystemAppearance::prefers_reduced_motion()) {+ m_shown_progress = *progress;+ } else {+ m_progress_animation.setStartValue(m_shown_progress);+ m_progress_animation.setEndValue(*progress);+ m_progress_animation.start();+ }+ }+ m_downloading = downloading;+ m_progress = progress;+ auto should_turn = downloading && !progress.has_value() && isVisible();+ if (should_turn && m_ring_animation.state() != QAbstractAnimation::Running)+ m_ring_animation.start();+ else if (!should_turn)+ m_ring_animation.stop();update();}- void set_progress_icon(QIcon icon)+ void set_needs_attention(bool needs_attention){- m_progress_icon = icon;+ if (m_needs_attention == needs_attention)+ return;+ m_needs_attention = needs_attention;update();}-protected:+private:virtual void paintEvent(QPaintEvent* event) override{ToolbarButton::paintEvent(event);- if (!m_progress.has_value())- return;-- auto progress = *m_progress;- if (progress < 0.0)- progress = 0.0;- if (progress > 1.0)- progress = 1.0;-- auto const icon_size = this->iconSize();- auto icon_rect = QRectF {- (static_cast<qreal>(width()) - icon_size.width()) / 2.0,- (static_cast<qreal>(height()) - icon_size.height()) / 2.0,- static_cast<qreal>(icon_size.width()),- static_cast<qreal>(icon_size.height())- };- auto fill_rect = QRectF {- icon_rect.left(),- icon_rect.top(),- icon_rect.width(),- icon_rect.height() * progress- };-QPainter painter(this);- painter.setClipRect(fill_rect);- auto pixmap = m_progress_icon.pixmap(icon_size, devicePixelRatioF(), isEnabled() ? QIcon::Normal : QIcon::Disabled);- painter.drawPixmap(icon_rect.toRect(), pixmap);+ painter.setRenderHint(QPainter::Antialiasing, true);+ auto palette = Theme::chrome_palette(*this);+ auto center = QRectF(rect()).center();+ auto ring_is_fading = m_ring_fade.state() == QAbstractAnimation::Running;+ if (m_downloading || ring_is_fading) {+ painter.save();+ if (ring_is_fading)+ painter.setOpacity(m_ring_fade.currentValue().toReal());+ auto progress = m_downloading ? (m_progress.has_value() ? Optional<double> { m_shown_progress } : Optional<double> {}) : m_progress_at_end;+ if (progress.has_value())+ ChromeStyle::paint_progress_ring(painter, palette, center, *progress);+ else+ ChromeStyle::paint_loading_ring(painter, palette, center);+ painter.restore();+ }+ if (m_needs_attention) {+ QPointF dot_center { width() - 7.0, 6.0 };+ painter.setPen(Qt::NoPen);+ painter.setBrush(Theme::chrome(palette).toolbar);+ painter.drawEllipse(dot_center, 5.5, 5.5);+ painter.setBrush(Theme::chrome(palette).warning);+ painter.drawEllipse(dot_center, 3.5, 3.5);+ }}-private:+ static constexpr int RING_FADE_DURATION_MS = 200;+ static constexpr int PROGRESS_GLIDE_DURATION_MS = 300;++ bool m_downloading { false };Optional<double> m_progress;- QIcon m_progress_icon;+ Optional<double> m_progress_at_end;+ double m_shown_progress { 0 };+ QVariantAnimation m_progress_animation;+ bool m_needs_attention { false };+ QVariantAnimation m_ring_animation;+ QVariantAnimation m_ring_fade;};-static constexpr int TOOLBAR_BUTTON_SIZE = 34;-template<typename ButtonType = ToolbarButton>static ButtonType* create_toolbar_button(QWidget& parent, QAction& action){@@ -328,8 +506,10 @@ static ButtonType* create_toolbar_button(QWidget& parent, QAction& action)button->setDefaultAction(&action);button->setAutoRaise(true);button->setFocusPolicy(Qt::NoFocus);- button->setIconSize({ 20, 20 });- button->setFixedSize(TOOLBAR_BUTTON_SIZE, TOOLBAR_BUTTON_SIZE);+ button->setIconSize({ TOOLBAR_ICON_SIZE, TOOLBAR_ICON_SIZE });+ button->setFixedSize(TOOLBAR_BUTTON_SIZE);+ // NB: The platform style pads tool buttons for its own frame, which would space them further apart than the design.+ button->setAttribute(Qt::WA_LayoutUsesWidgetRect);// FIXME: In Menu.cpp, we set the initial visibility of the action before we've associated it with this QToolButton.// It would be nicer if we didn't have to do this here.@@ -351,6 +531,9 @@ QToolButton* Tab::create_navigation_history_toolbar_button(QWidget& parent, QAct});button->setMenu(menu);button->setPopupMode(QToolButton::DelayedPopup);+ QObject::connect(button, &QToolButton::clicked, button, [button, direction] {+ button->play_icon_motion(direction < 0 ? ToolbarButton::IconMotion::NudgeLeft : ToolbarButton::IconMotion::NudgeRight);+ });button->setContextMenuPolicy(Qt::CustomContextMenu);QObject::connect(button, &QToolButton::customContextMenuRequested, button, [button, menu, &view, direction](QPoint const&) {populate_session_history_traversal_menu(*menu, view, direction);@@ -361,19 +544,28 @@ QToolButton* Tab::create_navigation_history_toolbar_button(QWidget& parent, QAct}static constexpr int TAB_FAVICON_SIZE = 16;-static constexpr int TOOLBAR_HORIZONTAL_MARGIN = 12;-#ifdef AK_OS_MACOS-static constexpr int WEB_VIEW_INSET = 5;-// The sidebar has its own padding, so a narrower frame of the toolbar's color sets the page apart from it.-static constexpr int WEB_VIEW_SIDEBAR_INSET = 4;-#endif-static constexpr int TOOLBAR_VERTICAL_MARGIN = 2;-// NB: The location field gets a point more room below it than above it, where the page begins.-static constexpr int TOOLBAR_BOTTOM_MARGIN = TOOLBAR_VERTICAL_MARGIN + 1;+static constexpr int TOOLBAR_HORIZONTAL_MARGIN = 8;+// The buttons in the toolbar sit close together, while the address field keeps a wider gap on either side.+static constexpr int TOOLBAR_SPACING = 2;+// The separator after the collapsed sidebar's buttons keeps a little more room on either side.+static constexpr int SIDEBAR_SLOT_SEPARATOR_MARGIN = 6;+// NB: With the toolbar's spacing, the address field starts 8 px after the reload button.+static constexpr int TOOLBAR_LOCATION_EDIT_MARGIN = 6;+// The address field's focus ring reaches 3 px past its edge. With the toolbar's spacing, this room also puts the+// downloads button 6 px after the field.+static constexpr int TOOLBAR_LOCATION_FOCUS_RING_ROOM = 4;static constexpr int TOOLBAR_WINDOW_CONTROLS_RIGHT_MARGIN = 4;++// NB: Unless window controls follow it, the address field ends the toolbar, and the room for its focus ring takes the+// place of some of the toolbar's margin.+static constexpr int toolbar_right_margin(bool has_custom_window_controls)+{+ return has_custom_window_controls ? TOOLBAR_WINDOW_CONTROLS_RIGHT_MARGIN : TOOLBAR_HORIZONTAL_MARGIN - TOOLBAR_LOCATION_FOCUS_RING_ROOM;+}static constexpr int DOWNLOADS_POPOVER_WIDTH = 380;static constexpr int DOWNLOADS_POPOVER_MAX_HEIGHT = 360;static constexpr int PRIVATE_SESSION_POPOVER_WIDTH = 320;+static constexpr int PERMISSION_POPOVER_WIDTH = 352;class ElidedLabel final : public QLabel {public:@@ -412,6 +604,44 @@ private:Qt::TextElideMode m_elide_mode { Qt::ElideRight };};+// A small page with the file's extension on it.+class DownloadFileIcon final : public QWidget {+public:+ AK_ALLOC_WITH_KMALLOC;++ explicit DownloadFileIcon(QWidget* parent)+ : QWidget(parent)+ {+ setFixedSize(28, 34);+ }++ void set_extension(QString extension)+ {+ m_extension = extension.toUpper().left(4);+ update();+ }++private:+ virtual void paintEvent(QPaintEvent*) override+ {+ QPainter painter(this);+ painter.setRenderHint(QPainter::Antialiasing, true);+ auto const& panel = Theme::panel();+ painter.setBrush(panel.page);+ painter.setPen(QPen(panel.separator, 1));+ painter.drawRoundedRect(QRectF(rect()).adjusted(0.5, 0.5, -0.5, -0.5), 4, 4);++ auto font = this->font();+ font.setPixelSize(8);+ font.setWeight(QFont::Bold);+ painter.setFont(font);+ painter.setPen(panel.muted);+ painter.drawText(rect().adjusted(0, 0, 0, -4), Qt::AlignHCenter | Qt::AlignBottom, m_extension);+ }++ QString m_extension;+};+class DownloadRow final : public QFrame {public:AK_ALLOC_WITH_KMALLOC;@@ -424,48 +654,74 @@ public:setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);auto* row_layout = new QHBoxLayout(this);- row_layout->setContentsMargins(10, 8, 10, 8);- row_layout->setSpacing(8);+ row_layout->setContentsMargins(10, 8, 6, 8);+ row_layout->setSpacing(12);++ m_file_icon = new DownloadFileIcon(this);+ row_layout->addWidget(m_file_icon, 0, Qt::AlignVCenter);auto* details_layout = new QVBoxLayout;details_layout->setContentsMargins(0, 0, 0, 0);- details_layout->setSpacing(4);+ details_layout->setSpacing(5);- m_file_name_label = new ElidedLabel({}, Qt::ElideRight, this);+ m_file_name_label = new ElidedLabel({}, Qt::ElideMiddle, this);m_file_name_label->setObjectName("LadybirdDownloadFileName");details_layout->addWidget(m_file_name_label);- m_status_label = new ElidedLabel({}, Qt::ElideRight, this);- m_status_label->setObjectName("LadybirdDownloadStatus");- details_layout->addWidget(m_status_label);-m_progress_bar = new QProgressBar(this);m_progress_bar->setObjectName("LadybirdDownloadProgress");m_progress_bar->setRange(0, 1000);m_progress_bar->setTextVisible(false);details_layout->addWidget(m_progress_bar);+ m_status_label = new ElidedLabel({}, Qt::ElideRight, this);+ m_status_label->setObjectName("LadybirdDownloadStatus");+ details_layout->addWidget(m_status_label);+row_layout->addLayout(details_layout, 1);- m_pause_button = new QPushButton("Pause", this);- m_pause_button->setFocusPolicy(Qt::NoFocus);- QObject::connect(m_pause_button, &QPushButton::clicked, this, [this] {- if (m_is_paused) {- if (on_resume_download)- on_resume_download(m_download_id);- } else if (on_pause_download) {- on_pause_download(m_download_id);+ auto make_action = [&](ChromeIcon icon, QString const& tooltip, auto callback) {+ auto* button = new ToolbarButton(this);+ button->setObjectName("LadybirdDownloadAction");+ button->setAutoRaise(true);+ button->setIcon(create_chrome_icon(icon, Theme::panel().body));+ button->setIconSize({ 16, 16 });+ button->setFixedSize(28, 28);+ button->setToolTip(tooltip);+ button->setAccessibleName(tooltip);+ button->setFocusPolicy(Qt::TabFocus);+ QObject::connect(button, &QToolButton::clicked, this, [this, callback] { callback(*this); });+ row_layout->addWidget(button, 0, Qt::AlignVCenter);+ return button;+ };++ m_pause_button = make_action(ChromeIcon::Pause, "Pause", [](DownloadRow& row) {+ if (row.m_is_paused) {+ if (row.on_resume_download)+ row.on_resume_download(row.m_download_id);+ } else if (row.on_pause_download) {+ row.on_pause_download(row.m_download_id);}});- row_layout->addWidget(m_pause_button, 0, Qt::AlignTop);-- m_cancel_button = new QPushButton("Cancel", this);- m_cancel_button->setFocusPolicy(Qt::NoFocus);- QObject::connect(m_cancel_button, &QPushButton::clicked, this, [this] {- if (on_cancel_download)- on_cancel_download(m_download_id);+ m_cancel_button = make_action(ChromeIcon::Close, "Cancel", [](DownloadRow& row) {+ if (row.on_cancel_download)+ row.on_cancel_download(row.m_download_id);+ });+ m_retry_button = make_action(ChromeIcon::Reload, "Retry", [](DownloadRow& row) {+ if (row.on_resume_download)+ row.on_resume_download(row.m_download_id);+ });+#if defined(AK_OS_MACOS)+ auto show_in_folder_name = "Show in Finder";+#elif defined(AK_OS_WINDOWS)+ auto show_in_folder_name = "Show in Explorer";+#else+ auto show_in_folder_name = "Show in Files";+#endif+ m_show_in_folder_button = make_action(ChromeIcon::Folder, show_in_folder_name, [](DownloadRow& row) {+ if (row.on_show_in_folder)+ row.on_show_in_folder(row.m_download_id);});- row_layout->addWidget(m_cancel_button, 0, Qt::AlignTop);(void)update_download(download);}@@ -476,40 +732,44 @@ public:{VERIFY(download.id == m_download_id);- m_file_name_label->setText(qstring_from_ak_string(download.destination.basename()));+ auto basename = qstring_from_ak_string(download.destination.basename());+ m_file_name_label->setText(basename);m_file_name_label->setToolTip(qstring_from_ak_string(download.destination.string()));+ m_file_icon->set_extension(qstring_from_ak_string(download.destination.extension()));auto status_text = qstring_from_ak_string(WebView::download_status_text(download));m_status_label->setText(status_text);m_status_label->setToolTip(status_text);+ auto failed = download.status == WebView::FileDownloader::DownloadStatus::Failed;+ if (m_status_label->property("failed").toBool() != failed) {+ m_status_label->setProperty("failed", failed);+ m_status_label->style()->unpolish(m_status_label);+ m_status_label->style()->polish(m_status_label);+ }bool geometry_changed = false;+ auto set_visible = [&](QWidget& widget, bool visible) {+ if (widget.isHidden() == visible) {+ widget.setVisible(visible);+ geometry_changed = true;+ }+ };++ auto is_active = WebView::FileDownloader::status_is_active(download.status);auto progress = download.progress();- auto show_progress = WebView::FileDownloader::status_is_active(download.status) && progress.has_value();- auto progress_bar_is_visible = !m_progress_bar->isHidden();- if (progress_bar_is_visible != show_progress) {- m_progress_bar->setVisible(show_progress);- geometry_changed = true;- }+ set_visible(*m_progress_bar, is_active && progress.has_value());if (progress.has_value())m_progress_bar->setValue(static_cast<int>(*progress * 1000.0));m_is_paused = download.status == WebView::FileDownloader::DownloadStatus::Paused;- m_pause_button->setText(m_is_paused ? "Resume" : "Pause");-- auto should_show_pause = download.can_resume && WebView::FileDownloader::status_is_active(download.status);- auto pause_button_is_visible = !m_pause_button->isHidden();- if (pause_button_is_visible != should_show_pause) {- m_pause_button->setVisible(should_show_pause);- geometry_changed = true;- }+ m_pause_button->setIcon(create_chrome_icon(m_is_paused ? ChromeIcon::Download : ChromeIcon::Pause, Theme::chrome_palette(*this)));+ m_pause_button->setToolTip(m_is_paused ? "Resume" : "Pause");+ m_pause_button->setAccessibleName(m_pause_button->toolTip());- auto should_show_cancel = WebView::FileDownloader::status_is_active(download.status);- auto cancel_button_is_visible = !m_cancel_button->isHidden();- if (cancel_button_is_visible != should_show_cancel) {- m_cancel_button->setVisible(should_show_cancel);- geometry_changed = true;- }+ set_visible(*m_pause_button, download.can_resume && is_active);+ set_visible(*m_cancel_button, is_active);+ set_visible(*m_retry_button, failed && download.can_resume);+ set_visible(*m_show_in_folder_button, download.status == WebView::FileDownloader::DownloadStatus::Completed);return geometry_changed;}@@ -517,15 +777,89 @@ public:Function<void(u64)> on_cancel_download;Function<void(u64)> on_pause_download;Function<void(u64)> on_resume_download;+ Function<void(u64)> on_show_in_folder;private:u64 m_download_id { 0 };bool m_is_paused { false };+ DownloadFileIcon* m_file_icon { nullptr };ElidedLabel* m_file_name_label { nullptr };ElidedLabel* m_status_label { nullptr };QProgressBar* m_progress_bar { nullptr };- QPushButton* m_pause_button { nullptr };- QPushButton* m_cancel_button { nullptr };+ QToolButton* m_pause_button { nullptr };+ QToolButton* m_cancel_button { nullptr };+ QToolButton* m_retry_button { nullptr };+ QToolButton* m_show_in_folder_button { nullptr };+};++// The page's zoom, with buttons to change it and a way back to the default.+class ZoomPopover final : public Popover {+public:+ AK_ALLOC_WITH_KMALLOC;++ explicit ZoomPopover(QWidget* parent)+ : Popover(parent)+ {+ setAccessibleName("Page zoom");+ card().setObjectName("LadybirdZoomPopover");+ card().setFixedWidth(232);++ auto* layout = new QVBoxLayout(&card());+ layout->setContentsMargins(14, 14, 14, 14);+ layout->setSpacing(10);++ auto* controls = new QHBoxLayout;+ controls->setSpacing(6);+ auto make_button = [&](ChromeIcon icon, QString const& name, auto callback) {+ auto* button = new QPushButton(&card());+ button->setObjectName("LadybirdZoomButton");+ button->setIcon(create_chrome_icon(icon, Theme::panel().body));+ button->setIconSize({ 16, 16 });+ button->setFixedSize(30, 28);+ button->setAccessibleName(name);+ button->setToolTip(name);+ QObject::connect(button, &QPushButton::clicked, this, [this, callback] {+ callback(*this);+ update_level();+ });+ return button;+ };+ controls->addWidget(make_button(ChromeIcon::ZoomOut, "Zoom out", [](ZoomPopover& popover) { if (popover.on_zoom_out) popover.on_zoom_out(); }));+ m_level = new QLabel(&card());+ m_level->setObjectName("LadybirdZoomLevel");+ m_level->setAlignment(Qt::AlignCenter);+ controls->addWidget(m_level, 1);+ controls->addWidget(make_button(ChromeIcon::NewTab, "Zoom in", [](ZoomPopover& popover) { if (popover.on_zoom_in) popover.on_zoom_in(); }));+ layout->addLayout(controls);++ auto* footer = new QHBoxLayout;+ footer->addStretch(1);+ auto* reset = new QPushButton("Reset", &card());+ reset->setObjectName("LadybirdPopoverLink");+ reset->setCursor(Qt::PointingHandCursor);+ QObject::connect(reset, &QPushButton::clicked, this, [this] {+ if (on_reset)+ on_reset();+ update_level();+ });+ footer->addWidget(reset);+ footer->addStretch(1);+ layout->addLayout(footer);+ }++ void update_level()+ {+ if (current_level)+ m_level->setText(qformatted("{}%", round_to<int>(current_level() * 100)));+ }++ Function<void()> on_zoom_in;+ Function<void()> on_zoom_out;+ Function<void()> on_reset;+ Function<double()> current_level;++private:+ QLabel* m_level { nullptr };};class DownloadsPopover final : public Popover {@@ -539,12 +873,23 @@ public:card().setFixedWidth(DOWNLOADS_POPOVER_WIDTH);auto* layout = new QVBoxLayout(&card());- layout->setContentsMargins(12, 10, 12, 12);- layout->setSpacing(8);+ layout->setContentsMargins(6, 12, 6, 6);+ layout->setSpacing(0);+ auto* header = new QHBoxLayout;+ header->setContentsMargins(10, 0, 4, 6);auto* title = new QLabel("Downloads", this);title->setObjectName("LadybirdDownloadsPopoverTitle");- layout->addWidget(title);+ header->addWidget(title, 1);+ auto* clear_button = new QPushButton("Clear finished", this);+ clear_button->setObjectName("LadybirdPopoverLink");+ clear_button->setCursor(Qt::PointingHandCursor);+ QObject::connect(clear_button, &QPushButton::clicked, this, [this] {+ if (on_clear_finished)+ on_clear_finished();+ });+ header->addWidget(clear_button);+ layout->addLayout(header);m_empty_label = new QLabel("No downloads", this);m_empty_label->setObjectName("LadybirdDownloadsEmpty");@@ -564,11 +909,20 @@ public:m_rows_widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);m_rows_layout = new QVBoxLayout(m_rows_widget);m_rows_layout->setContentsMargins(0, 0, 0, 0);- m_rows_layout->setSpacing(6);+ m_rows_layout->setSpacing(0);m_scroll_area->setWidget(m_rows_widget);layout->addWidget(m_scroll_area);- auto* show_all_button = new QPushButton("Show All Downloads", this);+ auto* separator = new QFrame(this);+ separator->setObjectName("LadybirdPopoverSeparator");+ separator->setFixedHeight(1);+ auto* separator_row = new QHBoxLayout;+ separator_row->setContentsMargins(10, 4, 10, 4);+ separator_row->addWidget(separator);+ layout->addLayout(separator_row);++ auto* show_all_button = new QPushButton("Show all downloads", this);+ show_all_button->setObjectName("LadybirdPopoverRow");QObject::connect(show_all_button, &QPushButton::clicked, this, [this] {if (on_open_all_downloads)on_open_all_downloads();@@ -615,6 +969,8 @@ public:Function<void(u64)> on_cancel_download;Function<void(u64)> on_pause_download;Function<void(u64)> on_resume_download;+ Function<void(u64)> on_show_in_folder;+ Function<void()> on_clear_finished;Function<void()> on_open_all_downloads;private:@@ -650,6 +1006,10 @@ private:if (on_resume_download)on_resume_download(id);};+ row->on_show_in_folder = [this](u64 id) {+ if (on_show_in_folder)+ on_show_in_folder(id);+ };m_rows_layout->addWidget(row);m_download_rows.append(row);}@@ -724,7 +1084,9 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)m_view->set_window_position({ m_window->x(), m_window->y() });m_view->set_window_size({ m_window->width(), m_window->height() });m_javascript_dialog = new JavaScriptDialog(m_view);+ m_javascript_dialog->on_page_dim_change = [this](qreal dim) { m_view->set_page_dim(dim); };m_find_in_page = new FindInPageWidget(this, m_view);+ m_view->add_floating_surface(*m_find_in_page);m_find_in_page->setVisible(false);m_toolbar = new QWidget(this);@@ -734,15 +1096,22 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)auto* toolbar_container_layout = new QVBoxLayout(m_toolbar_container);toolbar_container_layout->setSpacing(0);- toolbar_container_layout->setContentsMargins(0, 0, 0, 0);+ // NB: The container draws the line under the toolbar along its bottom edge, below the toolbar's full height.+ toolbar_container_layout->setContentsMargins(0, 0, 0, 1);auto* toolbar_layout = new QHBoxLayout(m_toolbar);- toolbar_layout->setSpacing(6);- toolbar_layout->setContentsMargins(TOOLBAR_HORIZONTAL_MARGIN, TOOLBAR_VERTICAL_MARGIN, TOOLBAR_HORIZONTAL_MARGIN, TOOLBAR_BOTTOM_MARGIN);+ toolbar_layout->setSpacing(TOOLBAR_SPACING);+ toolbar_layout->setContentsMargins(TOOLBAR_HORIZONTAL_MARGIN, 0, toolbar_right_margin(false), 0);m_location_edit = new LocationEdit(this, m_window->is_private());- m_loading_animation_timer = new QTimer(this);- m_loading_animation_timer->setInterval(80);++ m_downloads_button = new DownloadsButton(m_toolbar);+ m_downloads_button->setIcon(create_chrome_icon(ChromeIcon::Download, Theme::chrome_palette(*this)));+ QObject::connect(m_downloads_button, &QToolButton::clicked, this, [this] {+ // NB: The button only stays checked while the list is open, which showing it sees to.+ m_downloads_button->setChecked(m_downloads_popover && m_downloads_popover->isVisible());+ show_downloads_popover();+ });m_bookmarks_bar = new BookmarksBar(this);m_bookmarks_bar_container = new QWidget(this);@@ -791,26 +1160,13 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)QObject::connect(m_hover_label, &HyperlinkLabel::mouse_entered, [this] {update_hover_label();});- QObject::connect(m_loading_animation_timer, &QTimer::timeout, this, [this] {- m_loading_animation_frame = (m_loading_animation_frame + 1) % 12;- update_tab_icon();- });auto* focus_location_editor_action = new QAction("Edit Location", this);focus_location_editor_action->setShortcuts({ QKeySequence("Ctrl+L"), QKeySequence("Alt+D") });addAction(focus_location_editor_action);toolbar_container_layout->addWidget(m_toolbar);- toolbar_container_layout->addWidget(m_bookmarks_bar_container);-#ifdef AK_OS_MACOS- m_view_layout = new QHBoxLayout;- m_view_layout->addWidget(m_view);- update_web_view_frame(m_web_view_chrome_visible, m_web_view_sidebar_position);- tab_layout->addLayout(m_view_layout);-#elsetab_layout->addWidget(m_view);-#endif- tab_layout->addWidget(m_find_in_page);update_bookmarks_bar_visibility();m_navigate_back_action = create_application_action(*this, view().navigate_back_action());@@ -825,51 +1181,24 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)});m_open_downloads_page_action = create_application_action(*this, application.open_downloads_page_action());- m_downloads_button = new DownloadsButton(m_toolbar);- m_downloads_button->setText("Downloads");- m_downloads_button->setAutoRaise(true);- m_downloads_button->setFocusPolicy(Qt::NoFocus);- m_downloads_button->setIconSize({ 20, 20 });- m_downloads_button->setFixedSize(TOOLBAR_BUTTON_SIZE, TOOLBAR_BUTTON_SIZE);- m_downloads_button->setVisible(m_open_downloads_page_action->isVisible());- QObject::connect(m_downloads_button, &QToolButton::clicked, this, [this] {- show_downloads_popover();- });-- m_private_badge = new QPushButton("Private", m_toolbar);- m_private_badge->setObjectName("LadybirdPrivateBadge");- m_private_badge->setFixedHeight(22);- m_private_badge->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);- m_private_badge->setFocusPolicy(Qt::NoFocus);- m_private_badge->setToolTip("Close all private windows and start a fresh private browsing session");- m_private_badge->setVisible(m_window->is_private() == WebView::IsPrivate::Yes);- QObject::connect(m_private_badge, &QPushButton::clicked, this, [this] {- show_private_session_popover();+ // NB: A page can block many requests in a burst while it loads, so the open popover catches up with them at most+ // ten times a second rather than for each one.+ m_content_blocking_update_timer = new QTimer(this);+ m_content_blocking_update_timer->setSingleShot(true);+ m_content_blocking_update_timer->setInterval(100);+ QObject::connect(m_content_blocking_update_timer, &QTimer::timeout, this, [this] {+ if (m_site_settings_popover && m_site_settings_popover->isVisible())+ m_site_settings_popover->set_content_blocking(view().content_blocking_snapshot());});-- m_content_blocking_button = new ContentBlockingButton(m_toolbar);- m_content_blocking_button->setToolTip("Ad Block");- QObject::connect(m_content_blocking_button, &QToolButton::clicked, this, [this] { show_content_blocking_popover(); });- view().on_content_blocking_change = [this](auto const& snapshot) { update_content_blocking_controls(snapshot); };- update_content_blocking_controls(view().content_blocking_snapshot());- content_blocker_count_visibility_changed();-- m_hamburger_button = new HamburgerButton(m_toolbar);- m_hamburger_button->setObjectName("LadybirdHamburgerButton");- m_hamburger_button->setText("Show &Menu");- m_hamburger_button->setToolTip("Show Menu");- m_hamburger_button->setIcon(create_chrome_icon(ChromeIcon::Menu, palette()));- m_hamburger_button->setIconSize({ 20, 20 });- m_hamburger_button->setFixedSize(TOOLBAR_BUTTON_SIZE, TOOLBAR_BUTTON_SIZE);- m_hamburger_button->setAutoRaise(true);- m_hamburger_button->setFocusPolicy(Qt::NoFocus);- m_hamburger_button->setPopupMode(QToolButton::InstantPopup);- m_hamburger_button->setMenu(&m_window->hamburger_menu());- connect_hamburger_menu();+ view().on_content_blocking_change = [this](auto const&) {+ if (m_site_settings_popover && m_site_settings_popover->isVisible() && !m_content_blocking_update_timer->isActive())+ m_content_blocking_update_timer->start();+ };m_toolbar_window_controls_separator = new QWidget(m_toolbar);m_toolbar_window_controls_separator->setObjectName("LadybirdToolbarWindowControlsSeparator");m_toolbar_window_controls_separator->setFixedSize(1, 22);+ m_toolbar_window_controls_separator->setAttribute(Qt::WA_TransparentForMouseEvents);if constexpr (use_native_macos_window_controls()) {auto const native_controls_width = NATIVE_MACOS_WINDOW_CONTROLS_WIDTH + NATIVE_MACOS_WINDOW_CONTROLS_GAP;@@ -906,7 +1235,7 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)auto* navigation_button_cluster = new QWidget(m_toolbar);navigation_button_cluster->setProperty(WINDOW_DRAG_REGION_PROPERTY, true);auto* navigation_button_layout = new QHBoxLayout(navigation_button_cluster);- navigation_button_layout->setSpacing(2);+ navigation_button_layout->setSpacing(TOOLBAR_SPACING);navigation_button_layout->setContentsMargins(0, 0, 0, 0);navigation_button_layout->addWidget(create_navigation_history_toolbar_button(*navigation_button_cluster, *m_navigate_back_action, -1));@@ -919,9 +1248,14 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)location_edit_container->setProperty(WINDOW_DRAG_REGION_PROPERTY, true);auto* location_edit_layout = new QHBoxLayout(location_edit_container);location_edit_layout->setSpacing(0);- location_edit_layout->setContentsMargins(0, 0, 0, 0);-- m_location_edit->set_trailing_action(create_application_action(*m_location_edit, view().toggle_bookmark_action()));+ // NB: The field reaches the end of the toolbar, leaving room for its focus ring.+ location_edit_layout->setContentsMargins(TOOLBAR_LOCATION_EDIT_MARGIN, 0, TOOLBAR_LOCATION_FOCUS_RING_ROOM, 0);++ // The star bookmarks the page, then shows the bookmark to name it or file it, rather than toggling it.+ auto* bookmark_action = create_application_action(*m_location_edit, view().toggle_bookmark_action());+ QObject::disconnect(bookmark_action, &QAction::triggered, nullptr, nullptr);+ QObject::connect(bookmark_action, &QAction::triggered, this, [this] { show_bookmark_popover(); });+ m_location_edit->set_trailing_action(bookmark_action);m_location_edit->set_zoom_action(create_application_action(*m_location_edit, view().reset_zoom_action(), IncludeActionIcon::No));location_edit_layout->addWidget(m_location_edit);@@ -935,13 +1269,30 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)if constexpr (use_native_macos_window_controls())toolbar_layout->addWidget(m_toolbar_window_controls, 0, Qt::AlignVCenter);+ m_toolbar_sidebar_slot = new QWidget(m_toolbar);+ m_toolbar_sidebar_slot->setProperty(WINDOW_DRAG_REGION_PROPERTY, true);+ auto* sidebar_slot_layout = new QHBoxLayout(m_toolbar_sidebar_slot);+ // The Ladybird button keeps as clear of the traffic lights as on the tab strip.+ auto sidebar_slot_leading_margin = 0;+ if constexpr (use_native_macos_window_controls())+ sidebar_slot_leading_margin = NATIVE_MACOS_WINDOW_CONTROLS_INSET + NATIVE_MACOS_WINDOW_CONTROLS_WIDTH + LADYBIRD_BUTTON_TRAFFIC_LIGHTS_GAP - (TOOLBAR_HORIZONTAL_MARGIN + NATIVE_MACOS_WINDOW_CONTROLS_WIDTH + NATIVE_MACOS_WINDOW_CONTROLS_GAP + TOOLBAR_SPACING);+ sidebar_slot_layout->setContentsMargins(sidebar_slot_leading_margin, 0, 0, 0);+ sidebar_slot_layout->setSpacing(TOOLBAR_SPACING);+ // NB: The separator sits where the open sidebar's edge does, so the toolbar's contents keep their place as it toggles.+ sidebar_slot_layout->addSpacing(SIDEBAR_SLOT_SEPARATOR_MARGIN - 1);+ auto* sidebar_slot_separator = new QWidget(m_toolbar_sidebar_slot);+ sidebar_slot_separator->setObjectName("LadybirdToolbarWindowControlsSeparator");+ sidebar_slot_separator->setFixedSize(1, 16);+ sidebar_slot_separator->setAttribute(Qt::WA_TransparentForMouseEvents);+ sidebar_slot_layout->addWidget(sidebar_slot_separator, 0, Qt::AlignVCenter);+ sidebar_slot_layout->addSpacing(SIDEBAR_SLOT_SEPARATOR_MARGIN);+ m_toolbar_sidebar_slot->hide();+ toolbar_layout->addWidget(m_toolbar_sidebar_slot, 0, Qt::AlignVCenter);+toolbar_layout->addWidget(navigation_button_cluster, 0, Qt::AlignVCenter);toolbar_layout->addWidget(location_edit_container, 1);- toolbar_layout->addWidget(m_performance_monitor, 0, Qt::AlignVCenter);toolbar_layout->addWidget(m_downloads_button, 0, Qt::AlignVCenter);- toolbar_layout->addWidget(m_private_badge, 0, Qt::AlignVCenter);- toolbar_layout->addWidget(m_content_blocking_button, 0, Qt::AlignVCenter);- toolbar_layout->addWidget(m_hamburger_button, 0, Qt::AlignVCenter);+ toolbar_layout->addWidget(m_performance_monitor, 0, Qt::AlignVCenter);if constexpr (!use_native_macos_window_controls()) {toolbar_layout->addWidget(m_toolbar_window_controls_separator, 0, Qt::AlignVCenter);@@ -952,6 +1303,17 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)update_downloads_button();set_toolbar_window_controls_visible(false);+ m_location_edit->on_site_settings_requested = [this] {+ show_site_settings_popover();+ };+ m_location_edit->on_zoom_requested = [this] {+ show_zoom_popover();+ };++ QObject::connect(m_view, &WebContentView::crash_overlay_changed, this, [this] {+ update_tab_icon();+ });+view().on_activate_tab = [this] {m_window->activate_tab(tab_index());};@@ -968,6 +1330,10 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)view().on_request_web_compat_report_review = [this](WebCompatReportCapture capture) {auto& tab = m_window->new_tab_from_url(URL::about_blank(), Web::HTML::ActivateTab::Yes, BrowserWindow::TabLocation::after_tab(*this));+ tab.view().on_close_web_compat_report_tab = [&tab] {+ tab.m_tab_to_activate_on_close = nullptr;+ tab.view().on_close();+ };tab.view().review_web_compat_report(AK::move(capture));tab.enter_report_review(this, tr("Report Website Issue"));};@@ -996,14 +1362,10 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)};view().on_loading_state_change = [this](bool is_loading) {- if (!is_loading)- m_content_blocking_popover_reload_site.clear();set_loading(is_loading);};view().on_load_start = [this] {m_window->on_tab_load_start(*this);- if (m_content_blocking_popover && !m_content_blocking_popover_reload_site.has_value())- m_content_blocking_popover->close();};set_loading(view().is_loading());@@ -1012,20 +1374,16 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)};view().on_top_level_navigation_commit = [this] {- if (m_content_blocking_popover) {- auto snapshot = view().content_blocking_snapshot();- if (!m_content_blocking_popover_reload_site.has_value() || snapshot.site != m_content_blocking_popover_reload_site) {- m_content_blocking_popover->close();- } else {- m_content_blocking_popover_reload_site.clear();- update_content_blocking_controls(snapshot);- }- }+ m_is_waiting_for_response = false;m_suppress_javascript_dialogs_until_navigation = false;+ m_javascript_dialogs_shown_by_document = 0;+ m_javascript_dialogs_blocked_for_document = false;};view().on_browser_history_traversal_complete = [this] {m_suppress_javascript_dialogs_until_navigation = false;+ m_javascript_dialogs_shown_by_document = 0;+ m_javascript_dialogs_blocked_for_document = false;};view().on_url_change = [this](auto const& url) {@@ -1040,15 +1398,16 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)});view().on_title_change = [this](auto const& title) {- m_title = qstring_from_utf16_string(title);+ auto new_title = qstring_from_utf16_string(title);+ if (!m_is_loading && !m_title.isEmpty() && new_title != m_title && m_window->current_tab() != this)+ m_needs_attention = true;+ m_title = AK::move(new_title);update_tab_title();};view().on_favicon_change = [this](auto const& bitmap) {if (!bitmap.has_value()) {m_favicon = {};- if (m_content_blocking_popover)- m_content_blocking_popover->set_favicon(m_favicon);update_tab_icon();return;}@@ -1061,50 +1420,57 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)return;m_favicon = favicon_with_rounded_corners(qpixmap);- if (m_content_blocking_popover)- m_content_blocking_popover->set_favicon(m_favicon);update_tab_icon();};+ // A dialog from a page says which site it comes from.auto javascript_dialog_title = [this] {auto origin = view().url().origin();if (!origin.is_opaque())- return qstring_from_ak_string(origin.serialize());- return qformatted("{}://", qstring_from_ak_string(view().url().scheme()));+ return qformatted("{} says", qstring_from_ak_string(origin.host().serialize()));+ return qformatted("{}:// says", qstring_from_ak_string(view().url().scheme()));+ };++ auto offer_to_block_further_dialogs = [this] {+ return m_javascript_dialogs_shown_by_document++ > 0 ? JavaScriptDialog::OfferToBlockFurtherDialogs::Yes : JavaScriptDialog::OfferToBlockFurtherDialogs::No;};- view().on_request_alert = [this, javascript_dialog_title](auto const& message) {- if (m_suppress_javascript_dialogs_until_navigation) {+ view().on_request_alert = [this, javascript_dialog_title, offer_to_block_further_dialogs](auto const& message) {+ if (m_suppress_javascript_dialogs_until_navigation || m_javascript_dialogs_blocked_for_document) {view().alert_closed();return;}hide_hover_label();- m_javascript_dialog->show_alert(javascript_dialog_title(), qstring_from_utf16_string(message));+ m_javascript_dialog->set_title_icon(tab_icon());+ m_javascript_dialog->show_alert(javascript_dialog_title(), qstring_from_utf16_string(message), offer_to_block_further_dialogs());};view().on_request_before_unload = [this](auto const& source, auto on_complete) {hide_hover_label();m_before_unload_completion = AK::move(on_complete);m_window->raise_for_close_prompt();+ m_javascript_dialog->set_title_icon(tab_icon());m_javascript_dialog->show_before_unload(qstring_from_ak_string(source));};- view().on_request_confirm = [this, javascript_dialog_title](auto const& message) {- if (m_suppress_javascript_dialogs_until_navigation) {+ view().on_request_confirm = [this, javascript_dialog_title, offer_to_block_further_dialogs](auto const& message) {+ if (m_suppress_javascript_dialogs_until_navigation || m_javascript_dialogs_blocked_for_document) {view().confirm_closed(false);return;}hide_hover_label();- m_javascript_dialog->show_confirm(javascript_dialog_title(), qstring_from_utf16_string(message));+ m_javascript_dialog->set_title_icon(tab_icon());+ m_javascript_dialog->show_confirm(javascript_dialog_title(), qstring_from_utf16_string(message), offer_to_block_further_dialogs());};- view().on_request_prompt = [this, javascript_dialog_title](auto const& message, auto const& default_) {- if (m_suppress_javascript_dialogs_until_navigation) {+ view().on_request_prompt = [this, javascript_dialog_title, offer_to_block_further_dialogs](auto const& message, auto const& default_) {+ if (m_suppress_javascript_dialogs_until_navigation || m_javascript_dialogs_blocked_for_document) {view().prompt_closed({});return;}hide_hover_label();- m_javascript_dialog->show_prompt(javascript_dialog_title(), qstring_from_utf16_string(message), qstring_from_utf16_string(default_));+ m_javascript_dialog->set_title_icon(tab_icon());+ m_javascript_dialog->show_prompt(javascript_dialog_title(), qstring_from_utf16_string(message), qstring_from_utf16_string(default_), offer_to_block_further_dialogs());};view().on_request_set_prompt_text = [this](auto const& message) {@@ -1112,6 +1478,8 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)};m_javascript_dialog->on_complete = [this](auto type, bool accepted, auto const& prompt_text) {+ if (m_javascript_dialog->blocks_further_dialogs())+ m_javascript_dialogs_blocked_for_document = true;switch (type) {case JavaScriptDialog::Type::Alert:view().alert_closed();@@ -1167,8 +1535,8 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)m_external_url_confirmation_dialog->close();auto pending_permission_requests = AK::move(m_pending_permission_requests);for (auto& it : pending_permission_requests) {- if (it.value.dialog)- it.value.dialog->close();+ if (it.value.popover)+ it.value.popover->close();}};@@ -1209,38 +1577,41 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)dialog->open();};+ // A site's request for a permission hangs from the site settings button, and is denied unless it is allowed.view().on_request_permission = [this](auto const& name, auto const& origin, auto on_decided) {- auto requester = origin.is_opaque() ? "this page"_string : origin.serialize();- auto question = MUST(String::formatted("Allow {} to use your {}?", requester, name));+ auto requester = origin.is_opaque() ? "This page"_string : origin.host().serialize();+ auto question = MUST(String::formatted("{} wants to use your {}", requester, name));if (auto pending = m_pending_permission_requests.get(question); pending.has_value()) {pending.value().on_decided.append(AK::move(on_decided));return;}- auto* dialog = new QMessageBox(&view());- dialog->setAttribute(Qt::WA_DeleteOnClose);- dialog->setIcon(QMessageBox::Icon::Question);- dialog->setWindowTitle("Ladybird");- dialog->setTextFormat(Qt::PlainText);- dialog->setText(qstring_from_ak_string(question));- auto* allow_button = dialog->addButton("Allow", QMessageBox::ButtonRole::AcceptRole);- auto* block_button = dialog->addButton("Block", QMessageBox::ButtonRole::RejectRole);- dialog->setDefaultButton(block_button);+ // NB: The microphone is the only feature a site asks for permission to use.+ auto icon = name == "microphone"sv ? create_chrome_icon(ChromeIcon::Microphone, Theme::panel().link) : QIcon {};+ auto* popover = new MessagePopover(this, PERMISSION_POPOVER_WIDTH, qstring_from_ak_string(question), {}, "Block", "Allow", icon);+ popover->setAttribute(Qt::WA_DeleteOnClose);+ popover->update_chrome_style(palette());- PendingPermissionRequests pending { .dialog = dialog, .on_decided = {} };+ PendingPermissionRequests pending { .popover = popover, .on_decided = {} };pending.on_decided.append(AK::move(on_decided));m_pending_permission_requests.set(question, AK::move(pending));- QObject::connect(dialog, &QDialog::finished, this, [this, dialog = QPointer<QMessageBox> { dialog }, allow_button, question](auto) {+ auto decide = [this, question](bool granted) {auto pending = m_pending_permission_requests.take(question);if (!pending.has_value())return;- auto granted = dialog && dialog->clickedButton() == allow_button;for (auto& on_decided : pending.value().on_decided)on_decided(granted);- });-- dialog->open();+ };+ popover->on_accept = [decide] { decide(true); };+ popover->on_dismiss = [decide] { decide(false); };++ auto& anchor = m_location_edit->site_settings_button();+ QWidget& anchor_or_field = anchor.isVisible() ? anchor : static_cast<QWidget&>(*m_location_edit);+ popover->adjustSize();+ move_popover_below(*popover, anchor_or_field, PopoverAlignment::Leading);+ popover->show();+ move_popover_below(*popover, anchor_or_field, PopoverAlignment::Leading);};view().on_request_accept_dialog = [this]() {@@ -1353,7 +1724,7 @@ void Tab::initialize(Optional<WebView::CanonicalTraversable&> traversable)m_find_in_page->update_result_label(current_match_index, total_match_count);};- QObject::connect(focus_location_editor_action, &QAction::triggered, this, &Tab::focus_location_editor);+ QObject::connect(focus_location_editor_action, &QAction::triggered, this, [this] { focus_location_editor(); });view().on_restore_window = [this]() {m_window->showNormal();@@ -1409,30 +1780,37 @@ void Tab::create_tab_context_menu()m_window->pin_tab(*this);});- auto* move_to_start_action = new QAction("Move to &Start", this);- QObject::connect(move_to_start_action, &QAction::triggered, this, [this]() {- m_window->move_tab(tab_index(), 0);+ auto* new_tab_to_the_right_action = new QAction("New Tab to the &Right", this);+ QObject::connect(new_tab_to_the_right_action, &QAction::triggered, this, [this]() {+ m_window->new_tab_from_url(WebView::Application::settings().new_tab_page_url(), Web::HTML::ActivateTab::Yes, BrowserWindow::TabLocation::after_tab(*this));+ });++ auto* mute_tab_action = new QAction("&Mute Tab", this);+ QObject::connect(mute_tab_action, &QAction::triggered, this, [this]() {+ if (is_loaded())+ view().toggle_page_mute_state();+ });++ auto* move_to_new_window_action = new QAction("Move to New &Window", this);+ QObject::connect(move_to_new_window_action, &QAction::triggered, this, [this]() {+ m_window->detach_tab_to_new_window(tab_index(), m_window->mapToGlobal(QPoint(m_window->width() / 4, m_window->height() / 4)));});- auto* move_to_end_action = new QAction("Move to &End", this);- QObject::connect(move_to_end_action, &QAction::triggered, this, [this]() {- m_window->move_tab(tab_index(), m_window->tab_count() - 1);+ auto* copy_link_action = new QAction("Copy &Link", this);+ QObject::connect(copy_link_action, &QAction::triggered, this, [this]() {+ QGuiApplication::clipboard()->setText(qstring_from_ak_string(url().serialize()));});auto* close_tab_action = new QAction("&Close Tab", this);+ // NB: The shortcuts belong to the application's actions. The menu only shows them.+ close_tab_action->setShortcut(QKeySequence(QKeySequence::Close));+ close_tab_action->setShortcutContext(Qt::WidgetShortcut);+ close_tab_action->setShortcutVisibleInContextMenu(true);QObject::connect(close_tab_action, &QAction::triggered, this, [this]() {request_close();});- auto* close_tabs_to_left_action = new QAction("C&lose Tabs to Left", this);- QObject::connect(close_tabs_to_left_action, &QAction::triggered, this, [this]() {- for (auto i = tab_index() - 1; i >= 0; i--) {- if (!m_window->tab_at(i)->is_pinned())- m_window->request_to_close_tab(i);- }- });-- auto* close_tabs_to_right_action = new QAction("Close Tabs to R&ight", this);+ auto* close_tabs_to_right_action = new QAction("Close Tabs to the R&ight", this);QObject::connect(close_tabs_to_right_action, &QAction::triggered, this, [this]() {// Closing the current tab selects a neighbor, which may be a tab about to close too, and selecting a tab that// hasn't loaded loads it. So, this tab, which stays open, becomes the current tab first.@@ -1458,19 +1836,28 @@ void Tab::create_tab_context_menu()});m_context_menu = new QMenu("Context menu", this);+ m_context_menu->addAction(new_tab_to_the_right_action);+ m_context_menu->addSeparator();m_context_menu->addAction(create_application_action(*this, application.reload_action(), IncludeActionIcon::No));m_context_menu->addAction(duplicate_tab_action);m_context_menu->addAction(m_pin_tab_action);+ m_context_menu->addAction(mute_tab_action);m_context_menu->addSeparator();- auto* move_tab_menu = m_context_menu->addMenu("Mo&ve Tab");- move_tab_menu->addAction(move_to_start_action);- move_tab_menu->addAction(move_to_end_action);+ m_context_menu->addAction(move_to_new_window_action);+ m_context_menu->addAction(copy_link_action);m_context_menu->addSeparator();m_context_menu->addAction(close_tab_action);- auto* close_multiple_tabs_menu = m_context_menu->addMenu("Close &Multiple Tabs");- close_multiple_tabs_menu->addAction(close_tabs_to_left_action);- close_multiple_tabs_menu->addAction(close_tabs_to_right_action);- close_multiple_tabs_menu->addAction(close_other_tabs_action);+ m_context_menu->addAction(close_other_tabs_action);+ m_context_menu->addAction(close_tabs_to_right_action);+ m_context_menu->addSeparator();+ m_context_menu->addAction(Application::the().reopen_recently_closed_tab_action());++ QObject::connect(m_context_menu, &QMenu::aboutToShow, this, [this, mute_tab_action, move_to_new_window_action]() {+ // NB: A tab that hasn't loaded has no page to mute yet.+ mute_tab_action->setEnabled(is_loaded());+ mute_tab_action->setText(is_loaded() && view().page_mute_state() == Web::HTML::MuteState::Muted ? "Un&mute Tab" : "&Mute Tab");+ move_to_new_window_action->setEnabled(m_window->tab_count() > 1);+ });}Tab::~Tab() = default;@@ -1540,7 +1927,7 @@ void Tab::clear_session_tab_id()view().clear_session_tab_id();}-void Tab::focus_location_editor()+void Tab::focus_location_editor(FocusRingTransition focus_ring_transition){if (!is_loaded())return;@@ -1549,6 +1936,8 @@ void Tab::focus_location_editor()make_appkit_window_first_responder(*m_location_edit);#endifm_location_edit->setFocus();+ if (focus_ring_transition == FocusRingTransition::Immediate)+ m_location_edit->show_focus_ring_at_once();m_location_edit->selectAll();m_location_edit->show_autocomplete();}@@ -1563,11 +1952,7 @@ void Tab::set_window(BrowserWindow& window)return;}- QObject::disconnect(&m_window->hamburger_menu(), nullptr, m_hamburger_button, nullptr);-m_window = &window;- m_hamburger_button->setMenu(&m_window->hamburger_menu());- connect_hamburger_menu();recreate_toolbar_icons();// The tab's pages hold the geometry of the window that hosted them until now.@@ -1592,30 +1977,6 @@ void Tab::set_vertical_tabs_enabled(bool enabled)m_toolbar->layout()->invalidate();}-#ifdef AK_OS_MACOS-void Tab::update_web_view_frame(bool chrome_visible, Optional<WebView::VerticalTabsPosition> sidebar_position)-{- m_web_view_chrome_visible = chrome_visible;- m_web_view_sidebar_position = sidebar_position;- update();- if (!is_loaded())- return;-- // With the browser chrome hidden, the page fills the window edge to edge.- if (!chrome_visible) {- m_view_layout->setContentsMargins(0, 0, 0, 0);- m_view->set_has_rounded_corners(false);- return;- }-- // Keep the web view's rounded corners clear of the window edges.- auto left = sidebar_position == WebView::VerticalTabsPosition::Left ? WEB_VIEW_SIDEBAR_INSET : WEB_VIEW_INSET;- auto right = sidebar_position == WebView::VerticalTabsPosition::Right ? WEB_VIEW_SIDEBAR_INSET : WEB_VIEW_INSET;- m_view_layout->setContentsMargins(left, 0, right, WEB_VIEW_INSET);- m_view->set_has_rounded_corners(true);-}-#endif-void Tab::set_toolbar_container_in_tab_layout(bool in_tab_layout){auto* tab_layout = static_cast<QBoxLayout*>(layout());@@ -1636,16 +1997,9 @@ void Tab::set_toolbar_container_in_tab_layout(bool in_tab_layout)}}-// NB: The location field gets a point more room above it below the horizontal tab strip, where the selected tab flows-// into the toolbar, and at the top of a macOS window, whose outline covers the toolbar's first point.-static int toolbar_extra_top_margin(bool window_controls_visible)+int Tab::toolbar_height(bool){- return use_native_macos_window_controls() || !window_controls_visible ? 1 : 0;-}--int Tab::toolbar_height(bool window_controls_visible)-{- return browser_chrome_layout_policy().toolbar_height + toolbar_extra_top_margin(window_controls_visible) + (TOOLBAR_BOTTOM_MARGIN - TOOLBAR_VERTICAL_MARGIN);+ return browser_chrome_layout_policy().toolbar_height;}void Tab::set_toolbar_window_controls_visible(bool visible)@@ -1660,30 +2014,47 @@ void Tab::set_toolbar_window_controls_visible(bool visible)m_toolbar_window_controls_separator->setVisible(has_custom_window_controls);m_toolbar_window_controls->setVisible(has_native_window_controls || has_custom_window_controls);m_toolbar->setFixedHeight(toolbar_height(visible));- m_toolbar->layout()->setContentsMargins(TOOLBAR_HORIZONTAL_MARGIN, TOOLBAR_VERTICAL_MARGIN + toolbar_extra_top_margin(visible), has_custom_window_controls ? TOOLBAR_WINDOW_CONTROLS_RIGHT_MARGIN : TOOLBAR_HORIZONTAL_MARGIN, TOOLBAR_BOTTOM_MARGIN);+ m_toolbar->layout()->setContentsMargins(TOOLBAR_HORIZONTAL_MARGIN, 0, toolbar_right_margin(has_custom_window_controls), 0);m_toolbar->layout()->invalidate();}+// How far the navigation buttons sit past the toolbar's leading margin beside the collapsed sidebar, where the Ladybird+// button and the sidebar's toggle come before them.+int Tab::toolbar_lead_beside_collapsed_sidebar(QWidget const& ladybird_button, QSize sidebar_toggle_size) const+{+ auto toolbar_spacing = m_toolbar->layout()->spacing();+ auto lead = 0;+ if constexpr (use_native_macos_window_controls())+ lead += m_toolbar_window_controls->width() + toolbar_spacing;++ auto slot_width = m_toolbar_sidebar_slot->layout()->sizeHint().width();+ if (ladybird_button.parentWidget() != m_toolbar_sidebar_slot)+ slot_width += ladybird_button.sizeHint().width() + sidebar_toggle_size.width() + (2 * m_toolbar_sidebar_slot->layout()->spacing());+ return lead + slot_width + toolbar_spacing;+}++// While the sidebar opens or closes, the toolbar's contents keep clear of where the collapsed sidebar's buttons sit.+void Tab::set_toolbar_leading_room(int room)+{+ auto margins = m_toolbar->layout()->contentsMargins();+ if (margins.left() == TOOLBAR_HORIZONTAL_MARGIN + room)+ return;+ margins.setLeft(TOOLBAR_HORIZONTAL_MARGIN + room);+ m_toolbar->layout()->setContentsMargins(margins);+ // NB: The toolbar moves along with the sidebar's edge at once, so its contents must too, or they lag a frame behind.+ m_toolbar->layout()->activate();+}+void Tab::update_window_control_icons(){if (!m_minimize_window_button || !m_maximize_window_button || !m_close_window_button)return;auto is_maximized = m_window->isMaximized();- m_minimize_window_button->setIcon(create_chrome_icon(ChromeIcon::WindowMinimize, palette()));- m_maximize_window_button->setIcon(create_chrome_icon(is_maximized ? ChromeIcon::WindowRestore : ChromeIcon::WindowMaximize, palette()));+ m_minimize_window_button->setIcon(create_chrome_icon(ChromeIcon::WindowMinimize, Theme::chrome_palette(*this)));+ m_maximize_window_button->setIcon(create_chrome_icon(is_maximized ? ChromeIcon::WindowRestore : ChromeIcon::WindowMaximize, Theme::chrome_palette(*this)));m_maximize_window_button->setToolTip(is_maximized ? "Restore" : "Maximize");- m_close_window_button->setIcon(create_chrome_icon(ChromeIcon::WindowClose, palette()));-}--void Tab::connect_hamburger_menu()-{- QObject::connect(&m_window->hamburger_menu(), &QMenu::aboutToShow, m_hamburger_button, [this]() {- m_hamburger_button->setDown(true);- });- QObject::connect(&m_window->hamburger_menu(), &QMenu::aboutToHide, m_hamburger_button, [this]() {- m_hamburger_button->setDown(false);- });+ m_close_window_button->setIcon(create_chrome_icon(ChromeIcon::WindowClose, Theme::chrome_palette(*this)));}void Tab::navigate(URL::URL const& url)@@ -1719,16 +2090,20 @@ void Tab::location_edit_return_pressed(String input, Optional<URL::URL> fallbackview().setFocus();}+// A tab whose page crashed shows a warning in place of its favicon.QIcon Tab::tab_icon() const{- if (m_is_loading)- return loading_spinner_icon(palette(), m_loading_animation_frame);+ if (is_loaded() && view().crash_overlay_active())+ return create_chrome_icon(ChromeIcon::Warning, Theme::chrome(*this).warning);return m_favicon;}QString Tab::title() const{auto title = m_fixed_title.value_or(m_title);+ // A blank page is what a new tab shows, so it is called a new tab.+ if (!m_fixed_title.has_value() && is_loaded() && view().url() == URL::about_blank() && (title.isEmpty() || title == QStringLiteral("about:blank")))+ title = "New Tab";if (!is_loaded() || !WebView::Application::settings().config_variable_as_bool(WebView::ConfigVariableID::ShowWebContentProcessIDInTabTitle))return title;@@ -1799,12 +2174,22 @@ void Tab::config_variable_changed(WebView::ConfigVariableID variable)update_tab_title();}-void Tab::content_blocker_count_visibility_changed()+qreal Tab::loading_ring_opacity() const{- if (!is_loaded())- return;+ if (m_is_loading)+ return 1;+ if (!m_load_finished_clock.isValid())+ return 0;+ auto elapsed = static_cast<qreal>(m_load_finished_clock.elapsed());+ return max(0.0, 1 - (elapsed / Motion::FAST));+}- m_content_blocking_button->set_show_count_badge(WebView::Application::settings().show_content_blocker_count());+qreal Tab::loading_favicon_shrink() const+{+ if (!m_is_loading)+ return loading_ring_opacity();+ auto elapsed = static_cast<qreal>(m_load_started_clock.elapsed());+ return Motion::enter_easing().valueForProgress(min(1.0, elapsed / Motion::BASE));}void Tab::set_loading(bool is_loading)@@ -1813,22 +2198,14 @@ void Tab::set_loading(bool is_loading)return;m_is_loading = is_loading;- m_loading_animation_frame = 0;- emit loading_changed();-- if (m_is_loading)- m_loading_animation_timer->start();+ m_is_waiting_for_response = is_loading;+ if (is_loading)+ m_load_started_clock.start();else- m_loading_animation_timer->stop();-- update_tab_icon();+ m_load_finished_clock.start();+ emit loading_changed();m_reload_button->set_loading(m_is_loading);-- // Only mark the end of loads that finished, rather than being stopped. The browser's own about: pages are not- // marked.- if (!m_is_loading && view().last_load_finished() && view().url().scheme() != "about"sv)- emit loading_finished();}void Tab::update_tab_icon()@@ -1867,35 +2244,6 @@ void Tab::set_screen_wake_lock_state(Web::ScreenWakeLockState wake_lock_state)}}-#ifdef AK_OS_MACOS-void Tab::paintEvent(QPaintEvent*)-{- // The inset around the web view should match the chrome surrounding it.- QPainter painter(this);- auto const& palette = window()->palette();- painter.fillRect(rect(), ChromeStyle::chrome_background(palette));-- if (!m_web_view_chrome_visible || !m_web_view_sidebar_position.has_value() || !is_loaded())- return;-- // At the bottom of the window, the sidebar's color reaches around the web view's rounded corner beside it, so the- // inset bends around that corner rather than meeting the sidebar in a square corner. At the top, the inset joins- // the toolbar instead.- // NB: The curve meets the sidebar's edge and the window's bottom edge in a tangent.- auto radius = m_view->viewport_corner_radius() + WEB_VIEW_SIDEBAR_INSET;- auto left = *m_web_view_sidebar_position == WebView::VerticalTabsPosition::Right ? width() - radius : 0.0;- auto curve_left = *m_web_view_sidebar_position == WebView::VerticalTabsPosition::Right ? width() - (2 * radius) : 0.0;-- QPainterPath corner;- corner.addRect(left, height() - radius, radius, radius);- QPainterPath inside;- inside.addEllipse(curve_left, height() - (2 * radius), 2 * radius, 2 * radius);-- painter.setRenderHint(QPainter::Antialiasing, true);- painter.fillPath(corner.subtracted(inside), ChromeStyle::chrome_tab_strip_background(palette, ChromeStyle::window_activity(*this)));-}-#endif-void Tab::resizeEvent(QResizeEvent* event){QWidget::resizeEvent(event);@@ -1916,8 +2264,6 @@ void Tab::hideEvent(QHideEvent* event)set_bookmarks_bar_hover_expanded(false);m_hover_label->hide();- if (m_content_blocking_popover)- m_content_blocking_popover->close();}void Tab::update_hover_label()@@ -1926,8 +2272,6 @@ void Tab::update_hover_label()m_hover_label->resize(m_hover_label->sizeHint());auto hover_label_height = height() - m_hover_label->height();- if (m_find_in_page->isVisible())- hover_label_height -= m_find_in_page->height();auto left_position = mapToGlobal(QPoint { 0, hover_label_height });@@ -1946,9 +2290,9 @@ void Tab::hide_hover_label()bool Tab::event(QEvent* event){- // The sidebar's color, which the frame around the page bends around, follows the window's activity.- if (event->type() == QEvent::WindowActivate || event->type() == QEvent::WindowDeactivate)- update();+ // An inactive window's toolbar icons drop to the muted color.+ if ((event->type() == QEvent::WindowActivate || event->type() == QEvent::WindowDeactivate) && is_loaded())+ recreate_toolbar_icons();if (event->type() == QEvent::PaletteChange && is_loaded()) {update_chrome_style();@@ -1967,8 +2311,13 @@ bool Tab::eventFilter(QObject* watched, QEvent* event)if (static_cast<QDynamicPropertyChangeEvent*>(event)->propertyName() == "autocompleteOpen")update_bookmarks_bar_hover();}- if (watched == m_view && (event->type() == QEvent::Resize || event->type() == QEvent::Move))+ if (watched == m_view && (event->type() == QEvent::Resize || event->type() == QEvent::Move)) {update_bookmarks_bar_geometry();+ if (m_find_in_page->isVisible())+ m_find_in_page->reposition();+ if (m_restore_session_card)+ m_restore_session_card->reposition();+ }if (watched == m_bookmarks_bar_container && event->type() == QEvent::Resize)update_bookmarks_bar_geometry();if (watched == m_bookmarks_bar && event->type() == QEvent::LayoutRequest)@@ -1992,68 +2341,58 @@ void Tab::update_chrome_style()if (m_is_updating_chrome_style)return;m_is_updating_chrome_style = true;- m_toolbar_container->setStyleSheet(ChromeStyle::toolbar_container_style_sheet(palette()));+ m_toolbar_container->setStyleSheet(ChromeStyle::toolbar_container_style_sheet(Theme::chrome_palette(*this)));m_bookmarks_bar->update_chrome_style();- auto hover_surface = ChromeStyle::style_sheet_color(ChromeStyle::chrome_surface(palette()));- auto hover_border = ChromeStyle::style_sheet_color(ChromeStyle::chrome_border(palette()));- auto hover_text = ChromeStyle::style_sheet_color(ChromeStyle::chrome_text(palette()));+ auto hover_surface = ChromeStyle::style_sheet_color(ChromeStyle::chrome_surface(Theme::chrome_palette(*this)));+ auto hover_border = ChromeStyle::style_sheet_color(ChromeStyle::chrome_border(Theme::chrome_palette(*this)));+ auto hover_text = ChromeStyle::style_sheet_color(ChromeStyle::chrome_text(Theme::chrome_palette(*this)));m_hover_label->setStyleSheet(qformatted("background: {}; color: {}; border: 1px solid {}; border-radius: 6px;",hover_surface, hover_text, hover_border));if (m_downloads_popover)m_downloads_popover->update_chrome_style(palette());- if (m_content_blocking_popover)- m_content_blocking_popover->update_chrome_style(palette());m_is_updating_chrome_style = false;}void Tab::recreate_toolbar_icons(){- m_navigate_back_action->setIcon(create_chrome_icon(ChromeIcon::Back, palette()));- m_navigate_forward_action->setIcon(create_chrome_icon(ChromeIcon::Forward, palette()));- m_reload_action->setIcon(create_chrome_icon(ChromeIcon::Reload, palette()));- m_stop_action->setIcon(create_chrome_icon(ChromeIcon::Stop, palette()));- m_downloads_button_icon = {};- update_downloads_button();- m_hamburger_button->setIcon(create_chrome_icon(ChromeIcon::Menu, palette()));+ auto activity = ChromeStyle::window_activity(*this);+ m_navigate_back_action->setIcon(create_chrome_icon(ChromeIcon::Back, Theme::chrome_palette(*this), activity, TOOLBAR_ICON_SIZE));+ m_navigate_forward_action->setIcon(create_chrome_icon(ChromeIcon::Forward, Theme::chrome_palette(*this), activity, TOOLBAR_ICON_SIZE));+ m_reload_action->setIcon(create_chrome_icon(ChromeIcon::Reload, Theme::chrome_palette(*this), activity, TOOLBAR_ICON_SIZE));+ m_stop_action->setIcon(create_chrome_icon(ChromeIcon::Stop, Theme::chrome_palette(*this), activity, TOOLBAR_ICON_SIZE));+ m_downloads_button->setIcon(create_chrome_icon(ChromeIcon::Download, Theme::chrome_palette(*this), activity, TOOLBAR_ICON_SIZE));update_window_control_icons();if (auto* action = m_location_edit->trailing_action()) {- auto icon = view().toggle_bookmark_action().engaged() ? ChromeIcon::StarFilled : ChromeIcon::Star;- action->setIcon(create_chrome_icon(icon, palette()));+ auto engaged = view().toggle_bookmark_action().engaged();+ action->setIcon(create_chrome_icon(engaged ? ChromeIcon::StarFilled : ChromeIcon::Star, Theme::chrome_palette(*this), activity));}}void Tab::update_downloads_button(){- if (!m_downloads_button)- return;-auto downloads = WebView::Application::the().file_downloader().downloads_of_session(m_window->is_private());auto button_state = WebView::downloads_button_state(downloads);- m_downloads_button->setVisible(button_state.has_downloads);- if (!button_state.has_downloads) {- static_cast<DownloadsButton*>(m_downloads_button)->set_progress({});- if (m_downloads_popover)- m_downloads_popover->close();- }-- auto downloads_icon = button_state.active_download_count > 0 && !button_state.active_download_progress.has_value() ? ChromeIcon::DownloadActive : ChromeIcon::Download;- if (!m_downloads_button_icon.has_value() || *m_downloads_button_icon != downloads_icon) {- auto icon = create_chrome_icon(downloads_icon, palette());- m_open_downloads_page_action->setIcon(icon);- m_downloads_button->setIcon(icon);- static_cast<DownloadsButton*>(m_downloads_button)->set_progress_icon(create_chrome_icon(ChromeIcon::DownloadActive, palette()));- m_downloads_button_icon = downloads_icon;- }+ if (!button_state.has_downloads && m_downloads_popover)+ m_downloads_popover->close();- static_cast<DownloadsButton*>(m_downloads_button)->set_progress(button_state.active_download_count > 0 ? button_state.active_download_progress : Optional<double> {});+ // The arrow drops into place as the button appears, and bobs once as a download finishes.+ auto was_visible = m_downloads_button->isVisible();+ m_downloads_button->setVisible(button_state.has_downloads);+ if (!was_visible && button_state.has_downloads)+ m_downloads_button->play_icon_motion(ToolbarButton::IconMotion::DropIn);+ else if (button_state.completed_download_count > m_completed_download_count)+ m_downloads_button->play_icon_motion(ToolbarButton::IconMotion::Bob);+ m_completed_download_count = button_state.completed_download_count;+ m_downloads_button->set_progress(button_state.active_download_count > 0, button_state.active_download_progress);+ m_window->set_failed_download_count(button_state.failed_download_count);+ m_downloads_button->set_needs_attention(m_window->has_unseen_failed_downloads());auto tooltip = qstring_from_ak_string(button_state.tooltip);- if (m_downloads_button_tooltip != tooltip) {- m_downloads_button_tooltip = tooltip;- m_open_downloads_page_action->setToolTip(tooltip);+ if (m_downloads_button->toolTip() != tooltip) {m_downloads_button->setToolTip(tooltip);+ m_downloads_button->setAccessibleName(tooltip);}}@@ -2066,16 +2405,20 @@ void Tab::update_downloads_popover()position_downloads_popover();}+// The downloads hang from the downloads button. Without any, the downloads page opens instead.void Tab::show_downloads_popover(){- if (!m_downloads_button || !m_downloads_button->isVisible())+ auto downloads = WebView::Application::the().file_downloader().downloads_of_session(m_window->is_private());+ if (!WebView::downloads_button_state(downloads).has_downloads) {+ m_open_downloads_page_action->trigger();return;+ }+ m_window->acknowledge_failed_downloads();if (!m_downloads_popover) {m_downloads_popover = new DownloadsPopover(this);- m_downloads_popover->on_visibility_change = [button = QPointer(m_downloads_button)](bool visible) {- if (button)- button->setDown(visible);+ m_downloads_popover->on_visibility_change = [this](bool visible) {+ m_downloads_button->setChecked(visible);};m_downloads_popover->on_cancel_download = [this](u64 id) {auto& file_downloader = WebView::Application::the().file_downloader();@@ -2091,6 +2434,14 @@ void Tab::show_downloads_popover()WebView::Application::the().file_downloader().resume_download(id);update_downloads_popover();};+ m_downloads_popover->on_show_in_folder = [](u64 id) {+ if (auto download = WebView::Application::the().file_downloader().download(id); download.has_value())+ WebView::Application::the().show_download_in_folder(*download);+ };+ m_downloads_popover->on_clear_finished = [this] {+ (void)WebView::Application::the().file_downloader().prune_inactive_downloads(m_window->is_private());+ update_downloads_popover();+ };m_downloads_popover->on_open_all_downloads = [this] {if (m_downloads_popover)m_downloads_popover->close();@@ -2108,7 +2459,7 @@ void Tab::show_downloads_popover()void Tab::position_downloads_popover(){- if (!m_downloads_popover || !m_downloads_button)+ if (!m_downloads_popover)return;m_downloads_popover->adjustSize();@@ -2120,7 +2471,7 @@ void Tab::position_downloads_popover()card.setFixedSize(size);m_downloads_popover->adjustSize();- move_popover_below(*m_downloads_popover, *m_downloads_button);+ move_popover_below(*m_downloads_popover, *m_downloads_button, PopoverAlignment::Trailing);}void Tab::download_added(WebView::FileDownloader::Download const& download)@@ -2161,85 +2512,121 @@ void Tab::download_removed(u64, WebView::IsPrivate is_private)update_downloads_popover();}-void Tab::update_content_blocking_controls(WebView::ContentBlockingSnapshot const& snapshot)+void Tab::show_zoom_popover(){- m_content_blocking_button->set_snapshot(snapshot);- if (!m_content_blocking_popover || !m_content_blocking_popover->isVisible())- return;+ if (!m_zoom_popover) {+ auto* popover = new ZoomPopover(this);+ popover->on_zoom_in = [this] { view().zoom_in(); };+ popover->on_zoom_out = [this] { view().zoom_out(); };+ popover->on_reset = [this] {+ view().reset_zoom();+ m_zoom_popover->close();+ };+ popover->current_level = [this] { return view().zoom_level(); };+ m_zoom_popover = popover;+ }- if (snapshot.state == WebView::ContentBlockingState::Unavailable- || (m_content_blocking_popover_reload_site.has_value() && snapshot.site != m_content_blocking_popover_reload_site)) {- m_content_blocking_popover->close();- return;+ auto& popover = static_cast<ZoomPopover&>(*m_zoom_popover);+ popover.setStyleSheet(ChromeStyle::zoom_popover_style_sheet(Theme::chrome_palette(*this)));+ popover.update_level();+ popover.adjustSize();+ // The panel hangs from the address field, lined up with its right edge.+ move_popover_below(popover, *m_location_edit);+ popover.show();+ move_popover_below(popover, *m_location_edit);+}++void Tab::show_bookmark_popover()+{+ auto& store = WebView::Application::bookmark_store();+ auto just_added = BookmarkPopover::JustAdded::No;+ auto bookmark = store.find_bookmark_by_url(view().url());+ if (!bookmark.has_value()) {+ Optional<String> title;+ if (auto page_title = view().title().to_utf8(); !page_title.is_empty())+ title = AK::move(page_title);+ m_location_edit->animate_trailing_action_change(LocationEdit::TrailingActionMotion::Pop, [&] {+ store.add_bookmark(view().url(), AK::move(title), view().favicon_hash());+ });+ bookmark = store.find_bookmark_by_url(view().url());+ just_added = BookmarkPopover::JustAdded::Yes;}+ if (!bookmark.has_value())+ return;- m_content_blocking_popover->set_snapshot(snapshot);- move_popover_below(*m_content_blocking_popover, *m_content_blocking_button);+ if (!m_bookmark_popover) {+ m_bookmark_popover = new BookmarkPopover(this);+ m_bookmark_popover->on_remove = [this](Function<void()> const& remove) {+ m_location_edit->animate_trailing_action_change(LocationEdit::TrailingActionMotion::Fade, remove);+ };+ }+ m_bookmark_popover->update_chrome_style(palette());+ m_bookmark_popover->set_bookmark(bookmark->id, just_added);+ auto& anchor = m_location_edit->trailing_action_button();+ move_popover_below(*m_bookmark_popover, anchor);+ m_bookmark_popover->show();+ move_popover_below(*m_bookmark_popover, anchor);}-void Tab::show_content_blocking_popover()+void Tab::close_popovers(){- if (m_content_blocking_popover && m_content_blocking_popover->isVisible()) {- m_content_blocking_popover->close();- m_content_blocking_button->setFocus(Qt::PopupFocusReason);- return;+ for (auto* popover : { static_cast<QWidget*>(m_downloads_popover), static_cast<QWidget*>(m_private_session_popover), static_cast<QWidget*>(m_site_settings_popover), static_cast<QWidget*>(m_zoom_popover), static_cast<QWidget*>(m_bookmark_popover) }) {+ if (popover)+ popover->close();}+}- auto snapshot = view().content_blocking_snapshot();- if (snapshot.state == WebView::ContentBlockingState::Unavailable)+void Tab::show_site_settings_popover()+{+ auto url = view().url();+ if (!url.host().has_value())return;- if (!m_content_blocking_popover) {- m_content_blocking_popover = new ContentBlockingPopover(this);- m_content_blocking_popover->on_visibility_change = [this, button = QPointer(m_content_blocking_button)](bool visible) {- if (button)- button->setDown(visible);- if (!visible)- m_content_blocking_popover_reload_site.clear();+ if (!m_site_settings_popover) {+ m_site_settings_popover = new SiteSettingsPopover(this);+ m_location_edit->follow_site_settings_popover(*m_site_settings_popover);+ m_site_settings_popover->on_content_blocking_toggle = [this](bool enabled) {+ auto snapshot = view().content_blocking_snapshot();+ if (!snapshot.site.has_value() || !snapshot.can_toggle())+ return;+ if (WebView::Application::settings().set_content_blocker_enabled_for_site(*snapshot.site, enabled).is_error())+ return;+ view().reload();+ };+ m_site_settings_popover->on_open_all_site_settings = [this] {+ m_window->new_tab_from_url(URL::Parser::basic_parse("about:settings#permissions"sv).release_value(), Web::HTML::ActivateTab::Yes, BrowserWindow::TabLocation::after_current_tab());};- m_content_blocking_popover->on_keyboard_dismiss = [button = QPointer(m_content_blocking_button)] {- if (button && button->isVisible())- button->setFocus(Qt::PopupFocusReason);+ m_site_settings_popover->on_report_broken_site = [] {+ WebView::Application::the().report_website_issue_action().activate();+ };+ m_site_settings_popover->on_open_filter_lists = [this] {+ m_window->new_tab_from_url(URL::Parser::basic_parse("about:settings#blocking"sv).release_value(), Web::HTML::ActivateTab::Yes, BrowserWindow::TabLocation::after_current_tab());};}- m_content_blocking_popover->on_toggle = [this, site = snapshot.site](bool enabled) {- auto current = view().content_blocking_snapshot();- if (!site.has_value() || current.site != site || !current.can_toggle()) {- m_content_blocking_popover->close();- return;- }-- if (auto result = WebView::Application::settings().set_content_blocker_enabled_for_site(*site, enabled); result.is_error()) {- m_content_blocking_popover->set_snapshot(view().content_blocking_snapshot());- m_content_blocking_popover->show_error("Unable to save the site preference.");- move_popover_below(*m_content_blocking_popover, *m_content_blocking_button);- return;- }-- m_content_blocking_popover_reload_site = site;- view().reload();- };-- m_content_blocking_popover->update_chrome_style(palette());- m_content_blocking_popover->set_favicon(m_favicon);- m_content_blocking_popover->set_snapshot(snapshot);- move_popover_below(*m_content_blocking_popover, *m_content_blocking_button);- m_content_blocking_popover->show();- move_popover_below(*m_content_blocking_popover, *m_content_blocking_button);- m_content_blocking_popover->raise();- m_content_blocking_popover->focus_switch();+ m_site_settings_popover->update_chrome_style(palette());+ m_site_settings_popover->set_site({+ .host = MUST(String::from_utf8(url.serialized_host())),+ .is_secure = url.scheme() == "https"sv,+ .favicon = m_favicon,+ .content_blocking = view().content_blocking_snapshot(),+ });+ auto& anchor = m_location_edit->site_settings_button();+ move_popover_below(*m_site_settings_popover, anchor, PopoverAlignment::Leading);+ m_site_settings_popover->show();+ move_popover_below(*m_site_settings_popover, anchor, PopoverAlignment::Leading);+ m_site_settings_popover->raise();}void Tab::show_private_session_popover(){- if (!m_private_badge || !m_private_badge->isVisible())+ if (m_window->is_private() == WebView::IsPrivate::No)return;if (!m_private_session_popover) {m_private_session_popover = new MessagePopover(this, PRIVATE_SESSION_POPOVER_WIDTH, "Start a fresh private session?","This closes all private windows and deletes history and other site data from the current private browsing session.",- "Cancel", "Restart Private Session");+ "Cancel", "Start fresh session");m_private_session_popover->on_accept = [] {Application::the().restart_private_browsing_session();};@@ -2254,18 +2641,28 @@ void Tab::show_private_session_popover()void Tab::position_private_session_popover(){- if (!m_private_session_popover || !m_private_badge)+ if (!m_private_session_popover)return;m_private_session_popover->adjustSize();- move_popover_below(*m_private_session_popover, *m_private_badge);+ move_popover_below(*m_private_session_popover, m_window->ladybird_button(), PopoverAlignment::Leading, m_window->ladybird_button().tile_rect());+}++void Tab::show_restore_session_card(size_t tab_count, Function<void()> on_restore)+{+ if (m_restore_session_card)+ m_restore_session_card->deleteLater();+ m_restore_session_card = new RestoreSessionCard(*this, *m_view, tab_count);+ m_view->add_floating_surface(*m_restore_session_card);+ m_restore_session_card->on_restore = AK::move(on_restore);+ m_restore_session_card->show();}void Tab::show_find_in_page(){m_find_in_page->setVisible(true);- m_find_in_page->setFocus();+ m_find_in_page->focus_search_field();}void Tab::find_previous()@@ -2289,9 +2686,11 @@ void Tab::update_bookmarks_bar_visibility()static_cast<QBoxLayout*>(layout())->removeWidget(m_bookmarks_bar_container);if (m_bookmarks_bar_container->parentWidget() != this)m_bookmarks_bar_container->setParent(this);- } else if (toolbar_layout->indexOf(m_bookmarks_bar_container) == -1) {- // An always-visible bar remains in the full-width toolbar above the vertical tabs.- toolbar_layout->addWidget(m_bookmarks_bar_container);+ } else if (auto* tab_layout = static_cast<QBoxLayout*>(layout()); tab_layout->indexOf(m_bookmarks_bar_container) == -1) {+ // An always-visible bar sits above the page, so that it is beside a collapsed sidebar rather than above it.+ toolbar_layout->removeWidget(m_bookmarks_bar_container);+ m_bookmarks_bar_container->setParent(this);+ tab_layout->insertWidget(tab_layout->indexOf(m_view), m_bookmarks_bar_container);}update_bookmarks_bar_hover();@@ -2321,7 +2720,9 @@ bool Tab::cursor_is_over_bookmarks_bar_hover_region() constreturn true;}- if (!m_window->underMouse())+ // NB: The page can be presented by a native window of its own, which takes the pointer from the browser window.+ auto* widget_under_cursor = QApplication::widgetAt(QCursor::pos());+ if (!m_window->underMouse() && !(widget_under_cursor && widget_under_cursor->window() == m_window))return false;auto cursor_position = QCursor::pos();@@ -2354,7 +2755,7 @@ void Tab::set_bookmarks_bar_hover_expanded(bool expanded)m_bookmarks_bar_hover_expanded = expanded;m_bookmarks_bar_hover_expand_animation->stop();- auto duration = expanded+ auto duration = expanded && !SystemAppearance::prefers_reduced_motion()? Application::settings().config_variable_as_integer<int>(WebView::ConfigVariableID::VerticalTabsHoverExpandAnimationDuration): 0;m_bookmarks_bar_hover_expand_progress = expanded && duration == 0 ? 1.0 : 0.0;@@ -2399,9 +2800,9 @@ void Tab::update_bookmarks_bar_geometry()ensure_appkit_window_is_exposed(*m_bookmarks_bar_container);#endif- auto hover_bookmarks_visible = on_hover && visible;- if (m_toolbar_container->property("hoverBookmarksVisible").toBool() != hover_bookmarks_visible) {- m_toolbar_container->setProperty("hoverBookmarksVisible", hover_bookmarks_visible);+ // NB: The bar below the toolbar draws the line under both.+ if (m_toolbar_container->property("bookmarksBarBelow").toBool() != visible) {+ m_toolbar_container->setProperty("bookmarksBarBelow", visible);m_toolbar_container->style()->unpolish(m_toolbar_container);m_toolbar_container->style()->polish(m_toolbar_container);m_toolbar_container->update();diff --git a/UI/Qt/Tab.h b/UI/Qt/Tab.hindex 4518d881aae..a489feabda3 100644--- a/UI/Qt/Tab.h+++ b/UI/Qt/Tab.h@@ -26,6 +26,7 @@#include <UI/Qt/WebContentView.h>#include <QBoxLayout>+#include <QElapsedTimer>#include <QLabel>#include <QMenu>#include <QPointer>@@ -41,12 +42,13 @@ class QVariantAnimation;namespace Ladybird {+class BookmarkPopover;class BrowserWindow;enum class ChromeIcon;+class DownloadsButton;class DownloadsPopover;-class ContentBlockingButton;-class ContentBlockingPopover;class ReloadButton;+class RestoreSessionCard;class JavaScriptDialog;class MessagePopover;class WindowControlButton;@@ -81,6 +83,8 @@ struct DeferredTab {QIcon favicon;};+class Popover;+class SiteSettingsPopover;class Tab final: public QWidget, public WebView::FileDownloaderObserver@@ -126,6 +130,7 @@ public:void open_file();void show_find_in_page();+ void show_restore_session_card(size_t tab_count, Function<void()> on_restore);void find_previous();void find_next();@@ -141,20 +146,31 @@ public:QIcon const& favicon() const { return m_favicon; }QIcon tab_icon() const;bool is_loading() const { return m_is_loading; }+ // Whether the page being loaded has yet to respond.+ bool is_waiting_for_response() const { return m_is_loading && m_is_waiting_for_response; }+ // How strongly the tab's loading ring shows: fully while the tab loads, then fading out once it has loaded.+ qreal loading_ring_opacity() const;+ // How far the favicon has shrunk to sit inside the loading ring: it shrinks as the tab starts loading, and grows back+ // as the ring fades out.+ qreal loading_favicon_shrink() const;+ // A tab in the background whose title changes after it has loaded has news, until it is selected.+ bool needs_attention() const { return m_needs_attention; }+ void clear_attention() { m_needs_attention = false; }QString title() const;QMenu* context_menu() const { return m_context_menu; }- QToolButton* hamburger_button() const { return m_hamburger_button; }QWidget* toolbar_container() const { return m_toolbar_container; }void set_vertical_tabs_enabled(bool);-#ifdef AK_OS_MACOS- void update_web_view_frame(bool chrome_visible, Optional<WebView::VerticalTabsPosition> sidebar_position);-#endifvoid set_window(BrowserWindow&);void set_toolbar_container_in_tab_layout(bool);void set_toolbar_window_controls_visible(bool);+ // While the sidebar is collapsed, the toolbar holds the Ladybird button and the sidebar's toggle, after the window+ // controls, here.+ QWidget& toolbar_sidebar_slot() { return *m_toolbar_sidebar_slot; }+ int toolbar_lead_beside_collapsed_sidebar(QWidget const& ladybird_button, QSize sidebar_toggle_size) const;+ void set_toolbar_leading_room(int);static int toolbar_height(bool window_controls_visible);void update_window_control_icons();void update_hover_label();@@ -168,8 +184,21 @@ public:bool url_is_hidden() const { return m_location_edit->url_is_hidden(); }void set_url_is_hidden(bool url_is_hidden) { m_location_edit->set_url_is_hidden(url_is_hidden); }+public:+ enum class FocusRingTransition : u8 {+ FadeIn,+ Immediate,+ };+ void show_downloads_popover();+ void update_downloads_button();+ void show_private_session_popover();+ void show_site_settings_popover();+ void show_zoom_popover();+ void show_bookmark_popover();+ void close_popovers();+public slots:- void focus_location_editor();+ void focus_location_editor(FocusRingTransition = FocusRingTransition::FadeIn);void park_location_editing();LocationEdit* location_edit_with_parked_editing() const { return is_loaded() && m_location_edit->has_parked_editing_session() ? m_location_edit : nullptr; }@@ -178,7 +207,6 @@ signals:void favicon_changed(int id, QIcon const&);void audio_play_state_changed(int id, Web::HTML::AudioPlayState);void loading_changed();- void loading_finished();void loaded();private:@@ -187,9 +215,6 @@ private:void initialize(Optional<WebView::CanonicalTraversable&>);void location_edit_return_pressed(String, Optional<URL::URL>, WebView::OmniboxDestinationKind);-#ifdef AK_OS_MACOS- virtual void paintEvent(QPaintEvent*) override;-#endifvirtual void resizeEvent(QResizeEvent*) override;virtual void hideEvent(QHideEvent*) override;virtual bool event(QEvent*) override;@@ -197,21 +222,14 @@ private:virtual void tab_settings_changed() override;virtual void config_variable_changed(WebView::ConfigVariableID) override;- virtual void content_blocker_count_visibility_changed() override;void recreate_toolbar_icons();- void connect_hamburger_menu();QToolButton* create_navigation_history_toolbar_button(QWidget& parent, QAction&, int direction);void update_chrome_style();void update_tab_title();void leave_report_review();- void update_downloads_button();void update_downloads_popover();- void show_downloads_popover();void position_downloads_popover();- void show_content_blocking_popover();- void update_content_blocking_controls(WebView::ContentBlockingSnapshot const&);- void show_private_session_popover();void position_private_session_popover();void hide_hover_label();void set_loading(bool);@@ -233,6 +251,7 @@ private:QWidget* m_toolbar { nullptr };QWidget* m_performance_monitor { nullptr };QWidget* m_toolbar_window_controls_separator { nullptr };+ QWidget* m_toolbar_sidebar_slot { nullptr };QWidget* m_toolbar_window_controls { nullptr };WindowControlButton* m_minimize_window_button { nullptr };WindowControlButton* m_maximize_window_button { nullptr };@@ -246,18 +265,17 @@ private:bool m_bookmarks_bar_hover_expanded { false };qreal m_bookmarks_bar_hover_expand_progress { 0.0 };- QPushButton* m_private_badge { nullptr };- QToolButton* m_hamburger_button { nullptr };- ContentBlockingButton* m_content_blocking_button { nullptr };- QPointer<ContentBlockingPopover> m_content_blocking_popover;- Optional<String> m_content_blocking_popover_reload_site;- QToolButton* m_downloads_button { nullptr };QPointer<DownloadsPopover> m_downloads_popover;QPointer<MessagePopover> m_private_session_popover;+ QPointer<SiteSettingsPopover> m_site_settings_popover;+ QTimer* m_content_blocking_update_timer { nullptr };+ QPointer<Popover> m_zoom_popover;+ QPointer<BookmarkPopover> m_bookmark_popover;QPointer<Tab> m_tab_to_activate_on_close;LocationEdit* m_location_edit { nullptr };WebContentView* m_view { nullptr };FindInPageWidget* m_find_in_page { nullptr };+ QPointer<RestoreSessionCard> m_restore_session_card;Optional<WakeLock::DisplaySleepInhibitor> m_screen_display_sleep_inhibitor;BrowserWindow* m_window { nullptr };QString m_title;@@ -266,18 +284,14 @@ private:bool m_has_loaded_report_review_page { false };HyperlinkLabel* m_hover_label { nullptr };QIcon m_favicon;- QTimer* m_loading_animation_timer { nullptr };bool m_is_loading { false };+ bool m_needs_attention { false };+ bool m_is_waiting_for_response { false };+ QElapsedTimer m_load_started_clock;+ QElapsedTimer m_load_finished_clock;bool m_has_had_real_size { false };bool m_is_updating_chrome_style { false };bool m_vertical_tabs_enabled { false };-#ifdef AK_OS_MACOS- QHBoxLayout* m_view_layout { nullptr };- // The web view's frame as TabWidget last asked for it, which a tab that hasn't loaded gets once it loads.- bool m_web_view_chrome_visible { true };- Optional<WebView::VerticalTabsPosition> m_web_view_sidebar_position;-#endif- int m_loading_animation_frame { 0 };QMenu* m_context_menu { nullptr };QMenu* m_page_context_menu { nullptr };@@ -295,8 +309,8 @@ private:ReloadButton* m_reload_button { nullptr };QAction* m_open_downloads_page_action { nullptr };QAction* m_pin_tab_action { nullptr };- Optional<ChromeIcon> m_downloads_button_icon;- QString m_downloads_button_tooltip;+ DownloadsButton* m_downloads_button { nullptr };+ size_t m_completed_download_count { 0 };JavaScriptDialog* m_javascript_dialog { nullptr };Function<void(bool)> m_before_unload_completion;@@ -305,12 +319,15 @@ private:QPointer<QMessageBox> m_external_url_confirmation_dialog;// Requests the same dialog would answer wait on the one open, so a page cannot stack dialogs by asking again.struct PendingPermissionRequests {- QPointer<QMessageBox> dialog;+ QPointer<MessagePopover> popover;Vector<Function<void(bool granted)>> on_decided;};HashMap<String, PendingPermissionRequests> m_pending_permission_requests;bool m_suppress_javascript_dialogs_until_navigation { false };+ // The dialogs the current document has shown, and whether the user stopped it from showing more.+ u64 m_javascript_dialogs_shown_by_document { 0 };+ bool m_javascript_dialogs_blocked_for_document { false };bool m_already_requested_close { false };bool m_preserve_close_retry_state_on_dialog_dismissal { false };bool m_window_is_closing { false };diff --git a/UI/Qt/TabBar.cpp b/UI/Qt/TabBar.cppindex da864b20989..0de628c6b25 100644--- a/UI/Qt/TabBar.cpp+++ b/UI/Qt/TabBar.cpp@@ -6,28 +6,41 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/EnumBits.h>+#include <AK/Array.h>+#include <AK/Function.h>#include <AK/ScopeGuard.h>#include <AK/StdLibExtras.h>#include <AK/kmalloc.h>#include <LibCore/EventLoop.h>+#include <LibWebView/HistoryStore.h>+#include <LibWebView/SessionStore.h>+#include <UI/Qt/AllTabsPopover.h>#include <UI/Qt/Application.h>#include <UI/Qt/BrowserWindow.h>#include <UI/Qt/ChromeLayout.h>#include <UI/Qt/ChromeStyle.h>#include <UI/Qt/Icon.h>+#include <UI/Qt/LadybirdButton.h>#if defined(AK_OS_MACOS)# include <UI/Qt/MacWindow.h>#endif#include <UI/Qt/HiddenPageSizing.h>#include <UI/Qt/Menu.h>+#include <UI/Qt/Motion.h>+#include <UI/Qt/Popover.h>#include <UI/Qt/StringUtils.h>+#include <UI/Qt/SystemAppearance.h>#include <UI/Qt/TabBar.h>+#include <UI/Qt/Theme.h>+#if defined(LADYBIRD_HAS_WAYLAND_CLIENT)+# include <UI/Qt/WaylandWindow.h>+#endif#include <UI/Qt/WindowControlButton.h>#include <QApplication>#include <QContextMenuEvent>#include <QCursor>+#include <QDataStream>#include <QDrag>#include <QDragEnterEvent>#include <QDragLeaveEvent>@@ -38,6 +51,8 @@#include <QFontMetrics>#include <QFrame>#include <QGraphicsDropShadowEffect>+#include <QGraphicsPixmapItem>+#include <QGraphicsScene>#include <QHBoxLayout>#include <QHelpEvent>#include <QKeyEvent>@@ -69,86 +84,147 @@namespace Ladybird {static constexpr auto LADYBIRD_TAB_MIME_TYPE = "application/x-ladybird-tab";-static constexpr int HORIZONTAL_TAB_STRIP_HEIGHT = 39;-// Horizontal tabs reach the bottom of the strip, where the selected tab flows into the toolbar below it.-static constexpr int HORIZONTAL_TAB_HEIGHT = 37;-// Horizontal tabs shrink until only their favicon is left, then overflow the strip and get clipped.-static constexpr int HORIZONTAL_TAB_MIN_WIDTH = 40;-// Narrower background tabs drop their close button to keep room for the title.-static constexpr int HORIZONTAL_TAB_CLOSE_BUTTON_MIN_WIDTH = 96;-// The active tab keeps its close button for as long as it fits next to the favicon.-static constexpr int HORIZONTAL_ACTIVE_TAB_CLOSE_BUTTON_MIN_WIDTH = 68;+static constexpr int HORIZONTAL_TAB_STRIP_HEIGHT = 35;+// Horizontal tabs reach the bottom of the strip, where the selected tab joins the toolbar below it. What belongs to the+// tabs, such as their contents and the new tab button, is centered on the middle of the selected tab, 20 px down the+// strip. What belongs to the window, such as the window controls and the Ladybird button, is centered on the traffic+// lights' line, 18 px down the strip.+static constexpr int HORIZONTAL_TAB_HEIGHT = 34;+// NB: This is where the 12 px traffic lights are centered, at their inset from the window's top.+static constexpr int HORIZONTAL_WINDOW_ITEM_CENTER = 18;+// NB: The tab row starts below the top of the strip, so a window control as tall as this, at the top of the row, is+// centered on the window items' line.+static constexpr int HORIZONTAL_WINDOW_CONTROL_HEIGHT = 2 * (HORIZONTAL_WINDOW_ITEM_CENTER - (HORIZONTAL_TAB_STRIP_HEIGHT - HORIZONTAL_TAB_HEIGHT));+// The first item on the strip is as far from the window's edge as the traffic lights are from its corner on macOS.+static constexpr int HORIZONTAL_TAB_STRIP_LEADING_MARGIN = use_native_macos_window_controls() ? NATIVE_MACOS_WINDOW_CONTROLS_INSET : 13;+// Horizontal tabs shrink to this width, and past that the strip scrolls.+static constexpr int HORIZONTAL_TAB_MIN_WIDTH = 112;+// After the pointer leaves the tab bar, the tabs keep their locked widths for this long.+static constexpr int TAB_WIDTH_UNLOCK_DELAY_MS = 300;+static constexpr qreal ATTENTION_DOT_RADIUS = 3.5;+// While the strip scrolls, its ends fade into the strip over this width.+static constexpr int HORIZONTAL_TAB_STRIP_FADE_WIDTH = 28;// Below this content width, a horizontal tab shows its favicon alone.static constexpr int HORIZONTAL_TAB_MIN_CONTENT_WIDTH_FOR_TITLE = 48;static constexpr int HORIZONTAL_TAB_MAX_WIDTH = 232;-// A pinned tab's tile, which shows only its favicon.-static constexpr int PINNED_TAB_TILE_WIDTH = 40;-static constexpr int PINNED_TABS_SEPARATOR_HEIGHT = 9;-static constexpr int VERTICAL_TAB_HEIGHT = 37;+// A pinned tab's tile shows only its favicon. In the sidebar, the tiles sit in a grid of this many columns.+static constexpr int PINNED_TAB_COLUMNS = 4;+static constexpr int HORIZONTAL_PINNED_TAB_WIDTH = 44;+// The line between the sidebar's pinned tiles and its other tabs, with the room around it.+static constexpr int PINNED_TABS_SEPARATOR_HEIGHT = 15;+// Rows in the sidebar are 30 px, a point apart.+static constexpr int VERTICAL_TAB_HEIGHT = 31;+static constexpr qreal VERTICAL_TAB_RADIUS = 6;+static constexpr qreal COLLAPSED_VERTICAL_TAB_RADIUS = 7;static constexpr int VERTICAL_TABS_COLLAPSED_WIDTH = browser_chrome_layout_policy().collapsed_sidebar_width;static constexpr int VERTICAL_TABS_DEFAULT_EXPANDED_WIDTH = browser_chrome_layout_policy().expanded_sidebar_width;static constexpr int VERTICAL_TABS_MIN_EXPANDED_WIDTH = 190;static constexpr int VERTICAL_TABS_MAX_EXPANDED_WIDTH = 400;static constexpr int VERTICAL_TABS_RESIZE_HIT_AREA_WIDTH = 5;static constexpr int VERTICAL_TABS_COLLAPSED_SIDE_MARGIN = 6;-static constexpr int VERTICAL_TABS_EXPANDED_SIDE_MARGIN = 5;+static constexpr int VERTICAL_TABS_EXPANDED_SIDE_MARGIN = 3;+// A collapsed sidebar's tab is a card as far from the sidebar's edge as an open sidebar's tab, and its favicon sits where+// the open sidebar's tab has it, so the tabs only grow as the sidebar opens.+static constexpr int COLLAPSED_VERTICAL_TAB_CARD_INSET = 2;+static constexpr int VERTICAL_TAB_CONTENT_LEADING_INSET = 10;static constexpr int VERTICAL_TABS_TOP_MARGIN = 8;static constexpr int VERTICAL_TABS_TOGGLE_BUTTON_SIZE = 32;+// Beside the collapsed sidebar, the toggle sits in the toolbar and is as large as the toolbar's buttons.+static constexpr QSize COLLAPSED_VERTICAL_TABS_TOGGLE_BUTTON_SIZE { 32, 28 };// The collapsed sidebar's corner below the toolbar, beside the page, is as round as the page's own corners.-static constexpr qreal VERTICAL_TABS_COLLAPSED_CORNER_RADIUS = 10.0;static constexpr int TAB_CARD_SHAPE_HORIZONTAL_INSET = 5;-// A vertical tab's card sits a point higher than the middle of its row, so the cards in the sidebar sit close together-// while they keep an even height.-static constexpr int TAB_CARD_SHAPE_TOP_INSET = 3;-static constexpr int TAB_CARD_SHAPE_BOTTOM_INSET = 2;-// The selected vertical tab reaches across to the page's frame, with its sides flaring out into it above and below. The-// bar leaves this much room above its first tab and below its last, so the flares there are not cut off.-static constexpr int VERTICAL_TAB_FLARE_RADIUS = 6;-// A horizontal tab's card holds its contents, and is what lights up when the tab is hovered. The selected tab is its card-// extended down to the toolbar. The card sits above the middle of the tab, so its contents line up with the window-// controls.-static constexpr qreal HORIZONTAL_TAB_CARD_SHAPE_HORIZONTAL_INSET = 2.5;-static constexpr int HORIZONTAL_TAB_CARD_SHAPE_TOP_INSET = 4;-static constexpr int HORIZONTAL_TAB_CARD_SHAPE_BOTTOM_INSET = 5;-static constexpr qreal HORIZONTAL_TAB_CARD_RADIUS = (HORIZONTAL_TAB_HEIGHT - HORIZONTAL_TAB_CARD_SHAPE_TOP_INSET - HORIZONTAL_TAB_CARD_SHAPE_BOTTOM_INSET) / 2.0;-// The new tab button's circle is as tall as a tab's card, so its top is level with the top of the selected tab.-static constexpr qreal HORIZONTAL_NEW_TAB_BUTTON_SHAPE_SIZE = 2 * HORIZONTAL_TAB_CARD_RADIUS;-// The selected horizontal tab's sides flare out at the bottom into the toolbar. Each flare reaches into the tab beside-// it, which has no fill of its own, and curves around the end of that tab's card at a constant distance.-// NB: For that curve to also meet the toolbar in a tangent, the distance from the card's middle to the bottom of the tab-// must equal the curve's radius, which the card's insets are chosen for.-static constexpr qreal HORIZONTAL_TAB_FLARE_RADIUS = HORIZONTAL_TAB_CARD_RADIUS + (2 * HORIZONTAL_TAB_CARD_SHAPE_HORIZONTAL_INSET);-static_assert(HORIZONTAL_TAB_FLARE_RADIUS == HORIZONTAL_TAB_HEIGHT - HORIZONTAL_TAB_CARD_SHAPE_TOP_INSET - HORIZONTAL_TAB_CARD_RADIUS);-// The first and last tabs are this much wider, on the outer side, to make room for their flares at the ends of the tab-// bar.-static constexpr int HORIZONTAL_TAB_END_ROOM = 17;-static_assert(HORIZONTAL_TAB_END_ROOM + HORIZONTAL_TAB_CARD_SHAPE_HORIZONTAL_INSET >= HORIZONTAL_TAB_FLARE_RADIUS);-// The new tab button sits over the last tab's room for its flare, with its circle centered where the flare's curve is, as-// a tab's card beside the last tab would be. The curve then keeps clear of the circle.-static constexpr int HORIZONTAL_NEW_TAB_BUTTON_OVERLAP = static_cast<int>(HORIZONTAL_TAB_END_ROOM + HORIZONTAL_TAB_CARD_SHAPE_HORIZONTAL_INSET - HORIZONTAL_TAB_FLARE_RADIUS + (HORIZONTAL_TAB_HEIGHT / 2.0));-static constexpr qreal HORIZONTAL_TAB_SEPARATOR_WIDTH = 1.5;-static constexpr qreal HORIZONTAL_TAB_SEPARATOR_HEIGHT = 20.0;+// A vertical tab's card fills its row, but for the point between it and the next.+static constexpr int TAB_CARD_SHAPE_TOP_INSET = 0;+static constexpr int TAB_CARD_SHAPE_BOTTOM_INSET = 1;+// The sidebar's tab bar leaves this much room above its first tab and below its last.+static constexpr int VERTICAL_TAB_BAR_END_ROOM = 2;+// A horizontal tab's card holds its contents, and is what lights up when the tab is hovered. It is inset from the tab on+// every side.+static constexpr qreal HORIZONTAL_TAB_CARD_SHAPE_HORIZONTAL_INSET = 3;+// NB: The card is as low in the tab as the selected tab's body is, so the contents of both share the strip's line.+static constexpr int HORIZONTAL_TAB_CARD_SHAPE_TOP_INSET = 5;+static constexpr int HORIZONTAL_TAB_CARD_SHAPE_BOTTOM_INSET = 1;+static constexpr qreal HORIZONTAL_TAB_CARD_RADIUS = 6;+// The selected tab fills its whole tab, with rounded top corners, and joins the toolbar with an inverted curve at the+// foot of each side.+static constexpr qreal HORIZONTAL_SELECTED_TAB_RADIUS = 8;+// The selected tab's top sits this far below the top of the other tabs, 5 px down the strip, while its contents stay+// centered with theirs.+static constexpr int HORIZONTAL_SELECTED_TAB_TOP_INSET = 4;+static constexpr qreal HORIZONTAL_TAB_FOOT_RADIUS = 8;+// A dragged tab is drawn as a card with a shadow. Its image leaves room for the shadow.+static constexpr int TAB_DRAG_IMAGE_MARGIN = 48;+// A tab starts to be dragged once the mouse has moved this far with the button down.+static constexpr int TAB_DRAG_START_DISTANCE = 4;+// How far off the tab strip a dragged tab can be pulled, or dropped, and still stay in it.+static constexpr int TAB_DETACH_DISTANCE = 40;+// A closing tab fades out over this much of the time the other tabs take to close the gap it leaves.+static constexpr qreal CLOSING_TAB_FADE_PORTION = 0.4;+// The first and last tabs are this much wider, on the outer side, to make room for their feet at the ends of the tab bar.+static constexpr int HORIZONTAL_TAB_END_ROOM = 8;+static_assert(HORIZONTAL_TAB_END_ROOM >= HORIZONTAL_TAB_FOOT_RADIUS);+// Each end of a tab's content is about as far from the tab's side as it is from the tab's top: the favicon 7 px in from+// the left, and the close button's glyph 11 px in from the right.+static constexpr int HORIZONTAL_TAB_CONTENT_LEFT_PADDING = 4;+static constexpr int HORIZONTAL_TAB_CONTENT_RIGHT_PADDING = 2;+static constexpr int HORIZONTAL_TAB_CONTENT_GAP = 8;+// The buttons after the tabs each take a slot of this size. The new tab button is a little smaller, in the middle of its+// slot, and draws its icon smaller.+static constexpr int HORIZONTAL_NEW_TAB_BUTTON_SIZE = 28;+static constexpr int HORIZONTAL_NEW_TAB_BUTTON_FILL_SIZE = 26;+// NB: The new tab button takes clicks from around its fill as well.+static constexpr int HORIZONTAL_NEW_TAB_BUTTON_HIT_SIZE = 32;+static constexpr int HORIZONTAL_NEW_TAB_BUTTON_ICON_SIZE = 14;+static constexpr qreal HORIZONTAL_NEW_TAB_BUTTON_RADIUS = 6;+// The strip always keeps this much free after the new tab button, before the window controls or the window's edge, so+// there is somewhere to grab the window by however many tabs are open.+static constexpr int HORIZONTAL_TAB_STRIP_DRAG_SPACE = 44;+// The new tab button's slot starts this far after the last tab, not counting the last tab's room for its foot, which+// puts its fill 8 px after the tab, just clear of a selected tab's foot.+static constexpr int HORIZONTAL_NEW_TAB_BUTTON_GAP = 7;+// NB: With the room at the strip's end and the first tab's inset and padding, this keeps the first favicon 28 px from+// the Ladybird button.+static constexpr int LADYBIRD_BUTTON_TRAILING_GAP = 16;+// In the open sidebar, the Ladybird button sits just before the sidebar's toggle, and the toggle a little further from+// the page than the tabs below it.+// NB: The gap matches the toolbar's spacing, so the two keep their distance as they move between the sidebar's header+// and the toolbar.+static constexpr int SIDEBAR_LADYBIRD_BUTTON_GAP = 2;+static constexpr int SIDEBAR_TOGGLE_PAGE_SIDE_MARGIN = 5;+static constexpr qreal HORIZONTAL_TAB_SEPARATOR_WIDTH = 1;+static constexpr qreal HORIZONTAL_TAB_SEPARATOR_HEIGHT = 16;static constexpr int TAB_CONTENT_HORIZONTAL_INSET = 8;static constexpr int VERTICAL_TABS_HOVER_COLLAPSE_POLL_INTERVAL_MS = 250;static constexpr int TAB_PREVIEW_HOVER_DELAY_MS = 350;static constexpr int TAB_PREVIEW_THUMBNAIL_WIDTH = 320;static constexpr int TAB_PREVIEW_THUMBNAIL_HEIGHT = 180;-static constexpr int TAB_PREVIEW_SHADOW_MARGIN = 12;+// NB: The shadow falls downward, so it needs less room above the card.+static constexpr QMargins TAB_PREVIEW_SHADOW_MARGINS { 60, 36, 60, 90 };static constexpr int TAB_PREVIEW_CARD_GAP = 6;-static constexpr int TAB_BUTTON_SIZE = 22;+// A tab's close button is a smaller square than its speaker button, and both draw their icons at the same size. The+// close button takes clicks from the whole height of its tab, in a slot a little wider than its square.+static constexpr int TAB_CLOSE_BUTTON_SIZE = 18;+static constexpr QSize TAB_CLOSE_BUTTON_HIT_SIZE { 20, 28 };+static constexpr int TAB_AUDIO_BUTTON_SIZE = 20;static constexpr int TAB_BUTTON_ICON_SIZE = 14;-static constexpr qreal LOAD_SHEEN_FADE_PROGRESS = 0.15;-static constexpr int LOAD_SHEEN_DURATION_MS = 400;+static constexpr qreal TAB_BUTTON_RADIUS = 4;static constexpr int DROP_PREVIEW_DURATION_MS = 150;static constexpr int TAB_TITLE_FADE_WIDTH = 24;-static constexpr int COLLAPSED_VERTICAL_TAB_BUTTON_SIZE = 16;-static constexpr int COLLAPSED_VERTICAL_TAB_ICON_SIZE = 12;-static constexpr auto COLLAPSED_VERTICAL_TAB_BUTTON_PROPERTY = "collapsedVerticalTabButton";-static constexpr auto FULL_WIDTH_TOOLBAR_PROPERTY = "fullWidthToolbar";+// In the sidebar's rows, the speaker is a larger button with a larger icon, so that it matches the close button's weight.+static constexpr int SIDEBAR_ROW_AUDIO_BUTTON_SIZE = 22;+static constexpr int SIDEBAR_ROW_AUDIO_ICON_SIZE = 16;+static constexpr int SIDEBAR_ROW_BUTTON_GAP = 4;+// In the collapsed sidebar, the close button and the speaker are round badges on opposite corners of the favicon,+// reaching a little past them.+static constexpr int RAIL_BADGE_SIZE = 18;+static constexpr int RAIL_BADGE_CLOSE_ICON_SIZE = 12;+static constexpr int RAIL_BADGE_AUDIO_ICON_SIZE = 13;+static constexpr QPoint RAIL_BADGE_CORNER_OUTSET { 2, 1 };+// While a tab loads, its favicon shrinks to this size inside the loading ring.+static constexpr int LOADING_FAVICON_SIZE = 10;static constexpr auto VERTICAL_TABS_EXPANDED_PROPERTY = "verticalTabsExpanded";static constexpr auto VERTICAL_TABS_BUTTON_PROPERTY = "verticalTabsButton";static constexpr auto VERTICAL_TABS_POSITION_PROPERTY = "verticalTabsPosition";-static constexpr auto WINDOW_INACTIVE_PROPERTY = "windowInactive";static constexpr auto VERTICAL_TABS_RESIZE_HANDLE_HOVERED_PROPERTY = "hovered";static constexpr auto VERTICAL_TABS_RESIZE_HANDLE_ACTIVE_PROPERTY = "active";@@ -167,6 +243,17 @@ static QPointer<TabWidget> s_active_tab_drag_source;static QPointer<Tab> s_active_tab_dragged_tab;static QPointer<TabWidget> s_pending_tab_drop_target;static int s_pending_tab_drop_index { -1 };+// A tab dragged in a window of its own stays in that window's strip, rather than leaving a gap there.+static bool s_dragged_tab_has_own_window { false };++static bool compositor_moves_dragged_windows()+{+#if defined(LADYBIRD_HAS_WAYLAND_CLIENT)+ return wayland_compositor_moves_dragged_windows();+#else+ return false;+#endif+}static void show_window_context_menu(QWidget& widget, QPoint global_position){@@ -219,11 +306,6 @@ static constexpr int vertical_tab_width(int available_width, TabLayout tab_layoureturn width - vertical_tabs_horizontal_margin_width(tab_layout);}-static constexpr int clamp_vertical_tabs_expanded_width(int width)-{- return clamp(width, VERTICAL_TABS_MIN_EXPANDED_WIDTH, VERTICAL_TABS_MAX_EXPANDED_WIDTH);-}-static char const* vertical_tabs_position_property_value(WebView::VerticalTabsPosition position){switch (position) {@@ -240,38 +322,24 @@ static QRectF tab_card_shape_rect(QRectF const& rect)return rect.adjusted(TAB_CARD_SHAPE_HORIZONTAL_INSET, TAB_CARD_SHAPE_TOP_INSET, -TAB_CARD_SHAPE_HORIZONTAL_INSET, -TAB_CARD_SHAPE_BOTTOM_INSET);}-enum class TabBarEdge : u8 {- None = 0,- Left = 1 << 0,- Right = 1 << 1,-};-AK_ENUM_BITWISE_OPERATORS(TabBarEdge);--static TabBarEdge tab_bar_edges(int index, int count)+static HorizontalTabEndRoom settled_horizontal_tab_end_room(int index, int count){- auto edges = TabBarEdge::None;- if (index == 0)- edges |= TabBarEdge::Left;- if (index == count - 1)- edges |= TabBarEdge::Right;- return edges;+ return { index == 0 ? static_cast<qreal>(HORIZONTAL_TAB_END_ROOM) : 0, index == count - 1 ? static_cast<qreal>(HORIZONTAL_TAB_END_ROOM) : 0 };}-static QRectF horizontal_tab_card_shape_rect(QRectF const& rect, TabBarEdge edges = TabBarEdge::None)+static QRectF horizontal_tab_card_shape_rect(QRectF const& rect, HorizontalTabEndRoom end_room = {}){- auto left_inset = HORIZONTAL_TAB_CARD_SHAPE_HORIZONTAL_INSET + (has_flag(edges, TabBarEdge::Left) ? HORIZONTAL_TAB_END_ROOM : 0);- auto right_inset = HORIZONTAL_TAB_CARD_SHAPE_HORIZONTAL_INSET + (has_flag(edges, TabBarEdge::Right) ? HORIZONTAL_TAB_END_ROOM : 0);+ auto left_inset = HORIZONTAL_TAB_CARD_SHAPE_HORIZONTAL_INSET + end_room.left;+ auto right_inset = HORIZONTAL_TAB_CARD_SHAPE_HORIZONTAL_INSET + end_room.right;return rect.adjusted(left_inset, HORIZONTAL_TAB_CARD_SHAPE_TOP_INSET, -right_inset, -HORIZONTAL_TAB_CARD_SHAPE_BOTTOM_INSET);}-// The selected horizontal tab's outline, from the bottom of its left flare, over the top of its body, to the bottom of-// its right flare. The path is left open, so the loading swirl does not run along the bottom edge, where the tab meets-// the toolbar. Filling it closes it.+// The selected horizontal tab's outline, from the bottom of its left foot, over the top of its body, to the bottom of its+// right foot. Filling it closes it along the bottom edge, where the tab meets the toolbar.static QPainterPath horizontal_selected_tab_path(QRectF const& body){- // NB: The top corners are as round as a card's ends.- auto top_radius = HORIZONTAL_TAB_CARD_RADIUS;- auto flare = HORIZONTAL_TAB_FLARE_RADIUS;+ auto top_radius = HORIZONTAL_SELECTED_TAB_RADIUS;+ auto flare = HORIZONTAL_TAB_FOOT_RADIUS;auto left = body.left();auto right = body.right();@@ -287,45 +355,11 @@ static QPainterPath horizontal_selected_tab_path(QRectF const& body)return path;}-// The selected vertical tab's outline: Its card reaches across to the page's edge of the sidebar at x = page_edge, and-// flares out above and below into the page's frame there. As with the horizontal tab, the path is left open along the-// edge it shares with the frame, and runs clockwise, which is the way the loading swirl goes around it. Filling it closes-// it.-static QPainterPath vertical_selected_tab_path(QRectF const& card, qreal page_edge)+// The selected horizontal tab's body: the whole width of the tab, from just below its top down to the toolbar.+static QRectF horizontal_selected_tab_body_rect(QRectF const& tab_rect, HorizontalTabEndRoom end_room){- auto top = card.top();- auto bottom = card.bottom();- auto radius = card.height() / 2.0;- qreal flare = VERTICAL_TAB_FLARE_RADIUS;-- QPainterPath path;- if (page_edge > card.center().x()) {- // From the bottom of the page's edge, along the bottom, around the round end, and along the top.- path.moveTo(page_edge, bottom + flare);- path.arcTo(QRectF(page_edge - (2 * flare), bottom, 2 * flare, 2 * flare), 0, 90);- path.lineTo(card.left() + radius, bottom);- path.arcTo(QRectF(card.left(), top, 2 * radius, 2 * radius), 270, -180);- path.lineTo(page_edge - flare, top);- path.arcTo(QRectF(page_edge - (2 * flare), top - (2 * flare), 2 * flare, 2 * flare), 270, 90);- return path;- }-- // From the top of the page's edge, along the top, around the round end, and along the bottom.- path.moveTo(page_edge, top - flare);- path.arcTo(QRectF(page_edge, top - (2 * flare), 2 * flare, 2 * flare), 180, 90);- path.lineTo(card.right() - radius, top);- path.arcTo(QRectF(card.right() - (2 * radius), top, 2 * radius, 2 * radius), 90, -180);- path.lineTo(page_edge + flare, bottom);- path.arcTo(QRectF(page_edge, bottom, 2 * flare, 2 * flare), 90, 90);- return path;-}--// The new tab button lines up with the cards of the tabs beside it.-static QRectF horizontal_new_tab_button_shape_rect(QRectF const& rect)-{- auto center = horizontal_tab_card_shape_rect(rect).center();- auto half_size = HORIZONTAL_NEW_TAB_BUTTON_SHAPE_SIZE / 2.0;- return { center.x() - half_size, center.y() - half_size, HORIZONTAL_NEW_TAB_BUTTON_SHAPE_SIZE, HORIZONTAL_NEW_TAB_BUTTON_SHAPE_SIZE };+ auto card = horizontal_tab_card_shape_rect(tab_rect, end_room);+ return { card.left() - HORIZONTAL_TAB_CARD_SHAPE_HORIZONTAL_INSET, tab_rect.top() + HORIZONTAL_SELECTED_TAB_TOP_INSET, card.width() + (2 * HORIZONTAL_TAB_CARD_SHAPE_HORIZONTAL_INSET), tab_rect.height() - HORIZONTAL_SELECTED_TAB_TOP_INSET };}static QRect tab_card_shape_rect(QRect const& rect)@@ -333,55 +367,56 @@ static QRect tab_card_shape_rect(QRect const& rect)return rect.adjusted(TAB_CARD_SHAPE_HORIZONTAL_INSET, TAB_CARD_SHAPE_TOP_INSET, -TAB_CARD_SHAPE_HORIZONTAL_INSET, -TAB_CARD_SHAPE_BOTTOM_INSET);}-// When a tab finishes loading, a soft band of light sweeps across its pill from left to right.-static void paint_load_sheen(QPainter& painter, QPalette const& palette, QPainterPath const& tab_path, QRectF const& shape_rect, qreal progress)+static QColor tab_hover_surface(QPalette const& palette, qreal hover_progress){- // The bright middle of the band travels from the left edge of the tab to its right edge, so the sweep is seen to- // start at the very left. It fades out at the right edge rather than leaving the tab.- auto band_width = shape_rect.height() * 2.5;- auto center_x = shape_rect.left() + (shape_rect.width() * progress);- auto strength = min(1.0, (1.0 - progress) / LOAD_SHEEN_FADE_PROGRESS);-- // NB: The gradient runs from the top left to the bottom right of the band, which slants the band like "/".- QLinearGradient sheen(QPointF(center_x - (band_width / 2.0), shape_rect.top()), QPointF(center_x + (band_width / 2.0), shape_rect.bottom()));- auto peak = ChromeStyle::is_dark(palette) ? QColor(255, 255, 255, 46) : QColor(0, 0, 0, 14);- peak.setAlphaF(peak.alphaF() * strength);- auto clear = peak;- clear.setAlpha(0);- sheen.setColorAt(0.0, clear);- sheen.setColorAt(0.5, peak);- sheen.setColorAt(1.0, clear);-- painter.save();- painter.setClipPath(tab_path, Qt::IntersectClip);- painter.fillRect(shape_rect, sheen);- painter.restore();+ auto color = Theme::chrome(palette).hover;+ color.setAlphaF(color.alphaF() * static_cast<float>(hover_progress));+ return color;}-static QColor tab_hover_surface(QPalette const& palette, qreal hover_progress)+static QColor horizontal_tab_separator(QPalette const& palette){- auto dark = ChromeStyle::is_dark(palette);- auto color = dark ? QColor(255, 255, 255) : QColor(0, 0, 0);- color.setAlpha(static_cast<int>((dark ? 24 : 22) * hover_progress));- return color;+ return Theme::chrome(palette).separator;}-static QColor horizontal_tab_separator(QWidget const& widget)+// In the sidebar, the selected tab is raised: a card in the toolbar's color, with a fine outline and a soft shadow.+static void paint_selected_vertical_tab(QPainter& painter, QPalette const& palette, QRectF const& shape_rect, qreal radius){- auto const& palette = widget.palette();- auto dark = ChromeStyle::is_dark(palette);- auto background = ChromeStyle::chrome_tab_strip_background(palette, ChromeStyle::window_activity(widget));- return ChromeStyle::mix(background, ChromeStyle::chrome_text(palette), dark ? 0.18 : 0.25);+ // NB: On a dark sidebar a card of the toolbar's color barely stands out, so there the selected tab is lit instead,+ // and ringed with a hairline inside its edge.+ if (Theme::is_dark(palette)) {+ painter.setPen(Qt::NoPen);+ painter.setBrush(QColor(255, 255, 255, 38));+ painter.drawRoundedRect(shape_rect, radius, radius);+ painter.setPen(QPen(QColor(255, 255, 255, 26), 1));+ painter.setBrush(Qt::NoBrush);+ painter.drawRoundedRect(shape_rect.adjusted(0.5, 0.5, -0.5, -0.5), radius - 0.5, radius - 0.5);+ return;+ }++ auto shadow = QColor(0, 0, 0, 20);+ auto outline = QColor(0, 0, 0, 15);++ painter.setPen(Qt::NoPen);+ // NB: The shadow falls 1 px down and blurs 2 px, drawn as two layers.+ auto shadow_rect = shape_rect.translated(0, 1);+ painter.setBrush(QColor(shadow.red(), shadow.green(), shadow.blue(), shadow.alpha() / 2));+ painter.drawRoundedRect(shadow_rect.adjusted(-1, -1, 1, 1), radius + 1, radius + 1);+ painter.drawRoundedRect(shadow_rect, radius, radius);+ painter.setBrush(outline);+ painter.drawRoundedRect(shape_rect.adjusted(-1, -1, 1, 1), radius + 1, radius + 1);+ painter.setBrush(Theme::chrome(palette).toolbar);+ painter.drawRoundedRect(shape_rect, radius, radius);}static QRectF collapsed_vertical_tab_shape_rect(QRectF const& rect){- return rect.adjusted(4.0, TAB_CARD_SHAPE_TOP_INSET, -4.0, -TAB_CARD_SHAPE_BOTTOM_INSET);+ return rect.adjusted(COLLAPSED_VERTICAL_TAB_CARD_INSET, TAB_CARD_SHAPE_TOP_INSET, -COLLAPSED_VERTICAL_TAB_CARD_INSET, -TAB_CARD_SHAPE_BOTTOM_INSET);}static QRect collapsed_vertical_tab_shape_rect(QRect const& rect){- return rect.adjusted(4, TAB_CARD_SHAPE_TOP_INSET, -4, -TAB_CARD_SHAPE_BOTTOM_INSET);+ return rect.adjusted(COLLAPSED_VERTICAL_TAB_CARD_INSET, TAB_CARD_SHAPE_TOP_INSET, -COLLAPSED_VERTICAL_TAB_CARD_INSET, -TAB_CARD_SHAPE_BOTTOM_INSET);}class NewTabButton final : public QToolButton {@@ -407,6 +442,14 @@ private:update();}+ // NB: On the strip, the new tab button's fill is smaller than the button, which takes clicks from around it too.+ QRectF horizontal_button_fill_rect() const+ {+ if (objectName() != "LadybirdNewTabButton")+ return QRectF(rect());+ return { (width() - HORIZONTAL_NEW_TAB_BUTTON_FILL_SIZE) / 2.0, (height() - HORIZONTAL_NEW_TAB_BUTTON_FILL_SIZE) / 2.0, HORIZONTAL_NEW_TAB_BUTTON_FILL_SIZE, HORIZONTAL_NEW_TAB_BUTTON_FILL_SIZE };+ }+virtual void paintEvent(QPaintEvent* event) override{if (!property(VERTICAL_TABS_BUTTON_PROPERTY).toBool()) {@@ -419,57 +462,40 @@ private:QPainter painter(this);painter.setRenderHint(QPainter::Antialiasing, true);- auto dark = ChromeStyle::is_dark(palette());auto is_horizontal_new_tab_button = m_tab_bar.tab_layout() == TabLayout::Horizontal;auto shape_rect = expanded? tab_card_shape_rect(QRectF(rect())): (is_horizontal_new_tab_button- ? horizontal_new_tab_button_shape_rect(QRectF(rect()))- : QRectF(rect()).adjusted(4.0, TAB_CARD_SHAPE_TOP_INSET, -4.0, -TAB_CARD_SHAPE_BOTTOM_INSET));- // NB: The horizontal new tab button's shape is square, so this pill is a circle.+ ? horizontal_button_fill_rect()+ : collapsed_vertical_tab_shape_rect(QRectF(rect())));+ // NB: The horizontal new tab button is a rounded square like the toolbar's buttons, while the sidebar's is rounded+ // like the tabs above it.+ auto radius = is_horizontal_new_tab_button ? HORIZONTAL_NEW_TAB_BUTTON_RADIUS : (expanded ? VERTICAL_TAB_RADIUS : COLLAPSED_VERTICAL_TAB_RADIUS);QPainterPath tab_path;- tab_path.addRoundedRect(shape_rect, shape_rect.height() / 2.0, shape_rect.height() / 2.0);+ tab_path.addRoundedRect(shape_rect, radius, radius);// NB: Hovered and pressed, the button looks like the toolbar's buttons, though in the shape of a tab.auto hovered = underMouse() && rect().contains(mapFromGlobal(QCursor::pos()));- if (auto colors = ChromeStyle::circular_control_frame_colors(*this); colors.has_value()) {+ if (auto colors = ChromeStyle::control_frame_colors(*this); colors.has_value()) {// NB: Hovered but not pressed, it lights up like the tabs beside it.if (hovered && !isDown())- colors->background = tab_hover_surface(palette(), 1.0);+ colors->background = tab_hover_surface(Theme::chrome_palette(*this), 1.0);painter.setBrush(colors->background);painter.setPen(colors->border.alpha() > 0 ? QPen(colors->border, 1) : QPen(Qt::NoPen));painter.drawPath(tab_path);}- auto contents_rect = shape_rect.toAlignedRect().adjusted(TAB_CONTENT_HORIZONTAL_INSET, 0, -TAB_CONTENT_HORIZONTAL_INSET, 0);- auto icon_size = QSize(TAB_ICON_SIZE, TAB_ICON_SIZE);+ auto contents_rect = shape_rect.toAlignedRect().adjusted(VERTICAL_TAB_CONTENT_LEADING_INSET, 0, -TAB_CONTENT_HORIZONTAL_INSET, 0);+ // NB: The buttons on the strip draw their icons at their own sizes.+ auto icon_size = is_horizontal_new_tab_button ? iconSize() : QSize(TAB_ICON_SIZE, TAB_ICON_SIZE);QRect icon_rect {- expanded ? contents_rect.left() - ((icon_size.width() - TAB_ICON_SIZE) / 2) : rect().center().x() - (icon_size.width() / 2),+ expanded ? contents_rect.left() - ((icon_size.width() - TAB_ICON_SIZE) / 2) : (is_horizontal_new_tab_button ? (width() - icon_size.width()) / 2 : rect().center().x() - (icon_size.width() / 2)),contents_rect.top() + ((contents_rect.height() - icon_size.height()) / 2),icon_size.width(),icon_size.height(),};- if (is_horizontal_new_tab_button) {- painter.translate(0.5, 0);- } else if (!expanded) {+ if (!is_horizontal_new_tab_button && !expanded)painter.translate(1.0, 0);- }icon().paint(&painter, icon_rect);- if (!expanded)- return;-- contents_rect.setLeft(icon_rect.right() + 8);-- auto text_color = ChromeStyle::mix(ChromeStyle::chrome_button_text(palette()), ChromeStyle::chrome_muted_text(palette()), dark ? 0.26 : 0.40);- if (hovered || isDown())- text_color = ChromeStyle::chrome_button_text(palette());- painter.setPen(text_color);- auto text_font = ChromeStyle::chrome_title_font(m_tab_bar.font());- painter.setFont(text_font);-- QFontMetrics font_metrics(text_font);- auto title = font_metrics.elidedText(text(), Qt::ElideRight, max(0, contents_rect.width()));- contents_rect.translate(0, -1);- painter.drawText(contents_rect, Qt::AlignLeft | Qt::AlignVCenter, title);}TabBar& m_tab_bar;@@ -488,7 +514,7 @@ private:initStyleOption(&option);QStylePainter painter(this);- ChromeStyle::paint_circular_control_frame(painter, *this);+ ChromeStyle::paint_control_frame(painter, *this);painter.drawComplexControl(QStyle::CC_ToolButton, option);}};@@ -557,23 +583,21 @@ public:AK_ALLOC_WITH_KMALLOC;explicit TabPreviewPopup(QWidget* parent)- : QWidget(parent, Qt::ToolTip | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint)+ // NB: The preview only shows, and the room around it for its shadow lies over the tabs, so it lets the mouse through.+ : QWidget(parent, Qt::ToolTip | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint | Qt::WindowTransparentForInput){setAttribute(Qt::WA_TranslucentBackground);setAttribute(Qt::WA_ShowWithoutActivating);+ setAttribute(Qt::WA_TransparentForMouseEvents);auto* outer_layout = new QVBoxLayout(this);- outer_layout->setContentsMargins(TAB_PREVIEW_SHADOW_MARGIN, TAB_PREVIEW_SHADOW_MARGIN, TAB_PREVIEW_SHADOW_MARGIN, TAB_PREVIEW_SHADOW_MARGIN);+ outer_layout->setContentsMargins(TAB_PREVIEW_SHADOW_MARGINS);outer_layout->setSpacing(0);m_card = new QFrame(this);m_card->setObjectName("LadybirdTabPreviewCard");- auto* shadow = new QGraphicsDropShadowEffect(m_card);- shadow->setBlurRadius(28);- shadow->setOffset(0, 8);- shadow->setColor(QColor(0, 0, 0, 92));- m_card->setGraphicsEffect(shadow);+ cast_popover_shadow(*m_card);auto* card_layout = new QVBoxLayout(m_card);card_layout->setContentsMargins(10, 10, 10, 10);@@ -654,19 +678,65 @@ QLabel#LadybirdTabPreviewURL {{class TabDragCancellationFilter final : public QObject {public:+ AK_ALLOC_WITH_KMALLOC;++ TabDragCancellationFilter() = default;+ explicit TabDragCancellationFilter(Function<void()> on_cancel)+ : m_on_cancel(move(on_cancel))+ {+ }+bool was_canceled() const { return m_was_canceled; }private:virtual bool eventFilter(QObject*, QEvent* event) override{- if (event->type() == QEvent::KeyPress && static_cast<QKeyEvent*>(event)->key() == Qt::Key_Escape)+ // NB: Escape is also a shortcut, which would take the key before it is pressed in any widget.+ if (event->type() != QEvent::KeyPress && event->type() != QEvent::ShortcutOverride)+ return false;+ if (static_cast<QKeyEvent*>(event)->key() != Qt::Key_Escape)+ return false;+ if (!m_on_cancel) {m_was_canceled = true;- return false;+ return false;+ }+ // NB: Accepting the shortcut override has Escape pressed as a key, which is where the drag is canceled. That key+ // press is then taken, so it doesn't also reach the page or the address field.+ event->accept();+ if (event->type() == QEvent::ShortcutOverride)+ return true;+ m_was_canceled = true;+ m_on_cancel();+ return true;}+ Function<void()> m_on_cancel;bool m_was_canceled { false };};+// The card a tab dragged within its strip is drawn as, above the rest of the window.+class TabDragCard final : public QWidget {+public:+ AK_ALLOC_WITH_KMALLOC;++ TabDragCard(QWidget& parent, QPixmap pixmap)+ : QWidget(&parent)+ , m_pixmap(AK::move(pixmap))+ {+ setAttribute(Qt::WA_TransparentForMouseEvents);+ resize(m_pixmap.deviceIndependentSize().toSize());+ }++private:+ virtual void paintEvent(QPaintEvent*) override+ {+ QPainter painter(this);+ painter.drawPixmap(0, 0, m_pixmap);+ }++ QPixmap m_pixmap;+};+TabBar::TabBar(TabWidget* tab_widget): QTabBar(tab_widget), m_tab_widget(tab_widget)@@ -678,6 +748,17 @@ TabBar::TabBar(TabWidget* tab_widget)setMinimumHeight(HORIZONTAL_TAB_HEIGHT);recreate_icons();+ m_tab_width_unlock_timer = new QTimer(this);+ m_tab_width_unlock_timer->setSingleShot(true);+ m_tab_width_unlock_timer->setInterval(TAB_WIDTH_UNLOCK_DELAY_MS);+ QObject::connect(m_tab_width_unlock_timer, &QTimer::timeout, this, [this] {+ m_locked_tab_width = {};+ // NB: QTabBar keeps its tabs' sizes until something changes them, and a font change is what lays them out anew.+ QEvent font_change(QEvent::FontChange);+ changeEvent(&font_change);+ refresh_tab_layout();+ });+m_tab_preview_timer = new QTimer(this);m_tab_preview_timer->setInterval(TAB_PREVIEW_HOVER_DELAY_MS);m_tab_preview_timer->setSingleShot(true);@@ -685,30 +766,39 @@ TabBar::TabBar(TabWidget* tab_widget)m_tab_preview_popup = new TabPreviewPopup(this);- m_loading_swirl_animation = new QVariantAnimation(this);- m_loading_swirl_animation->setDuration(ChromeStyle::LOADING_SWIRL_PERIOD_MS);- m_loading_swirl_animation->setStartValue(0.0);- m_loading_swirl_animation->setEndValue(1.0);- m_loading_swirl_animation->setLoopCount(-1);- // NB: Each frame repaints only the loading tabs, and checks again, so the swirl also stops when the last loading tab- // is closed.- connect(m_loading_swirl_animation, &QVariantAnimation::valueChanged, this, [this] {+ // While the preview shows, the pointer's moves over the tab bar and out of it are followed by where it is.+ m_tab_preview_pointer_timer = new QTimer(this);+ m_tab_preview_pointer_timer->setInterval(50);+ connect(m_tab_preview_pointer_timer, &QTimer::timeout, this, [this] {+ auto position = mapFromGlobal(QCursor::pos());+ if (rect().contains(position))+ set_hovered_tab_index(tab_index_at(position));+ else+ pointer_left();+ });++ m_loading_ring_animation = new QVariantAnimation(this);+ m_loading_ring_animation->setDuration(ChromeStyle::LOADING_RING_PERIOD_MS);+ m_loading_ring_animation->setStartValue(0.0);+ m_loading_ring_animation->setEndValue(1.0);+ m_loading_ring_animation->setLoopCount(-1);+ // NB: Each frame repaints only the loading tabs, and checks again, so the ring also stops turning when the last loading+ // tab is closed.+ connect(m_loading_ring_animation, &QVariantAnimation::valueChanged, this, [this] {auto any_tab_loading = false;for (int index = 0; index < count(); ++index) {- if (!is_tab_loading(index))+ if (loading_ring_opacity(index) <= 0)continue;any_tab_loading = true;- // NB: The selected horizontal tab's flares, which the swirl runs along, reach past its rect.- auto flare = qCeil(HORIZONTAL_TAB_FLARE_RADIUS);- update(visual_tab_rect(index).adjusted(-flare, 0, flare, 0));+ update(visual_tab_rect(index));}if (!any_tab_loading || !isVisible())- update_loading_swirl_animation();+ update_loading_ring_animation();});m_hover_animation = new QVariantAnimation(this);- m_hover_animation->setDuration(120);- m_hover_animation->setEasingCurve(QEasingCurve::OutCubic);+ m_hover_animation->setDuration(Motion::FAST);+ m_hover_animation->setEasingCurve(Motion::enter_easing());connect(m_hover_animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {m_hover_progress = value.toReal();update();@@ -718,6 +808,65 @@ TabBar::TabBar(TabWidget* tab_widget)m_hover_animation_tab_index = -1;});+ m_selection_animation = new QVariantAnimation(this);+ m_selection_animation->setDuration(Motion::FAST);+ m_selection_animation->setEasingCurve(Motion::enter_easing());+ m_selection_animation->setStartValue(0.0);+ m_selection_animation->setEndValue(1.0);+ connect(m_selection_animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ m_selection_progress = value.toReal();+ update_tab_button_geometry();+ update();+ });+ // NB: The tab the selection moved from is kept until the tabs have also settled, as the lines beside it stay hidden+ // until then.+ connect(m_selection_animation, &QVariantAnimation::finished, this, [this] {+ if (m_layout_animation_progress >= 1.0)+ m_previously_selected_tab = nullptr;+ update();+ });+ QPointer<Tab> selected_tab;+ connect(this, &QTabBar::currentChanged, this, [this, selected_tab](int index) mutable {+ auto* tab = m_tab_widget ? m_tab_widget->tab(index) : nullptr;+ // NB: A selection that moves because its tab closed fades from the picture of the closing tab, if there is one.+ m_previously_selected_tab = selected_tab;+ selected_tab = tab;+ if ((!m_previously_selected_tab && !m_closing_tab.has_value()) || !isVisible()) {+ m_selection_animation->stop();+ m_selection_progress = 1.0;+ return;+ }+ m_selection_animation->stop();+ // NB: The animation only reports its start value on its first step, after the tab bar may have repainted.+ m_selection_progress = 0.0;+ m_selection_animation->start();+ });++ m_layout_animation = new QVariantAnimation(this);+ m_layout_animation->setDuration(Motion::BASE);+ m_layout_animation->setEasingCurve(Motion::move_easing());+ m_layout_animation->setStartValue(0.0);+ m_layout_animation->setEndValue(1.0);+ connect(m_layout_animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ m_layout_animation_progress = value.toReal();+ update_tab_button_geometry();+ if (m_tab_widget) {+ // NB: While tabs close, the tabs after them slide back from beyond where the tabs will end, so the bar+ // keeps room for them.+ if (horizontal_tabs_end_offset() > 0 || m_layout_animation_progress >= 1.0)+ m_tab_widget->update_tab_layout();+ else+ m_tab_widget->place_horizontal_new_tab_button();+ }+ update();+ });+ connect(m_layout_animation, &QVariantAnimation::finished, this, [this] {+ m_closing_tab.clear();+ if (m_selection_animation->state() != QAbstractAnimation::Running)+ m_previously_selected_tab = nullptr;+ update();+ });+m_drop_preview_animation = new QVariantAnimation(this);m_drop_preview_animation->setDuration(DROP_PREVIEW_DURATION_MS);m_drop_preview_animation->setEasingCurve(QEasingCurve::OutCubic);@@ -752,6 +901,8 @@ void TabBar::set_tab_layout(TabLayout tab_layout)return;m_tab_layout = tab_layout;+ m_scroll_offset = 0;+ m_locked_tab_width = {};if (m_tab_layout == TabLayout::Horizontal) {setShape(QTabBar::RoundedNorth);@@ -759,7 +910,6 @@ void TabBar::set_tab_layout(TabLayout tab_layout)setMaximumWidth(QWIDGETSIZE_MAX);setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);setUsesScrollButtons(false);- set_vertical_scroll_offset(0);} else {setShape(vertical_tabs_are_on_right() ? QTabBar::RoundedEast : QTabBar::RoundedWest);setMinimumSize({ 0, 0 });@@ -792,9 +942,28 @@ void TabBar::set_vertical_tabs_position(WebView::VerticalTabsPosition position)refresh_tab_layout();}+void TabBar::lock_tab_widths()+{+ if (tab_layout() != TabLayout::Horizontal)+ return;++ auto pinned_count = pinned_tab_count();+ if (pinned_count >= count())+ return;++ // NB: Only an unpinned tab between the first and the last has no room for a foot.+ auto end_room = (pinned_count == 0 ? HORIZONTAL_TAB_END_ROOM : 0) + (pinned_count == count() - 1 ? HORIZONTAL_TAB_END_ROOM : 0);+ m_locked_tab_width = tabRect(pinned_count).width() - end_room;+ m_tab_width_unlock_timer->stop();+}+void TabBar::refresh_tab_layout(){- set_vertical_scroll_offset(m_vertical_scroll_offset);+ // NB: Qt lays the tabs out only as the bar resizes, but their size can change while the bar's does not, such as when+ // the sidebar collapses to the width its tab bar had in the open layout.+ QResizeEvent resize_event(size(), size());+ QTabBar::resizeEvent(&resize_event);+ set_scroll_offset(m_scroll_offset);updateGeometry();update_tab_button_geometry();update();@@ -818,7 +987,7 @@ int TabBar::pinned_tab_count() constvoid TabBar::recreate_icons(){- m_fallback_tab_icon = create_chrome_icon(ChromeIcon::Globe, palette());+ m_fallback_tab_icon = create_chrome_icon(ChromeIcon::Globe, Theme::chrome_palette(*this));update();}@@ -833,7 +1002,7 @@ QSize TabBar::minimumSizeHint() const{// However many tabs are pinned, one row is enough: Pinned tabs that don't fit in half the bar scroll with the rest.if (tab_layout() != TabLayout::Horizontal)- return { vertical_tab_width(m_available_width, tab_layout()), count() > 0 ? (2 * VERTICAL_TAB_FLARE_RADIUS) + VERTICAL_TAB_HEIGHT : 0 };+ return { vertical_tab_width(m_available_width, tab_layout()), count() > 0 ? (2 * VERTICAL_TAB_BAR_END_ROOM) + VERTICAL_TAB_HEIGHT : 0 };return QTabBar::minimumSizeHint();}@@ -849,16 +1018,22 @@ QSize TabBar::tabSizeHint(int index) constif (auto count = this->count(); count > 0) {auto pinned_count = pinned_tab_count();- // The first and last tabs also take room for their flares at the ends of the tab bar.+ // The first and last tabs also take room for their feet at the ends of the tab bar.auto end_room = (index == 0 ? HORIZONTAL_TAB_END_ROOM : 0) + (index == count - 1 ? HORIZONTAL_TAB_END_ROOM : 0);if (index < pinned_count) {- hint.setWidth(PINNED_TAB_TILE_WIDTH + end_room);+ hint.setWidth(HORIZONTAL_PINNED_TAB_WIDTH + end_room);+ hint.setHeight(HORIZONTAL_TAB_HEIGHT);+ return hint;+ }++ if (m_locked_tab_width.has_value()) {+ hint.setWidth(*m_locked_tab_width + end_room);hint.setHeight(HORIZONTAL_TAB_HEIGHT);return hint;}// The unpinned tabs share whatever width the pinned tiles and the room at the ends leave.- auto available_width = (m_available_width > 0 ? m_available_width : this->width()) - (pinned_count * PINNED_TAB_TILE_WIDTH) - (2 * HORIZONTAL_TAB_END_ROOM);+ auto available_width = (m_available_width > 0 ? m_available_width : this->width()) - (pinned_count * HORIZONTAL_PINNED_TAB_WIDTH) - (2 * HORIZONTAL_TAB_END_ROOM);auto width = available_width / max(1, count - pinned_count);width = min(HORIZONTAL_TAB_MAX_WIDTH, width);width = max(HORIZONTAL_TAB_MIN_WIDTH, width);@@ -874,7 +1049,7 @@ void TabBar::resizeEvent(QResizeEvent* event){hide_tab_preview();QTabBar::resizeEvent(event);- set_vertical_scroll_offset(m_vertical_scroll_offset);+ set_scroll_offset(m_scroll_offset);ensure_tab_visible(currentIndex());update_tab_button_geometry();}@@ -882,7 +1057,8 @@ void TabBar::resizeEvent(QResizeEvent* event)void TabBar::tabLayoutChange(){QTabBar::tabLayoutChange();- set_vertical_scroll_offset(m_vertical_scroll_offset);+ update_layout_animation();+ set_scroll_offset(m_scroll_offset);update_tab_button_geometry();if (m_tab_preview_index < 0)@@ -907,9 +1083,9 @@ bool TabBar::event(QEvent* event)if (event->type() == QEvent::WindowActivate || event->type() == QEvent::WindowDeactivate)update();- // The swirl stops while the tab bar is hidden, so it has to start again for tabs still loading when it is shown.+ // The ring stops turning while the tab bar is hidden, so it has to start again for tabs still loading when it is shown.if (event->type() == QEvent::Show)- update_loading_swirl_animation();+ update_loading_ring_animation();if (event->type() == QEvent::ToolTip) {auto* help_event = static_cast<QHelpEvent*>(event);@@ -922,6 +1098,19 @@ bool TabBar::event(QEvent* event)}}}++ // The selected tab shows no preview, so a title too long for it shows in full, with the site, in a tooltip.+ if (hovered_tab >= 0 && hovered_tab == currentIndex()) {+ auto* tab = m_tab_widget ? m_tab_widget->tab(hovered_tab) : nullptr;+ if (tab && m_tabs_with_cut_titles.contains(tab)) {+ auto text = tabText(hovered_tab);+ if (auto host = tab->view().url().serialized_host(); !host.is_empty())+ text = qformatted("{}\n{}", ak_string_from_qstring(text), host);+ QToolTip::showText(help_event->globalPos(), text, this, tabRect(hovered_tab));+ event->accept();+ return true;+ }+ }}return QTabBar::event(event);@@ -932,12 +1121,12 @@ void TabBar::paintEvent(QPaintEvent*)QPainter painter(this);painter.setRenderHint(QPainter::Antialiasing, true);- auto dark = ChromeStyle::is_dark(palette());- auto text_color = ChromeStyle::chrome_text(palette());auto is_vertical = tab_layout() != TabLayout::Horizontal;auto is_collapsed_vertical = tab_layout() == TabLayout::VerticalCollapsed;auto dragged_index = dragged_tab_index();auto hover_progress_of = [&](int index) {+ if (index == m_tab_painted_unselected)+ return 0.0;return index == m_hover_animation_tab_index ? m_hover_progress : (index == m_hovered_tab_index ? 1.0 : 0.0);};auto region = pinned_region();@@ -946,7 +1135,7 @@ void TabBar::paintEvent(QPaintEvent*)auto pinned_region_growth = qRound(current_pinned_region_growth());auto fixed_height = region.scrolls ? 0 : region.height + pinned_region_growth;// NB: Without pinned tabs in the way, the unpinned tabs also use the room above them.- auto unpinned_clip_top = fixed_height > 0 ? VERTICAL_TAB_FLARE_RADIUS + fixed_height : 0;+ auto unpinned_clip_top = fixed_height > 0 ? VERTICAL_TAB_BAR_END_ROOM + fixed_height : 0;QRect unpinned_clip { 0, unpinned_clip_top, width(), max(0, height() - unpinned_clip_top) };// Titles are shaped once and kept for as long as some tab shows them, since resizing the window repaints the tab@@ -957,20 +1146,37 @@ void TabBar::paintEvent(QPaintEvent*)m_tab_title_texts_font = title_font;}QHash<QString, QStaticText> title_texts;+ HashTable<Tab const*> tabs_with_cut_titles;auto title_line_height = QFontMetricsF(title_font).height();+ if (auto rect = closing_tab_rect(); !rect.isEmpty()) {+ painter.save();+ // NB: The closing tab narrows from its end, which is rounded like the top corners of a tab. Its bottom reaches+ // past the clip's rounded corners, as the selected tab joins the toolbar there.+ QPainterPath clip;+ clip.addRoundedRect(QRectF(rect).adjusted(0, 0, 0, HORIZONTAL_SELECTED_TAB_RADIUS), HORIZONTAL_SELECTED_TAB_RADIUS, HORIZONTAL_SELECTED_TAB_RADIUS);+ painter.setClipPath(clip);+ // The closing tab fades out well before the gap it leaves closes, so none of it is seen cut short.+ painter.setOpacity(max(0.0, 1.0 - (m_layout_animation_progress / CLOSING_TAB_FADE_PORTION)));+ painter.drawPixmap(rect.topLeft(), m_closing_tab->image);+ painter.restore();+ }++ auto previously_selected_index = m_previously_selected_tab && m_tab_widget ? m_tab_widget->index_of(m_previously_selected_tab) : -1;for (int index = 0; index < count(); ++index) {// The tab being dragged follows the cursor as the drag's image, leaving a gap where it would be dropped.if (index == dragged_index)continue;- // Unpinned tabs scroll under the pinned ones, so they never paint over them. The clips that each tab's sheen- // and title set later intersect with this one, rather than replacing it.+ // Unpinned tabs scroll under the pinned ones, so they never paint over them. The clips that each tab's title sets+ // later intersect with this one, rather than replacing it.if (is_vertical) {if (index >= pinned_count)painter.setClipRect(unpinned_clip);elsepainter.setClipping(false);+ } else {+ painter.setClipping(false);}auto tab_rect = shifted_tab_rect(index);@@ -982,6 +1188,7 @@ void TabBar::paintEvent(QPaintEvent*)continue;bool is_selected = index == currentIndex();+ auto selection = selection_of(index);auto hover_progress = hover_progress_of(index);bool is_hovered = hover_progress > 0.0;// A pinned tab is a tile that shows only its favicon, except where the pinned tabs keep their rows.@@ -991,65 +1198,119 @@ void TabBar::paintEvent(QPaintEvent*)if (is_collapsed_vertical)shape_rect = collapsed_vertical_tab_shape_rect(QRectF(tab_rect));else if (!is_vertical)- shape_rect = horizontal_tab_card_shape_rect(QRectF(tab_rect), tab_bar_edges(index, count()));+ shape_rect = horizontal_tab_card_shape_rect(QRectF(tab_rect), horizontal_tab_end_room(index));elseshape_rect = tab_card_shape_rect(QRectF(tab_rect));+ QRectF horizontal_body_rect;+ if (!is_vertical)+ horizontal_body_rect = horizontal_selected_tab_body_rect(QRectF(tab_rect), horizontal_tab_end_room(index));QPainterPath tab_path;- if (!is_vertical && is_selected)- tab_path = horizontal_selected_tab_path(QRectF(shape_rect.left(), shape_rect.top(), shape_rect.width(), tab_rect.bottom() + 1 - shape_rect.top()));- else if (is_selected && !is_pinned_tile)- tab_path = vertical_selected_tab_path(shape_rect, vertical_tabs_are_on_right() ? 0.0 : static_cast<qreal>(width()));- else- tab_path.addRoundedRect(shape_rect, shape_rect.height() / 2.0, shape_rect.height() / 2.0);+ // NB: A tab too narrow for the selected tab's rounded corners, such as one just opening, has no room for its shape.+ if (!is_vertical && selection > 0.0 && horizontal_body_rect.width() < 2 * HORIZONTAL_SELECTED_TAB_RADIUS)+ selection = 0.0;+ if (!is_vertical && selection > 0.0)+ tab_path = horizontal_selected_tab_path(horizontal_body_rect);+ else if (!is_vertical)+ tab_path.addRoundedRect(shape_rect, HORIZONTAL_TAB_CARD_RADIUS, HORIZONTAL_TAB_CARD_RADIUS);+ auto vertical_tab_radius = is_collapsed_vertical ? COLLAPSED_VERTICAL_TAB_RADIUS : VERTICAL_TAB_RADIUS;+ if (is_vertical)+ tab_path.addRoundedRect(shape_rect, vertical_tab_radius, vertical_tab_radius);- // Horizontal tabs are divided by lines, except around the selected tab and the hovered one.+ // Horizontal tabs are divided by lines, except around the selected tab and the hovered one, and between pinned+ // tabs. The last tab has none after it.if (!is_vertical) {auto next_index = index + 1;- auto next_is_selected = next_index == currentIndex();- auto separator_opacity = 1.0 - max(hover_progress, hover_progress_of(next_index));- if (!is_selected && !next_is_selected && separator_opacity > 0.0) {+ auto next_is_pinned = next_index < pinned_count;+ // NB: The lines beside the tabs the selection moves between stay hidden until the tabs have settled, so none+ // shows over a tab still being selected or not, nor over one opening or closing.+ auto selection_is_settling = m_selection_animation->state() == QAbstractAnimation::Running || m_layout_animation_progress < 1.0;+ auto beside_selection_change = selection > 0.0 || selection_of(next_index) > 0.0 || index == previously_selected_index || next_index == previously_selected_index;+ auto separator_opacity = selection_is_settling && beside_selection_change ? 0.0 : 1.0 - max(hover_progress, hover_progress_of(next_index));+ if (next_index < count() && index != currentIndex() && next_index != currentIndex() && !next_is_pinned && separator_opacity > 0.0) {auto separator_center_y = shape_rect.center().y();- // NB: The separator sits as far from the card as the edge between two tabs, which is also where it sits after- // the last tab, whose room for its flare lies beyond. This keeps it on whole device pixels at a pixel- // ratio of 2.+ // NB: The separator sits just inside the edge between two tabs. This keeps it on whole device pixels.auto separator_x = shape_rect.right() + HORIZONTAL_TAB_CARD_SHAPE_HORIZONTAL_INSET - 1;QRectF separator_rect { separator_x, separator_center_y - (HORIZONTAL_TAB_SEPARATOR_HEIGHT / 2.0), HORIZONTAL_TAB_SEPARATOR_WIDTH, HORIZONTAL_TAB_SEPARATOR_HEIGHT };painter.save();painter.setOpacity(separator_opacity);- painter.fillRect(separator_rect, horizontal_tab_separator(*this));+ painter.fillRect(separator_rect, horizontal_tab_separator(Theme::chrome_palette(*this)));painter.restore();}}- if (!is_vertical && is_selected) {- painter.setPen(Qt::NoPen);- painter.setBrush(ChromeStyle::chrome_active_tab_surface(palette()));- painter.drawPath(tab_path);- } else if (is_selected) {+ if (selection < 1.0 && is_hovered) {+ QPainterPath hover_path;+ if (!is_vertical)+ hover_path.addRoundedRect(shape_rect, HORIZONTAL_TAB_CARD_RADIUS, HORIZONTAL_TAB_CARD_RADIUS);+ else+ hover_path = tab_path;+ painter.setBrush(tab_hover_surface(Theme::chrome_palette(*this), hover_progress));painter.setPen(Qt::NoPen);- painter.setBrush(ChromeStyle::chrome_active_tab_surface(palette()));- painter.drawPath(tab_path);- } else if (is_hovered) {- painter.setBrush(tab_hover_surface(palette(), hover_progress));+ painter.drawPath(hover_path);+ } else if (selection < 1.0 && is_vertical && !is_collapsed_vertical && is_pinned_tile) {+ // The pinned tiles at the top of the sidebar are always filled, so they read as a grid of buttons.+ painter.setBrush(tab_hover_surface(Theme::chrome_palette(*this), 1.0));painter.setPen(Qt::NoPen);painter.drawPath(tab_path);}+ if (selection > 0.0) {+ painter.save();+ painter.setOpacity(selection);+ if (is_vertical) {+ paint_selected_vertical_tab(painter, Theme::chrome_palette(*this), shape_rect, vertical_tab_radius);+ } else {+ painter.setPen(Qt::NoPen);+ painter.setBrush(ChromeStyle::chrome_active_tab_surface(Theme::chrome_palette(*this)));+ painter.drawPath(tab_path);+ }+ painter.restore();+ }- if (is_tab_loading(index))- ChromeStyle::paint_loading_swirl(painter, tab_path);- if (auto progress = load_sheen_progress(index); progress.has_value())- paint_load_sheen(painter, palette(), tab_path, tab_path.boundingRect(), *progress);+ auto ring_opacity = loading_ring_opacity(index);auto icon = tabIcon(index);+ auto* tab_for_index = m_tab_widget ? m_tab_widget->tab(index) : nullptr;+ auto needs_attention = tab_for_index && tab_for_index->needs_attention() && !is_selected;+ auto favicon_shrink = tab_for_index ? tab_for_index->loading_favicon_shrink() : 0;auto paint_icon = [&](QRect const& icon_rect) {- if (!icon.isNull()) {- icon.paint(&painter, icon_rect);- return;+ if (ring_opacity > 0) {+ painter.save();+ painter.setOpacity(ring_opacity);+ ChromeStyle::paint_loading_ring(painter, Theme::chrome_palette(*this), QRectF(icon_rect).center(), tab_for_index && tab_for_index->is_waiting_for_response() ? ChromeStyle::LoadingPhase::WaitingForResponse : ChromeStyle::LoadingPhase::Receiving);+ painter.restore();}// NB: The fallback globe is drawn on a chrome icon's larger canvas, with room around it, so it is painted at// that size to be about as large as a favicon.auto overhang = (CHROME_ICON_CANVAS_SIZE - TAB_ICON_SIZE) / 2;- m_fallback_tab_icon.paint(&painter, icon_rect.adjusted(-overhang, -overhang, overhang, overhang));+ auto const& shown_icon = icon.isNull() ? m_fallback_tab_icon : icon;+ auto shown_rect = icon.isNull() ? icon_rect.adjusted(-overhang, -overhang, overhang, overhang) : icon_rect;+ if (favicon_shrink > 0) {+ // While the tab loads, the favicon shrinks to fit inside the ring, so a square favicon never touches it.+ auto scale = 1 - ((1 - (static_cast<qreal>(LOADING_FAVICON_SIZE) / TAB_ICON_SIZE)) * favicon_shrink);+ auto pixmap = shown_icon.pixmap(shown_rect.size(), devicePixelRatioF());+ QRectF target { QPointF(), QSizeF(shown_rect.size()) * scale };+ target.moveCenter(QRectF(shown_rect).center());+ painter.save();+ painter.setRenderHint(QPainter::SmoothPixmapTransform);+ painter.drawPixmap(target, pixmap, QRectF(pixmap.rect()));+ painter.restore();+ } else {+ shown_icon.paint(&painter, shown_rect);+ }++ // A tab with news has a dot on its favicon's corner, cut out of the strip around it.+ if (needs_attention) {+ QPointF dot_center { icon_rect.right() + 0.5, icon_rect.bottom() + 0.5 };+ painter.save();+ painter.setRenderHint(QPainter::Antialiasing);+ painter.setPen(Qt::NoPen);+ auto backing = is_vertical ? ChromeStyle::chrome_sidebar_background(Theme::chrome_palette(*this)) : ChromeStyle::chrome_tab_strip_background(Theme::chrome_palette(*this));+ painter.setBrush(is_hovered ? tab_hover_surface(Theme::chrome_palette(*this), 1.0) : backing);+ painter.drawEllipse(dot_center, ATTENTION_DOT_RADIUS + 1.5, ATTENTION_DOT_RADIUS + 1.5);+ painter.setBrush(Theme::accent());+ painter.drawEllipse(dot_center, ATTENTION_DOT_RADIUS, ATTENTION_DOT_RADIUS);+ painter.restore();+ }};if (is_collapsed_vertical || is_pinned_tile) {@@ -1057,26 +1318,37 @@ void TabBar::paintEvent(QPaintEvent*)if (is_pinned_tile && tabButton(index, QTabBar::LeftSide))continue;- // NB: A QRect's center is rounded down, so add 1 to center the icon in the tab.- auto icon_center = is_vertical ? QPointF(tab_rect.center() + QPoint(1, 1)) : shape_rect.center();+ auto icon_center = shape_rect.center();QRect icon_rect {qRound(icon_center.x()) - (TAB_ICON_SIZE / 2),qRound(icon_center.y()) - (TAB_ICON_SIZE / 2),TAB_ICON_SIZE,TAB_ICON_SIZE,};- if (!is_selected)- painter.setOpacity(is_hovered ? 0.92 : (dark ? 0.88 : 0.84));paint_icon(icon_rect);- painter.setOpacity(1.0);continue;}- auto contents_rect = shape_rect.toAlignedRect().adjusted(TAB_CONTENT_HORIZONTAL_INSET, 0, -TAB_CONTENT_HORIZONTAL_INSET, 0);+ // A tab that grows, such as one opening, lays out its contents at the width it grows to, and shows as much of+ // them as it has grown into.+ auto layout_rect = tab_rect;+ if (!is_vertical && is_growing_horizontal_tab(index, tab_rect)) {+ layout_rect.setWidth(visual_tab_rect(index).width());+ painter.setClipRect(shape_rect, Qt::IntersectClip);+ }+ auto contents_rect = is_vertical+ ? shape_rect.toAlignedRect().adjusted(VERTICAL_TAB_CONTENT_LEADING_INSET, 0, -TAB_CONTENT_HORIZONTAL_INSET, 0)+ : horizontal_tab_contents_rect(index, layout_rect).toAlignedRect();+ // The speaker sits after the title, with the close button.if (auto* left_button = tabButton(index, QTabBar::LeftSide); left_button && left_button->isVisible())- contents_rect.setLeft(max(contents_rect.left(), left_button->geometry().right() + 6));- if (auto* right_button = tabButton(index, QTabBar::RightSide); right_button && right_button->isVisible())- contents_rect.setRight(min(contents_rect.right(), right_button->geometry().left() - 6));+ contents_rect.setRight(min(contents_rect.right(), left_button->geometry().left() - 6));+ // NB: A horizontal tab keeps its close button's slot whether the button shows or not, so that the title ends at+ // the same place either way.+ if (auto* right_button = tabButton(index, QTabBar::RightSide)) {+ auto keeps_slot = !is_vertical && right_button->x() - HORIZONTAL_TAB_CONTENT_GAP >= contents_rect.left() + TAB_ICON_SIZE;+ if (right_button->isVisible() || keeps_slot)+ contents_rect.setRight(min(contents_rect.right(), right_button->geometry().left() - 6));+ }if (!is_vertical && contents_rect.width() < HORIZONTAL_TAB_MIN_CONTENT_WIDTH_FOR_TITLE) {// NB: A tab too narrow for its favicon next to its mute button shows the mute button alone, rather than@@ -1089,10 +1361,7 @@ void TabBar::paintEvent(QPaintEvent*)TAB_ICON_SIZE,TAB_ICON_SIZE,};- if (!is_selected)- painter.setOpacity(is_hovered ? 0.92 : (dark ? 0.88 : 0.84));paint_icon(icon_rect);- painter.setOpacity(1.0);continue;}@@ -1102,83 +1371,105 @@ void TabBar::paintEvent(QPaintEvent*)TAB_ICON_SIZE,TAB_ICON_SIZE,};- if (!is_selected)- painter.setOpacity(is_hovered ? 0.92 : (dark ? 0.88 : 0.84));paint_icon(icon_rect);- painter.setOpacity(1.0);- contents_rect.setLeft(icon_rect.right() + 8);-- painter.setFont(title_font);+ contents_rect.setLeft(icon_rect.right() + HORIZONTAL_TAB_CONTENT_GAP);auto title = tabText(index);- auto title_text = m_tab_title_texts.value(title);- if (title_text.text().isEmpty() && !title.isEmpty()) {- auto single_line_title = title;- single_line_title.replace(QLatin1Char('\n'), QLatin1Char(' '));- title_text.setText(single_line_title);- title_text.setTextFormat(Qt::PlainText);- title_text.prepare(QTransform(), title_font);- }- title_texts.insert(title, title_text);-- auto tab_text_color = text_color;- if (!is_selected)- tab_text_color.setAlpha(is_hovered ? (dark ? 236 : 228) : (dark ? 226 : 216));-- // NB: A static text's height includes the font's leading, but a title is centered on its ascent and descent.- auto title_size = title_text.size();- QPointF title_position(contents_rect.left(), contents_rect.top() + ((contents_rect.height() - title_line_height) / 2));+ // In an inactive window, the tabs' titles drop to the muted color.+ auto is_inactive = ChromeStyle::window_activity(*this) == ChromeStyle::WindowActivity::Inactive;+ auto unselected_text_color = is_inactive ? Theme::chrome(*this).muted : (is_vertical ? Theme::chrome(*this).row_title : Theme::chrome(*this).tab_title);+ auto selected_text_color = is_inactive ? Theme::chrome(*this).muted : Theme::chrome(*this).text;+ auto tab_text_color = ChromeStyle::mix(unselected_text_color, selected_text_color, selection);++ // NB: A title keeps its weight whether its tab is selected or not, so nothing reflows as only its color+ // cross-fades.+ auto paint_title = [&] {+ painter.setFont(title_font);++ auto title_text = m_tab_title_texts.value(title);+ if (title_text.text().isEmpty() && !title.isEmpty()) {+ auto single_line_title = title;+ single_line_title.replace(QLatin1Char('\n'), QLatin1Char(' '));+ title_text.setText(single_line_title);+ title_text.setTextFormat(Qt::PlainText);+ title_text.prepare(QTransform(), title_font);+ }+ title_texts.insert(title, title_text);- painter.save();- painter.setPen(tab_text_color);+ // NB: A static text's height includes the font's leading, but a title is centered on its ascent and descent.+ auto title_size = title_text.size();+ QPointF title_position(contents_rect.left(), contents_rect.top() + ((contents_rect.height() - title_line_height) / 2));- // A title too long for its tab fades out toward the tab's end, rather than being cut short with an ellipsis.- // NB: Compare in fractional pixels, so a title that just fits is not taken for one that does not.- if (title_size.width() > contents_rect.width()) {- QRect fade_rect(contents_rect.right() + 1 - TAB_TITLE_FADE_WIDTH, contents_rect.top(), TAB_TITLE_FADE_WIDTH, contents_rect.height());- // The fading end gets a clip of its own below, which intersects the tab's clip rather than this one.painter.save();- painter.setClipRect(contents_rect.adjusted(0, 0, -TAB_TITLE_FADE_WIDTH, 0), Qt::IntersectClip);- painter.drawStaticText(title_position, title_text);- painter.restore();+ painter.setPen(tab_text_color);+ painter.setOpacity(is_vertical && m_tab_widget ? m_tab_widget->vertical_tab_title_opacity() : 1.0);++ // A title too long for its tab fades out toward the tab's end, rather than being cut short with an ellipsis.+ // NB: Compare in fractional pixels, so a title that just fits is not taken for one that does not.+ if (auto* tab = m_tab_widget ? m_tab_widget->tab(index) : nullptr; tab && title_size.width() > contents_rect.width())+ tabs_with_cut_titles.set(tab);+ if (title_size.width() > contents_rect.width()) {+ QRect fade_rect(contents_rect.right() + 1 - TAB_TITLE_FADE_WIDTH, contents_rect.top(), TAB_TITLE_FADE_WIDTH, contents_rect.height());+ // The fading end gets a clip of its own below, which intersects the tab's clip rather than this one.+ painter.save();+ painter.setClipRect(contents_rect.adjusted(0, 0, -TAB_TITLE_FADE_WIDTH, 0), Qt::IntersectClip);+ painter.drawStaticText(title_position, title_text);+ painter.restore();- // NB: Qt draws text with a gradient pen far more slowly than with a solid one, so only the fading end is- // drawn offscreen and faded out there.- auto device_pixel_ratio = devicePixelRatioF();- // NB: Round up, so the image covers all of the fade at a fractional pixel ratio. It is clipped to it.- QImage fade_image(QSize(ceil(fade_rect.width() * device_pixel_ratio), ceil(fade_rect.height() * device_pixel_ratio)), QImage::Format_ARGB32_Premultiplied);- fade_image.setDevicePixelRatio(device_pixel_ratio);- fade_image.fill(Qt::transparent);- {- QPainter fade_painter(&fade_image);- fade_painter.setFont(title_font);- fade_painter.setPen(tab_text_color);- fade_painter.drawStaticText(title_position - QPointF(fade_rect.topLeft()), title_text);-- QLinearGradient fade(0, 0, fade_rect.width(), 0);- fade.setColorAt(0.0, Qt::black);- fade.setColorAt(1.0, Qt::transparent);- fade_painter.setCompositionMode(QPainter::CompositionMode_DestinationIn);- fade_painter.fillRect(QRect(QPoint(), fade_rect.size()), fade);+ // NB: Qt draws text with a gradient pen far more slowly than with a solid one, so only the fading end is+ // drawn offscreen and faded out there.+ auto device_pixel_ratio = devicePixelRatioF();+ // NB: Round up, so the image covers all of the fade at a fractional pixel ratio. It is clipped to it.+ QImage fade_image(QSize(ceil(fade_rect.width() * device_pixel_ratio), ceil(fade_rect.height() * device_pixel_ratio)), QImage::Format_ARGB32_Premultiplied);+ fade_image.setDevicePixelRatio(device_pixel_ratio);+ fade_image.fill(Qt::transparent);+ {+ QPainter fade_painter(&fade_image);+ fade_painter.setFont(title_font);+ fade_painter.setPen(tab_text_color);+ fade_painter.drawStaticText(title_position - QPointF(fade_rect.topLeft()), title_text);++ QLinearGradient fade(0, 0, fade_rect.width(), 0);+ fade.setColorAt(0.0, Qt::black);+ fade.setColorAt(1.0, Qt::transparent);+ fade_painter.setCompositionMode(QPainter::CompositionMode_DestinationIn);+ fade_painter.fillRect(QRect(QPoint(), fade_rect.size()), fade);+ }+ // NB: A title narrower than the fade starts fading at its start, never over the icon before it.+ painter.setClipRect(fade_rect.intersected(contents_rect), Qt::IntersectClip);+ painter.drawImage(fade_rect.topLeft(), fade_image);+ } else {+ painter.setClipRect(contents_rect, Qt::IntersectClip);+ painter.drawStaticText(title_position, title_text);}- // NB: A title narrower than the fade starts fading at its start, never over the icon before it.- painter.setClipRect(fade_rect.intersected(contents_rect), Qt::IntersectClip);- painter.drawImage(fade_rect.topLeft(), fade_image);- } else {- painter.setClipRect(contents_rect, Qt::IntersectClip);- painter.drawStaticText(title_position, title_text);- }- painter.restore();+ painter.restore();+ };+ paint_title();}m_tab_title_texts = AK::move(title_texts);+ m_tabs_with_cut_titles = AK::move(tabs_with_cut_titles);painter.setClipping(false);+ // While the strip scrolls, it fades out at each end that has more tabs beyond it.+ if (!is_vertical) {+ auto strip = ChromeStyle::chrome_tab_strip_background(Theme::chrome_palette(*this));+ auto paint_fade = [&](int x, bool fades_right) {+ QLinearGradient fade(x, 0, x + HORIZONTAL_TAB_STRIP_FADE_WIDTH, 0);+ auto transparent_strip = strip;+ transparent_strip.setAlpha(0);+ fade.setColorAt(fades_right ? 0.0 : 1.0, transparent_strip);+ fade.setColorAt(fades_right ? 1.0 : 0.0, strip);+ painter.fillRect(QRect(x, 0, HORIZONTAL_TAB_STRIP_FADE_WIDTH, height()), fade);+ };+ if (m_scroll_offset > 0)+ paint_fade(0, false);+ if (m_scroll_offset < max_scroll_offset())+ paint_fade(width() - HORIZONTAL_TAB_STRIP_FADE_WIDTH, true);+ }if (is_vertical && (region.count > 0 || pinned_region_growth > 0)) {- auto separator = ChromeStyle::chrome_border(palette());- separator.setAlpha(dark ? 40 : 32);- painter.setPen(separator);- auto separator_y = VERTICAL_TAB_FLARE_RADIUS + region.height + pinned_region_growth - (PINNED_TABS_SEPARATOR_HEIGHT / 2) - (region.scrolls ? m_vertical_scroll_offset : 0);+ painter.setPen(Theme::chrome(*this).separator);+ auto separator_y = VERTICAL_TAB_BAR_END_ROOM + region.height + pinned_region_growth - (PINNED_TABS_SEPARATOR_HEIGHT / 2) - (region.scrolls ? m_scroll_offset : 0);painter.drawLine(QPoint(10, separator_y), QPoint(width() - 10, separator_y));}}@@ -1282,19 +1573,12 @@ void TabBar::mousePressEvent(QMouseEvent* event)m_drag_start_position = event->pos();}- if (tab_layout() != TabLayout::Horizontal) {- if (pressed_tab >= 0 && event->button() == Qt::LeftButton) {- setCurrentIndex(pressed_tab);- } else if (event->button() == Qt::LeftButton && start_window_move()) {- event->accept();- return;- }- } else {- if (pressed_tab < 0 && event->button() == Qt::LeftButton && start_window_move()) {- event->accept();- return;- }- QTabBar::mousePressEvent(event);+ // NB: QTabBar finds the pressed tab without our scroll offset, so we select it ourselves.+ if (pressed_tab >= 0 && event->button() == Qt::LeftButton) {+ setCurrentIndex(pressed_tab);+ } else if (event->button() == Qt::LeftButton && start_window_move()) {+ event->accept();+ return;}if (m_pressed_tab)@@ -1305,6 +1589,12 @@ void TabBar::mousePressEvent(QMouseEvent* event)void TabBar::mouseMoveEvent(QMouseEvent* event){+ if (m_strip_drag_card) {+ update_strip_drag(event->pos());+ event->accept();+ return;+ }+set_hovered_tab_index(tab_index_at(event->pos()));if (count() == 0) {@@ -1317,7 +1607,7 @@ void TabBar::mouseMoveEvent(QMouseEvent* event)auto pressed_tab_index = m_tab_widget ? m_tab_widget->index_of(m_pressed_tab) : -1;if (pressed_tab_index < 0) {m_pressed_tab = nullptr;- } else if ((event->pos() - m_drag_start_position).manhattanLength() >= QApplication::startDragDistance()) {+ } else if ((event->pos() - m_drag_start_position).manhattanLength() >= TAB_DRAG_START_DISTANCE) {start_tab_drag(pressed_tab_index);event->accept();return;@@ -1330,20 +1620,56 @@ void TabBar::mouseMoveEvent(QMouseEvent* event)event->ignore();}+void TabBar::enterEvent(QEnterEvent* event)+{+ m_tab_width_unlock_timer->stop();+ QTabBar::enterEvent(event);+}+void TabBar::leaveEvent(QEvent* event){+ // NB: The tab preview's window reaches over the tabs, to make room for its shadow. Though it lets the mouse through,+ // the pointer leaves the tab bar for it while it is still over the tab bar, so where the pointer is is watched+ // instead while the preview shows.+ if (m_tab_preview_popup && m_tab_preview_popup->isVisible() && rect().contains(mapFromGlobal(QCursor::pos()))) {+ QTabBar::leaveEvent(event);+ return;+ }++ pointer_left();+ QTabBar::leaveEvent(event);+}++void TabBar::pointer_left()+{+ if (m_locked_tab_width.has_value())+ m_tab_width_unlock_timer->start();+hide_tab_preview();set_hovered_tab_index(-1);- QTabBar::leaveEvent(event);}void TabBar::mouseReleaseEvent(QMouseEvent* event){+ if (m_strip_drag_card && event->button() == Qt::LeftButton) {+ auto dragged_tab = s_active_tab_dragged_tab;+ auto drop_index = drop_index_at(event->pos());+ end_strip_drag();+ if (auto* source_window = qobject_cast<BrowserWindow*>(window()); source_window && dragged_tab) {+ if (auto current_index = source_window->tab_index(dragged_tab); current_index >= 0)+ source_window->move_tab_to_window(current_index, *source_window, drop_index);+ }+ clear_drop_preview();+ event->accept();+ return;+ }+auto pressed_tab = m_pressed_tab;m_pressed_tab = nullptr;if (event->button() == Qt::MiddleButton && pressed_tab && m_tab_widget) {if (auto index = m_tab_widget->index_of(pressed_tab); index >= 0 && tab_index_at(event->pos()) == index) {+ lock_tab_widths();emit tabCloseRequested(index);event->accept();return;@@ -1370,25 +1696,33 @@ void TabBar::mouseDoubleClickEvent(QMouseEvent* event)void TabBar::wheelEvent(QWheelEvent* event){- if (tab_layout() == TabLayout::Horizontal || max_vertical_scroll_offset() <= 0) {- QTabBar::wheelEvent(event);+ // Scrolling moves the tabs when they overflow, and never switches tabs.+ if (max_scroll_offset() <= 0) {+ event->ignore();return;}- auto old_offset = m_vertical_scroll_offset;- auto pixel_delta = event->pixelDelta().y();- auto angle_delta = event->angleDelta().y();+ auto old_offset = m_scroll_offset;+ auto is_horizontal = tab_layout() == TabLayout::Horizontal;+ // NB: On a horizontal strip, both a vertical wheel and a sideways swipe scroll the tabs.+ auto dominant_delta = [&](QPoint delta) {+ if (!is_horizontal)+ return delta.y();+ return abs(delta.x()) > abs(delta.y()) ? delta.x() : delta.y();+ };+ auto pixel_delta = dominant_delta(event->pixelDelta());+ auto angle_delta = dominant_delta(event->angleDelta());if (pixel_delta != 0) {- set_vertical_scroll_offset(m_vertical_scroll_offset - pixel_delta);+ set_scroll_offset(m_scroll_offset - pixel_delta);} else if (angle_delta != 0) {- auto scroll_delta = angle_delta * VERTICAL_TAB_HEIGHT / 120;+ auto scroll_delta = angle_delta * (is_horizontal ? HORIZONTAL_TAB_MIN_WIDTH : VERTICAL_TAB_HEIGHT) / 120;if (scroll_delta == 0)scroll_delta = angle_delta > 0 ? 1 : -1;- set_vertical_scroll_offset(m_vertical_scroll_offset - scroll_delta);+ set_scroll_offset(m_scroll_offset - scroll_delta);}- if (m_vertical_scroll_offset != old_offset)+ if (m_scroll_offset != old_offset)event->accept();elseevent->ignore();@@ -1396,7 +1730,7 @@ void TabBar::wheelEvent(QWheelEvent* event)Optional<int> TabBar::dragged_tab_index() const{- if (!m_tab_widget || s_active_tab_drag_source != m_tab_widget || !s_active_tab_dragged_tab)+ if (!m_tab_widget || s_active_tab_drag_source != m_tab_widget || !s_active_tab_dragged_tab || s_dragged_tab_has_own_window)return {};if (auto index = m_tab_widget->index_of(s_active_tab_dragged_tab); index >= 0)return index;@@ -1422,13 +1756,13 @@ QRect TabBar::incoming_drop_layout_rect(int position) constreturn vertical_tab_rect(position, pinned_region_for(pinned_count));auto unpinned_count = count() + 1 - pinned_count;- auto first_tab_rect = tabRect(0);- auto strip_width = tabRect(count() - 1).right() + 1 - first_tab_rect.left() - (2 * HORIZONTAL_TAB_END_ROOM);- auto unpinned_width = unpinned_count > 0 ? max(0.0, static_cast<qreal>(strip_width - (pinned_count * PINNED_TAB_TILE_WIDTH)) / unpinned_count) : 0.0;+ auto first_tab_rect = visual_tab_rect(0);+ auto strip_width = visual_tab_rect(count() - 1).right() + 1 - first_tab_rect.left() - (2 * HORIZONTAL_TAB_END_ROOM);+ auto unpinned_width = unpinned_count > 0 ? max(0.0, static_cast<qreal>(strip_width - (pinned_count * HORIZONTAL_PINNED_TAB_WIDTH)) / unpinned_count) : 0.0;- auto left = first_tab_rect.left() + HORIZONTAL_TAB_END_ROOM + (min(position, pinned_count) * PINNED_TAB_TILE_WIDTH) + (max(0, position - pinned_count) * unpinned_width);- auto width = position < pinned_count ? PINNED_TAB_TILE_WIDTH : unpinned_width;- // NB: The first and last places also take room for their flares at the ends of the tab bar.+ auto left = first_tab_rect.left() + HORIZONTAL_TAB_END_ROOM + (min(position, pinned_count) * HORIZONTAL_PINNED_TAB_WIDTH) + (max(0, position - pinned_count) * unpinned_width);+ auto width = position < pinned_count ? HORIZONTAL_PINNED_TAB_WIDTH : unpinned_width;+ // NB: The first and last places also take room for their feet at the ends of the tab bar.if (position == 0) {left -= HORIZONTAL_TAB_END_ROOM;width += HORIZONTAL_TAB_END_ROOM;@@ -1508,6 +1842,8 @@ void TabBar::set_drop_slot(Optional<int> slot)m_drop_preview_target = drop_preview_for_slot(slot);m_drop_preview_progress = 0.0;m_drop_preview_animation->stop();+ // With reduced motion, the other tabs jump into place.+ m_drop_preview_animation->setDuration(SystemAppearance::prefers_reduced_motion() ? 0 : DROP_PREVIEW_DURATION_MS);m_drop_preview_animation->start();}@@ -1603,9 +1939,180 @@ qreal TabBar::current_pinned_region_growth() const}// Returns where a tab is drawn, which differs from its place in the layout while tabs move aside for a dragged tab.+void TabBar::update_layout_animation()+{+ if (!m_tab_widget || tab_layout() != TabLayout::Horizontal)+ return;++ HashMap<Tab const*, QRect> targets;+ HashMap<Tab const*, HorizontalTabEndRoom> target_end_rooms;+ for (int index = 0; index < count(); ++index) {+ if (auto* tab = m_tab_widget->tab(index)) {+ targets.set(tab, tabRect(index));+ target_end_rooms.set(tab, settled_horizontal_tab_end_room(index, count()));+ }+ }++ // Only opening and closing tabs move the others. Resizing the window or a title changing does not.+ auto tabs_were_added_or_removed = count() != m_settled_tab_count && m_settled_tab_count > 0;+ auto can_animate = isVisible() && !dragged_tab_index().has_value() && !m_drop_slot.has_value() && !SystemAppearance::prefers_reduced_motion();+ // NB: A closing tab shrinks away only while the tabs move to close the gap it leaves.+ if (tabs_were_added_or_removed && !(count() < m_settled_tab_count && can_animate))+ m_closing_tab.clear();+ if (tabs_were_added_or_removed && can_animate) {+ HashMap<Tab const*, QRect> start_rects;+ HashMap<Tab const*, HorizontalTabEndRoom> start_end_rooms;+ for (auto const& [tab, target] : targets) {+ // A tab starts where it is drawn now, or as nothing at its place if it is new.+ auto settled = m_settled_tab_rects.get(tab);+ if (!settled.has_value()) {+ start_rects.set(tab, QRect { target.left(), target.top(), 0, target.height() });+ start_end_rooms.set(tab, *target_end_rooms.get(tab));+ continue;+ }+ // NB: A tab that becomes or stops being the first or last one gains or loses the room at the end of the strip+ // as it moves, so what of it is drawn stays in place.+ auto settled_end_room = m_settled_tab_end_rooms.get(tab).value_or({});+ auto start_end_room = m_layout_animation_start_end_rooms.get(tab);+ if (m_layout_animation_progress < 1.0 && start_end_room.has_value()) {+ auto p = m_layout_animation_progress;+ start_end_rooms.set(tab, { start_end_room->left + ((settled_end_room.left - start_end_room->left) * p), start_end_room->right + ((settled_end_room.right - start_end_room->right) * p) });+ } else {+ start_end_rooms.set(tab, settled_end_room);+ }+ auto start = m_layout_animation_start_rects.get(tab);+ if (m_layout_animation_progress < 1.0 && start.has_value()) {+ auto p = m_layout_animation_progress;+ auto mix = [p](int a, int b) { return qRound(a + ((b - a) * p)); };+ start_rects.set(tab, QRect { mix(start->left(), settled->left()), mix(start->top(), settled->top()), mix(start->width(), settled->width()), mix(start->height(), settled->height()) });+ } else {+ start_rects.set(tab, *settled);+ }+ }+ m_layout_animation_start_rects = AK::move(start_rects);+ m_layout_animation_start_end_rooms = AK::move(start_end_rooms);+ m_layout_animation_progress = 0.0;+ m_layout_animation->stop();+ m_layout_animation->start();+ }++ m_settled_tab_rects = AK::move(targets);+ m_settled_tab_end_rooms = AK::move(target_end_rooms);+ m_settled_tab_count = count();+}++QRect TabBar::animated_tab_rect(int index, QRect const& target) const+{+ if (m_layout_animation_progress >= 1.0 || !m_tab_widget || tab_layout() != TabLayout::Horizontal)+ return target;+ auto* tab = m_tab_widget->tab(index);+ if (!tab)+ return target;+ auto start = m_layout_animation_start_rects.get(tab);+ if (!start.has_value())+ return target;++ // NB: The start is where the tab was in the tab bar, before any scrolling.+ auto from = start->translated(-m_scroll_offset, 0);+ auto p = m_layout_animation_progress;+ auto mix = [p](int a, int b) { return qRound(a + ((b - a) * p)); };+ return { mix(from.left(), target.left()), mix(from.top(), target.top()), mix(from.width(), target.width()), mix(from.height(), target.height()) };+}++HorizontalTabEndRoom TabBar::horizontal_tab_end_room(int index) const+{+ auto settled = settled_horizontal_tab_end_room(index, count());+ if (m_layout_animation_progress >= 1.0 || !m_tab_widget)+ return settled;+ auto* tab = m_tab_widget->tab(index);+ if (!tab)+ return settled;+ auto start = m_layout_animation_start_end_rooms.get(tab);+ if (!start.has_value())+ return settled;+ auto p = m_layout_animation_progress;+ return { start->left + ((settled.left - start->left) * p), start->right + ((settled.right - start->right) * p) };+}++void TabBar::prepare_for_tab_removal(int index)+{+ m_closing_tab.clear();+ if (tab_layout() != TabLayout::Horizontal || !isVisible() || SystemAppearance::prefers_reduced_motion() || dragged_tab_index().has_value() || count() <= 1)+ return;+ auto rect = shifted_tab_rect(index);+ if (rect.isEmpty())+ return;++ auto device_pixel_ratio = devicePixelRatioF();+ QPixmap image(rect.size() * device_pixel_ratio);+ image.setDevicePixelRatio(device_pixel_ratio);+ image.fill(Qt::transparent);+ {+ // NB: The closing tab is pictured as it looks unselected, and without its buttons, so that only the tab the+ // selection moves to looks selected as it fades out.+ QPainter painter(&image);+ m_tab_painted_unselected = index;+ render(&painter, QPoint(), QRegion(rect), {});+ m_tab_painted_unselected = -1;+ }+ m_closing_tab = ClosingTab { AK::move(image), rect.translated(m_scroll_offset, 0) };+}++// The closing tab shrinks toward its start as the tabs after it close the gap.+QRect TabBar::closing_tab_rect() const+{+ if (!m_closing_tab.has_value() || m_layout_animation_progress >= 1.0)+ return {};+ auto rect = m_closing_tab->rect.translated(-m_scroll_offset, 0);+ rect.setWidth(qRound(rect.width() * (1.0 - m_layout_animation_progress)));+ return rect;+}++bool TabBar::is_growing_horizontal_tab(int index, QRect const& tab_rect) const+{+ return tab_rect.width() < visual_tab_rect(index).width();+}++// How selected a tab looks, while the selection cross-fades from one tab to another.+qreal TabBar::selection_of(int index) const+{+ if (index == m_tab_painted_unselected)+ return 0.0;+ auto previously_selected_index = m_previously_selected_tab && m_tab_widget ? m_tab_widget->index_of(m_previously_selected_tab) : -1;+ if (index == currentIndex())+ return m_selection_animation->state() == QAbstractAnimation::Running ? m_selection_progress : 1.0;+ if (index == previously_selected_index)+ return 1.0 - m_selection_progress;+ return 0.0;+}++// A horizontal tab's content is padded within its card, or within its body once it is selected. It moves between the+// two as the selection cross-fades.+QRectF TabBar::horizontal_tab_contents_rect(int index, QRect const& tab_rect) const+{+ // NB: A tab's contents keep their place as it is selected, while only its background grows around them.+ auto card = horizontal_tab_card_shape_rect(QRectF(tab_rect), horizontal_tab_end_room(index));+ return card.adjusted(HORIZONTAL_TAB_CONTENT_LEFT_PADDING, 0, -HORIZONTAL_TAB_CONTENT_RIGHT_PADDING, 0);+}++int TabBar::horizontal_tabs_end_offset() const+{+ if (count() == 0 || m_layout_animation_progress >= 1.0)+ return 0;+ // NB: A tab that opens starts out as nothing, so the tab before it may end further along.+ auto animated_end = closing_tab_rect().isEmpty() ? NumericLimits<int>::min() : closing_tab_rect().right();+ auto settled_end = NumericLimits<int>::min();+ for (int index = 0; index < count(); ++index) {+ auto target = visual_tab_rect(index);+ animated_end = max(animated_end, animated_tab_rect(index, target).right());+ settled_end = max(settled_end, target.right());+ }+ return animated_end - settled_end;+}+QRect TabBar::shifted_tab_rect(int index) const{- auto tab_rect = visual_tab_rect(index);+ auto tab_rect = animated_tab_rect(index, visual_tab_rect(index));auto shift = current_tab_shift(index);return {qRound(tab_rect.left() + shift.x_offset),@@ -1615,84 +2122,300 @@ QRect TabBar::shifted_tab_rect(int index) const};}-QPixmap TabBar::render_tab_drag_pixmap(int index) const+// The card a dragged tab is drawn as. A horizontal tab's card is the selected tab's body, which starts a little below+// the top of the tab, and leaves out the room for its foot at either end of the strip.+QRect TabBar::tab_drag_card_rect(int index) const+{+ auto tab_rect = visual_tab_rect(index);+ if (tab_layout() != TabLayout::Horizontal)+ return tab_rect;+ return horizontal_selected_tab_body_rect(QRectF(tab_rect), horizontal_tab_end_room(index)).toAlignedRect();+}++QPixmap TabBar::render_tab_drag_pixmap(int index) const+{+ auto tab_rect = tab_drag_card_rect(index);+ auto device_pixel_ratio = devicePixelRatioF();+ auto dark = Theme::is_dark(*this);++ // The card: the tab on the toolbar color, rounded all around and outlined.+ QPixmap card(tab_rect.size() * device_pixel_ratio);+ card.setDevicePixelRatio(device_pixel_ratio);+ card.fill(Qt::transparent);+ {+ QPainter painter(&card);+ painter.setRenderHint(QPainter::Antialiasing);+ QPainterPath shape;+ shape.addRoundedRect(QRectF(QPointF(), tab_rect.size()), HORIZONTAL_SELECTED_TAB_RADIUS, HORIZONTAL_SELECTED_TAB_RADIUS);+ painter.setClipPath(shape);+ painter.fillPath(shape, Theme::chrome(*this).toolbar);+ const_cast<TabBar&>(*this).render(&painter, QPoint(), QRegion(tab_rect), QWidget::DrawChildren);+ painter.setClipping(false);+ painter.setPen(QPen(dark ? QColor(255, 255, 255, 26) : QColor(0, 0, 0, 36), 1));+ painter.setBrush(Qt::NoBrush);+ painter.drawRoundedRect(QRectF(QPointF(), tab_rect.size()).adjusted(0.5, 0.5, -0.5, -0.5), HORIZONTAL_SELECTED_TAB_RADIUS - 0.5, HORIZONTAL_SELECTED_TAB_RADIUS - 0.5);+ }++ // The card casts a tight shadow and a wider, softer one beneath it.+ auto image_size = tab_rect.size() + QSize(2 * TAB_DRAG_IMAGE_MARGIN, 2 * TAB_DRAG_IMAGE_MARGIN);+ QPixmap lifted(image_size * device_pixel_ratio);+ lifted.setDevicePixelRatio(device_pixel_ratio);+ lifted.fill(Qt::transparent);+ struct Shadow {+ qreal blur;+ qreal offset;+ qreal alpha;+ };+ Array<Shadow, 2> const shadows { Shadow { 16, 6, dark ? 0.30 : 0.12 }, Shadow { 2, 1, dark ? 0.36 : 0.18 } };+ for (auto const& shadow : shadows) {+ QGraphicsScene scene;+ auto* item = scene.addPixmap(card);+ auto* effect = new QGraphicsDropShadowEffect;+ effect->setBlurRadius(ChromeStyle::drop_shadow_blur_radius(shadow.blur));+ effect->setOffset(0, shadow.offset);+ effect->setColor(QColor(0, 0, 0, qRound(shadow.alpha * 255)));+ item->setGraphicsEffect(effect);+ auto source = QRectF(-TAB_DRAG_IMAGE_MARGIN, -TAB_DRAG_IMAGE_MARGIN, image_size.width(), image_size.height());+ QPainter painter(&lifted);+ painter.setRenderHint(QPainter::Antialiasing);+ scene.render(&painter, QRectF(QPointF(), image_size), source);+ }+ return lifted;+}++void TabBar::start_tab_drag(int index)+{+ hide_tab_preview();++ if (!m_tab_widget || !m_tab_widget->tab(index))+ return;++ start_strip_drag(index);+}++// The tab comes loose from its strip and follows the pointer freely, until it is dropped on a tab strip or, anywhere+// else, opens in a window of its own.+void TabBar::drag_tab_loose(Tab& tab, QPixmap card)+{+ hide_drop_preview();++ QPointer<Tab> dragged_tab = &tab;+ auto* drag = new QDrag(this);+ auto* mime_data = new QMimeData;+ mime_data->setData(LADYBIRD_TAB_MIME_TYPE, QByteArray {});+ drag->setMimeData(mime_data);+ drag->setPixmap(card);+ drag->setHotSpot(tab_drag_hot_spot());++ s_active_tab_drag_source = m_tab_widget;+ s_active_tab_dragged_tab = dragged_tab;+ s_pending_tab_drop_target = nullptr;+ s_pending_tab_drop_index = -1;+ update_tab_button_geometry();+ update();++ TabDragCancellationFilter cancellation_filter;++ // Qt installs its own drag event filter in exec(). Install ours afterward so Escape is observed before Qt consumes it.+ QTimer::singleShot(0, &cancellation_filter, [&cancellation_filter]() {+ QApplication::instance()->installEventFilter(&cancellation_filter);+ });++#if defined(AK_OS_MACOS)+ auto action = execute_appkit_tab_drag(*this, *drag);+#else+ auto action = drag->exec(Qt::MoveAction, Qt::MoveAction);+#endif+ QApplication::instance()->removeEventFilter(&cancellation_filter);++ // NB: On Wayland, a drag dropped where no window takes it ends just as one canceled with Escape does, and the+ // compositor keeps the Escape key to itself. A tab dropped away from every tab strip is detached, as it is+ // elsewhere, so a drag canceled there with Escape detaches its tab too.+ auto was_canceled = cancellation_filter.was_canceled();++ auto drop_target = s_pending_tab_drop_target;++ if (auto* source_window = qobject_cast<BrowserWindow*>(window()); source_window && dragged_tab) {+ if (auto current_index = source_window->tab_index(dragged_tab); current_index >= 0) {+ if (action == Qt::MoveAction && drop_target) {+ if (auto* target_window = qobject_cast<BrowserWindow*>(drop_target->window()))+ source_window->move_tab_to_window(current_index, *target_window, s_pending_tab_drop_index);+ } else if (!drop_target && !was_canceled && m_tab_widget->count() > 1) {+ source_window->detach_tab_to_new_window(current_index, QCursor::pos());+ }+ }+ }++ s_active_tab_drag_source = nullptr;+ s_active_tab_dragged_tab = nullptr;+ s_pending_tab_drop_target = nullptr;+ s_pending_tab_drop_index = -1;+ m_pressed_tab = nullptr;++ // The dropped tab has taken its place in the target's layout by now, so the tabs can go back to their own places.+ clear_drop_preview();+ if (drop_target && drop_target != m_tab_widget)+ drop_target->tab_bar()->clear_drop_preview();+}++QPoint TabBar::tab_drag_hot_spot() const+{+ return m_position_in_selected_tab_while_dragging - m_tab_drag_card_offset + QPoint(TAB_DRAG_IMAGE_MARGIN, TAB_DRAG_IMAGE_MARGIN);+}++void TabBar::start_strip_drag(int index)+{+ // NB: The card is drawn once, before the tab is dragged, since the strip leaves a gap where the dragged tab is, and+ // the other tabs move about it from then on. It shows the tab fully selected, even if the drag started while+ // its selection was still fading in.+ if (m_selection_animation->state() == QAbstractAnimation::Running) {+ m_selection_animation->stop();+ m_selection_progress = 1.0;+ if (m_layout_animation_progress >= 1.0)+ m_previously_selected_tab = nullptr;+ }+ m_tab_drag_pixmap = render_tab_drag_pixmap(index);+ m_tab_drag_card_offset = tab_drag_card_rect(index).topLeft() - visual_tab_rect(index).topLeft();+ m_strip_drag_card = new TabDragCard(*window(), m_tab_drag_pixmap);++ s_active_tab_drag_source = m_tab_widget;+ s_active_tab_dragged_tab = m_tab_widget->tab(index);+ s_pending_tab_drop_target = nullptr;+ s_pending_tab_drop_index = -1;++ m_strip_drag_card->show();+ m_strip_drag_card->raise();+ m_strip_drag_cancellation_filter = new TabDragCancellationFilter([this] {+ end_strip_drag();+ clear_drop_preview();+ });+ QApplication::instance()->installEventFilter(m_strip_drag_cancellation_filter);++ update_tab_button_geometry();+ update();+ update_strip_drag(mapFromGlobal(QCursor::pos()));+}++void TabBar::update_strip_drag(QPoint position)+{+ auto dragged_tab = s_active_tab_dragged_tab;+ if (!dragged_tab || m_tab_widget->index_of(dragged_tab) < 0) {+ end_strip_drag();+ clear_drop_preview();+ return;+ }++ if (!m_tab_widget->tab_drop_area_contains(*this, position)) {+ auto card = m_tab_drag_pixmap;+ end_strip_drag();+ if (compositor_moves_dragged_windows())+ drag_tab_in_own_window(*dragged_tab);+ else+ drag_tab_loose(*dragged_tab, AK::move(card));+ return;+ }++ // The tab stays in its strip, and only slides along it.+ auto card_rect = tab_drag_card_rect(m_tab_widget->index_of(dragged_tab));+ auto card_position = tab_layout() == TabLayout::Horizontal+ ? QPoint(position.x() - m_position_in_selected_tab_while_dragging.x() + m_tab_drag_card_offset.x(), card_rect.top())+ : QPoint(card_rect.left(), position.y() - m_position_in_selected_tab_while_dragging.y());+ m_strip_drag_card->move(mapTo(window(), card_position) - QPoint(TAB_DRAG_IMAGE_MARGIN, TAB_DRAG_IMAGE_MARGIN));+ update_drop_preview(position);+}++void TabBar::end_strip_drag(){- auto tab_rect = visual_tab_rect(index);- QPixmap pixmap(tab_rect.size() * devicePixelRatioF());- pixmap.setDevicePixelRatio(devicePixelRatioF());- pixmap.fill(Qt::transparent);+ if (!m_strip_drag_card)+ return;- QPainter painter(&pixmap);- painter.setOpacity(0.75);- const_cast<TabBar&>(*this).render(&painter, QPoint(), QRegion(tab_rect), QWidget::DrawChildren);- return pixmap;+ delete m_strip_drag_card;+ m_strip_drag_card = nullptr;+ m_tab_drag_pixmap = {};+ // NB: This can run from within the filter itself, as Escape cancels the drag.+ m_strip_drag_cancellation_filter->deleteLater();+ QApplication::instance()->removeEventFilter(m_strip_drag_cancellation_filter);+ m_strip_drag_cancellation_filter = nullptr;++ s_active_tab_drag_source = nullptr;+ s_active_tab_dragged_tab = nullptr;+ m_pressed_tab = nullptr;+ update_tab_button_geometry();+ update();}-void TabBar::start_tab_drag(int index)+// The tab leaves the strip in a window of its own, which the compositor moves with the pointer until it is dropped. A+// tab that is alone in its window takes the whole window along.+// NB: Qt attaches the window to the drag before it starts the drag, and Mutter only moves a window attached that early+// once it is first shown. So there, a window that was already shown stays in place, though its tab still lands+// wherever it is dropped.+void TabBar::drag_tab_in_own_window(Tab& tab){- hide_tab_preview();-- if (!m_tab_widget)+ auto* source_window = qobject_cast<BrowserWindow*>(window());+ if (!source_window)return;- auto* tab = m_tab_widget->tab(index);- if (!tab)- return;+ hide_drop_preview();++ QPointer<Tab> dragged_tab = &tab;+ auto* dragged_window = source_window;+ if (m_tab_widget->count() > 1)+ dragged_window = &source_window->detach_tab_to_new_window(source_window->tab_index(&tab), QCursor::pos(), BrowserWindow::DetachedWindowFollowsPointer::Yes);++ auto& tab_widget = dragged_window->tab_widget();+ auto* tab_bar = tab_widget.tab_bar();+ auto tab_rect = tab_bar->visual_tab_rect(tab_widget.index_of(&tab));+ auto position_in_tab = QPoint(+ min(m_position_in_selected_tab_while_dragging.x(), tab_rect.width() - 1),+ min(m_position_in_selected_tab_while_dragging.y(), tab_rect.height() - 1));+ auto position_in_window = tab_bar->mapTo(dragged_window, tab_rect.topLeft() + position_in_tab);++ // NB: Qt has the compositor move the window this mime data names with the pointer, at this position in the window.+ QByteArray window_data;+ QDataStream window_stream(&window_data, QIODevice::WriteOnly);+ window_stream << reinterpret_cast<qintptr>(dragged_window->windowHandle());+ QByteArray position_data;+ QDataStream position_stream(&position_data, QIODevice::WriteOnly);+ position_stream << position_in_window;- QPointer<Tab> dragged_tab = tab;- auto* drag = new QDrag(this);auto* mime_data = new QMimeData;mime_data->setData(LADYBIRD_TAB_MIME_TYPE, QByteArray {});+ mime_data->setData(QStringLiteral("application/x-qt-mainwindowdrag-window"), window_data);+ mime_data->setData(QStringLiteral("application/x-qt-mainwindowdrag-position"), position_data);++ // The window itself shows what is being dragged, so the drag has no image.+ QPixmap no_image(1, 1);+ no_image.fill(Qt::transparent);++ auto* drag = new QDrag(dragged_window);drag->setMimeData(mime_data);- drag->setPixmap(render_tab_drag_pixmap(index));- drag->setHotSpot(m_position_in_selected_tab_while_dragging);+ drag->setPixmap(no_image);- s_active_tab_drag_source = m_tab_widget;+ s_active_tab_drag_source = &tab_widget;s_active_tab_dragged_tab = dragged_tab;+ s_dragged_tab_has_own_window = true;s_pending_tab_drop_target = nullptr;s_pending_tab_drop_index = -1;- update_tab_button_geometry();- update();-- TabDragCancellationFilter cancellation_filter;-- // Qt installs its own drag event filter in exec(). Install ours afterward so Escape is observed before Qt consumes it.- QTimer::singleShot(0, &cancellation_filter, [&cancellation_filter]() {- QApplication::instance()->installEventFilter(&cancellation_filter);- });-#if defined(AK_OS_MACOS)- auto action = execute_appkit_tab_drag(*this, *drag);-#elseauto action = drag->exec(Qt::MoveAction, Qt::MoveAction);-#endif- QApplication::instance()->removeEventFilter(&cancellation_filter);-- static auto const is_wayland = QGuiApplication::platformName().startsWith("wayland");- auto was_canceled = cancellation_filter.was_canceled() || (is_wayland && action == Qt::IgnoreAction);auto drop_target = s_pending_tab_drop_target;-- if (auto* source_window = qobject_cast<BrowserWindow*>(window()); source_window && dragged_tab) {- if (auto current_index = source_window->tab_index(dragged_tab); current_index >= 0) {- if (action == Qt::MoveAction && drop_target) {- if (auto* target_window = qobject_cast<BrowserWindow*>(drop_target->window()))- source_window->move_tab_to_window(current_index, *target_window, s_pending_tab_drop_index);- } else if (!drop_target && !was_canceled && m_tab_widget->count() > 1) {- source_window->detach_tab_to_new_window(current_index, QCursor::pos());- }- }- }-+ auto drop_index = s_pending_tab_drop_index;s_active_tab_drag_source = nullptr;s_active_tab_dragged_tab = nullptr;+ s_dragged_tab_has_own_window = false;s_pending_tab_drop_target = nullptr;s_pending_tab_drop_index = -1;- m_pressed_tab = nullptr;- // The dropped tab has taken its place in the target's layout by now, so the tabs can go back to their own places.- clear_drop_preview();- if (drop_target && drop_target != m_tab_widget)+ // A tab dropped on another window's strip joins that window. Dropped anywhere else, it stays in its own window.+ // NB: Moving the window's last tab away closes the window, which may be the one this tab bar is in.+ if (action == Qt::MoveAction && drop_target && dragged_tab && drop_target != &tab_widget) {+ if (auto* target_window = qobject_cast<BrowserWindow*>(drop_target->window())) {+ if (auto current_index = dragged_window->tab_index(dragged_tab); current_index >= 0)+ dragged_window->move_tab_to_window(current_index, *target_window, drop_index);+ }+ }+ if (drop_target)drop_target->tab_bar()->clear_drop_preview();}@@ -1702,6 +2425,7 @@ void TabBar::start_hover_animation(int tab_index, qreal target_progress)return;if (tab_index < 0) {+ m_hover_animation->stop();m_hover_animation_tab_index = -1;m_hover_progress = 0.0;update();@@ -1716,68 +2440,29 @@ void TabBar::start_hover_animation(int tab_index, qreal target_progress)m_hover_animation->start();}-void TabBar::play_load_sheen(Tab& tab)-{- m_load_sheens.remove_all_matching([&](auto const& sheen) {- if (sheen.tab != &tab)- return false;- sheen.animation->deleteLater();- return true;- });-- auto* animation = new QVariantAnimation(this);- animation->setDuration(LOAD_SHEEN_DURATION_MS);- animation->setEasingCurve(QEasingCurve::InOutSine);- animation->setStartValue(0.0);- animation->setEndValue(1.0);- connect(animation, &QVariantAnimation::valueChanged, this, [this] { update(); });- connect(animation, &QVariantAnimation::finished, this, [this, animation] {- m_load_sheens.remove_first_matching([&](auto const& sheen) { return sheen.animation == animation; });- animation->deleteLater();- update();- });- m_load_sheens.append({ &tab, animation });- animation->start();-}--bool TabBar::is_tab_loading(int index) const+qreal TabBar::loading_ring_opacity(int index) const{if (!m_tab_widget || index < 0 || index >= count())- return false;+ return 0;auto* tab = m_tab_widget->tab(index);- return tab && tab->is_loading();+ return tab ? tab->loading_ring_opacity() : 0;}-// The swirl only needs repainting while a tab is loading and the tab bar can be seen.-void TabBar::update_loading_swirl_animation()+// The ring only needs repainting while a tab is loading and the tab bar can be seen.+void TabBar::update_loading_ring_animation(){auto any_tab_loading = false;for (int index = 0; index < count() && !any_tab_loading; ++index)- any_tab_loading = is_tab_loading(index);+ any_tab_loading = loading_ring_opacity(index) > 0;auto should_run = any_tab_loading && isVisible();- if (should_run && m_loading_swirl_animation->state() != QAbstractAnimation::Running)- m_loading_swirl_animation->start();- else if (!should_run && m_loading_swirl_animation->state() != QAbstractAnimation::Stopped)- m_loading_swirl_animation->stop();+ if (should_run && m_loading_ring_animation->state() != QAbstractAnimation::Running)+ m_loading_ring_animation->start();+ else if (!should_run && m_loading_ring_animation->state() != QAbstractAnimation::Stopped)+ m_loading_ring_animation->stop();update();}-Optional<qreal> TabBar::load_sheen_progress(int index) const-{- if (m_load_sheens.is_empty() || !m_tab_widget)- return {};- // NB: A sheen whose tab was closed has a null tab, which must not match a missing one here.- auto* tab = m_tab_widget->tab(index);- if (!tab)- return {};- for (auto const& sheen : m_load_sheens) {- if (sheen.tab == tab)- return sheen.animation->currentValue().toReal();- }- return {};-}-void TabBar::schedule_tab_preview(int index){if (!m_tab_preview_timer || !m_tab_preview_popup)@@ -1820,6 +2505,7 @@ void TabBar::show_tab_preview()m_tab_preview_popup->move(tab_preview_position_for(index, m_tab_preview_popup->sizeHint()));m_tab_preview_popup->show();m_tab_preview_popup->raise();+ m_tab_preview_pointer_timer->start();return;}@@ -1839,6 +2525,7 @@ void TabBar::show_tab_preview()m_tab_preview_popup->move(tab_preview_position_for(index, m_tab_preview_popup->sizeHint()));m_tab_preview_popup->show();m_tab_preview_popup->raise();+ m_tab_preview_pointer_timer->start();}void TabBar::hide_tab_preview()@@ -1851,6 +2538,8 @@ void TabBar::hide_tab_preview()if (m_tab_preview_timer)m_tab_preview_timer->stop();+ if (m_tab_preview_pointer_timer)+ m_tab_preview_pointer_timer->stop();m_tab_preview_index = -1;@@ -1872,35 +2561,35 @@ QPoint TabBar::tab_preview_position_for(int index, QSize const& popup_size) consif (tab_layout() == TabLayout::Horizontal) {position = mapToGlobal(QPoint {tab_rect.center().x() - popup_size.width() / 2,- tab_rect.bottom() + TAB_PREVIEW_CARD_GAP - TAB_PREVIEW_SHADOW_MARGIN,+ tab_rect.bottom() + TAB_PREVIEW_CARD_GAP - TAB_PREVIEW_SHADOW_MARGINS.top(),});if (position.y() + popup_size.height() > available_geometry.bottom())- position.setY(mapToGlobal(QPoint { 0, tab_rect.top() }).y() - popup_size.height() - TAB_PREVIEW_CARD_GAP + TAB_PREVIEW_SHADOW_MARGIN);+ position.setY(mapToGlobal(QPoint { 0, tab_rect.top() }).y() - popup_size.height() - TAB_PREVIEW_CARD_GAP + TAB_PREVIEW_SHADOW_MARGINS.bottom());} else {auto place_popup_to_right = !vertical_tabs_are_on_right();// The popup sits beside the tab bar rather than the tab, so it never covers the other pinned tiles in a row.auto bar_rect = rect();position = mapToGlobal(QPoint {place_popup_to_right- ? bar_rect.right() + TAB_PREVIEW_CARD_GAP - TAB_PREVIEW_SHADOW_MARGIN- : bar_rect.left() - popup_size.width() - TAB_PREVIEW_CARD_GAP + TAB_PREVIEW_SHADOW_MARGIN,+ ? bar_rect.right() + TAB_PREVIEW_CARD_GAP - TAB_PREVIEW_SHADOW_MARGINS.left()+ : bar_rect.left() - popup_size.width() - TAB_PREVIEW_CARD_GAP + TAB_PREVIEW_SHADOW_MARGINS.right(),tab_rect.center().y() - popup_size.height() / 2,});if (place_popup_to_right && position.x() + popup_size.width() > available_geometry.right())- position.setX(mapToGlobal(QPoint { bar_rect.left(), 0 }).x() - popup_size.width() - TAB_PREVIEW_CARD_GAP + TAB_PREVIEW_SHADOW_MARGIN);+ position.setX(mapToGlobal(QPoint { bar_rect.left(), 0 }).x() - popup_size.width() - TAB_PREVIEW_CARD_GAP + TAB_PREVIEW_SHADOW_MARGINS.right());else if (!place_popup_to_right && position.x() < available_geometry.left())- position.setX(mapToGlobal(QPoint { bar_rect.right(), 0 }).x() + TAB_PREVIEW_CARD_GAP - TAB_PREVIEW_SHADOW_MARGIN);+ position.setX(mapToGlobal(QPoint { bar_rect.right(), 0 }).x() + TAB_PREVIEW_CARD_GAP - TAB_PREVIEW_SHADOW_MARGINS.left());}- auto minimum_x = available_geometry.left() + TAB_PREVIEW_CARD_GAP - TAB_PREVIEW_SHADOW_MARGIN;- auto maximum_x = available_geometry.right() - popup_size.width() - TAB_PREVIEW_CARD_GAP + TAB_PREVIEW_SHADOW_MARGIN;+ auto minimum_x = available_geometry.left() + TAB_PREVIEW_CARD_GAP - TAB_PREVIEW_SHADOW_MARGINS.left();+ auto maximum_x = available_geometry.right() - popup_size.width() - TAB_PREVIEW_CARD_GAP + TAB_PREVIEW_SHADOW_MARGINS.right();if (minimum_x <= maximum_x)position.setX(clamp(position.x(), minimum_x, maximum_x));- auto minimum_y = available_geometry.top() + TAB_PREVIEW_CARD_GAP - TAB_PREVIEW_SHADOW_MARGIN;- auto maximum_y = available_geometry.bottom() - popup_size.height() - TAB_PREVIEW_CARD_GAP + TAB_PREVIEW_SHADOW_MARGIN;+ auto minimum_y = available_geometry.top() + TAB_PREVIEW_CARD_GAP - TAB_PREVIEW_SHADOW_MARGINS.top();+ auto maximum_y = available_geometry.bottom() - popup_size.height() - TAB_PREVIEW_CARD_GAP + TAB_PREVIEW_SHADOW_MARGINS.bottom();if (minimum_y <= maximum_y)position.setY(clamp(position.y(), minimum_y, maximum_y));@@ -1942,7 +2631,7 @@ TabBar::PinnedRegion TabBar::pinned_region_for(int pinned_count) constregion.tile_width = bar_width;} else {// The tiles stretch to fill each row.- region.columns = max(1, bar_width / PINNED_TAB_TILE_WIDTH);+ region.columns = PINNED_TAB_COLUMNS;region.tile_width = bar_width / region.columns;}@@ -1960,7 +2649,7 @@ bool TabBar::pinned_tabs_are_tiles() constQRect TabBar::visual_tab_rect(int index) const{if (tab_layout() == TabLayout::Horizontal)- return tabRect(index);+ return tabRect(index).translated(-m_scroll_offset, 0);if (index < 0 || index >= count())return {};@@ -1973,27 +2662,38 @@ QRect TabBar::vertical_tab_rect(int index, PinnedRegion const& region) constif (index < region.count) {auto row = index / region.columns;auto column = index % region.columns;- auto top = VERTICAL_TAB_FLARE_RADIUS + (row * VERTICAL_TAB_HEIGHT) - (region.scrolls ? m_vertical_scroll_offset : 0);+ auto top = VERTICAL_TAB_BAR_END_ROOM + (row * VERTICAL_TAB_HEIGHT) - (region.scrolls ? m_scroll_offset : 0);return { vertical_tabs_left() + (column * region.tile_width), top, region.tile_width, VERTICAL_TAB_HEIGHT };}auto unpinned_index = index - region.count;- return { vertical_tabs_left(), VERTICAL_TAB_FLARE_RADIUS + region.height + (unpinned_index * VERTICAL_TAB_HEIGHT) - m_vertical_scroll_offset, vertical_bar_width(), VERTICAL_TAB_HEIGHT };+ return { vertical_tabs_left(), VERTICAL_TAB_BAR_END_ROOM + region.height + (unpinned_index * VERTICAL_TAB_HEIGHT) - m_scroll_offset, vertical_bar_width(), VERTICAL_TAB_HEIGHT };}int TabBar::tab_index_at(QPoint const& position) const{- if (tab_layout() == TabLayout::Horizontal)- return tabAt(position);+ if (tab_layout() == TabLayout::Horizontal) {+ if (position.x() < 0 || position.x() >= width())+ return -1;+ auto index = tabAt(position + QPoint(m_scroll_offset, 0));+ // NB: The room for the selected tab's foot at either end of the strip is not part of the tab, so a press there+ // drags the window, as one elsewhere on the empty strip does.+ if (index >= 0) {+ auto body = horizontal_selected_tab_body_rect(QRectF(visual_tab_rect(index)), horizontal_tab_end_room(index));+ if (position.x() < body.left() || position.x() >= body.right())+ return -1;+ }+ return index;+ }if (position.x() < 0 || position.x() >= width() || position.y() < 0 || position.y() >= height())return -1;auto region = pinned_region();- auto y = position.y() - VERTICAL_TAB_FLARE_RADIUS;+ auto y = position.y() - VERTICAL_TAB_BAR_END_ROOM;if (y < 0)return -1;- auto pinned_y = y + (region.scrolls ? m_vertical_scroll_offset : 0);+ auto pinned_y = y + (region.scrolls ? m_scroll_offset : 0);if (pinned_y < region.height) {if (pinned_y >= region.height - PINNED_TABS_SEPARATOR_HEIGHT)return -1;@@ -2006,7 +2706,7 @@ int TabBar::tab_index_at(QPoint const& position) constreturn index < region.count ? index : -1;}- auto index = region.count + ((y - region.height + m_vertical_scroll_offset) / VERTICAL_TAB_HEIGHT);+ auto index = region.count + ((y - region.height + m_scroll_offset) / VERTICAL_TAB_HEIGHT);if (index >= count())return -1;@@ -2019,7 +2719,7 @@ int TabBar::tab_index_at(QPoint const& position) constQSize TabBar::vertical_size_hint(int tab_count) const{auto region = pinned_region();- return { vertical_tab_width(m_available_width, tab_layout()), (2 * VERTICAL_TAB_FLARE_RADIUS) + region.height + (max(0, tab_count - region.count) * VERTICAL_TAB_HEIGHT) };+ return { vertical_tab_width(m_available_width, tab_layout()), (2 * VERTICAL_TAB_BAR_END_ROOM) + region.height + (max(0, tab_count - region.count) * VERTICAL_TAB_HEIGHT) };}bool TabBar::vertical_tabs_are_on_right() const@@ -2027,29 +2727,41 @@ bool TabBar::vertical_tabs_are_on_right() constreturn m_vertical_tabs_position == WebView::VerticalTabsPosition::Right;}-int TabBar::max_vertical_scroll_offset() const+int TabBar::max_scroll_offset() const{if (tab_layout() == TabLayout::Horizontal)- return 0;+ return count() > 0 ? max(0, tabRect(count() - 1).right() + 1 - width()) : 0;auto region = pinned_region();- return max(0, (2 * VERTICAL_TAB_FLARE_RADIUS) + region.height + ((count() - region.count) * VERTICAL_TAB_HEIGHT) - height());+ return max(0, (2 * VERTICAL_TAB_BAR_END_ROOM) + region.height + ((count() - region.count) * VERTICAL_TAB_HEIGHT) - height());}-void TabBar::set_vertical_scroll_offset(int offset)+void TabBar::set_scroll_offset(int offset){- auto clamped_offset = max(0, min(offset, max_vertical_scroll_offset()));- if (m_vertical_scroll_offset == clamped_offset)+ auto clamped_offset = max(0, min(offset, max_scroll_offset()));+ if (m_scroll_offset == clamped_offset)return;- m_vertical_scroll_offset = clamped_offset;+ m_scroll_offset = clamped_offset;update_tab_button_geometry();update();}void TabBar::ensure_tab_visible(int index){- if (tab_layout() == TabLayout::Horizontal || index < 0 || index >= count())+ if (index < 0 || index >= count())+ return;++ if (tab_layout() == TabLayout::Horizontal) {+ // A tab scrolled into view clears the fade at the end it comes from, unless it is the first or the last.+ auto tab_rect = tabRect(index);+ auto left = tab_rect.left() - (index > 0 ? HORIZONTAL_TAB_STRIP_FADE_WIDTH : 0);+ auto right = tab_rect.right() + 1 + (index < count() - 1 ? HORIZONTAL_TAB_STRIP_FADE_WIDTH : 0);+ if (left < m_scroll_offset)+ set_scroll_offset(left);+ else if (right > m_scroll_offset + width())+ set_scroll_offset(right - width());return;+ }// A pinned tab that stays in place is always in view.auto region = pinned_region();@@ -2061,12 +2773,12 @@ void TabBar::ensure_tab_visible(int index)? (index / region.columns) * VERTICAL_TAB_HEIGHT: region.height + ((index - region.count) * VERTICAL_TAB_HEIGHT) - region.fixed_height();auto tab_bottom = tab_top + VERTICAL_TAB_HEIGHT;- auto visible_height = height() - (2 * VERTICAL_TAB_FLARE_RADIUS) - region.fixed_height();+ auto visible_height = height() - (2 * VERTICAL_TAB_BAR_END_ROOM) - region.fixed_height();- if (tab_top < m_vertical_scroll_offset)- set_vertical_scroll_offset(tab_top);- else if (tab_bottom > m_vertical_scroll_offset + visible_height)- set_vertical_scroll_offset(tab_bottom - visible_height);+ if (tab_top < m_scroll_offset)+ set_scroll_offset(tab_top);+ else if (tab_bottom > m_scroll_offset + visible_height)+ set_scroll_offset(tab_bottom - visible_height);}void TabBar::set_hovered_tab_index(int index)@@ -2074,26 +2786,22 @@ void TabBar::set_hovered_tab_index(int index)if (m_hovered_tab_index == index)return;- auto previous_hovered_tab = m_hovered_tab_index;m_hovered_tab_index = index;update_tab_button_geometry();- start_hover_animation(index >= 0 ? index : previous_hovered_tab, index >= 0 ? 1.0 : 0.0);+ // A tab's hover fill fades in, but disappears at once when the pointer leaves.+ start_hover_animation(index, 1.0);schedule_tab_preview(index);update();}void TabBar::update_tab_button_geometry(){- auto set_button_collapsed_overlay = [](QWidget* button, bool enabled) {- if (auto* tab_bar_button = qobject_cast<TabBarButton*>(button))- tab_bar_button->set_collapsed_vertical_overlay(enabled);- };-- auto prepare_button = [&](QWidget* button, bool collapsed_overlay) {+ auto prepare_button = [&](QWidget* button, TabBarButton::Placement placement) {if (!button)return;button->installEventFilter(this);- set_button_collapsed_overlay(button, collapsed_overlay);+ if (auto* tab_bar_button = qobject_cast<TabBarButton*>(button))+ tab_bar_button->set_placement(placement);};// The audio button takes the favicon's place, in the middle of a pinned tile's card.@@ -2115,44 +2823,63 @@ void TabBar::update_tab_button_geometry()if (tab_layout() == TabLayout::Horizontal) {auto pinned_count = pinned_tab_count();+ // Buttons are widgets above the tab bar's painting, so the fade at a scrolling end can't cover them. They hide+ // there instead.+ auto visible_left = m_scroll_offset > 0 ? HORIZONTAL_TAB_STRIP_FADE_WIDTH : 0;+ auto visible_right = width() - (m_scroll_offset < max_scroll_offset() ? HORIZONTAL_TAB_STRIP_FADE_WIDTH : 0);+ auto is_in_view = [&](QWidget* button) {+ return button->x() >= visible_left && button->x() + button->width() <= visible_right;+ };for (int index = 0; index < count(); ++index) {auto is_dragged = index == dragged_index;auto tab_rect = shifted_tab_rect(index);- auto shape_rect = horizontal_tab_card_shape_rect(QRectF(tab_rect), tab_bar_edges(index, count()));+ auto shape_rect = horizontal_tab_card_shape_rect(QRectF(tab_rect), horizontal_tab_end_room(index));auto* left_button = tabButton(index, QTabBar::LeftSide);- prepare_button(left_button, false);+ prepare_button(left_button, TabBarButton::Placement::Tab);if (index < pinned_count) {if (!left_button)continue;center_button_in(left_button, shape_rect);- if (left_button->isVisible() == is_dragged)- left_button->setVisible(!is_dragged);+ if (auto visible = !is_dragged && is_in_view(left_button); left_button->isVisible() != visible)+ left_button->setVisible(visible);continue;}- // NB: The style puts a tab's left button 1pt inside the tab's card, where its icon looks flush against the- // card's edge. Give it 3pt.+ auto is_selected = index == currentIndex();+ auto content_rect = horizontal_tab_contents_rect(index, tab_rect);+ // NB: A tab shows its buttons once it has grown to its width.+ auto is_growing = is_growing_horizontal_tab(index, tab_rect);++ // The close button ends the tab's content, and only shows on the selected tab and the hovered one.+ auto* close_button = tabButton(index, QTabBar::RightSide);+ prepare_button(close_button, TabBarButton::Placement::Tab);+ auto trailing_edge = qRound(content_rect.right());+ if (close_button) {+ QPoint close_button_position { trailing_edge - close_button->width(), button_y_in(close_button, shape_rect) };+ if (close_button->pos() != close_button_position)+ close_button->move(close_button_position);+ // NB: Every tab with room for it keeps a slot for its close button, which shows on the selected tab and+ // the hovered one. While the strip scrolls, only the selected tab shows it. A tab too narrow for+ // its favicon beside the slot, such as one opening or closing, has none.+ auto has_room = close_button_position.x() - HORIZONTAL_TAB_CONTENT_GAP >= content_rect.left() + TAB_ICON_SIZE;+ auto show_close_button = !is_dragged && !is_growing && has_room && (is_selected || (index == m_hovered_tab_index && max_scroll_offset() <= 0)) && is_in_view(close_button);+ if (auto* tab_bar_button = qobject_cast<TabBarButton*>(close_button))+ tab_bar_button->set_revealed(show_close_button);+ else if (close_button->isVisible() != show_close_button)+ close_button->setVisible(show_close_button);+ if (has_room)+ trailing_edge = close_button_position.x() - 2;+ }++ // The speaker of a tab playing audio sits left of the close button's slot.if (left_button) {- QPoint position { qRound(shape_rect.left()) + 3, button_y_in(left_button, shape_rect) };+ QPoint position { trailing_edge - left_button->width(), button_y_in(left_button, shape_rect) };if (left_button->pos() != position)left_button->move(position);- if (left_button->isVisible() == is_dragged)- left_button->setVisible(!is_dragged);+ if (auto visible = !is_dragged && !is_growing && is_in_view(left_button); left_button->isVisible() != visible)+ left_button->setVisible(visible);}- auto* close_button = tabButton(index, QTabBar::RightSide);- prepare_button(close_button, false);- if (!close_button)- continue;- // The close button's circle shares its center with the round end of the card.- auto close_button_center_x = shape_rect.right() - (shape_rect.height() / 2.0);- QPoint close_button_position { qRound(close_button_center_x - (close_button->width() / 2.0)), button_y_in(close_button, shape_rect) };- if (close_button->pos() != close_button_position)- close_button->move(close_button_position);- auto minimum_width = index == currentIndex() ? HORIZONTAL_ACTIVE_TAB_CLOSE_BUTTON_MIN_WIDTH : HORIZONTAL_TAB_CLOSE_BUTTON_MIN_WIDTH;- auto show_close_button = !is_dragged && tab_rect.width() >= minimum_width;- if (close_button->isVisible() != show_close_button)- close_button->setVisible(show_close_button);}return;}@@ -2164,7 +2891,7 @@ void TabBar::update_tab_button_geometry()auto* button = tabButton(index, position);if (!button)return;- prepare_button(button, false);+ prepare_button(button, TabBarButton::Placement::SidebarRow);auto button_size = button->size();if (button_size.isEmpty())@@ -2172,21 +2899,20 @@ void TabBar::update_tab_button_geometry()if (button_size.isEmpty())return;- // A button's circle shares its center with the round end of the card it sits in.+ // The close button's circle shares its center with the round end of the card it sits in. The speaker sits+ // before the close button while it shows, and in its place otherwise.// NB: A QRect's right() is its last column, one short of its right edge.auto end_radius = shape_rect.height() / 2;- auto x = position == QTabBar::RightSide ? shape_rect.right() + 1 - end_radius - (button_size.width() / 2) : shape_rect.left() + end_radius - (button_size.width() / 2);- auto icon_left = shape_rect.left() + TAB_CONTENT_HORIZONTAL_INSET;- if (position == QTabBar::RightSide) {- if (auto* left_button = tabButton(index, QTabBar::LeftSide); left_button && left_button->isVisible())- icon_left = max(icon_left, left_button->geometry().right() + 6);+ auto x = shape_rect.right() + 1 - end_radius - (button_size.width() / 2);+ if (position == QTabBar::LeftSide) {+ if (auto* close_button = tabButton(index, QTabBar::RightSide); close_button && close_button->isVisible())+ x = close_button->x() - SIDEBAR_ROW_BUTTON_GAP - button_size.width();}// The expanded layout is also used at narrow widths during hover expansion. Keep buttons from covering the// favicon while the sidebar grows.- auto has_room_for_icon = position == QTabBar::RightSide- ? x - 6 >= icon_left + TAB_ICON_SIZE- : x + button_size.width() + 6 + TAB_ICON_SIZE <= shape_rect.right() - TAB_CONTENT_HORIZONTAL_INSET;+ auto icon_left = shape_rect.left() + VERTICAL_TAB_CONTENT_LEADING_INSET;+ auto has_room_for_icon = x - 6 >= icon_left + TAB_ICON_SIZE;// NB: Move a button before showing it. Shown where it was, under the pointer, it would take a hover that it// keeps at its new place until the pointer moves.@@ -2198,8 +2924,10 @@ void TabBar::update_tab_button_geometry()did_update_button = true;}+ // NB: The close buttons stay hidden while the sidebar opens or closes, as the titles fade.+ auto is_toggling = m_tab_widget && m_tab_widget->vertical_tabs_are_toggling();auto should_be_visible = index != dragged_index && has_room_for_icon- && (position != QTabBar::RightSide || index == currentIndex() || index == m_hovered_tab_index);+ && (position != QTabBar::RightSide || ((index == currentIndex() || index == m_hovered_tab_index) && !is_toggling));if (button->isVisible() != should_be_visible) {button->setVisible(should_be_visible);did_update_button = true;@@ -2209,11 +2937,11 @@ void TabBar::update_tab_button_geometry()button->raise();};- auto place_collapsed_button = [&](int index, QTabBar::ButtonPosition position, QRect tab_rect, QRect shape_rect) {+ auto place_collapsed_button = [&](int index, QTabBar::ButtonPosition position, QRect shape_rect) {auto* button = tabButton(index, position);if (!button)return;- prepare_button(button, true);+ prepare_button(button, TabBarButton::Placement::RailBadge);auto button_size = button->size();if (button_size.isEmpty())@@ -2221,17 +2949,13 @@ void TabBar::update_tab_button_geometry()if (button_size.isEmpty())return;- QPoint button_position;- if (position == QTabBar::RightSide) {- button_position = {- max(tab_rect.left(), shape_rect.left() - 5),- max(tab_rect.top(), shape_rect.top() - 5),- };- } else {- auto x = min(tab_rect.right() - button_size.width() + 1, shape_rect.right() - button_size.width() + 5);- auto y = min(tab_rect.bottom() - button_size.height() + 1, shape_rect.bottom() - button_size.height() + 5);- button_position = { x, y };- }+ // The close button sits on the favicon's top left corner, and the speaker on its bottom right corner.+ auto icon_center = QRectF(shape_rect).center();+ QPoint icon_top_left { qRound(icon_center.x()) - (TAB_ICON_SIZE / 2), qRound(icon_center.y()) - (TAB_ICON_SIZE / 2) };+ auto badge_center = position == QTabBar::RightSide+ ? icon_top_left - RAIL_BADGE_CORNER_OUTSET+ : icon_top_left + QPoint(TAB_ICON_SIZE, TAB_ICON_SIZE) + RAIL_BADGE_CORNER_OUTSET;+ auto button_position = badge_center - QPoint(button_size.width() / 2, button_size.height() / 2);// NB: As above, move the button before showing it.bool did_update_button = false;@@ -2269,19 +2993,19 @@ void TabBar::update_tab_button_geometry()if (tab_layout() == TabLayout::VerticalCollapsed) {auto shape_rect = collapsed_vertical_tab_shape_rect(tab_rect);- place_collapsed_button(index, QTabBar::LeftSide, tab_rect, shape_rect);- place_collapsed_button(index, QTabBar::RightSide, tab_rect, shape_rect);+ place_collapsed_button(index, QTabBar::LeftSide, shape_rect);+ place_collapsed_button(index, QTabBar::RightSide, shape_rect);} else if (index < region.count && pinned_tabs_are_tiles()) {if (auto* button = tabButton(index, QTabBar::LeftSide)) {- prepare_button(button, false);+ prepare_button(button, TabBarButton::Placement::Tab);center_button_in(button, tab_rect);if (button->isVisible() != (index != dragged_index))button->setVisible(index != dragged_index);}} else {auto shape_rect = tab_card_shape_rect(tab_rect);- place_expanded_button(index, QTabBar::LeftSide, shape_rect);place_expanded_button(index, QTabBar::RightSide, shape_rect);+ place_expanded_button(index, QTabBar::LeftSide, shape_rect);}}}@@ -2307,14 +3031,16 @@ bool TabBar::start_window_move()return handle->startSystemMove();}-TabWidget::TabWidget(QWidget* parent)+TabWidget::TabWidget(WebView::IsPrivate is_private, QWidget* parent): QWidget(parent){+ // NB: The window is marked as private before any chrome inside it is made.+ if (is_private == WebView::IsPrivate::Yes)+ Theme::mark_private_window(*window());if (auto* top_level_window = window(); top_level_window != this)top_level_window->installEventFilter(this);m_vertical_tabs_expanded_width = Application::settings().tab_settings().vertical_tabs_expanded_width.value_or(VERTICAL_TABS_DEFAULT_EXPANDED_WIDTH);- m_vertical_tabs_expanded_width = clamp_vertical_tabs_expanded_width(m_vertical_tabs_expanded_width);m_tab_bar = new TabBar(this);setAcceptDrops(true);@@ -2333,23 +3059,37 @@ TabWidget::TabWidget(QWidget* parent)m_toolbar_container->installEventFilter(this);m_stacked_widget = new QStackedWidget(this);m_page_column = new QWidget(this);+ m_page_column->installEventFilter(this);+ m_toolbar_placeholder = new QWidget(m_page_column);m_page_column_layout = new QVBoxLayout(m_page_column);m_page_column_layout->setSpacing(0);m_page_column_layout->setContentsMargins(0, 0, 0, 0);+ m_ladybird_button = new LadybirdButton(is_private, this);+ m_vertical_tabs_expanded_width = clamp(m_vertical_tabs_expanded_width, minimum_vertical_tabs_expanded_width(), VERTICAL_TABS_MAX_EXPANDED_WIDTH);+m_new_tab_button = new NewTabButton(*m_tab_bar, this);m_new_tab_button->setObjectName("LadybirdNewTabButton");- m_new_tab_button->setIconSize(QSize(18, 18));m_new_tab_button->setFixedSize(32, 32);m_new_tab_button->setFocusPolicy(Qt::NoFocus);- m_new_tab_button->setToolTip("New Tab");+ m_new_tab_button->setToolTip(qformatted("New Tab {}", QKeySequence(QKeySequence::AddTab).toString(QKeySequence::NativeText)));m_new_tab_button->installEventFilter(this);+ // Once the tabs overflow the strip, a button before the new tab button lists them all.+ m_all_tabs_button = new NewTabButton(*m_tab_bar, this);+ m_all_tabs_button->setObjectName("LadybirdAllTabsButton");+ m_all_tabs_button->setProperty(VERTICAL_TABS_BUTTON_PROPERTY, true);+ m_all_tabs_button->setIconSize(QSize(16, 16));+ m_all_tabs_button->setFixedSize(HORIZONTAL_NEW_TAB_BUTTON_SIZE, HORIZONTAL_NEW_TAB_BUTTON_SIZE);+ m_all_tabs_button->setFocusPolicy(Qt::NoFocus);+ m_all_tabs_button->setToolTip("Show All Tabs");+ m_all_tabs_button->hide();+ QObject::connect(m_all_tabs_button, &QToolButton::clicked, this, [this] { show_all_tabs(); });+if constexpr (use_native_macos_window_controls()) {- // NB: The first tab's room for its flare takes the place of the gap after the window controls.- m_window_controls = create_window_controls_spacer(*this, "LadybirdTabStripWindowControls", { NATIVE_MACOS_WINDOW_CONTROLS_WIDTH + max(0, NATIVE_MACOS_WINDOW_CONTROLS_GAP - HORIZONTAL_TAB_END_ROOM), HORIZONTAL_TAB_HEIGHT });+ m_window_controls = create_window_controls_spacer(*this, "LadybirdTabStripWindowControls", { NATIVE_MACOS_WINDOW_CONTROLS_WIDTH, HORIZONTAL_TAB_HEIGHT });} else {- auto window_control_buttons = create_window_control_buttons(*this, "LadybirdTabStripWindowControls", { 18, 18 }, { 40, 40 });+ auto window_control_buttons = create_window_control_buttons(*this, "LadybirdTabStripWindowControls", { 18, 18 }, { 46, HORIZONTAL_WINDOW_CONTROL_HEIGHT });m_window_controls = window_control_buttons.container;m_minimize_window_button = window_control_buttons.minimize;m_maximize_window_button = window_control_buttons.maximize;@@ -2392,7 +3132,7 @@ TabWidget::TabWidget(QWidget* parent)m_vertical_tabs_toggle_button->setDefaultAction(create_application_action(*this, Application::the().toggle_vertical_tabs_expanded_action()));m_vertical_tabs_toggle_button->setAutoRaise(true);m_vertical_tabs_toggle_button->setFocusPolicy(Qt::NoFocus);- m_vertical_tabs_toggle_button->setIconSize({ 20, 20 });+ m_vertical_tabs_toggle_button->setIconSize({ 16, 16 });m_vertical_tabs_toggle_button->setFixedSize(VERTICAL_TABS_TOGGLE_BUTTON_SIZE, VERTICAL_TABS_TOGGLE_BUTTON_SIZE);m_vertical_tabs_content_separator = new QWidget(this);@@ -2402,6 +3142,8 @@ TabWidget::TabWidget(QWidget* parent)m_vertical_tabs_reserved_space = new QWidget(m_vertical_tabs_content);m_vertical_tabs_reserved_space->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);+ // NB: While the sidebar narrows, the room it leaves shows the strip until the page takes it.+ m_vertical_tabs_reserved_space->setAutoFillBackground(true);m_vertical_tabs_resize_handle = new QWidget(this);m_vertical_tabs_resize_handle->setObjectName("LadybirdVerticalTabsResizeHandle");@@ -2453,6 +3195,7 @@ TabWidget::TabWidget(QWidget* parent)m_toolbar_container->setCurrentIndex(index);emit current_tab_changed(index);+ place_collapsed_sidebar_buttons();update_vertical_tabs_content_separator();update_vertical_tabs_overlay_geometry();update_vertical_tabs_resize_handle();@@ -2540,18 +3283,16 @@ void TabWidget::insert_tab(int index, Tab* widget, QString const& label)m_tab_bar->insertTab(index, label);widget->set_toolbar_container_in_tab_layout(false);m_toolbar_container->insertWidget(index, widget->toolbar_container());+ place_toolbar_over_page_column();widget->set_vertical_tabs_enabled(m_vertical_tabs_enabled);-#ifdef AK_OS_MACOS- update_web_view_frame(*widget);-#endifupdate_toolbar_placement();update_tab_layout();update_tab_button_visibility();// A tab moved here from another window can already be loading.- m_tab_bar->update_loading_swirl_animation();+ m_tab_bar->update_loading_ring_animation();}void TabWidget::remove_tab(int index)@@ -2565,6 +3306,18 @@ Tab* TabWidget::take_tab(int index)if (!widget)return nullptr;+ // NB: Beside the collapsed sidebar, the Ladybird button and the sidebar's toggle sit in the current tab's toolbar,+ // which the tab owns. They belong to this widget, so they don't go along with a tab that leaves it, or is+ // deleted.+ auto* tab_toolbar = as<Tab>(widget)->toolbar_container();+ for (QWidget* button : { static_cast<QWidget*>(m_ladybird_button), static_cast<QWidget*>(m_vertical_tabs_toggle_button) }) {+ if (button && (widget->isAncestorOf(button) || tab_toolbar->isAncestorOf(button))) {+ button->hide();+ button->setParent(this);+ }+ }++ m_tab_bar->prepare_for_tab_removal(index);m_stacked_widget->removeWidget(widget);if (as<Tab>(widget)->is_loaded()) {as<Tab>(widget)->view().removeEventFilter(this);@@ -2583,6 +3336,7 @@ Tab* TabWidget::take_tab(int index)update_tab_layout();update_tab_button_visibility();+ place_collapsed_sidebar_buttons();return as<Tab>(widget);}@@ -2645,12 +3399,155 @@ void TabWidget::set_vertical_tabs_enabled(bool enabled)void TabWidget::set_vertical_tabs_expanded(bool expanded){- if (m_vertical_tabs_expanded == expanded)+ if (m_vertical_tabs_collapse_pending && !expanded)return;+ if (m_vertical_tabs_expanded == expanded && !m_vertical_tabs_collapse_pending)+ return;++ auto animate = m_vertical_tabs_enabled && m_tab_bar_visible && isVisible() && !SystemAppearance::prefers_reduced_motion();+ if (m_vertical_tabs_toggle_animation)+ m_vertical_tabs_toggle_animation->stop();+ m_vertical_tabs_toggling = false;+ m_vertical_tabs_collapse_pending = false;++ if (!animate) {+ m_vertical_tabs_expanded = expanded;+ set_vertical_tabs_hover_expanded(false);+ rebuild_layout();+ float_sidebar_buttons_while_toggling();+ slide_page_with_toggling_sidebar();+ return;+ }- m_vertical_tabs_expanded = expanded;+ // The sidebar keeps its open layout while it narrows, and switches to the collapsed one at the end. Opening, it+ // switches at once and widens over the page.+ m_vertical_tabs_toggle_from_width = current_vertical_tabs_width();+ m_vertical_tabs_toggle_layout_width = vertical_tabs_layout_width();+ m_vertical_tabs_toggle_to_width = expanded ? m_vertical_tabs_expanded_width : VERTICAL_TABS_COLLAPSED_WIDTH;set_vertical_tabs_hover_expanded(false);+ if (expanded)+ m_vertical_tabs_expanded = true;+ else+ m_vertical_tabs_collapse_pending = true;+ m_vertical_tabs_toggling = true;+ m_vertical_tabs_toggle_progress = 0.0;+ // NB: The pictures of the buttons are taken where they are, before the layout changes.+ float_sidebar_buttons_while_toggling();rebuild_layout();+ float_sidebar_buttons_while_toggling();++ if (!m_vertical_tabs_toggle_animation) {+ m_vertical_tabs_toggle_animation = new QVariantAnimation(this);+ m_vertical_tabs_toggle_animation->setDuration(Motion::SLOW);+ m_vertical_tabs_toggle_animation->setEasingCurve(Motion::move_easing());+ m_vertical_tabs_toggle_animation->setStartValue(0.0);+ m_vertical_tabs_toggle_animation->setEndValue(1.0);+ connect(m_vertical_tabs_toggle_animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ m_vertical_tabs_toggle_progress = value.toReal();+ m_vertical_tab_bar_column->update();+ update_tab_layout();+ float_sidebar_buttons_while_toggling();+ slide_page_with_toggling_sidebar();+ update_vertical_tabs_content_overlay();+ });+ connect(m_vertical_tabs_toggle_animation, &QVariantAnimation::finished, this, [this] {+ m_vertical_tabs_toggling = false;+ if (m_vertical_tabs_collapse_pending) {+ m_vertical_tabs_collapse_pending = false;+ m_vertical_tabs_expanded = false;+ }+ rebuild_layout();+ float_sidebar_buttons_while_toggling();+ slide_page_with_toggling_sidebar();+ });+ }+ m_vertical_tabs_toggle_animation->start();+}++// The Ladybird button and the sidebar's toggle sit after the window controls in the toolbar beside the collapsed+// sidebar, and at the edge of the open sidebar's top row. While the sidebar opens or closes, neither layout holds them,+// so pictures of them stand in: The toggle rides the sidebar's edge, and pushes the Ladybird button along once it+// reaches it.+void TabWidget::float_sidebar_buttons_while_toggling()+{+ auto* current = as_if<Tab>(m_stacked_widget->currentWidget());+ auto floats = m_vertical_tabs_toggling && !vertical_tabs_are_on_right() && current;+ if (!floats) {+ for (auto* image : { m_floating_ladybird_button, m_floating_sidebar_toggle }) {+ if (image)+ image->hide();+ }+ return;+ }++ auto make_image = [this](QLabel*& image, QWidget& button) {+ if (!image) {+ image = new QLabel(this);+ image->setAttribute(Qt::WA_TransparentForMouseEvents);+ }+ // NB: The pictures are taken once, where the buttons were in place. A toggle that is reversed midway keeps them.+ if (!image->isVisible() && button.isVisible()) {+ auto device_pixel_ratio = button.devicePixelRatioF();+ QPixmap picture(button.size() * device_pixel_ratio);+ picture.setDevicePixelRatio(device_pixel_ratio);+ picture.fill(Qt::transparent);+ button.render(&picture, QPoint(), QRegion(), QWidget::DrawChildren);+ image->setPixmap(picture);+ image->setFixedSize(button.size());+ }+ button.hide();+ image->show();+ image->raise();+ };+ make_image(m_floating_ladybird_button, *m_ladybird_button);+ make_image(m_floating_sidebar_toggle, *m_vertical_tabs_toggle_button);++ auto column_origin = m_vertical_tab_bar_column->mapTo(this, QPoint());+ auto toolbar_height = Tab::toolbar_height(should_show_window_controls_in_tab_toolbar());+ auto center_y = [&](QWidget const& image) { return column_origin.y() + ((toolbar_height - image.height()) / 2); };++ auto& ladybird_button = *m_floating_ladybird_button;+ auto& toggle = *m_floating_sidebar_toggle;+ auto collapsed_ladybird_x = column_origin.x() + (vertical_tabs_hold_window_controls() ? NATIVE_MACOS_WINDOW_CONTROLS_INSET + NATIVE_MACOS_WINDOW_CONTROLS_WIDTH + LADYBIRD_BUTTON_TRAFFIC_LIGHTS_GAP : vertical_tabs_side_margin(true));+ auto collapsed_toggle_x = collapsed_ladybird_x + ladybird_button.width() + current->toolbar_sidebar_slot().layout()->spacing();+ auto at_edge_x = column_origin.x() + current_vertical_tabs_width() - vertical_tabs_side_margin(true) - SIDEBAR_TOGGLE_PAGE_SIDE_MARGIN - toggle.width();+ auto toggle_x = max(collapsed_toggle_x, at_edge_x);+ toggle.move(toggle_x, center_y(toggle));+ ladybird_button.move(max(collapsed_ladybird_x, toggle_x - SIDEBAR_LADYBIRD_BUTTON_GAP - ladybird_button.width()), center_y(ladybird_button));+}++// While the sidebar on the left opens or closes, the page and its toolbar slide along with the sidebar's edge, so neither+// is covered by the sidebar nor left apart from it. The page keeps the width it has beside the collapsed sidebar,+// reaching past the window's edge where the sidebar is wider, so it resizes only once: as the sidebar starts to close, or+// once it is open.+// NB: The sidebar on the right widens over the page instead, as sliding the toolbar to the left would take the window+// controls and the navigation buttons under the window's edge.+bool TabWidget::slides_page_with_toggling_sidebar() const+{+ return m_vertical_tabs_toggling && !vertical_tabs_are_on_right();+}++void TabWidget::slide_page_with_toggling_sidebar()+{+ auto* current = as_if<Tab>(m_stacked_widget->currentWidget());+ if (!slides_page_with_toggling_sidebar()) {+ if (current)+ current->set_toolbar_leading_room(0);+ return;+ }+ // NB: The toolbar's contents start where they sit beside the collapsed sidebar, until the sidebar's edge reaches them.+ if (current)+ current->set_toolbar_leading_room(max(0, current->toolbar_lead_beside_collapsed_sidebar(*m_ladybird_button, COLLAPSED_VERTICAL_TABS_TOGGLE_BUTTON_SIZE) - current_vertical_tabs_width()));+ auto page_width = m_vertical_tabs_content->width() - min(m_vertical_tabs_toggle_from_width, m_vertical_tabs_toggle_to_width);+ m_page_column->setGeometry(current_vertical_tabs_width(), 0, page_width, m_vertical_tabs_content->height());+}++// While the sidebar collapses, its tab titles fade out at the start of its narrowing.+qreal TabWidget::vertical_tab_title_opacity() const+{+ if (!m_vertical_tabs_collapse_pending || !m_vertical_tabs_toggle_animation || m_vertical_tabs_toggle_animation->state() != QAbstractAnimation::Running)+ return 1;+ return max(0.0, 1 - (static_cast<qreal>(m_vertical_tabs_toggle_animation->currentTime()) / Motion::EXIT));}void TabWidget::set_vertical_tabs_expand_on_hover(bool expand_on_hover)@@ -2682,10 +3579,10 @@ bool TabWidget::event(QEvent* event)} else if (type == QEvent::WindowStateChange) {update_window_button_icons();} else if (type == QEvent::WindowActivate || type == QEvent::WindowDeactivate) {- // The tab strip and the sidebar are lighter while the window is inactive.- auto inactive = type == QEvent::WindowDeactivate;- set_dynamic_property_if_needed(*m_tab_bar_row, WINDOW_INACTIVE_PROPERTY, inactive);- set_dynamic_property_if_needed(*m_vertical_tab_bar_column, WINDOW_INACTIVE_PROPERTY, inactive);+ // An inactive window's tab titles and strip icons drop to the muted color.+ recreate_icons();+ m_tab_bar->update();+ m_ladybird_button->update();} else if (type == QEvent::Leave) {defer_update_vertical_tabs_hover_expanded();}@@ -2721,8 +3618,8 @@ bool TabWidget::eventFilter(QObject* watched, QEvent* event)if (watched == m_tab_bar && (event->type() == QEvent::Move || event->type() == QEvent::Resize))place_horizontal_new_tab_button();- if (watched == m_vertical_tab_bar_column && event->type() == QEvent::Paint && !m_vertical_tabs_expanded) {- paint_collapsed_vertical_tabs_column();+ if (watched == m_vertical_tab_bar_column && event->type() == QEvent::Paint) {+ paint_vertical_tabs_column();return true;}@@ -2818,8 +3715,13 @@ bool TabWidget::eventFilter(QObject* watched, QEvent* event)if (watched == m_vertical_tabs_content && event->type() == QEvent::Leave)defer_update_vertical_tabs_hover_expanded();- if (watched == m_toolbar_container && event->type() == QEvent::Resize)+ if ((watched == m_page_column || watched == m_vertical_tabs_content) && (event->type() == QEvent::Move || event->type() == QEvent::Resize))+ place_toolbar_over_page_column();++ if (watched == m_toolbar_container && event->type() == QEvent::Resize) {+ update_vertical_tabs_column_margins();update_tab_layout();+ }auto is_vertical_tabs_hover_target = watched == m_vertical_tab_bar_column|| watched == m_tab_bar@@ -2876,6 +3778,7 @@ void TabWidget::resizeEvent(QResizeEvent* event){QWidget::resizeEvent(event);update_tab_layout();+ slide_page_with_toggling_sidebar();}// The stacked layout sizes only the current page, so the tabs behind it keep stale geometry: Qt's default 100x30 for@@ -2904,9 +3807,7 @@ void TabWidget::accept_tab_drag(QDragMoveEvent* event, QWidget* target)return;}- auto* drag_area = tab_drag_area_widget();- auto position_in_drag_area = drag_area->mapFrom(target, event->position().toPoint());- if (!drag_area->rect().contains(position_in_drag_area)) {+ if (!tab_drop_area_contains(*target, event->position().toPoint())) {m_tab_bar->hide_drop_preview();event->ignore();return;@@ -2937,6 +3838,18 @@ TabLayout TabWidget::current_tab_layout() constreturn vertical_tabs_effectively_expanded() ? TabLayout::VerticalExpanded : TabLayout::VerticalCollapsed;}+// A tab dragged a little way off the strip, onto the toolbar for example, still lands in it. Only one dragged further+// away is detached into a window of its own.+bool TabWidget::tab_drop_area_contains(QWidget const& widget, QPoint position) const+{+ auto* drag_area = tab_drag_area_widget();+ auto position_in_drag_area = drag_area->mapFrom(window(), widget.mapTo(window(), position));+ auto drop_area = m_tab_bar->tab_layout() == TabLayout::Horizontal+ ? drag_area->rect().adjusted(0, -TAB_DETACH_DISTANCE, 0, TAB_DETACH_DISTANCE)+ : drag_area->rect().adjusted(-TAB_DETACH_DISTANCE, 0, TAB_DETACH_DISTANCE, 0);+ return drop_area.contains(position_in_drag_area);+}+QWidget* TabWidget::tab_drag_area_widget() const{return m_tab_bar->tab_layout() == TabLayout::Horizontal ? m_tab_bar_row : m_vertical_tab_bar_column;@@ -2977,6 +3890,9 @@ int TabWidget::vertical_tabs_layout_width() const{if (!m_tab_bar_visible)return 0;+ // NB: While the sidebar opens or closes, the page keeps its room, and resizes once at the end.+ if (m_vertical_tabs_toggling)+ return m_vertical_tabs_toggle_layout_width;return m_vertical_tabs_expanded ? m_vertical_tabs_expanded_width : VERTICAL_TABS_COLLAPSED_WIDTH;}@@ -2991,22 +3907,33 @@ bool TabWidget::vertical_tabs_hold_window_controls() constreturn use_native_macos_window_controls() && m_window_controls_visible && m_vertical_tabs_expanded && !vertical_tabs_are_on_right();}-int TabWidget::vertical_tabs_column_top_margin() const+// The open sidebar's top row is level with the toolbar, and the collapsed sidebar starts below the toolbar and the line+// under it. The open sidebar's tabs start as far down as the collapsed sidebar's, so they stay in place as it toggles.+int TabWidget::vertical_tabs_header_spacing() const{- // NB: The open sidebar's top row is level with the toolbar, at the top of the window.- return m_vertical_tabs_expanded ? 0 : VERTICAL_TABS_TOP_MARGIN;+ auto toolbar_line_height = max(0, m_toolbar_container->height() - Tab::toolbar_height(should_show_window_controls_in_tab_toolbar()));+ return VERTICAL_TABS_TOP_MARGIN - VERTICAL_TAB_BAR_END_ROOM + toolbar_line_height;}-void TabWidget::update_toolbar_placement()+// On macOS, the open sidebar is at its narrowest when its Ladybird button and toggle sit where they do beside the+// collapsed sidebar, so neither moves as it toggles.+int TabWidget::minimum_vertical_tabs_expanded_width() const{- auto use_full_width_toolbar = current_tab_layout() != TabLayout::Horizontal;+ if (!use_native_macos_window_controls() || !m_ladybird_button)+ return VERTICAL_TABS_MIN_EXPANDED_WIDTH;+ return NATIVE_MACOS_WINDOW_CONTROLS_INSET + NATIVE_MACOS_WINDOW_CONTROLS_WIDTH + LADYBIRD_BUTTON_TRAFFIC_LIGHTS_GAP+ + m_ladybird_button->width() + SIDEBAR_LADYBIRD_BUTTON_GAP + VERTICAL_TABS_TOGGLE_BUTTON_SIZE+ + SIDEBAR_TOGGLE_PAGE_SIDE_MARGIN + vertical_tabs_side_margin(true);+}- for (int index = 0; index < m_stacked_widget->count(); ++index) {- auto* current_tab = tab(index);- auto* toolbar = current_tab->toolbar_container();- set_dynamic_property_if_needed(*toolbar, FULL_WIDTH_TOOLBAR_PROPERTY, use_full_width_toolbar);- }+// How far the opening or closing sidebar is from open, from 0 when open to 1 when collapsed.+qreal TabWidget::vertical_tabs_toggle_collapsedness() const+{+ return m_vertical_tabs_collapse_pending ? m_vertical_tabs_toggle_progress : 1 - m_vertical_tabs_toggle_progress;+}+void TabWidget::update_toolbar_placement()+{m_toolbar_container->setCurrentIndex(m_tab_bar->currentIndex());update_tab_toolbar_window_controls_visibility();}@@ -3048,6 +3975,7 @@ void TabWidget::rebuild_layout()clear_layout(*m_tab_bar_row_layout);clear_layout(*m_page_column_layout);clear_layout(*m_vertical_tab_bar_column_layout);+ m_vertical_tabs_header_spacer = nullptr;clear_layout(*m_vertical_tabs_content_layout);m_tab_bar->set_vertical_tabs_position(m_vertical_tabs_position);@@ -3060,25 +3988,41 @@ void TabWidget::rebuild_layout()// The open sidebar runs the full height of the window, with the toolbar beside it above the page. The collapsed// sidebar sits below a toolbar across the whole window.- QWidget* page = m_stacked_widget;+ // NB: The page stays in the page column either way, as a page that moves to another parent is shown at a stale+ // place for a few frames on macOS.+ QWidget* page = m_page_column;if (m_vertical_tabs_expanded) {rebuild_page_column();- page = m_page_column;- m_page_column->show();} else {+ m_toolbar_follows_page_column = false;+ m_toolbar_placeholder->hide();m_main_layout->addWidget(m_toolbar_container);- m_page_column->hide();+ m_page_column_layout->addWidget(m_stacked_widget, 1);}+ m_page_column->show();- if (vertical_tabs_are_on_right()) {+ if (slides_page_with_toggling_sidebar()) {+ // NB: While the sidebar opens or closes, the page is placed by slide_page_with_toggling_sidebar() rather+ // than laid out.+ if (page->parentWidget() != m_vertical_tabs_content)+ page->setParent(m_vertical_tabs_content);+ m_vertical_tabs_reserved_space->hide();+ page->show();+ } else if (vertical_tabs_are_on_right()) {m_vertical_tabs_content_layout->addWidget(page, 1);m_vertical_tabs_content_layout->addWidget(m_vertical_tabs_reserved_space);+ m_vertical_tabs_reserved_space->show();} else {m_vertical_tabs_content_layout->addWidget(m_vertical_tabs_reserved_space);m_vertical_tabs_content_layout->addWidget(page, 1);+ m_vertical_tabs_reserved_space->show();}m_main_layout->addWidget(m_vertical_tabs_content, 1);m_vertical_tabs_content->show();+ if (slides_page_with_toggling_sidebar()) {+ m_main_layout->activate();+ slide_page_with_toggling_sidebar();+ }} else {rebuild_layout_for_horizontal_tabs();rebuild_page_column();@@ -3092,38 +4036,53 @@ void TabWidget::rebuild_layout()update_tab_button_visibility();update_tab_chrome_visibility();update_tab_layout();+ place_collapsed_sidebar_buttons();+ m_main_layout->activate();+ place_toolbar_over_page_column();}void TabWidget::rebuild_layout_for_horizontal_tabs(){m_tab_bar_row->setMinimumHeight(HORIZONTAL_TAB_STRIP_HEIGHT);m_tab_bar_row_layout->setSpacing(0);- // NB: Without window controls before it, the first tab's room for its flare takes the place of the strip's margin.- m_tab_bar_row_layout->setContentsMargins(use_native_macos_window_controls() ? 12 : max(0, 12 - HORIZONTAL_TAB_END_ROOM), 2, 4, 0);+ m_tab_bar_row_layout->setContentsMargins(HORIZONTAL_TAB_STRIP_LEADING_MARGIN, HORIZONTAL_TAB_STRIP_HEIGHT - HORIZONTAL_TAB_HEIGHT, 8, 0);- m_new_tab_button->setText({});set_dynamic_property_if_needed(*m_new_tab_button, VERTICAL_TABS_EXPANDED_PROPERTY, false);set_dynamic_property_if_needed(*m_new_tab_button, VERTICAL_TABS_BUTTON_PROPERTY, true);- m_new_tab_button->setToolButtonStyle(Qt::ToolButtonIconOnly);- m_new_tab_button->setFixedSize(HORIZONTAL_TAB_HEIGHT, HORIZONTAL_TAB_HEIGHT);+ m_new_tab_button->setFixedSize(HORIZONTAL_NEW_TAB_BUTTON_HIT_SIZE, HORIZONTAL_NEW_TAB_BUTTON_HIT_SIZE);+ m_new_tab_button->setIconSize(QSize(HORIZONTAL_NEW_TAB_BUTTON_ICON_SIZE, HORIZONTAL_NEW_TAB_BUTTON_ICON_SIZE));m_new_tab_button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);// NB: The tabs sit on the bottom of the strip, so the selected tab meets the toolbar however tall the strip is.- // NB: The new tab button overlaps the tab bar, which a layout cannot do, so the row only leaves room for the rest of- // it, and place_horizontal_new_tab_button() puts it in place.+ // NB: The new tab button is placed by place_horizontal_new_tab_button(), as its gap is measured from the last tab+ // rather than from that tab's room for its foot. The row leaves room for it after the tab bar.m_new_tab_button->setParent(m_tab_bar_row);m_new_tab_button->show();- auto new_tab_button_room = HORIZONTAL_TAB_HEIGHT - HORIZONTAL_NEW_TAB_BUTTON_OVERLAP;+ auto new_tab_button_room = HORIZONTAL_NEW_TAB_BUTTON_GAP - HORIZONTAL_TAB_END_ROOM + HORIZONTAL_NEW_TAB_BUTTON_SIZE + horizontal_tab_strip_drag_space();+ // The Ladybird button comes first after the traffic lights, and first on the strip where the window controls are+ // on the other side. Like the new tab button, it is centered on the middle of the tabs.+ // NB: The first tab's room for its foot takes part of the gap after the Ladybird button.+ m_ladybird_button->setParent(m_tab_bar_row);+ // NB: The button sits at the bottom of the tab row, and its tile is centered in the strip.+ m_ladybird_button->set_tile_vertical_offset(HORIZONTAL_WINDOW_ITEM_CENTER - (HORIZONTAL_TAB_STRIP_HEIGHT - HORIZONTAL_TAB_HEIGHT) - (m_ladybird_button->sizeHint().height() / 2));+ m_ladybird_button->show();+ auto add_ladybird_button = [&] {+ m_tab_bar_row_layout->addWidget(m_ladybird_button, 0, Qt::AlignBottom);+ m_tab_bar_row_layout->addSpacing(LADYBIRD_BUTTON_TRAILING_GAP - HORIZONTAL_TAB_END_ROOM);+ };if constexpr (use_native_macos_window_controls()) {m_tab_bar_row_layout->addWidget(m_window_controls, 0, Qt::AlignVCenter);+ m_tab_bar_row_layout->addSpacing(LADYBIRD_BUTTON_TRAFFIC_LIGHTS_GAP);+ add_ladybird_button();m_tab_bar_row_layout->addWidget(m_tab_bar, 0, Qt::AlignBottom);m_tab_bar_row_layout->addSpacing(new_tab_button_room);m_tab_bar_row_layout->addStretch(1);} else {+ add_ladybird_button();m_tab_bar_row_layout->addWidget(m_tab_bar, 0, Qt::AlignBottom);m_tab_bar_row_layout->addSpacing(new_tab_button_room);m_tab_bar_row_layout->addStretch(1);- m_tab_bar_row_layout->addWidget(m_window_controls);+ m_tab_bar_row_layout->addWidget(m_window_controls, 0, Qt::AlignTop);}place_horizontal_new_tab_button();}@@ -3133,11 +4092,134 @@ void TabWidget::place_horizontal_new_tab_button()if (m_tab_bar->tab_layout() != TabLayout::Horizontal)return;+ // The button is centered on the middle of the tabs, like everything else on the strip.auto tab_bar_geometry = m_tab_bar->geometry();- m_new_tab_button->move(tab_bar_geometry.right() + 1 - HORIZONTAL_NEW_TAB_BUTTON_OVERLAP, tab_bar_geometry.bottom() + 1 - m_new_tab_button->height());+ // NB: While tabs open and close, the button follows the end of the tabs, rather than the end of the tab bar. The bar+ // already grows to hold tabs that end beyond where they settle (see update_tab_layout()).+ auto x = tab_bar_geometry.right() + 1 - HORIZONTAL_TAB_END_ROOM + HORIZONTAL_NEW_TAB_BUTTON_GAP + min(0, m_tab_bar->horizontal_tabs_end_offset());+ // NB: The buttons are centered on the tabs' cards, which the strip's line runs through.+ auto card_height = HORIZONTAL_TAB_HEIGHT - HORIZONTAL_TAB_CARD_SHAPE_TOP_INSET - HORIZONTAL_TAB_CARD_SHAPE_BOTTOM_INSET;+ auto y = tab_bar_geometry.top() + HORIZONTAL_TAB_CARD_SHAPE_TOP_INSET + ((card_height - m_new_tab_button->height()) / 2);+ // NB: Before the window is first shown, no widget in it is visible, so this asks whether the button is hidden.+ if (!m_all_tabs_button->isHidden()) {+ m_all_tabs_button->move(x, y);+ m_all_tabs_button->raise();+ x += HORIZONTAL_NEW_TAB_BUTTON_SIZE;+ }+ m_new_tab_button->move(x + ((HORIZONTAL_NEW_TAB_BUTTON_SIZE - m_new_tab_button->width()) / 2), y);m_new_tab_button->raise();}+// NB: Where the strip ends at the window's edge, its margin there is part of the free space.+int TabWidget::horizontal_tab_strip_drag_space() const+{+ if constexpr (use_native_macos_window_controls())+ return HORIZONTAL_TAB_STRIP_DRAG_SPACE - m_tab_bar_row_layout->contentsMargins().right();+ return HORIZONTAL_TAB_STRIP_DRAG_SPACE;+}++static constexpr size_t RECENTLY_CLOSED_LIMIT = 5;++static QString time_since_closed(AK::Duration duration)+{+ auto minutes = duration.to_seconds() / 60;+ if (minutes < 1)+ return QStringLiteral("Just now");+ if (minutes < 60)+ return qformatted("{} min ago", minutes);+ auto hours = minutes / 60;+ if (hours < 24)+ return hours == 1 ? QStringLiteral("1 hour ago") : qformatted("{} hours ago", hours);+ auto days = hours / 24;+ return days == 1 ? QStringLiteral("Yesterday") : qformatted("{} days ago", days);+}++void TabWidget::show_all_tabs()+{+ if (!m_all_tabs_popover) {+ m_all_tabs_popover = new AllTabsPopover(this);+ m_all_tabs_popover->update_chrome_style(palette());+ m_all_tabs_popover->on_tab_activated = [this](size_t index) {+ if (static_cast<int>(index) < count())+ set_current_index(static_cast<int>(index));+ };+ m_all_tabs_popover->on_recently_closed_activated = [this](size_t index) {+ if (index < m_recently_closed_unit_ids.size())+ Application::the().reopen_recently_closed_tab(as_if<BrowserWindow>(window()), m_recently_closed_unit_ids[index]);+ };+ }++ Vector<AllTabsPopover::Entry> entries;+ entries.ensure_capacity(count());+ for (int index = 0; index < count(); ++index) {+ auto* tab = this->tab(index);+ auto url = tab->url();+ entries.unchecked_append({+ .icon = tab->favicon(),+ .title = tab->title(),+ .detail = url.host().has_value() ? qstring_from_ak_string(url.serialized_host()) : QString {},+ .is_current = index == current_index(),+ });+ }+ m_all_tabs_popover->set_tabs(AK::move(entries));++ Vector<AllTabsPopover::Entry> closed_entries;+ m_recently_closed_unit_ids.clear();+ if (auto* browser_window = as_if<BrowserWindow>(window())) {+ auto& session = browser_window->session();+ auto now = UnixDateTime::now();+ for (auto const& unit : session.session_store->recently_closed_units(RECENTLY_CLOSED_LIMIT)) {+ auto entry = session.history_store->entry_for_url(unit.active_url);+ auto title = entry.has_value() && entry->title.has_value() && !entry->title->is_empty() ? qstring_from_ak_string(*entry->title) : qstring_from_ak_string(unit.active_url.serialize());+ if (unit.was_window)+ title = unit.tab_count == 1 ? QStringLiteral("Window with 1 tab") : qformatted("Window with {} tabs", unit.tab_count);+ closed_entries.append({+ .icon = entry.has_value() && entry->favicon_png.has_value() ? icon_from_png(entry->favicon_png->bytes(), TAB_ICON_SIZE) : QIcon {},+ .title = AK::move(title),+ .detail = time_since_closed(now - unit.closed_at),+ .is_current = false,+ });+ m_recently_closed_unit_ids.append(unit.id);+ }+ }+ m_all_tabs_popover->set_recently_closed(AK::move(closed_entries));++ // The list hangs from the button that opens it, or else from the Ladybird button.+ if (!m_all_tabs_button->isHidden())+ move_popover_below(*m_all_tabs_popover, *m_all_tabs_button, PopoverAlignment::Trailing);+ else+ move_popover_below(*m_all_tabs_popover, *m_ladybird_button, PopoverAlignment::Leading, m_ladybird_button->tile_rect());+ m_all_tabs_popover->show();+}++void TabWidget::place_collapsed_sidebar_buttons()+{+ auto collapsed = m_tab_bar_visible && m_tab_bar->tab_layout() != TabLayout::Horizontal && !m_vertical_tabs_expanded;+ auto* current = as_if<Tab>(m_stacked_widget->currentWidget());+ for (int index = 0; index < m_stacked_widget->count(); ++index) {+ if (auto* tab = this->tab(index); tab && (tab != current || !collapsed))+ tab->toolbar_sidebar_slot().hide();+ }+ if (!current || !collapsed)+ return;++ auto& slot = current->toolbar_sidebar_slot();+ auto* slot_layout = static_cast<QBoxLayout*>(slot.layout());+ if (m_ladybird_button->parentWidget() != &slot) {+ m_ladybird_button->setParent(&slot);+ m_ladybird_button->set_tile_vertical_offset(0);+ slot_layout->insertWidget(0, m_ladybird_button, 0, Qt::AlignVCenter);+ }+ if (m_vertical_tabs_toggle_button->parentWidget() != &slot) {+ m_vertical_tabs_toggle_button->setParent(&slot);+ m_vertical_tabs_toggle_button->setFixedSize(COLLAPSED_VERTICAL_TABS_TOGGLE_BUTTON_SIZE);+ slot_layout->insertWidget(1, m_vertical_tabs_toggle_button, 0, Qt::AlignVCenter);+ }+ m_ladybird_button->show();+ m_vertical_tabs_toggle_button->show();+ slot.show();+}+void TabWidget::rebuild_layout_for_vertical_tabs(){update_vertical_tabs_toggle_icon();@@ -3158,80 +4240,122 @@ void TabWidget::rebuild_layout_for_vertical_tabs()top_row_layout->setSpacing(0);if (m_vertical_tabs_expanded) {// The open sidebar runs the full height of the window. Its top row sits beside the toolbar, and holds the window- // controls when they are on its side, with the sidebar's toggle at the edge toward the page.- auto page_side_margin = vertical_tabs_side_margin(true);- top_row_layout->setContentsMargins(vertical_tabs_are_on_right() ? page_side_margin : 0, 0, vertical_tabs_are_on_right() ? 0 : page_side_margin, 0);+ // controls when they are on its side, with the Ladybird button and the sidebar's toggle at the edge toward the+ // page.+ top_row_layout->setContentsMargins(vertical_tabs_are_on_right() ? SIDEBAR_TOGGLE_PAGE_SIDE_MARGIN : 0, 0, vertical_tabs_are_on_right() ? 0 : SIDEBAR_TOGGLE_PAGE_SIDE_MARGIN, 0);top_row_layout->addStrut(Tab::toolbar_height(should_show_window_controls_in_tab_toolbar()));- if (vertical_tabs_hold_window_controls())- top_row_layout->addSpacing(NATIVE_MACOS_WINDOW_CONTROLS_WIDTH);- if (!vertical_tabs_are_on_right())+ m_vertical_tabs_toggle_button->setParent(m_vertical_tab_bar_column);+ // NB: The button was smaller while it sat in the collapsed sidebar's slot.+ m_vertical_tabs_toggle_button->setFixedSize(VERTICAL_TABS_TOGGLE_BUTTON_SIZE, VERTICAL_TABS_TOGGLE_BUTTON_SIZE);+ m_vertical_tabs_toggle_button->show();+ if (vertical_tabs_are_on_right()) {+ top_row_layout->addWidget(m_vertical_tabs_toggle_button, 0, Qt::AlignVCenter);+ top_row_layout->addSpacing(SIDEBAR_LADYBIRD_BUTTON_GAP);+ top_row_layout->addWidget(m_ladybird_button, 0, Qt::AlignVCenter);top_row_layout->addStretch(1);- top_row_layout->addWidget(m_vertical_tabs_toggle_button, 0, Qt::AlignVCenter);- if (vertical_tabs_are_on_right())+ } else {top_row_layout->addStretch(1);+ top_row_layout->addWidget(m_ladybird_button, 0, Qt::AlignVCenter);+ top_row_layout->addSpacing(SIDEBAR_LADYBIRD_BUTTON_GAP);+ top_row_layout->addWidget(m_vertical_tabs_toggle_button, 0, Qt::AlignVCenter);+ }} else {- // The collapsed sidebar's toggle sits above its tabs, centered on the collapsed sidebar, and stays put while- // the sidebar opens on hover.- auto collapsed_tab_width = VERTICAL_TABS_COLLAPSED_WIDTH - vertical_tabs_horizontal_margin_width(TabLayout::VerticalCollapsed);- auto inset = (collapsed_tab_width - VERTICAL_TABS_TOGGLE_BUTTON_SIZE) / 2;- top_row_layout->setContentsMargins(vertical_tabs_are_on_right() ? 0 : inset, 0, vertical_tabs_are_on_right() ? inset : 0, 0);- // NB: The tab bar below leaves room above its first tab.- top_row_layout->addStrut(VERTICAL_TAB_HEIGHT - VERTICAL_TAB_FLARE_RADIUS);- if (vertical_tabs_are_on_right())- top_row_layout->addStretch(1);- top_row_layout->addWidget(m_vertical_tabs_toggle_button, 0, Qt::AlignVCenter);- if (!vertical_tabs_are_on_right())- top_row_layout->addStretch(1);+ // The collapsed rail holds only tabs. The Ladybird button and the sidebar's toggle move to the toolbar, after+ // the window controls (see place_collapsed_sidebar_buttons()). Its tabs start as far below the toolbar as the+ // open sidebar's start below its top row.+ m_vertical_tab_bar_column_layout->addSpacing(VERTICAL_TABS_TOP_MARGIN - VERTICAL_TAB_BAR_END_ROOM);+ }+ if (m_vertical_tabs_expanded) {+ m_ladybird_button->setParent(m_vertical_tab_bar_column);+ m_ladybird_button->set_tile_vertical_offset(0);+ m_ladybird_button->show();+ m_vertical_tab_bar_column_layout->addLayout(top_row_layout);+ m_vertical_tabs_header_spacer = new QSpacerItem(0, vertical_tabs_header_spacing(), QSizePolicy::Fixed, QSizePolicy::Fixed);+ m_vertical_tab_bar_column_layout->addItem(m_vertical_tabs_header_spacer);+ } else {+ delete top_row_layout;}- m_vertical_tab_bar_column_layout->addLayout(top_row_layout);- if (m_vertical_tabs_expanded)- m_vertical_tab_bar_column_layout->addSpacing(VERTICAL_TABS_TOP_MARGIN - VERTICAL_TAB_FLARE_RADIUS);m_vertical_tab_bar_column_layout->addWidget(m_tab_bar);m_vertical_tab_bar_column_layout->addWidget(m_new_tab_button, 0, vertical_tabs_are_on_right() ? Qt::AlignRight : Qt::AlignLeft);m_vertical_tab_bar_column_layout->addStretch(1);}-// The collapsed sidebar sits below the toolbar, which flows around its rounded corner beside the page into the frame-// around the page.-void TabWidget::paint_collapsed_vertical_tabs_column()+// A divider runs along the sidebar's edge toward the page.+void TabWidget::paint_vertical_tabs_column(){QPainter painter(m_vertical_tab_bar_column);QStyleOption option;option.initFrom(m_vertical_tab_bar_column);m_vertical_tab_bar_column->style()->drawPrimitive(QStyle::PE_Widget, &option, &painter, m_vertical_tab_bar_column);- auto radius = VERTICAL_TABS_COLLAPSED_CORNER_RADIUS;- auto page_edge = vertical_tabs_are_on_right() ? 0.0 : static_cast<qreal>(m_vertical_tab_bar_column->width());- auto corner_left = vertical_tabs_are_on_right() ? page_edge : page_edge - radius;-- QPainterPath corner;- corner.addRect(corner_left, 0, radius, radius);- QPainterPath inside;- inside.addEllipse(QPointF(vertical_tabs_are_on_right() ? page_edge + radius : page_edge - radius, radius), radius, radius);-- painter.setRenderHint(QPainter::Antialiasing, true);- painter.fillPath(corner.subtracted(inside), ChromeStyle::chrome_background(palette()));+ auto const& chrome = Theme::chrome(*this);+ auto column_rect = m_vertical_tab_bar_column->rect();+ auto page_edge_x = vertical_tabs_are_on_right() ? column_rect.left() : column_rect.right();++ // NB: While the sidebar opens or closes, its top row turns between its own color and the toolbar's, which the+ // collapsed sidebar sits below, so that the corner doesn't change color at once as the layout switches.+ auto top_row_height = 0;+ if (m_vertical_tabs_toggling) {+ auto collapsedness = vertical_tabs_toggle_collapsedness();+ top_row_height = Tab::toolbar_height(should_show_window_controls_in_tab_toolbar());+ painter.fillRect(QRect(0, 0, column_rect.width(), top_row_height), ChromeStyle::mix(chrome.sidebar, chrome.toolbar, collapsedness));+ auto faded_divider = chrome.divider;+ faded_divider.setAlphaF(faded_divider.alphaF() * (1 - collapsedness));+ painter.fillRect(QRect(page_edge_x, 0, 1, top_row_height), faded_divider);+ }+ painter.fillRect(QRect(page_edge_x, top_row_height, 1, column_rect.height() - top_row_height), chrome.divider);}void TabWidget::update_vertical_tabs_column_margins(){- // NB: The tab bar reaches the page's side of the sidebar, where its selected tab joins the page's frame, so the- // column has no margin on that side.- auto side_margin = vertical_tabs_side_margin(m_tab_bar->tab_layout() != TabLayout::VerticalCollapsed);- auto left = vertical_tabs_are_on_right() ? 0 : side_margin;- auto right = vertical_tabs_are_on_right() ? side_margin : 0;- m_vertical_tab_bar_column_layout->setContentsMargins(left, vertical_tabs_column_top_margin(), right, 8);+ // NB: In the open sidebar, the tabs are inset alike from both of its sides. The collapsed sidebar's tab bar reaches+ // the page's side of it.+ auto expanded = m_tab_bar->tab_layout() != TabLayout::VerticalCollapsed;+ auto side_margin = vertical_tabs_side_margin(expanded);+ auto page_side_margin = expanded ? side_margin : 0;+ auto left = vertical_tabs_are_on_right() ? page_side_margin : side_margin;+ auto right = vertical_tabs_are_on_right() ? side_margin : page_side_margin;+ m_vertical_tab_bar_column_layout->setContentsMargins(left, 0, right, 8);+ if (m_vertical_tabs_header_spacer && m_vertical_tabs_header_spacer->sizeHint().height() != vertical_tabs_header_spacing()) {+ m_vertical_tabs_header_spacer->changeSize(0, vertical_tabs_header_spacing(), QSizePolicy::Fixed, QSizePolicy::Fixed);+ m_vertical_tab_bar_column_layout->invalidate();+ }}+// The toolbar heads the page column, except beside the collapsed sidebar, where it runs across the whole window.+// NB: The toolbar is never moved to another parent, as that would hide it for a frame and take focus from the address+// field. Instead, it is placed over a stand-in at the top of the page column.void TabWidget::rebuild_page_column(){- m_page_column_layout->addWidget(m_toolbar_container);+ m_toolbar_follows_page_column = true;+ m_toolbar_placeholder->setVisible(m_tab_bar_visible);+ m_page_column_layout->addWidget(m_toolbar_placeholder);m_page_column_layout->addWidget(m_stacked_widget, 1);}+void TabWidget::place_toolbar_over_page_column()+{+ if (!m_toolbar_follows_page_column)+ return;++ // NB: The stand-in is as tall as the toolbar, which is only known once a tab's toolbar is in it.+ if (auto toolbar_height = m_toolbar_container->sizeHint().height(); m_toolbar_placeholder->height() != toolbar_height) {+ m_toolbar_placeholder->setFixedHeight(toolbar_height);+ m_page_column_layout->activate();+ }++ auto position = m_page_column->mapTo(this, QPoint());+ m_toolbar_container->setGeometry(position.x(), position.y(), m_page_column->width(), m_toolbar_placeholder->height());+ m_toolbar_container->stackUnder(m_vertical_tab_bar_column);+ if (m_vertical_tabs_content_separator->isVisible())+ m_vertical_tabs_content_separator->raise();+}+int TabWidget::current_vertical_tabs_width() const{+ if (m_vertical_tabs_toggling)+ return m_vertical_tabs_toggle_from_width + qRound((m_vertical_tabs_toggle_to_width - m_vertical_tabs_toggle_from_width) * m_vertical_tabs_toggle_progress);if (m_vertical_tabs_hover_expanded)return VERTICAL_TABS_COLLAPSED_WIDTH + qRound((m_vertical_tabs_expanded_width - VERTICAL_TABS_COLLAPSED_WIDTH) * m_vertical_tabs_hover_expand_progress);@@ -3240,7 +4364,7 @@ int TabWidget::current_vertical_tabs_width() constvoid TabWidget::apply_vertical_tabs_expanded_width(int width){- auto clamped_width = clamp_vertical_tabs_expanded_width(width);+ auto clamped_width = clamp(width, minimum_vertical_tabs_expanded_width(), VERTICAL_TABS_MAX_EXPANDED_WIDTH);if (m_vertical_tabs_expanded_width == clamped_width)return;@@ -3266,7 +4390,9 @@ void TabWidget::set_resize_handle_property(char const* property, bool enabled)void TabWidget::update_vertical_tabs_resize_handle(){auto is_vertical = m_tab_bar->tab_layout() != TabLayout::Horizontal;- auto show_resize_handle = m_tab_bar_visible && is_vertical && m_vertical_tabs_expanded;+ // NB: The handle is a native view over the page, and shows what Qt drew behind it rather than the page. While the+ // sidebar opens or closes, its edge moves away from the handle, so the handle stays hidden until it settles.+ auto show_resize_handle = m_tab_bar_visible && is_vertical && m_vertical_tabs_expanded && !m_vertical_tabs_toggling;m_vertical_tabs_resize_handle->setVisible(show_resize_handle);if (!show_resize_handle) {m_vertical_tabs_resize_handle->releaseMouse();@@ -3307,13 +4433,6 @@ void TabWidget::update_vertical_tabs_content_separator()m_vertical_tabs_content_separator->raise();}-void TabWidget::update_vertical_tabs_action_labels()-{- auto text = vertical_tabs_effectively_expanded() ? "New Tab" : QString {};- if (m_new_tab_button->text() != text)- m_new_tab_button->setText(text);-}-void TabWidget::update_vertical_tabs_hover_layout(){m_tab_bar->set_pinned_tabs_in_rows(m_vertical_tabs_hover_expanded && !m_vertical_tabs_expanded);@@ -3349,10 +4468,6 @@ int TabWidget::vertical_tabs_tab_width() constvoid TabWidget::update_vertical_tabs_button_layout(){auto expanded = vertical_tabs_effectively_expanded();- auto tool_button_style = expanded ? Qt::ToolButtonTextBesideIcon : Qt::ToolButtonIconOnly;- if (m_new_tab_button->toolButtonStyle() != tool_button_style)- m_new_tab_button->setToolButtonStyle(tool_button_style);- update_vertical_tabs_action_labels();set_dynamic_property_if_needed(*m_new_tab_button, VERTICAL_TABS_BUTTON_PROPERTY, true);set_dynamic_property_if_needed(*m_new_tab_button, VERTICAL_TABS_EXPANDED_PROPERTY, expanded);auto tab_width = vertical_tabs_tab_width();@@ -3365,6 +4480,7 @@ void TabWidget::update_vertical_tabs_button_layout()void TabWidget::update_tab_layout(){if (m_tab_bar->tab_layout() != TabLayout::Horizontal) {+ m_all_tabs_button->hide();auto reserved_width = vertical_tabs_layout_width();auto side_bar_width = current_vertical_tabs_width();m_vertical_tabs_reserved_space->setFixedWidth(reserved_width);@@ -3382,22 +4498,35 @@ void TabWidget::update_tab_layout()update_vertical_tabs_resize_handle();update_vertical_tabs_content_separator();- auto controls_width = m_new_tab_button->width();- if (m_window_controls->isVisible())- controls_width += m_window_controls->width();+ // Everything on the strip but the tab bar: its margins, the window controls, and the new tab button with its gap.+ auto margins = m_tab_bar_row_layout->contentsMargins();+ auto controls_width = margins.left() + margins.right() + HORIZONTAL_NEW_TAB_BUTTON_GAP - HORIZONTAL_TAB_END_ROOM + HORIZONTAL_NEW_TAB_BUTTON_SIZE + horizontal_tab_strip_drag_space();+ controls_width += m_ladybird_button->width() + LADYBIRD_BUTTON_TRAILING_GAP - HORIZONTAL_TAB_END_ROOM;+ if (!m_window_controls->isHidden())+ controls_width += m_window_controls->width() + (use_native_macos_window_controls() ? LADYBIRD_BUTTON_TRAFFIC_LIGHTS_GAP : 0);++ auto available_for_tabs = width() - controls_width;- auto available_for_tabs = width() - controls_width - 36;+ // Tabs that overflow the strip even at their narrowest make room for the button that lists them all.+ auto pinned_count = m_tab_bar->pinned_tab_count();+ auto narrowest_tabs_width = (pinned_count * HORIZONTAL_PINNED_TAB_WIDTH) + ((m_tab_bar->count() - pinned_count) * HORIZONTAL_TAB_MIN_WIDTH) + (2 * HORIZONTAL_TAB_END_ROOM);+ auto tabs_overflow = narrowest_tabs_width > available_for_tabs;+ if (tabs_overflow)+ available_for_tabs -= HORIZONTAL_NEW_TAB_BUTTON_SIZE;+ if (m_all_tabs_button->parentWidget() != m_tab_bar_row)+ m_all_tabs_button->setParent(m_tab_bar_row);+ m_all_tabs_button->setVisible(tabs_overflow && m_tab_bar_visible);// NB: The tab strip has no minimum width from its contents (see the constructor), so it keeps the window wide enough- // for its controls with a minimum of its own.- m_tab_bar_row->setMinimumWidth(controls_width + 36);+ // for its controls and one narrow tab with a minimum of its own.+ m_tab_bar_row->setMinimumWidth(controls_width + HORIZONTAL_TAB_MIN_WIDTH + (2 * HORIZONTAL_TAB_END_ROOM));m_tab_bar->set_available_width(available_for_tabs);- auto pinned_count = m_tab_bar->pinned_tab_count();- auto tabs_width = (pinned_count * PINNED_TAB_TILE_WIDTH) + ((m_tab_bar->count() - pinned_count) * HORIZONTAL_TAB_MAX_WIDTH) + (2 * HORIZONTAL_TAB_END_ROOM);- auto tab_bar_width = min(available_for_tabs, tabs_width);+ auto tabs_width = (pinned_count * HORIZONTAL_PINNED_TAB_WIDTH) + ((m_tab_bar->count() - pinned_count) * HORIZONTAL_TAB_MAX_WIDTH) + (2 * HORIZONTAL_TAB_END_ROOM);+ auto tab_bar_width = min(available_for_tabs, tabs_width + max(0, m_tab_bar->horizontal_tabs_end_offset()));m_tab_bar->setFixedWidth(max(0, tab_bar_width));+ place_horizontal_new_tab_button();}void TabWidget::update_tab_button_visibility()@@ -3429,12 +4558,9 @@ void TabWidget::update_tab_chrome_visibility()auto show_top_row = m_tab_bar_visible && is_horizontal;m_tab_bar_row->setVisible(show_top_row);m_toolbar_container->setVisible(m_tab_bar_visible);+ m_toolbar_placeholder->setVisible(m_tab_bar_visible && m_toolbar_follows_page_column);m_vertical_tab_bar_column->setVisible(m_tab_bar_visible && !is_horizontal);update_vertical_tabs_content_separator();-#ifdef AK_OS_MACOS- for (int index = 0; index < m_stacked_widget->count(); ++index)- update_web_view_frame(*tab(index));-#endifauto show_window_controls = m_window_controls_visible&& m_tab_bar_visible@@ -3442,22 +4568,13 @@ void TabWidget::update_tab_chrome_visibility()m_window_controls->setVisible(show_window_controls);}-#ifdef AK_OS_MACOS-void TabWidget::update_web_view_frame(Tab& tab)-{- Optional<WebView::VerticalTabsPosition> sidebar_position;- if (m_tab_bar_visible && m_tab_bar->tab_layout() != TabLayout::Horizontal)- sidebar_position = m_vertical_tabs_position;- tab.update_web_view_frame(m_tab_bar_visible, sidebar_position);-}-#endif-void TabWidget::recreate_icons(){m_tab_bar->recreate_icons();update_vertical_tabs_toggle_icon();- m_new_tab_button->setIcon(create_chrome_icon(ChromeIcon::NewTab, palette()));- update_vertical_tabs_action_labels();+ auto activity = ChromeStyle::window_activity(*this);+ m_new_tab_button->setIcon(create_chrome_icon(ChromeIcon::NewTab, Theme::chrome_palette(*this), activity));+ m_all_tabs_button->setIcon(create_chrome_icon(ChromeIcon::ChevronDown, Theme::chrome_palette(*this), activity));update_window_button_icons();}@@ -3466,10 +4583,8 @@ void TabWidget::update_vertical_tabs_toggle_icon()// NB: The icons are first made before the sidebar and its toggle are.if (!m_vertical_tabs_toggle_button)return;- auto icon = vertical_tabs_are_on_right()- ? (m_vertical_tabs_expanded ? ChromeIcon::VerticalTabBarCollapseRight : ChromeIcon::VerticalTabBarExpandRight)- : (m_vertical_tabs_expanded ? ChromeIcon::VerticalTabBarCollapse : ChromeIcon::VerticalTabBarExpand);- m_vertical_tabs_toggle_button->defaultAction()->setIcon(create_chrome_icon(icon, palette()));+ auto icon = vertical_tabs_are_on_right() ? ChromeIcon::SidebarRight : ChromeIcon::Sidebar;+ m_vertical_tabs_toggle_button->defaultAction()->setIcon(create_chrome_icon(icon, Theme::chrome_palette(*this), ChromeStyle::window_activity(*this)));}void TabWidget::update_chrome_style()@@ -3478,11 +4593,16 @@ void TabWidget::update_chrome_style()return;m_is_updating_chrome_style = true;- auto style_sheet = ChromeStyle::tab_widget_style_sheet(palette());+ auto style_sheet = ChromeStyle::tab_widget_style_sheet(Theme::chrome_palette(*this));m_tab_bar_row->setStyleSheet(style_sheet);m_vertical_tab_bar_column->setStyleSheet(style_sheet);m_vertical_tabs_content_separator->setStyleSheet(style_sheet);m_vertical_tabs_resize_handle->setStyleSheet(style_sheet);+ auto reserved_space_palette = m_vertical_tabs_reserved_space->palette();+ reserved_space_palette.setColor(QPalette::Window, ChromeStyle::chrome_sidebar_background(Theme::chrome_palette(*this)));+ m_vertical_tabs_reserved_space->setPalette(reserved_space_palette);+ if (m_all_tabs_popover)+ m_all_tabs_popover->update_chrome_style(palette());m_is_updating_chrome_style = false;}@@ -3508,7 +4628,7 @@ void TabWidget::set_vertical_tabs_hover_expanded(bool expanded)m_vertical_tabs_hover_expanded = expanded;m_vertical_tabs_hover_expand_animation->stop();- auto duration = m_vertical_tabs_hover_expanded+ auto duration = m_vertical_tabs_hover_expanded && !SystemAppearance::prefers_reduced_motion()? Application::settings().config_variable_as_integer<int>(WebView::ConfigVariableID::VerticalTabsHoverExpandAnimationDuration): 0;m_vertical_tabs_hover_expand_progress = m_vertical_tabs_hover_expanded && duration == 0 ? 1.0 : 0.0;@@ -3564,10 +4684,10 @@ void TabWidget::update_window_button_icons(){if (m_minimize_window_button && m_maximize_window_button && m_close_window_button) {auto is_maximized = window()->isMaximized();- m_minimize_window_button->setIcon(create_chrome_icon(ChromeIcon::WindowMinimize, palette()));- m_maximize_window_button->setIcon(create_chrome_icon(is_maximized ? ChromeIcon::WindowRestore : ChromeIcon::WindowMaximize, palette()));+ m_minimize_window_button->setIcon(create_chrome_icon(ChromeIcon::WindowMinimize, Theme::chrome_palette(*this)));+ m_maximize_window_button->setIcon(create_chrome_icon(is_maximized ? ChromeIcon::WindowRestore : ChromeIcon::WindowMaximize, Theme::chrome_palette(*this)));m_maximize_window_button->setToolTip(is_maximized ? "Restore" : "Maximize");- m_close_window_button->setIcon(create_chrome_icon(ChromeIcon::WindowClose, palette()));+ m_close_window_button->setIcon(create_chrome_icon(ChromeIcon::WindowClose, Theme::chrome_palette(*this)));}for (int index = 0; index < m_stacked_widget->count(); ++index)@@ -3596,43 +4716,95 @@ bool TabWidget::start_window_move()return handle->startSystemMove();}-void TabBarButton::set_collapsed_vertical_overlay(bool enabled)+void TabBarButton::set_placement(Placement placement){- if (property(COLLAPSED_VERTICAL_TAB_BUTTON_PROPERTY).toBool() == enabled)+ if (m_placement == placement)return;- setProperty(COLLAPSED_VERTICAL_TAB_BUTTON_PROPERTY, enabled);-- auto button_size = enabled ? COLLAPSED_VERTICAL_TAB_BUTTON_SIZE : TAB_BUTTON_SIZE;- setFixedSize(button_size, button_size);- update_icon_size();- style()->unpolish(this);- style()->polish(this);+ m_placement = placement;+ update_size();update();}-TabBarButton::TabBarButton(QIcon const& icon, QWidget* parent)+TabBarButton::TabBarButton(QIcon const& icon, Role role, QWidget* parent): QPushButton(icon, {}, parent)+ , m_role(role){setObjectName("LadybirdTabButton");- setFixedSize({ TAB_BUTTON_SIZE, TAB_BUTTON_SIZE });- update_icon_size();+ update_size();setFocusPolicy(Qt::NoFocus);setFlat(true);hide();}-void TabBarButton::set_icon_inset(int inset)+void TabBarButton::update_size(){- m_icon_inset = inset;- update_icon_size();+ auto icon_size = TAB_BUTTON_ICON_SIZE;+ switch (m_placement) {+ case Placement::Tab:+ case Placement::SidebarRow:+ if (m_role == Role::Close) {+ setFixedSize(TAB_CLOSE_BUTTON_HIT_SIZE);+ } else if (m_placement == Placement::SidebarRow) {+ setFixedSize(SIDEBAR_ROW_AUDIO_BUTTON_SIZE, SIDEBAR_ROW_AUDIO_BUTTON_SIZE);+ icon_size = SIDEBAR_ROW_AUDIO_ICON_SIZE;+ } else {+ setFixedSize(TAB_AUDIO_BUTTON_SIZE, TAB_AUDIO_BUTTON_SIZE);+ }+ break;+ case Placement::RailBadge:+ setFixedSize(RAIL_BADGE_SIZE, RAIL_BADGE_SIZE);+ icon_size = m_role == Role::Close ? RAIL_BADGE_CLOSE_ICON_SIZE : RAIL_BADGE_AUDIO_ICON_SIZE;+ break;+ }+ setIconSize({ icon_size, icon_size });}-void TabBarButton::update_icon_size()+// The close button fades into the slot its tab keeps for it, and out of it, so that nothing else on the tab moves.+// NB: Other layouts show and hide the button outright, so it is left opaque whenever it is not fading.+void TabBarButton::set_revealed(bool revealed){- auto collapsed = property(COLLAPSED_VERTICAL_TAB_BUTTON_PROPERTY).toBool();- auto icon_size = (collapsed ? COLLAPSED_VERTICAL_TAB_ICON_SIZE : TAB_BUTTON_ICON_SIZE) - (2 * m_icon_inset);- setIconSize({ icon_size, icon_size });+ auto is_fading = m_reveal_animation && m_reveal_animation->state() == QAbstractAnimation::Running;+ if (revealed == m_revealed && (is_fading || isVisible() == revealed))+ return;+ m_revealed = revealed;++ if (!revealed && !isVisible()) {+ if (m_reveal_animation)+ m_reveal_animation->stop();+ m_opacity = 1;+ return;+ }++ if (SystemAppearance::prefers_reduced_motion()) {+ m_opacity = 1;+ setVisible(revealed);+ return;+ }++ if (!m_reveal_animation) {+ m_reveal_animation = new QVariantAnimation(this);+ m_reveal_animation->setDuration(Motion::FAST);+ m_reveal_animation->setEasingCurve(Motion::move_easing());+ QObject::connect(m_reveal_animation, &QVariantAnimation::valueChanged, this, [this](QVariant const& value) {+ m_opacity = value.toReal();+ update();+ });+ QObject::connect(m_reveal_animation, &QVariantAnimation::finished, this, [this] {+ if (!m_revealed)+ hide();+ m_opacity = 1;+ });+ }++ auto from = isVisible() ? m_opacity : 0.0;+ m_reveal_animation->stop();+ m_reveal_animation->setStartValue(from);+ m_reveal_animation->setEndValue(revealed ? 1.0 : 0.0);+ m_opacity = from;+ if (revealed)+ show();+ m_reveal_animation->start();}bool TabBarButton::event(QEvent* event)@@ -3650,16 +4822,28 @@ void TabBarButton::paintEvent(QPaintEvent*)QStyleOptionButton option;initStyleOption(&option);- QStylePainter painter(this);+ // The speaker in the sidebar and both badges in the collapsed sidebar take the icon color, rather than the tabs'+ // quieter one.+ auto takes_icon_color = m_placement == Placement::RailBadge || (m_placement == Placement::SidebarRow && m_role == Role::Audio);+ if (takes_icon_color && isEnabled() && ChromeStyle::window_activity(*this) == ChromeStyle::WindowActivity::Active)+ option.icon = QIcon(icon().pixmap(iconSize(), devicePixelRatioF(), QIcon::Active));- if (objectName() == "LadybirdTabButton") {- auto collapsed = property(COLLAPSED_VERTICAL_TAB_BUTTON_PROPERTY).toBool();- auto frame_style = collapsed- ? ChromeStyle::CircularControlFrameStyle::ActiveTabOverlay- : ChromeStyle::CircularControlFrameStyle::InteractionOnly;- ChromeStyle::paint_circular_control_frame(painter, *this, frame_style);- } else if (objectName() == "LadybirdAudioState") {- ChromeStyle::paint_circular_control_frame(painter, *this);+ QStylePainter painter(this);+ painter.setOpacity(m_opacity);++ if (m_placement == Placement::RailBadge) {+ ChromeStyle::paint_control_frame(painter, *this, ChromeStyle::ControlFrameStyle::ActiveTabOverlay);+ } else if (m_role == Role::Close) {+ if (isDown() || (underMouse() && rect().contains(mapFromGlobal(QCursor::pos())))) {+ // A tab's close button is a small rounded square that lights up over the tab's own fill.+ painter.setRenderHint(QPainter::Antialiasing, true);+ painter.setPen(Qt::NoPen);+ painter.setBrush(isDown() ? Theme::panel().pressed : Theme::chrome(*this).hover);+ QRectF square { (width() - TAB_CLOSE_BUTTON_SIZE) / 2.0, (height() - TAB_CLOSE_BUTTON_SIZE) / 2.0, TAB_CLOSE_BUTTON_SIZE, TAB_CLOSE_BUTTON_SIZE };+ painter.drawRoundedRect(square, TAB_BUTTON_RADIUS, TAB_BUTTON_RADIUS);+ }+ } else {+ ChromeStyle::paint_control_frame(painter, *this);}painter.drawControl(QStyle::CE_PushButton, option);diff --git a/UI/Qt/TabBar.h b/UI/Qt/TabBar.hindex 66ffd357bee..d7b62d36583 100644--- a/UI/Qt/TabBar.h+++ b/UI/Qt/TabBar.h@@ -8,14 +8,18 @@#pragma once+#include <AK/HashMap.h>+#include <AK/HashTable.h>#include <AK/Optional.h>#include <AK/TypeCasts.h>#include <AK/Vector.h>#include <AK/kmalloc.h>+#include <LibWebView/BrowsingSession.h>#include <LibWebView/Settings.h>#include <UI/Qt/Tab.h>#include <QHash>+#include <QPixmap>#include <QPointer>#include <QPushButton>#include <QStackedWidget>@@ -32,10 +36,11 @@ class QDragMoveEvent;class QDropEvent;class QEvent;class QIcon;+class QLabel;class QMouseEvent;class QPaintEvent;-class QPixmap;class QResizeEvent;+class QSpacerItem;class QToolButton;class QTimer;class QVariantAnimation;@@ -43,11 +48,21 @@ class QWheelEvent;namespace Ladybird {+class AllTabsPopover;+class LadybirdButton;+class TabPreviewPopup;class TabWidget;static constexpr int TAB_ICON_SIZE = 16;+// How much further the first and last horizontal tabs reach toward the ends of the strip, to make room for the selected+// tab's foot there.+struct HorizontalTabEndRoom {+ qreal left { 0 };+ qreal right { 0 };+};+enum class TabLayout : u8 {Horizontal,VerticalCollapsed,@@ -64,6 +79,7 @@ public:void set_available_width(int width);+ TabWidget* tab_widget() const { return m_tab_widget; }TabLayout tab_layout() const { return m_tab_layout; }void set_tab_layout(TabLayout);// While collapsed vertical tabs only peek open on hover, the pinned tabs keep their rows, one tab each, rather than@@ -71,11 +87,17 @@ public:void set_pinned_tabs_in_rows(bool);void set_vertical_tabs_position(WebView::VerticalTabsPosition);void refresh_tab_layout();+ // After a tab is closed with a click, the tabs keep their width until the pointer leaves the tab bar, so the next+ // close button lands under the pointer.+ void lock_tab_widths();void recreate_icons();int pinned_tab_count() const;- void play_load_sheen(Tab&);- void update_loading_swirl_animation();+ void update_loading_ring_animation();+ // How far the end of the horizontal tabs is from where it settles, while tabs open and close.+ int horizontal_tabs_end_offset() const;+ // A horizontal tab that closes shrinks away as the others close the gap.+ void prepare_for_tab_removal(int index);int drop_index_at(QPoint const&) const;void update_drop_preview(QPoint const&);@@ -97,6 +119,7 @@ private:virtual void dragMoveEvent(QDragMoveEvent*) override;virtual void dropEvent(QDropEvent*) override;virtual bool eventFilter(QObject*, QEvent*) override;+ virtual void enterEvent(QEnterEvent*) override;virtual void leaveEvent(QEvent*) override;virtual void mouseDoubleClickEvent(QMouseEvent*) override;virtual void mousePressEvent(QMouseEvent*) override;@@ -129,11 +152,25 @@ private:qreal current_strip_growth() const;qreal current_pinned_region_growth() const;QRect shifted_tab_rect(int index) const;+ qreal selection_of(int index) const;+ bool is_growing_horizontal_tab(int index, QRect const& tab_rect) const;+ QRectF horizontal_tab_contents_rect(int index, QRect const& tab_rect) const;+ QRect tab_drag_card_rect(int index) const;QPixmap render_tab_drag_pixmap(int index) const;void toggle_window_maximized();bool start_window_move();void start_tab_drag(int index);+ QPoint tab_drag_hot_spot() const;+ void pointer_left();+ void start_strip_drag(int index);+ void update_strip_drag(QPoint position);+ void end_strip_drag();+ void drag_tab_loose(Tab&, QPixmap card);+ void drag_tab_in_own_window(Tab&);void start_hover_animation(int tab_index, qreal target_progress);+ void update_layout_animation();+ QRect animated_tab_rect(int index, QRect const& target) const;+ HorizontalTabEndRoom horizontal_tab_end_room(int index) const;void schedule_tab_preview(int index);void show_tab_preview();void hide_tab_preview();@@ -164,12 +201,11 @@ private:QSize vertical_size_hint(int tab_count) const;bool vertical_tabs_are_on_right() const;- int max_vertical_scroll_offset() const;- void set_vertical_scroll_offset(int);+ int max_scroll_offset() const;+ void set_scroll_offset(int);void set_hovered_tab_index(int);- Optional<qreal> load_sheen_progress(int index) const;- bool is_tab_loading(int index) const;+ qreal loading_ring_opacity(int index) const;void ensure_tab_visible(int index);void update_tab_button_geometry();@@ -179,31 +215,61 @@ private:bool m_pinned_tabs_in_rows { false };WebView::VerticalTabsPosition m_vertical_tabs_position { WebView::VerticalTabsPosition::Left };int m_available_width { 0 };+ Optional<int> m_locked_tab_width;+ QTimer* m_tab_width_unlock_timer { nullptr };int m_hovered_tab_index { -1 };int m_hover_animation_tab_index { -1 };- int m_vertical_scroll_offset { 0 };+ int m_scroll_offset { 0 };qreal m_hover_progress { 0.0 };QVariantAnimation* m_hover_animation { nullptr };+ // When another tab is selected, the selected tab's look cross-fades from the one before it.+ QPointer<Tab> m_previously_selected_tab;+ qreal m_selection_progress { 1.0 };+ QVariantAnimation* m_selection_animation { nullptr };+Optional<int> m_drop_slot;DropPreview m_drop_preview_start;DropPreview m_drop_preview_target;qreal m_drop_preview_progress { 1.0 };QVariantAnimation* m_drop_preview_animation { nullptr };- struct LoadSheen {- QPointer<Tab> tab;- QVariantAnimation* animation { nullptr };+ // When tabs open or close, each one moves from where it was drawn to its new place, and a new one grows into place.+ QVariantAnimation* m_layout_animation { nullptr };+ qreal m_layout_animation_progress { 1.0 };+ // The image of a closing tab, and where it was in the tab bar before any scrolling.+ struct ClosingTab {+ QPixmap image;+ QRect rect;};- Vector<LoadSheen> m_load_sheens;- QVariantAnimation* m_loading_swirl_animation { nullptr };+ Optional<ClosingTab> m_closing_tab;+ // The tab painted as if it were not selected, while a picture of it is taken as it closes.+ int m_tab_painted_unselected { -1 };+ QRect closing_tab_rect() const;+ HashMap<Tab const*, QRect> m_layout_animation_start_rects;+ HashMap<Tab const*, HorizontalTabEndRoom> m_layout_animation_start_end_rooms;+ HashMap<Tab const*, QRect> m_settled_tab_rects;+ HashMap<Tab const*, HorizontalTabEndRoom> m_settled_tab_end_rooms;+ int m_settled_tab_count { 0 };++ QVariantAnimation* m_loading_ring_animation { nullptr };QIcon m_fallback_tab_icon;QHash<QString, QStaticText> m_tab_title_texts;+ // The tabs whose titles were too long to show in full when last painted.+ HashTable<Tab const*> m_tabs_with_cut_titles;QFont m_tab_title_texts_font;QPointer<Tab> m_pressed_tab;QPoint m_position_in_selected_tab_while_dragging;QPoint m_drag_start_position;+ // NB: A tab is dragged within its strip without a drag and drop session. It is drawn as a card that slides along the+ // strip, until it is pulled out of the strip.+ QWidget* m_strip_drag_card { nullptr };+ QPixmap m_tab_drag_pixmap;+ // Where the card a dragged tab is drawn as sits in the tab.+ QPoint m_tab_drag_card_offset;+ QObject* m_strip_drag_cancellation_filter { nullptr };QTimer* m_tab_preview_timer { nullptr };+ QTimer* m_tab_preview_pointer_timer { nullptr };TabPreviewPopup* m_tab_preview_popup { nullptr };int m_tab_preview_index { -1 };QPointer<Tab> m_previewed_tab;@@ -216,9 +282,14 @@ class TabWidget final : public QWidget {public:AK_ALLOC_WITH_KMALLOC;- explicit TabWidget(QWidget* parent = nullptr);+ TabWidget(WebView::IsPrivate, QWidget* parent);++ LadybirdButton& ladybird_button() const { return *m_ladybird_button; }TabBar* tab_bar() const { return m_tab_bar; }++ // Whether a tab dragged to a position, in the given widget, lands in the tab strip rather than leaving it.+ bool tab_drop_area_contains(QWidget const&, QPoint position) const;QWidget* tab_bar_row() const { return m_tab_bar_row; }void add_tab(Tab* widget, QString const& label);@@ -247,10 +318,16 @@ public:void set_vertical_tabs_enabled(bool);void set_vertical_tabs_expanded(bool);void set_vertical_tabs_expand_on_hover(bool);+ // How strongly the vertical tabs' titles show, which they don't for long once the sidebar starts to collapse.+ qreal vertical_tab_title_opacity() const;+ bool vertical_tabs_are_toggling() const { return m_vertical_tabs_toggling; }void set_vertical_tabs_position(WebView::VerticalTabsPosition);bool can_expand_vertical_tabs_on_hover() const;void update_tab_button_visibility();void update_tab_layout();+ void place_horizontal_new_tab_button();+ int horizontal_tab_strip_drag_space() const;+ void show_all_tabs();signals:void current_tab_changed(int index);@@ -274,15 +351,25 @@ private:int vertical_tabs_layout_width() const;bool should_show_window_controls_in_tab_toolbar() const;bool vertical_tabs_hold_window_controls() const;- int vertical_tabs_column_top_margin() const;+ int vertical_tabs_header_spacing() const;+ int minimum_vertical_tabs_expanded_width() const;void rebuild_layout();void rebuild_layout_for_horizontal_tabs();- void place_horizontal_new_tab_button();+ void place_collapsed_sidebar_buttons();+ void float_sidebar_buttons_while_toggling();+ bool slides_page_with_toggling_sidebar() const;+ void slide_page_with_toggling_sidebar();+ qreal vertical_tabs_toggle_collapsedness() const;+ QLabel* m_floating_ladybird_button { nullptr };+ QLabel* m_floating_sidebar_toggle { nullptr };+ // Where the toolbar's slot for the buttons ends when the sidebar starts to open, in the window. The slot keeps+ // ending there until the sidebar is open, so the toolbar's other buttons stay in place under the sidebar.void rebuild_layout_for_vertical_tabs();void rebuild_page_column();+ void place_toolbar_over_page_column();void update_vertical_tabs_column_margins();- void paint_collapsed_vertical_tabs_column();+ void paint_vertical_tabs_column();void update_toolbar_placement();void update_tab_toolbar_window_controls_visibility();int current_vertical_tabs_width() const;@@ -291,15 +378,11 @@ private:void update_vertical_tabs_resize_handle();void update_vertical_tabs_content_separator();void set_resize_handle_property(char const* property, bool enabled);- void update_vertical_tabs_action_labels();void update_vertical_tabs_hover_layout();QRect vertical_tabs_chrome_rect() const;int vertical_tabs_tab_width() const;void update_vertical_tabs_button_layout();void update_tab_chrome_visibility();-#ifdef AK_OS_MACOS- void update_web_view_frame(Tab&);-#endifvoid recreate_icons();void update_vertical_tabs_toggle_icon();void update_chrome_style();@@ -318,6 +401,10 @@ private:QStackedWidget* m_stacked_widget { nullptr };QToolButton* m_new_tab_button { nullptr };+ QToolButton* m_all_tabs_button { nullptr };+ AllTabsPopover* m_all_tabs_popover { nullptr };+ Vector<WebView::SessionWindowId> m_recently_closed_unit_ids;+ LadybirdButton* m_ladybird_button { nullptr };QToolButton* m_vertical_tabs_toggle_button { nullptr };QToolButton* m_minimize_window_button { nullptr };QToolButton* m_maximize_window_button { nullptr };@@ -325,6 +412,8 @@ private:QWidget* m_window_controls { nullptr };QStackedWidget* m_toolbar_container { nullptr };QWidget* m_page_column { nullptr };+ QWidget* m_toolbar_placeholder { nullptr };+ bool m_toolbar_follows_page_column { false };QWidget* m_tab_bar_row { nullptr };QWidget* m_vertical_tabs_reserved_space { nullptr };QWidget* m_vertical_tab_bar_column { nullptr };@@ -339,6 +428,7 @@ private:QBoxLayout* m_page_column_layout { nullptr };QBoxLayout* m_vertical_tab_bar_column_layout { nullptr };QBoxLayout* m_vertical_tabs_content_layout { nullptr };+ QSpacerItem* m_vertical_tabs_header_spacer { nullptr };bool m_tab_bar_visible { true };bool m_window_controls_visible { true };bool m_vertical_tabs_enabled { false };@@ -347,6 +437,15 @@ private:WebView::VerticalTabsPosition m_vertical_tabs_position { WebView::VerticalTabsPosition::Left };bool m_vertical_tabs_hover_expanded { false };qreal m_vertical_tabs_hover_expand_progress { 0.0 };+ // Opening or closing the sidebar animates its width, from the width it had to the one it will have. The page keeps+ // the room it had until the end.+ QVariantAnimation* m_vertical_tabs_toggle_animation { nullptr };+ qreal m_vertical_tabs_toggle_progress { 1.0 };+ int m_vertical_tabs_toggle_from_width { 0 };+ int m_vertical_tabs_toggle_to_width { 0 };+ int m_vertical_tabs_toggle_layout_width { 0 };+ bool m_vertical_tabs_toggling { false };+ bool m_vertical_tabs_collapse_pending { false };bool m_is_resizing_vertical_tabs { false };bool m_is_updating_chrome_style { false };int m_vertical_tabs_expanded_width { 0 };@@ -360,19 +459,36 @@ class TabBarButton final : public QPushButton {public:AK_ALLOC_WITH_KMALLOC;- explicit TabBarButton(QIcon const& icon, QWidget* parent = nullptr);- void set_collapsed_vertical_overlay(bool);- // Shrinks the icon by this much on each side, within the same button.- void set_icon_inset(int);+ enum class Role : u8 {+ Close,+ Audio,+ };++ // Where the button sits: on a tab of the strip or a pinned tile, on a row of the expanded sidebar, or as a badge on+ // a favicon in the collapsed sidebar.+ enum class Placement : u8 {+ Tab,+ SidebarRow,+ RailBadge,+ };++ TabBarButton(QIcon const& icon, Role, QWidget* parent = nullptr);+ void set_placement(Placement);+ // Shows the button by fading it in, or fades it out and hides it.+ void set_revealed(bool);protected:virtual bool event(QEvent* event) override;virtual void paintEvent(QPaintEvent*) override;private:- void update_icon_size();+ void update_size();- int m_icon_inset { 0 };+ Role m_role { Role::Close };+ Placement m_placement { Placement::Tab };+ bool m_revealed { false };+ qreal m_opacity { 1 };+ QVariantAnimation* m_reveal_animation { nullptr };};}diff --git a/UI/Qt/Theme.cpp b/UI/Qt/Theme.cppnew file mode 100644index 00000000000..a6c36ef7f2a--- /dev/null+++ b/UI/Qt/Theme.cpp@@ -0,0 +1,341 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Array.h>+#include <UI/Qt/Theme.h>++#include <QAccessibilityHints>+#include <QGuiApplication>+#include <QPalette>+#include <QStyleHints>+#include <QWidget>++namespace Ladybird::Theme {++bool is_dark()+{+ auto color_scheme = QGuiApplication::styleHints()->colorScheme();+ if (color_scheme != Qt::ColorScheme::Unknown)+ return color_scheme == Qt::ColorScheme::Dark;+ return QGuiApplication::palette().color(QPalette::Window).lightness() < 128;+}++bool has_increased_contrast()+{+ return QGuiApplication::styleHints()->accessibility()->contrastPreference() == Qt::ContrastPreference::HighContrast;+}++static QColor rgb(QRgb value)+{+ return QColor::fromRgb(value);+}++static QColor rgba(int red, int green, int blue, qreal alpha)+{+ return QColor(red, green, blue, qRound(alpha * 255));+}++static ChromeColors const light_chrome {+ .strip = rgb(0xdcdce0),+ .toolbar = rgb(0xffffff),+ .sidebar = rgb(0xdcdce0),+ .field = rgba(0, 0, 0, 0.08),+ .field_focused = rgb(0xffffff),+ .text = rgb(0x1d1d1f),+ .muted = rgb(0x5d5d64),+ .tab_title = rgb(0x3a3a40),+ .icon = rgb(0x3a3a40),+ .disabled = rgb(0xb3b3b9),+ .hover = rgba(0, 0, 0, 0.06),+ .row_title = rgb(0x3f3f45),+ .separator = rgb(0xbcbcc2),+ .divider = rgb(0xd2d2d6),+ .warning = rgb(0xb25d00),+ .warning_fill = rgb(0xfde0b8),+ .warning_ink = rgb(0x6e3300),+ .frame = rgba(0, 0, 0, 0.18),+ .field_edge = Qt::transparent,+ .active_tab_edge = Qt::transparent,+};++static ChromeColors const dark_chrome {+ .strip = rgb(0x141416),+ .toolbar = rgb(0x2e2e31),+ .sidebar = rgb(0x2e2e31),+ .field = rgba(255, 255, 255, 0.08),+ .field_focused = rgb(0x3a3a3e),+ .text = rgb(0xf2f2f5),+ .muted = rgb(0xacacb4),+ .tab_title = rgb(0xacacb4),+ .icon = rgb(0xdcdce1),+ .disabled = rgb(0x5b5b61),+ .hover = rgba(255, 255, 255, 0.06),+ .row_title = rgb(0xcfcfd6),+ .separator = rgb(0x3d3d42),+ .divider = rgb(0x0a0a0c),+ .warning = rgb(0xf2a33a),+ .warning_fill = rgb(0x4f3416),+ .warning_ink = rgb(0xffc46e),+ .frame = rgba(255, 255, 255, 0.10),+ .field_edge = Qt::transparent,+ .active_tab_edge = Qt::transparent,+};++static ChromeColors const private_chrome {+ .strip = rgb(0x1d1430),+ .toolbar = rgb(0x2f2347),+ .sidebar = rgb(0x2f2347),+ .field = rgba(255, 255, 255, 0.09),+ .field_focused = rgb(0x3b2e55),+ .text = rgb(0xf3f0fa),+ .muted = rgb(0xb3aac4),+ .tab_title = rgb(0xb3aac4),+ .icon = rgb(0xe2dcef),+ .disabled = rgb(0x5e566e),+ .hover = rgba(255, 255, 255, 0.07),+ .row_title = rgb(0xd5cee2),+ .separator = rgb(0x4a3d63),+ .divider = rgb(0x0f0a19),+ .warning = rgb(0xf2a33a),+ .warning_fill = rgb(0x4f3416),+ .warning_ink = rgb(0xffc46e),+ .frame = rgba(255, 255, 255, 0.12),+ .field_edge = Qt::transparent,+ .active_tab_edge = Qt::transparent,+};++static ChromeColors const light_increased_contrast_chrome {+ .strip = rgb(0xcfcfd4),+ .toolbar = rgb(0xffffff),+ .sidebar = rgb(0xcfcfd4),+ .field = rgb(0xffffff),+ .field_focused = rgb(0xffffff),+ .text = rgb(0x000000),+ .muted = rgb(0x3a3a40),+ .tab_title = rgb(0x3a3a40),+ .icon = rgb(0x1d1d1f),+ .disabled = rgb(0x8e8e93),+ .hover = rgba(0, 0, 0, 0.10),+ .row_title = rgb(0x1d1d1f),+ .separator = rgb(0x8e8e93),+ .divider = rgb(0x6e6e73),+ .warning = rgb(0x8a4700),+ .warning_fill = rgb(0xfbd29c),+ .warning_ink = rgb(0x5a2900),+ .frame = rgba(0, 0, 0, 0.55),+ .field_edge = rgb(0x6e6e73),+ .active_tab_edge = rgb(0x6e6e73),+};++static ChromeColors const dark_increased_contrast_chrome {+ .strip = rgb(0x000000),+ .toolbar = rgb(0x1c1c1e),+ .sidebar = rgb(0x1c1c1e),+ .field = rgb(0x000000),+ .field_focused = rgb(0x000000),+ .text = rgb(0xffffff),+ .muted = rgb(0xd0d0d6),+ .tab_title = rgb(0xd0d0d6),+ .icon = rgb(0xf2f2f5),+ .disabled = rgb(0x8a8a90),+ .hover = rgba(255, 255, 255, 0.14),+ .row_title = rgb(0xf2f2f5),+ .separator = rgb(0x8a8a90),+ .divider = rgb(0x8a8a90),+ .warning = rgb(0xf2a33a),+ .warning_fill = rgb(0x4f3416),+ .warning_ink = rgb(0xffc46e),+ .frame = rgba(255, 255, 255, 0.55),+ .field_edge = rgb(0x8e8e93),+ .active_tab_edge = rgb(0x8a8a90),+};++static PanelColors const light_panel {+ .surface = rgb(0xfbfbfc),+ .text = rgb(0x1d1d1f),+ .body = rgb(0x3a3a40),+ .muted = rgb(0x5d5d64),+ .shortcut = rgb(0x6e6e75),+ .separator = rgb(0xdcdce0),+ .separator_soft = rgb(0xececef),+ .control = rgba(0, 0, 0, 0.06),+ .pressed = rgba(0, 0, 0, 0.09),+ .page = rgb(0xffffff),+ .edge = rgba(0, 0, 0, 0.10),+ .link = rgb(0x0a66d0),+ .warning = rgb(0x8a4700),+ .badge_background = rgba(106, 57, 219, 0.12),+ .badge_text = rgb(0x4d2bb0),+ .information = rgb(0xdce9fb),+};++static PanelColors const dark_panel {+ .surface = rgb(0x333336),+ .text = rgb(0xf2f2f5),+ .body = rgb(0xdcdce1),+ .muted = rgb(0xacacb4),+ .shortcut = rgb(0x9a9aa2),+ .separator = rgb(0x3d3d42),+ .separator_soft = rgb(0x333337),+ .control = rgba(255, 255, 255, 0.10),+ .pressed = rgba(255, 255, 255, 0.14),+ .page = rgb(0x1c1c1e),+ .edge = rgba(255, 255, 255, 0.12),+ .link = rgb(0x6aa8ff),+ .warning = rgb(0xf2a33a),+ .badge_background = rgba(150, 110, 255, 0.22),+ .badge_text = rgb(0xc9b5ff),+ .information = rgba(10, 122, 255, 0.22),+};++ChromeColors const& chrome()+{+ if (has_increased_contrast())+ return is_dark() ? dark_increased_contrast_chrome : light_increased_contrast_chrome;+ return is_dark() ? dark_chrome : light_chrome;+}++static constexpr auto PRIVATE_WINDOW_PROPERTY = "ladybirdPrivateWindow";++// NB: Style sheets give each widget a whole palette of its own, so a window's palette does not reach the widgets in it.+// The window is marked instead, and a palette marked as private is made for the chrome in it.+void mark_private_window(QWidget& window)+{+ window.setProperty(PRIVATE_WINDOW_PROPERTY, true);+}++// NB: A palette is marked as private by its color for visited links, which nothing in the chrome uses.+QPalette chrome_palette(QWidget const& widget)+{+ auto palette = widget.palette();+ if (auto const* window = widget.window(); window && window->property(PRIVATE_WINDOW_PROPERTY).toBool())+ palette.setColor(QPalette::LinkVisited, private_chrome.strip);+ return palette;+}++bool is_private(QPalette const& palette)+{+ return palette.color(QPalette::LinkVisited) == private_chrome.strip;+}++ChromeColors const& chrome(QPalette const& palette)+{+ return is_private(palette) ? private_chrome : chrome();+}++ChromeColors const& chrome(QWidget const& widget)+{+ return chrome(chrome_palette(widget));+}++bool is_dark(QPalette const& palette)+{+ return is_private(palette) || is_dark();+}++bool is_dark(QWidget const& widget)+{+ return is_dark(chrome_palette(widget));+}++PanelColors const& panel()+{+ return is_dark() ? dark_panel : light_panel;+}++struct AccentColor {+ int hue;+ QColor light;+ QColor dark;+};++// The accent colors the system offers, each with a variant that clears 3:1 on the light toolbar and one that clears it+// on the dark toolbar. The hues are those of the system's own swatches.+static Array<AccentColor, 7> const accent_colors { {+ { 211, rgb(0x0a7aff), rgb(0x0a7aff) }, // Blue+ { 298, rgb(0xa550a7), rgb(0xc47fc6) }, // Purple+ { 332, rgb(0xe0438f), rgb(0xf2509e) }, // Pink+ { 357, rgb(0xee3b31), rgb(0xee3b31) }, // Red+ { 28, rgb(0xc96400), rgb(0xf7821b) }, // Orange+ { 46, rgb(0x9a7b00), rgb(0xf5c400) }, // Yellow+ { 104, rgb(0x208a3a), rgb(0x30b14f) }, // Green+} };+static AccentColor const graphite_accent { 0, rgb(0x7c7c82), rgb(0x8c8c92) };++static AccentColor const& system_accent_color()+{+ auto system_accent = QGuiApplication::palette().color(QPalette::Accent);+ if (system_accent.hsvSaturation() < 40)+ return graphite_accent;++ auto hue_distance = [&](int hue) {+ auto distance = abs(system_accent.hsvHue() - hue);+ return min(distance, 360 - distance);+ };++ auto const* closest = accent_colors.data();+ for (auto const& accent : accent_colors) {+ if (hue_distance(accent.hue) < hue_distance(closest->hue))+ closest = &accent;+ }+ return *closest;+}++QColor accent()+{+ auto const& accent = system_accent_color();+ return is_dark() ? accent.dark : accent.light;+}++// On the dark appearance, the focus ring is a lighter tint of the accent, as the accent itself is too deep there.+static QColor focus_color()+{+ auto color = accent();+ if (!is_dark())+ return color;+ auto lighten = [](int channel) { return channel + qRound((255 - channel) * 0.2); };+ return QColor(lighten(color.red()), lighten(color.green()), lighten(color.blue()));+}++QColor focus_edge()+{+ auto color = focus_color();+ if (is_dark())+ color.setAlphaF(0.75f);+ return color;+}++QColor focus_ring()+{+ auto color = focus_color();+ color.setAlphaF(0.16f);+ return color;+}++QColor selection()+{+ auto color = accent();+ color.setAlphaF(is_dark() ? 0.40f : 0.22f);+ return color;+}++QColor primary()+{+ return rgb(0x0a66d0);+}++// A selected row is filled with the primary blue, a little softer on the dark appearance.+QColor selected_row()+{+ return is_dark() ? rgb(0x2463b8) : primary();+}++QColor brand()+{+ return is_dark() ? rgb(0x7a4ce6) : rgb(0x6a39db);+}++}diff --git a/UI/Qt/Theme.h b/UI/Qt/Theme.hnew file mode 100644index 00000000000..66ad1c20fd5--- /dev/null+++ b/UI/Qt/Theme.h@@ -0,0 +1,94 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <QColor>+#include <QPalette>++class QWidget;++namespace Ladybird::Theme {++// The colors of the window chrome: the tab strip, the toolbar and what sits on them.+struct ChromeColors {+ QColor strip; // Tab strip, sidebar+ QColor toolbar; // Toolbar, active tab, selected tab in the sidebar+ QColor sidebar; // Vertical tabs sidebar and rail+ QColor field; // Address field fill+ QColor field_focused; // Address field fill while editing+ QColor text; // Titles, URL domain+ QColor muted; // URL path, secondary text+ QColor tab_title; // Inactive tab titles+ QColor icon; // Toolbar icons+ QColor disabled; // Disabled controls+ QColor hover; // Hover fills+ QColor row_title; // Unselected tab titles in the sidebar+ QColor separator; // Between inactive tabs+ QColor divider; // Chrome / page edge+ QColor warning; // Crashed tab, lookalike URL+ QColor warning_fill; // Not secure pill+ QColor warning_ink; // Text and icon on the warning fill+ QColor frame; // Window outline++ // With increased contrast, the address field and the active tab are outlined. Otherwise these are transparent.+ QColor field_edge;+ QColor active_tab_edge;+};++// The colors of menus, popovers, dialogs and the other surfaces that float over the chrome or the page.+struct PanelColors {+ QColor surface; // Panel background+ QColor text; // Primary text+ QColor body; // Body text, icons on controls+ QColor muted; // Secondary text+ QColor shortcut; // Keyboard shortcuts in menus+ QColor separator; // Separator lines+ QColor separator_soft; // Lines between rows+ QColor control; // Fill of secondary buttons and fields+ QColor pressed; // Fill of a pressed row or button+ QColor page; // The page behind panels, and fields inside them+ QColor edge; // Panel outline+ QColor link; // Text buttons and links+ QColor warning; // Failures and warnings+ QColor badge_background; // Brand badges+ QColor badge_text; // Brand badges+ QColor information; // Informational highlights+};++bool is_dark();+bool has_increased_contrast();++ChromeColors const& chrome();++// A private window's chrome is violet-dark in either appearance, so it never looks like a normal window. The chrome+// inside a window marked as private takes its colors from a palette marked as private.+void mark_private_window(QWidget& window);+QPalette chrome_palette(QWidget const&);+bool is_private(QPalette const&);+ChromeColors const& chrome(QPalette const&);+ChromeColors const& chrome(QWidget const&);+bool is_dark(QPalette const&);+bool is_dark(QWidget const&);+PanelColors const& panel();++// The system's accent color, adjusted so it stays clear on the chrome in light and dark appearances. It is used only+// for focus rings, selection and load progress.+QColor accent();+// A focus ring is a fine line of the focus edge color right outside the focused control, in a wider, fainter halo.+QColor focus_edge();+QColor focus_ring();+QColor selection();++// The fill of a primary button, a blue that white text stays clear on.+QColor primary();+// The fill of the selected row of a menu or a list navigated with the keyboard.+QColor selected_row();++// Ladybird purple, used for the default profile's tile and brand accents.+QColor brand();++}diff --git a/UI/Qt/WaylandWindow.cpp b/UI/Qt/WaylandWindow.cppnew file mode 100644index 00000000000..946c48e7dc1--- /dev/null+++ b/UI/Qt/WaylandWindow.cpp@@ -0,0 +1,48 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <UI/Qt/WaylandWindow.h>++#include <QGuiApplication>++#include <string.h>+#include <wayland-client.h>++namespace Ladybird {++bool wayland_compositor_moves_dragged_windows()+{+ static bool const moves_dragged_windows = [] {+ auto* wayland_application = qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>();+ if (!wayland_application || !wayland_application->display())+ return false;++ // NB: The globals are listed on a queue of our own, so that Qt's queue never sees our registry's events.+ auto* display = wayland_application->display();+ auto* queue = wl_display_create_queue(display);+ auto* display_on_queue = static_cast<wl_display*>(wl_proxy_create_wrapper(display));+ wl_proxy_set_queue(reinterpret_cast<wl_proxy*>(display_on_queue), queue);+ auto* registry = wl_display_get_registry(display_on_queue);++ bool has_toplevel_drag_manager = false;+ static wl_registry_listener const listener {+ .global = [](void* data, wl_registry*, uint32_t, char const* interface, uint32_t) {+ if (strcmp(interface, "xdg_toplevel_drag_manager_v1") == 0)+ *static_cast<bool*>(data) = true; },+ .global_remove = [](void*, wl_registry*, uint32_t) { },+ };+ wl_registry_add_listener(registry, &listener, &has_toplevel_drag_manager);+ wl_display_roundtrip_queue(display, queue);++ wl_registry_destroy(registry);+ wl_proxy_wrapper_destroy(display_on_queue);+ wl_event_queue_destroy(queue);+ return has_toplevel_drag_manager;+ }();+ return moves_dragged_windows;+}++}diff --git a/UI/Qt/WaylandWindow.h b/UI/Qt/WaylandWindow.hnew file mode 100644index 00000000000..3a4575cb9c4--- /dev/null+++ b/UI/Qt/WaylandWindow.h@@ -0,0 +1,14 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++namespace Ladybird {++// Whether the Wayland compositor can move a window with the pointer while it is dragged. It never can off Wayland.+bool wayland_compositor_moves_dragged_windows();++}diff --git a/UI/Qt/WebCompatReportReview.cpp b/UI/Qt/WebCompatReportReview.cppindex 1b17e5d94bb..a7a5ed616b2 100644--- a/UI/Qt/WebCompatReportReview.cpp+++ b/UI/Qt/WebCompatReportReview.cpp@@ -5,9 +5,11 @@*/#include <AK/Math.h>+#include <LibWebView/URL.h>#include <UI/Qt/Icon.h>#include <UI/Qt/ReportReview.h>#include <UI/Qt/StringUtils.h>+#include <UI/Qt/Theme.h>#include <UI/Qt/WebCompatReportReview.h>#include <QAbstractButton>@@ -30,7 +32,7 @@ namespace Ladybird {using namespace ReportReview;-static constexpr QSize SCREENSHOT_PREVIEW_SIZE { 480, 270 };+static constexpr QSize SCREENSHOT_PREVIEW_SIZE { 150, 184 };static constexpr qreal SCREENSHOT_PREVIEW_RADIUS = 8;static constexpr qreal SCREENSHOT_BADGE_SIZE = 44;static constexpr qreal SCREENSHOT_SIZE_MARGIN = 0.9;@@ -152,7 +154,7 @@ WebCompatReportReview::WebCompatReportReview(WebView::WebCompatReport::Page pageauto* heading = new QWidget(m_review_page);auto* heading_layout = create_group_layout(heading);heading_layout->addWidget(create_title(tr("Report a website issue"), heading));- auto* website = create_label(qstring_from_ak_string(m_report.page().url.serialize()), heading);+ auto* website = create_label(qstring_from_ak_string(WebView::url_for_display(m_report.page().url)), heading);website->setObjectName("WebCompatReportWebsite");website->setForegroundRole(QPalette::PlaceholderText);heading_layout->addWidget(website);@@ -160,33 +162,41 @@ WebCompatReportReview::WebCompatReportReview(WebView::WebCompatReport::Page pageauto* description = new QWidget(m_review_page);auto* description_layout = create_group_layout(description);- description_layout->addWidget(create_label(tr("What is wrong with this website?"), description));+ description_layout->addWidget(create_heading(tr("What’s wrong with this site?"), 1.0, description));m_description_edit = new QPlainTextEdit(description);m_description_edit->setObjectName("WebCompatReportDescription");- m_description_edit->setPlaceholderText(tr("Describe what you expected to see or do, and what happened instead."));+ m_description_edit->setPlaceholderText(tr("What did you expect to see or do, and what happened instead?"));m_description_edit->setTabChangesFocus(true);- m_description_edit->setFixedHeight(m_description_edit->fontMetrics().lineSpacing() * 5);+ m_description_edit->setFixedHeight(76);description_layout->addWidget(m_description_edit);review_layout->addWidget(description);auto* screenshot_group = new QWidget(m_review_page);auto* screenshot_layout = create_group_layout(screenshot_group);- screenshot_layout->addWidget(create_label(tr("Screenshot"), screenshot_group));+ screenshot_layout->addWidget(create_heading(tr("Screenshot"), 1.0, screenshot_group));+ // The screenshot sits beside its size and what can be done with it.+ auto* screenshot_row = new QHBoxLayout;+ screenshot_row->setSpacing(16);m_screenshot_preview = new ScreenshotThumbnail(screenshot_group);m_screenshot_preview->setObjectName("WebCompatReportScreenshot");QObject::connect(m_screenshot_preview, &QAbstractButton::clicked, this, [this] {if (on_view_screenshot)on_view_screenshot(m_screenshot);});- screenshot_layout->addWidget(m_screenshot_preview, 0, Qt::AlignLeft);+ screenshot_row->addWidget(m_screenshot_preview, 0, Qt::AlignTop);+ auto* screenshot_side = new QVBoxLayout;+ screenshot_side->setSpacing(8);+ m_selected_area_label = create_label(tr("Selected area"), screenshot_group);+ m_selected_area_label->setForegroundRole(QPalette::PlaceholderText);+ screenshot_side->addWidget(m_selected_area_label);m_no_screenshot_note = create_label(tr("The report will not include a screenshot."), screenshot_group);m_no_screenshot_note->setObjectName("WebCompatReportNoScreenshotNote");m_no_screenshot_note->setForegroundRole(QPalette::PlaceholderText);- screenshot_layout->addWidget(m_no_screenshot_note);+ screenshot_side->addWidget(m_no_screenshot_note);m_select_screenshot_button = new QPushButton(screenshot_group);m_select_screenshot_button->setObjectName("WebCompatReportSelectScreenshotButton");m_select_screenshot_button->setAutoDefault(false);- m_remove_screenshot_button = new QPushButton(tr("Remove screenshot"), screenshot_group);+ m_remove_screenshot_button = new QPushButton(tr("Remove"), screenshot_group);m_remove_screenshot_button->setObjectName("WebCompatReportRemoveScreenshotButton");m_remove_screenshot_button->setAutoDefault(false);auto* screenshot_buttons = new QHBoxLayout;@@ -194,7 +204,10 @@ WebCompatReportReview::WebCompatReportReview(WebView::WebCompatReport::Page pagescreenshot_buttons->addWidget(m_select_screenshot_button);screenshot_buttons->addWidget(m_remove_screenshot_button);screenshot_buttons->addStretch();- screenshot_layout->addLayout(screenshot_buttons);+ screenshot_side->addLayout(screenshot_buttons);+ screenshot_side->addStretch();+ screenshot_row->addLayout(screenshot_side, 1);+ screenshot_layout->addLayout(screenshot_row);review_layout->addWidget(screenshot_group);auto* page_dumps = new QWidget(m_review_page);@@ -203,61 +216,74 @@ WebCompatReportReview::WebCompatReportReview(WebView::WebCompatReport::Page pagem_include_page_dumps->setObjectName("WebCompatReportIncludePageDumps");m_include_page_dumps->setEnabled(false);page_dumps_layout->addWidget(m_include_page_dumps);- auto* page_dumps_note = create_label(tr("This can contain personal information, such as text on the page."), page_dumps);+ auto* page_dumps_note = create_label(tr("Helps us fix rendering bugs. It can contain text from the page."), page_dumps);page_dumps_note->setForegroundRole(QPalette::PlaceholderText);page_dumps_layout->addWidget(page_dumps_note);review_layout->addWidget(page_dumps);- auto* contents = new QWidget(m_review_page);- auto* contents_layout = create_group_layout(contents);- auto* contents_summary = create_label(tr("Includes the website URL, your Ladybird version, platform, user agent, window size and zoom level."), contents);- contents_summary->setForegroundRole(QPalette::PlaceholderText);- contents_layout->addWidget(contents_summary);- auto* details = create_details_panel(contents);- auto* details_layout = static_cast<QVBoxLayout*>(details->layout());- auto* details_form = create_details_form();- set_details(*details_form, m_report.details(), details);- details_layout->addLayout(details_form);- details_layout->addSpacing(item_spacing);- m_show_report_button = new QPushButton(tr("View full report"), details);- m_show_report_button->setObjectName("WebCompatReportShowReportButton");- m_show_report_button->setAutoDefault(false);- QObject::connect(m_show_report_button, &QPushButton::clicked, this, [this] { show_report_text(); });- details_layout->addWidget(m_show_report_button, 0, Qt::AlignLeft);- auto* details_toggle = create_disclosure(tr("Report details"), details, contents);- // The toggle comes before what it shows, although it is created after it.- QWidget::setTabOrder(details_toggle, m_show_report_button);- contents_layout->addWidget(details_toggle);- contents_layout->addWidget(details);- review_layout->addWidget(contents);-m_validation = create_label({}, m_review_page);m_validation->setObjectName("WebCompatReportValidation");m_validation->hide();review_layout->addWidget(m_validation);+ // The footer says what else the report carries, with a way to see all of it, beside the buttons that leave or send it.+ // It stays at the bottom of the tab.+ review_layout->addStretch(1);+ auto* footer_line = new QFrame(m_review_page);+ footer_line->setFrameShape(QFrame::HLine);+ footer_line->setObjectName("WebCompatReportFooterLine");+ review_layout->addWidget(footer_line);+ auto* contents_summary = create_label(tr("Also sends the address and your browser setup."), m_review_page);+ contents_summary->setForegroundRole(QPalette::PlaceholderText);+ contents_summary->setWordWrap(false);+ m_show_report_button = new QPushButton(tr("See everything"), m_review_page);+ m_show_report_button->setObjectName("WebCompatReportShowReportButton");+ m_show_report_button->setAutoDefault(false);+ m_show_report_button->setFlat(true);+ m_show_report_button->setCursor(Qt::PointingHandCursor);+ QObject::connect(m_show_report_button, &QPushButton::clicked, this, [this] { show_report_text(); });+ // The footer is set smaller than the review above it.+ for (QWidget* widget : { static_cast<QWidget*>(contents_summary), static_cast<QWidget*>(m_show_report_button) }) {+ auto font = contents_summary->font();+ font.setPixelSize(12);+ widget->setFont(font);+ }+auto* send_button = new QPushButton(tr("Send report"), m_review_page);send_button->setObjectName("WebCompatReportSendButton");send_button->setDefault(true);- auto* review_close_button = new QPushButton(tr("Close tab"), m_review_page);+ auto* review_close_button = new QPushButton(tr("Cancel"), m_review_page);review_close_button->setObjectName("WebCompatReportReviewCloseButton");review_close_button->setAutoDefault(false);auto* review_buttons = new QHBoxLayout;review_buttons->setSpacing(button_spacing);- review_buttons->addStretch();+ // NB: The link continues the sentence.+ auto* contents = new QHBoxLayout;+ contents->setSpacing(4);+ contents->addWidget(contents_summary);+ contents->addWidget(m_show_report_button);+ contents->addStretch(1);+ review_buttons->addLayout(contents, 1);review_buttons->addWidget(review_close_button);review_buttons->addWidget(send_button);review_layout->addLayout(review_buttons);layout->addWidget(m_review_page);+ // The outcome of sending the report stands in the middle of the tab.m_status_page = new QWidget(this);auto* status_layout = new QVBoxLayout(m_status_page);status_layout->setContentsMargins(0, 0, 0, 0);status_layout->setSpacing(group_spacing);+ status_layout->addStretch();auto* outcome = new QWidget(m_status_page);auto* outcome_layout = create_group_layout(outcome);+ m_status_icon = new QLabel(outcome);+ m_status_icon->setAlignment(Qt::AlignHCenter);+ m_status_icon->hide();+ outcome_layout->addWidget(m_status_icon);m_status_title = create_title({}, outcome);m_status_title->setObjectName("WebCompatReportStatusTitle");+ m_status_title->setAlignment(Qt::AlignHCenter);outcome_layout->addWidget(m_status_title);m_progress = new QProgressBar(outcome);m_progress->setObjectName("WebCompatReportProgress");@@ -267,6 +293,7 @@ WebCompatReportReview::WebCompatReportReview(WebView::WebCompatReport::Page pagem_status_message = create_label({}, outcome);m_status_message->setObjectName("WebCompatReportStatusMessage");m_status_message->setForegroundRole(QPalette::PlaceholderText);+ m_status_message->setAlignment(Qt::AlignHCenter);outcome_layout->addWidget(m_status_message);status_layout->addWidget(outcome);@@ -274,6 +301,8 @@ WebCompatReportReview::WebCompatReportReview(WebView::WebCompatReport::Page pagem_retry_button->setObjectName("WebCompatReportRetryButton");m_cancel_button = new QPushButton(tr("Cancel"), m_status_page);m_cancel_button->setObjectName("WebCompatReportCancelButton");+ m_back_to_site_button = new QPushButton(tr("Back to the site"), m_status_page);+ m_back_to_site_button->setObjectName("WebCompatReportBackToSiteButton");m_close_button = new QPushButton(tr("Close tab"), m_status_page);m_close_button->setObjectName("WebCompatReportCloseButton");auto* status_buttons = new QHBoxLayout;@@ -281,7 +310,9 @@ WebCompatReportReview::WebCompatReportReview(WebView::WebCompatReport::Page pagestatus_buttons->addStretch();status_buttons->addWidget(m_retry_button);status_buttons->addWidget(m_cancel_button);+ status_buttons->addWidget(m_back_to_site_button);status_buttons->addWidget(m_close_button);+ status_buttons->addStretch();status_layout->addLayout(status_buttons);status_layout->addStretch();m_status_page->hide();@@ -315,7 +346,13 @@ WebCompatReportReview::WebCompatReportReview(WebView::WebCompatReport::Page pageshow_page(*m_review_page);m_description_edit->setFocus(Qt::OtherFocusReason);});- QObject::connect(m_close_button, &QPushButton::clicked, this, [this] { exit(); });+ QObject::connect(m_back_to_site_button, &QPushButton::clicked, this, [this] { exit(); });+ QObject::connect(m_close_button, &QPushButton::clicked, this, [this] {+ if (on_close_tab)+ on_close_tab();+ else+ exit();+ });m_report.on_progress = [this](auto stage) { show_progress(stage); };m_report.on_retry = [this](String const& reason, u32 retry_number, u32 maximum_retries, u32 delay_seconds) {@@ -337,8 +374,9 @@ void WebCompatReportReview::set_screenshot(QImage screenshot)m_screenshot_preview->set_screenshot(m_screenshot);m_screenshot_preview->setVisible(has_screenshot);m_remove_screenshot_button->setVisible(has_screenshot);- m_select_screenshot_button->setText(has_screenshot ? tr("Retake screenshot") : tr("Take a screenshot"));+ m_select_screenshot_button->setText(has_screenshot ? tr("Retake") : tr("Take a screenshot"));m_no_screenshot_note->setVisible(!has_screenshot);+ m_selected_area_label->setVisible(has_screenshot);}void WebCompatReportReview::set_page_dumps(String page_dumps)@@ -409,8 +447,9 @@ void WebCompatReportReview::show_status(QString const& title, QString const& mes{m_status_title->setText(title);m_status_message->setText(message);+ m_status_icon->hide();show_page(*m_status_page);- QPushButton* all_actions[] = { m_retry_button, m_cancel_button, m_close_button };+ QPushButton* all_actions[] = { m_retry_button, m_cancel_button, m_back_to_site_button, m_close_button };show_actions(all_actions, actions, primary);}@@ -431,7 +470,11 @@ void WebCompatReportReview::show_retry(String const& reason, u32 retry_number, uvoid WebCompatReportReview::show_sent(){m_progress->setValue(100);- show_status(tr("Report sent"), tr("Thank you for helping Ladybird."), { m_close_button }, m_close_button);+ show_status(tr("Report sent"), tr("Thanks for helping make the web work in Ladybird."), { m_back_to_site_button, m_close_button }, nullptr);+ m_progress->hide();+ auto sent_color = Theme::is_dark() ? QColor(0x30b14f) : QColor(0x208a3a);+ m_status_icon->setPixmap(create_chrome_icon(ChromeIcon::CheckCircle, sent_color).pixmap(QSize(40, 40), devicePixelRatioF()));+ m_status_icon->show();}void WebCompatReportReview::show_failure(WebView::ReportSubmission::Failure, String const& reason)diff --git a/UI/Qt/WebCompatReportReview.h b/UI/Qt/WebCompatReportReview.hindex 5229c4377cc..88756c32853 100644--- a/UI/Qt/WebCompatReportReview.h+++ b/UI/Qt/WebCompatReportReview.h@@ -46,7 +46,9 @@ public:Function<void()> on_select_screenshot;Function<void(QImage const&)> on_view_screenshot;+ // Leaving the review returns to the site it is about; closing the tab once the report is sent need not.Function<void()> on_exit;+ Function<void()> on_close_tab;Function<void(bool)> on_report_text_visibility_change;protected:@@ -74,6 +76,7 @@ private:QPlainTextEdit* m_description_edit { nullptr };ScreenshotThumbnail* m_screenshot_preview { nullptr };QLabel* m_no_screenshot_note { nullptr };+ QLabel* m_selected_area_label { nullptr };QPushButton* m_select_screenshot_button { nullptr };QPushButton* m_remove_screenshot_button { nullptr };QCheckBox* m_include_page_dumps { nullptr };@@ -81,11 +84,13 @@ private:QPlainTextEdit* m_report_text { nullptr };QLabel* m_validation { nullptr };+ QLabel* m_status_icon { nullptr };QLabel* m_status_title { nullptr };QProgressBar* m_progress { nullptr };QLabel* m_status_message { nullptr };QPushButton* m_retry_button { nullptr };QPushButton* m_cancel_button { nullptr };+ QPushButton* m_back_to_site_button { nullptr };QPushButton* m_close_button { nullptr };bool m_is_updating_chrome_style { false };diff --git a/UI/Qt/WebContentView.cpp b/UI/Qt/WebContentView.cppindex 42dd332cbbd..8195cc36885 100644--- a/UI/Qt/WebContentView.cpp+++ b/UI/Qt/WebContentView.cpp@@ -6,6 +6,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/AnyOf.h>#include <AK/Array.h>#include <AK/Assertions.h>#include <AK/ByteBuffer.h>@@ -37,6 +38,7 @@#include <UI/Qt/Application.h>#include <UI/Qt/ChromeStyle.h>#include <UI/Qt/CrashReportReviewWidget.h>+#include <UI/Qt/Icon.h>#include <UI/Qt/ReportReview.h>#include <UI/Qt/ScreenshotViewer.h>#include <UI/Qt/WebCompatReportReview.h>@@ -46,6 +48,8 @@#include <UI/Qt/InputMethodUtils.h>#include <UI/Qt/SelectDropdown.h>#include <UI/Qt/StringUtils.h>+#include <UI/Qt/SystemAppearance.h>+#include <UI/Qt/Theme.h>#include <UI/Qt/WebContentView.h>#if defined(Q_OS_MACOS)@@ -68,7 +72,7 @@#include <QPaintEvent>#include <QPainter>#include <QPainterPath>-#include <QPainterPathStroker>+#include <QPalette>#include <QPixmap>#include <QPointer>@@ -82,13 +86,27 @@#include <QToolTip>#include <QVBoxLayout>#include <QWheelEvent>+#include <QWindow>template<>constexpr bool AllocatedWithSystemAllocator<QKeyEvent> = true;namespace Ladybird {-bool is_using_dark_system_theme(QWidget&);+// Whether pages get the dark system colors. This follows the website color scheme setting rather than the interface+// theme, so pages can stay light in a dark window.+static bool websites_prefer_dark()+{+ switch (WebView::Application::settings().appearance().website_color_scheme) {+ case WebView::ThemePreference::System:+ return SystemAppearance::the().prefers_dark();+ case WebView::ThemePreference::Light:+ return false;+ case WebView::ThemePreference::Dark:+ return true;+ }+ VERIFY_NOT_REACHED();+}static QWidget* initial_web_content_view_parent([[maybe_unused]] QWidget* window){@@ -141,7 +159,7 @@ WebContentView::WebContentView(QWidget* window, Optional<WebView::CanonicalTravem_maximum_frames_per_second = initial_state.maximum_frames_per_second;m_display_id = initial_state.display_id;- set_page_background_color_to_system_canvas(is_using_dark_system_theme(*this));+ set_page_background_color_to_system_canvas(websites_prefer_dark());#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYERon_page_background_color_change = [this](Gfx::Color) {update_iosurface_layer_background_color();@@ -160,12 +178,14 @@ WebContentView::WebContentView(QWidget* window, Optional<WebView::CanonicalTravefor (auto* screen : QGuiApplication::screens())watch_screen_geometry(*screen);- QObject::connect(QGuiApplication::styleHints(), &QStyleHints::colorSchemeChanged, this, [this] {+ auto update_palette_soon = [this] {QTimer::singleShot(0, this, [this] {update_palette();schedule_repaint();});- });+ };+ QObject::connect(QGuiApplication::styleHints(), &QStyleHints::colorSchemeChanged, this, update_palette_soon);+ QObject::connect(&SystemAppearance::the(), &SystemAppearance::changed, this, update_palette_soon);m_tooltip_hover_timer.setSingleShot(true);@@ -328,6 +348,7 @@ WebContentView::WebContentView(QWidget* window, Optional<WebView::CanonicalTraveif (active)close_select_dropdown_after_crash();set_crash_overlay_visible(active);+ emit crash_overlay_changed();};on_crash_report_saved = [this] {@@ -800,6 +821,17 @@ static bool is_browser_reserved_shortcut(QKeyEvent const& event)if (modifiers == Qt::ControlModifier && key == Qt::Key_PageUp)return true;+ // F6 moves focus between the chrome and the page, and the sidebar shows or hides with its own shortcut.+ if (modifiers == Qt::NoModifier && key == Qt::Key_F6)+ return true;+#if defined(AK_OS_MACOS)+ if (modifiers == (Qt::ControlModifier | Qt::AltModifier) && key == Qt::Key_S)+ return true;+#else+ if (modifiers == (Qt::ControlModifier | Qt::ShiftModifier) && key == Qt::Key_S)+ return true;+#endif+return false;}@@ -1159,7 +1191,7 @@ void WebContentView::paintEvent(QPaintEvent*)#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYERvoid WebContentView::paintEvent(QPaintEvent*){- // The page layer has rounded corners, so the area outside them should match the chrome around this view.+ // The page layer covers the view, except before its first frame, which shows the chrome's color.QPainter painter(this);painter.fillRect(rect(), ChromeStyle::chrome_background(window()->palette()));}@@ -1212,51 +1244,13 @@ Optional<QPixmap> WebContentView::tab_preview_pixmap(QSize const& maximum_size)namespace {-static void draw_crash_overlay_icon(QPainter& painter, QColor const& color)-{- auto draw_path = [&](QPainterPath const& path) {- QPainterPathStroker stroker;- stroker.setWidth(1.5);- stroker.setCapStyle(Qt::RoundCap);- stroker.setJoinStyle(Qt::RoundJoin);- painter.fillPath(stroker.createStroke(path), color);- };-- QPainterPath page_outline(QPointF(11.75, 0.75));- page_outline.lineTo(2.75, 0.75);- page_outline.cubicTo(1.65, 0.75, 0.75, 1.65, 0.75, 2.75);- page_outline.lineTo(0.75, 18.75);- page_outline.cubicTo(0.75, 19.85, 1.65, 20.75, 2.75, 20.75);- page_outline.lineTo(14.75, 20.75);- page_outline.cubicTo(15.85, 20.75, 16.75, 19.85, 16.75, 18.75);- page_outline.lineTo(16.75, 5.75);- page_outline.closeSubpath();- draw_path(page_outline);-- QPainterPath page_details(QPointF(10.75, 0.75));- page_details.lineTo(10.75, 4.75);- page_details.cubicTo(10.75, 5.85, 11.65, 6.75, 12.75, 6.75);- page_details.lineTo(16.75, 6.75);- page_details.moveTo(4.75, 9.75);- page_details.lineTo(6.75, 11.75);- page_details.moveTo(6.75, 9.75);- page_details.lineTo(4.75, 11.75);- page_details.moveTo(10.75, 9.75);- page_details.lineTo(12.75, 11.75);- page_details.moveTo(12.75, 9.75);- page_details.lineTo(10.75, 11.75);- page_details.moveTo(5.75, 16.75);- page_details.cubicTo(6.75, 14.08, 10.75, 14.08, 11.75, 16.75);- draw_path(page_details);-}-static constexpr int PAGE_OVERLAY_MAXIMUM_WIDTH = 640;static constexpr int PAGE_OVERLAY_MARGIN = 32;static constexpr int CRASH_SCREEN_ICON_SPACING = 16;static QString crash_screen_message(){- return WebContentView::tr("This page crashed. You can reload it to try again.");+ return WebContentView::tr("Something went wrong while showing this page. Your other tabs are fine.");}class CrashOverlayIcon final : public QWidget {@@ -1266,16 +1260,14 @@ public:explicit CrashOverlayIcon(QWidget* parent): QWidget(parent){- setFixedSize(39, 48);+ setFixedSize(40, 40);}protected:virtual void paintEvent(QPaintEvent*) override{QPainter painter(this);- painter.setRenderHint(QPainter::Antialiasing);- painter.scale(width() / 17.5, height() / 21.5);- draw_crash_overlay_icon(painter, palette().color(QPalette::WindowText));+ create_chrome_icon(ChromeIcon::Warning, Theme::panel().muted).paint(&painter, rect());}};@@ -1321,11 +1313,20 @@ public:QWidget& content() { return *m_content; }QWidget& column() { return *m_column; }+ // The column reaches from the top of the tab to its bottom rather than being centered in it.+ void set_fills_height()+ {+ m_fills_height = true;+ m_layout->setStretch(0, 0);+ m_layout->setStretch(1, 1);+ m_layout->setStretch(2, 0);+ }+// The column takes all of the tab rather than being centered in it, so a review's full report gets as much room as// the tab has.void set_fills_tab(bool fills_tab){- m_layout->setStretch(1, fills_tab ? 1 : 0);+ m_layout->setStretch(1, fills_tab || m_fills_height ? 1 : 0);m_column->setMaximumWidth(fills_tab ? QWIDGETSIZE_MAX : PAGE_OVERLAY_MAXIMUM_WIDTH);}@@ -1333,6 +1334,7 @@ private:QWidget* m_content { nullptr };QWidget* m_column { nullptr };QVBoxLayout* m_layout { nullptr };+ bool m_fills_height { false };};class CrashOverlayUrlLabel final : public QLabel {@@ -1402,7 +1404,7 @@ void WebContentView::set_crash_overlay_visible(bool visible)heading_layout->setContentsMargins(0, 0, 0, 0);heading_layout->setSpacing(ReportReview::item_spacing);- auto* title = ReportReview::create_title(tr("Ladybird flew off-course!"), heading);+ auto* title = ReportReview::create_title(tr("This tab crashed"), heading);m_crash_overlay_url = new CrashOverlayUrlLabel(heading);@@ -1411,7 +1413,8 @@ void WebContentView::set_crash_overlay_visible(bool visible)m_crash_overlay_message->setForegroundRole(QPalette::PlaceholderText);m_crash_overlay_message->setTextInteractionFlags(Qt::TextSelectableByMouse);- m_crash_overlay_reload_button = new QPushButton(tr("Reload page"), column);+ m_crash_overlay_reload_button = new QPushButton(tr("Reload"), column);+ m_crash_overlay_reload_button->setStyleSheet(ChromeStyle::primary_button_style_sheet());QObject::connect(m_crash_overlay_reload_button, &QPushButton::clicked, this, [this] {reload();});@@ -1536,6 +1539,7 @@ void WebContentView::review_web_compat_report(WebCompatReportCapture capture)return;m_web_compat_report_overlay = new PageOverlay(this);+ m_web_compat_report_overlay->set_fills_height();auto* column = &m_web_compat_report_overlay->column();auto* review = new WebCompatReportReview(AK::move(capture.page), AK::move(capture.screenshot), column);@@ -1568,6 +1572,10 @@ void WebContentView::review_web_compat_report(WebCompatReportCapture capture)if (on_close)on_close();};+ review->on_close_tab = [this] {+ if (on_close_web_compat_report_tab)+ on_close_web_compat_report_tab();+ };// The review is part of the overlay and cannot outlive it, even once leaving the review has let go of the overlay.review->on_report_text_visibility_change = [overlay = m_web_compat_report_overlay](bool visible) {overlay->set_fills_tab(visible);@@ -1655,6 +1663,43 @@ Array<QWidget*, 4> WebContentView::overlays() constreturn { m_crash_overlay, m_web_compat_report_overlay, m_screenshot_selection_overlay, m_screenshot_viewer };}+namespace {++class FloatingSurfaceWatcher final : public QObject {+public:+ AK_ALLOC_WITH_KMALLOC;++ FloatingSurfaceWatcher(QWidget& surface, Function<void()> on_shown_or_hidden)+ : QObject(&surface)+ , m_on_shown_or_hidden(AK::move(on_shown_or_hidden))+ {+ surface.installEventFilter(this);+ }++private:+ virtual bool eventFilter(QObject*, QEvent* event) override+ {+ if (event->type() == QEvent::Show || event->type() == QEvent::Hide)+ m_on_shown_or_hidden();+ return false;+ }++ Function<void()> m_on_shown_or_hidden;+};++}++void WebContentView::add_floating_surface(QWidget& surface)+{+ m_floating_surfaces.append(&surface);+ new FloatingSurfaceWatcher(surface, [this] { schedule_repaint(); });+}++bool WebContentView::has_floating_surface_over_page() const+{+ return any_of(m_floating_surfaces, [](auto const& surface) { return surface && surface->isVisible(); });+}+// Overlays are painted by Qt, underneath whatever presents the page on some platforms, which has to step aside for them.bool WebContentView::is_page_covered_by_overlay() const{@@ -1791,6 +1836,13 @@ void WebContentView::set_vertical_tab_overlay_insets([[maybe_unused]] int left,#endif}+#ifndef LADYBIRD_QT_USE_IOSURFACE_LAYER+void WebContentView::set_page_dim(qreal)+{+ // NB: Elsewhere, the dialog dims the page by painting over it.+}+#endif+void WebContentView::set_bookmarks_bar_overlay_height([[maybe_unused]] int height){#ifdef LADYBIRD_QT_USE_VULKAN_WINDOW@@ -1866,15 +1918,21 @@ void WebContentView::hideEvent(QHideEvent* event)static Core::AnonymousBuffer make_system_theme_from_qt_palette(QWidget& widget, WebContentView::PaletteMode mode){auto qt_palette = widget.palette();+ auto dark = websites_prefer_dark();- auto theme_file = mode == WebContentView::PaletteMode::Default ? "Default"sv : "Dark"sv;+ auto theme_file = mode == WebContentView::PaletteMode::Dark || dark ? "Dark"sv : "Default"sv;auto theme_ini = MUST(Core::Resource::load_from_uri(MUST(String::formatted("resource://themes/{}.ini", theme_file))));auto theme = Gfx::load_system_theme(theme_ini->filesystem_path().to_byte_string()).release_value_but_fixme_should_propagate_errors();auto palette_impl = Gfx::PaletteImpl::create_with_anonymous_buffer(theme);auto palette = Gfx::Palette(move(palette_impl));+ // The widgets' palette follows the interface theme. When pages get the other appearance, they keep the colors of+ // the theme file instead.+ auto qt_palette_matches = ChromeStyle::is_dark(qt_palette) == dark;auto translate = [&](Gfx::ColorRole gfx_color_role, QPalette::ColorRole qt_color_role) {+ if (!qt_palette_matches)+ return;auto new_color = Gfx::Color::from_bgra(qt_palette.color(qt_color_role).rgba());palette.set_color(gfx_color_role, new_color);};@@ -1902,26 +1960,24 @@ static Core::AnonymousBuffer make_system_theme_from_qt_palette(QWidget& widget,palette.set_color(Gfx::ColorRole::InactiveSelectionText, Gfx::Color::from_bgra(inactive_highlighted_text.rgba()));} else {// The Qt theme does not differentiate inactive selections; use a neutral gray.- auto inactive_selection = is_using_dark_system_theme(widget) ? Gfx::Color(0x60, 0x60, 0x60) : Gfx::Color(0xd4, 0xd4, 0xd4);+ auto inactive_selection = dark ? Gfx::Color(0x60, 0x60, 0x60) : Gfx::Color(0xd4, 0xd4, 0xd4);palette.set_color(Gfx::ColorRole::InactiveSelection, inactive_selection);}#endif- palette.set_flag(Gfx::FlagRole::IsDark, is_using_dark_system_theme(widget));+ palette.set_flag(Gfx::FlagRole::IsDark, dark);return theme;}void WebContentView::update_palette(PaletteMode mode){- set_page_background_color_to_system_canvas(is_using_dark_system_theme(*this));+ set_page_background_color_to_system_canvas(websites_prefer_dark());// NB: Every page hosting documents of this tab takes the palette, including the pages of out-of-process iframes.// Their prefers-color-scheme and system colors resolve against it.update_system_theme(make_system_theme_from_qt_palette(*this, mode));-#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYER- update_iosurface_layer_border();-#endif+ update_interface_color_scheme();}Core::AnonymousBuffer WebContentView::system_theme()@@ -2157,6 +2213,45 @@ Gfx::IntPoint WebContentView::to_widget_position(Gfx::IntPoint content_position)return content_position;}+#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYER+// NB: Qt places this native view when the view moves within its parent, but not when a widget it is in moves, such as+// the page sliding along with the sidebar. The view watches the widgets it is in, and is placed again when they move.+void WebContentView::watch_ancestors_for_moves()+{+ for (auto& ancestor : m_watched_ancestors) {+ if (ancestor)+ ancestor->removeEventFilter(this);+ }+ m_watched_ancestors.clear();+ for (auto* ancestor = parentWidget(); ancestor && !ancestor->isWindow(); ancestor = ancestor->parentWidget()) {+ ancestor->installEventFilter(this);+ m_watched_ancestors.append(ancestor);+ }+ place_native_view_again();+}++bool WebContentView::eventFilter(QObject* watched, QEvent* event)+{+ if (event->type() == QEvent::Move && watched != this)+ place_native_view_again();+ return WebContentViewBase::eventFilter(watched, event);+}++void WebContentView::place_native_view_again()+{+ auto* native_view = windowHandle();+ auto* native_parent = nativeParentWidget();+ if (!native_view || !native_parent || !isVisible())+ return;+ if (native_view->geometry().topLeft() == mapTo(native_parent, QPoint()))+ return;+ // NB: Moving the view itself is what makes Qt place its native view, so it moves away and back.+ auto position = pos();+ move(position + QPoint(1, 0));+ move(position);+}+#endif+bool WebContentView::event(QEvent* event){// NOTE: We have to implement event() manually as Qt's focus navigation mechanism@@ -2183,6 +2278,11 @@ bool WebContentView::event(QEvent* event)}}+#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYER+ if (event->type() == QEvent::ParentChange || event->type() == QEvent::Show)+ watch_ancestors_for_moves();+#endif+if (event->type() == QEvent::PaletteChange || event->type() == QEvent::ApplicationPaletteChange || event->type() == QEvent::ThemeChange) {QTimer::singleShot(0, this, [this] {update_palette();diff --git a/UI/Qt/WebContentView.h b/UI/Qt/WebContentView.hindex a1611496de1..ef0a3700725 100644--- a/UI/Qt/WebContentView.h+++ b/UI/Qt/WebContentView.h@@ -149,6 +149,12 @@ public:void set_zoom_level(double);void set_vertical_tab_overlay_insets(int left, int right);void set_bookmarks_bar_overlay_height(int);+ // How much the page is dimmed under a page dialog, from 0 to 1, where the page is presented above anything Qt paints+ // over it.+ void set_page_dim(qreal);+ // A card that floats over the page, such as the find bar. Qt paints it above the page, so whatever presents the+ // page above Qt's painting steps aside while it shows.+ void add_floating_surface(QWidget&);void prepare_for_window_move();void finish_window_move();void close_select_dropdown_after_crash();@@ -160,6 +166,7 @@ public:Function<void(WebCompatReportCapture)> on_request_web_compat_report_review;Function<void(Function<void(QImage)> on_selected)> on_request_web_compat_report_screenshot;+ Function<void()> on_close_web_compat_report_tab;enum class PaletteMode {Default,@@ -168,10 +175,6 @@ public:void update_palette(PaletteMode = PaletteMode::Default);Optional<QPixmap> tab_preview_pixmap(QSize const& maximum_size) const;-#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYER- void set_has_rounded_corners(bool);-#endif-WebView::AccessibilityTreeManager const* accessibility_tree_manager() const { return m_accessibility_manager.ptr(); }#if !defined(Q_OS_MACOS) && !defined(Q_OS_WIN)@@ -186,6 +189,7 @@ public:signals:void ready_to_paint();+ void crash_overlay_changed();void urls_dropped(QList<QUrl> const&);private:@@ -245,6 +249,7 @@ private:Array<QWidget*, 4> overlays() const;bool is_page_covered_by_overlay() const;+ bool has_floating_surface_over_page() const;#if !defined(Q_OS_WIN)virtual void accessibilityActiveChanged(bool active) override;@@ -299,6 +304,7 @@ private:QPointer<ScreenshotSelectionOverlay> m_screenshot_selection_overlay;QPointer<ScreenshotViewer> m_screenshot_viewer;+ Vector<QPointer<QWidget>> m_floating_surfaces;PageOverlay* m_web_compat_report_overlay { nullptr };#ifdef AK_OS_MACOS@@ -306,15 +312,20 @@ private:#endif#ifdef LADYBIRD_QT_USE_IOSURFACE_LAYER+ virtual bool eventFilter(QObject*, QEvent*) override;+ void watch_ancestors_for_moves();+ void place_native_view_again();+ Vector<QPointer<QWidget>> m_watched_ancestors;+bool ensure_iosurface_layer_attached_to_native_view();void present_current_paintable_as_layer_contents();void update_iosurface_layer_frame();void update_iosurface_layer_background_color();- void update_iosurface_layer_border();void detach_iosurface_layer_from_native_view();void destroy_iosurface_layer();void* m_iosurface_layer { nullptr };+ void* m_page_dim_layer { nullptr };#endif#ifdef LADYBIRD_QT_USE_RHI_WIDGETdiff --git a/UI/Qt/WebContentViewLinux.cpp b/UI/Qt/WebContentViewLinux.cppindex b0b005c8f7b..80f06ec55c0 100644--- a/UI/Qt/WebContentViewLinux.cpp+++ b/UI/Qt/WebContentViewLinux.cpp@@ -1037,7 +1037,8 @@ void WebContentView::schedule_vulkan_window_update()}if (m_vulkan_window) {- if (!current_paintable_can_use_vulkan_window()) {+ // NB: The page is painted by Qt while a card floats over it, so that the card shows above it.+ if (!current_paintable_can_use_vulkan_window() || has_floating_surface_over_page()) {set_vulkan_window_container_visible(false);update();return;diff --git a/UI/Qt/WebContentViewMac.mm b/UI/Qt/WebContentViewMac.mmindex ea660ea1bc2..251e227968a 100644--- a/UI/Qt/WebContentViewMac.mm+++ b/UI/Qt/WebContentViewMac.mm@@ -5,7 +5,6 @@*/#include <LibGfx/SharedImageBuffer.h>-#include <UI/Qt/ChromeStyle.h>#include <UI/Qt/WebContentView.h>#include <QWindow>@@ -17,22 +16,11 @@namespace Ladybird {-static constexpr CGFloat WEB_VIEW_CORNER_RADIUS = 10;-static CALayer* as_layer(void* layer){return static_cast<CALayer*>(layer);}-// The page layer and WebContent share one corner radius, which stays zero until a tab rounds its view.-void WebContentView::set_has_rounded_corners(bool has_rounded_corners)-{- set_viewport_corner_radius(has_rounded_corners ? WEB_VIEW_CORNER_RADIUS : 0);- if (m_iosurface_layer)- as_layer(m_iosurface_layer).cornerRadius = viewport_corner_radius();- update_iosurface_layer_border();-}-bool WebContentView::ensure_iosurface_layer_attached_to_native_view(){auto* window_handle = windowHandle();@@ -48,12 +36,7 @@ bool WebContentView::ensure_iosurface_layer_attached_to_native_view()if (!m_iosurface_layer) {auto* layer = [[CALayer alloc] init];- // NB: The chrome painted behind the rounded corners shows through, so the layer is not opaque.- layer.opaque = NO;- layer.masksToBounds = YES;- layer.cornerRadius = viewport_corner_radius();- // NB: The compositor clips the viewport's scrollbars to arcs concentric with circular corners.- layer.cornerCurve = kCACornerCurveCircular;+ layer.opaque = YES;// Without this every new frame would cross-fade in and geometry changes would slide.layer.actions = @ {@"contents" : NSNull.null,@@ -64,12 +47,8 @@ bool WebContentView::ensure_iosurface_layer_attached_to_native_view()@"position" : NSNull.null,@"hidden" : NSNull.null,@"backgroundColor" : NSNull.null,- @"cornerRadius" : NSNull.null,- @"borderWidth" : NSNull.null,- @"borderColor" : NSNull.null,};m_iosurface_layer = layer;- update_iosurface_layer_border();}auto* layer = as_layer(m_iosurface_layer);@@ -132,6 +111,42 @@ void WebContentView::update_iosurface_layer_frame()if (!m_iosurface_layer)return;as_layer(m_iosurface_layer).frame = CGRectMake(0, 0, width(), height());+ if (m_page_dim_layer)+ as_layer(m_page_dim_layer).frame = CGRectMake(0, 0, width(), height());+}++// The dim is a layer of its own right above the page, under the native views of the dialog and the other floating+// surfaces.+void WebContentView::set_page_dim(qreal dim)+{+ if (!m_page_dim_layer && dim <= 0)+ return;+ if (!ensure_iosurface_layer_attached_to_native_view())+ return;++ auto* page_layer = as_layer(m_iosurface_layer);+ if (!m_page_dim_layer) {+ auto* layer = [[CALayer alloc] init];+ layer.actions = @ {+ @"bounds" : NSNull.null,+ @"position" : NSNull.null,+ @"opacity" : NSNull.null,+ @"hidden" : NSNull.null,+ };+ auto* black = CGColorCreateSRGB(0, 0, 0, 0.22);+ layer.backgroundColor = black;+ CGColorRelease(black);+ m_page_dim_layer = layer;+ }+ auto* layer = as_layer(m_page_dim_layer);+ if (layer.superlayer != page_layer.superlayer || [page_layer.superlayer.sublayers indexOfObject:layer] != [page_layer.superlayer.sublayers indexOfObject:page_layer] + 1) {+ [layer removeFromSuperlayer];+ [page_layer.superlayer insertSublayer:layer above:page_layer];+ }+ layer.frame = CGRectMake(0, 0, width(), height());+ layer.opacity = dim;+ layer.hidden = dim <= 0;+ reinterpret_cast<NSView*>(winId()).window.viewsNeedDisplay = YES;}void WebContentView::update_iosurface_layer_background_color()@@ -144,24 +159,6 @@ void WebContentView::update_iosurface_layer_background_color()CGColorRelease(background_color);}-// The rounded page is outlined like the location field, so that it stands apart from chrome of a similar color. In dark-// mode, the page stands apart from the chrome around it without one, like the location field does.-void WebContentView::update_iosurface_layer_border()-{- if (!m_iosurface_layer)- return;- auto* layer = as_layer(m_iosurface_layer);- if (viewport_corner_radius() <= 0 || ChromeStyle::is_dark(window()->palette())) {- layer.borderWidth = 0;- return;- }- auto color = ChromeStyle::location_edit_border(window()->palette());- auto* border_color = CGColorCreateSRGB(color.redF(), color.greenF(), color.blueF(), color.alphaF());- layer.borderColor = border_color;- CGColorRelease(border_color);- layer.borderWidth = 1;-}-void WebContentView::detach_iosurface_layer_from_native_view(){if (m_iosurface_layer)@@ -177,6 +174,12 @@ void WebContentView::destroy_iosurface_layer()[layer removeFromSuperlayer];[layer release];m_iosurface_layer = nullptr;++ if (m_page_dim_layer) {+ [as_layer(m_page_dim_layer) removeFromSuperlayer];+ [as_layer(m_page_dim_layer) release];+ m_page_dim_layer = nullptr;+ }}}diff --git a/UI/Qt/WindowControlButton.cpp b/UI/Qt/WindowControlButton.cppindex 2ebf9fa1afb..d8eb06eaa6c 100644--- a/UI/Qt/WindowControlButton.cpp+++ b/UI/Qt/WindowControlButton.cpp@@ -4,6 +4,8 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <UI/Qt/ChromeStyle.h>+#include <UI/Qt/Theme.h>#include <UI/Qt/WindowControlButton.h>#include <AK/Assertions.h>@@ -11,11 +13,29 @@#include <QBoxLayout>#include <QEnterEvent>#include <QMouseEvent>+#include <QPainter>+#include <QPainterPath>#include <QStyle>#include <QWidget>+#if defined(AK_OS_LINUX)+# include <AK/StringView.h>+// NB: GLib uses "signals" as a name, which Qt defines as a keyword.+# pragma push_macro("signals")+# undef signals+# include <gio/gio.h>+# pragma pop_macro("signals")+#endif+namespace Ladybird {+// A round button is a 24 px circle at the end of its button, with a little room before it.+static constexpr int ROUND_BUTTON_SIZE = 24;+static constexpr int ROUND_BUTTON_LEADING_GAP = 6;+// Its glyph is drawn in a 10 px box, with a heavier line than the hairlines of the square buttons.+static constexpr qreal ROUND_BUTTON_GLYPH_SIZE = 10;+static constexpr qreal ROUND_BUTTON_GLYPH_STROKE_WIDTH = 1.5;+static constexpr auto pressed_outside_property = "pressedOutside";static char const* object_name_for_type(WindowControlButtonType type)@@ -32,6 +52,7 @@ static char const* object_name_for_type(WindowControlButtonType type)WindowControlButton::WindowControlButton(WindowControlButtonType type, QString const& tool_tip, QSize icon_size, QSize button_size, QWidget* parent): QToolButton(parent)+ , m_type(type){setObjectName(object_name_for_type(type));setToolTip(tool_tip);@@ -41,6 +62,93 @@ WindowControlButton::WindowControlButton(WindowControlButtonType type, QString csetProperty(pressed_outside_property, false);}+void WindowControlButton::set_round(bool is_round)+{+ m_is_round = is_round;+ if (m_is_round)+ setFixedWidth(ROUND_BUTTON_SIZE + ROUND_BUTTON_LEADING_GAP);+ update();+}++void WindowControlButton::paintEvent(QPaintEvent* event)+{+ if (!m_is_round) {+ QToolButton::paintEvent(event);+ return;+ }++ QPainter painter(this);+ painter.setRenderHint(QPainter::Antialiasing, true);+ QRectF circle { static_cast<qreal>(width() - ROUND_BUTTON_SIZE), (height() - ROUND_BUTTON_SIZE) / 2.0, ROUND_BUTTON_SIZE, ROUND_BUTTON_SIZE };+ auto const& chrome = Theme::chrome(*this);+ painter.setPen(Qt::NoPen);+ painter.setBrush(chrome.field);+ painter.drawEllipse(circle);+ if (isDown() || underMouse()) {+ painter.setBrush(isDown() ? Theme::panel().pressed : chrome.hover);+ painter.drawEllipse(circle);+ }++ QPainterPath glyph;+ switch (m_type) {+ case WindowControlButtonType::Minimize:+ glyph.moveTo(1.5, 5);+ glyph.lineTo(8.5, 5);+ break;+ case WindowControlButtonType::Maximize:+ glyph.addRoundedRect(QRectF(1.5, 1.5, 7, 7), 1.5, 1.5);+ break;+ case WindowControlButtonType::Close:+ glyph.moveTo(1.5, 1.5);+ glyph.lineTo(8.5, 8.5);+ glyph.moveTo(8.5, 1.5);+ glyph.lineTo(1.5, 8.5);+ break;+ }+ auto inactive = ChromeStyle::window_activity(*this) == ChromeStyle::WindowActivity::Inactive;+ painter.translate(circle.center() - QPointF(ROUND_BUTTON_GLYPH_SIZE / 2, ROUND_BUTTON_GLYPH_SIZE / 2));+ painter.setPen(QPen(inactive ? chrome.muted : chrome.icon, ROUND_BUTTON_GLYPH_STROKE_WIDTH, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));+ painter.setBrush(Qt::NoBrush);+ painter.drawPath(glyph);+}++struct DesktopWindowButtons {+ bool minimize { true };+ bool maximize { true };+ bool close { true };+ bool round { false };+};++// The window controls follow the desktop's: on GNOME, the buttons its settings list, as circles.+// FIXME: Place the window controls on the leading side when the desktop puts them there.+static DesktopWindowButtons desktop_window_buttons()+{+ DesktopWindowButtons buttons;+#if defined(AK_OS_LINUX)+ auto const* desktop = getenv("XDG_CURRENT_DESKTOP");+ if (!desktop || !StringView { desktop, strlen(desktop) }.contains("GNOME"sv))+ return buttons;+ buttons.round = true;++ auto* source = g_settings_schema_source_get_default();+ auto* schema = source ? g_settings_schema_source_lookup(source, "org.gnome.desktop.wm.preferences", TRUE) : nullptr;+ if (!schema)+ return buttons;+ g_settings_schema_unref(schema);++ auto* settings = g_settings_new("org.gnome.desktop.wm.preferences");+ auto* layout = g_settings_get_string(settings, "button-layout");+ // The layout lists the buttons on the left of a colon and those on the right after it, such as "appmenu:close".+ auto layout_view = StringView { layout, strlen(layout) };+ buttons.minimize = layout_view.contains("minimize"sv);+ buttons.maximize = layout_view.contains("maximize"sv);+ buttons.close = layout_view.contains("close"sv);+ g_free(layout);+ g_object_unref(settings);+#endif+ return buttons;+}+WindowControlButtons create_window_control_buttons(QWidget& parent, char const* object_name, QSize icon_size, QSize button_size){auto* container = new QWidget(&parent);@@ -57,6 +165,13 @@ WindowControlButtons create_window_control_buttons(QWidget& parent, char const*layout->addWidget(maximize);layout->addWidget(close);+ static auto const desktop_buttons = desktop_window_buttons();+ minimize->setVisible(desktop_buttons.minimize);+ maximize->setVisible(desktop_buttons.maximize);+ close->setVisible(desktop_buttons.close);+ for (auto* button : { minimize, maximize, close })+ button->set_round(desktop_buttons.round);+return { container, minimize, maximize, close };}diff --git a/UI/Qt/WindowControlButton.h b/UI/Qt/WindowControlButton.hindex 6ef6dc5c8a9..fcd0804a91f 100644--- a/UI/Qt/WindowControlButton.h+++ b/UI/Qt/WindowControlButton.h@@ -31,7 +31,11 @@ public:WindowControlButton(WindowControlButtonType, QString const& tool_tip, QSize icon_size, QSize button_size, QWidget* parent = nullptr);+ // GNOME draws its window controls as small circles, at the trailing end of the button's room.+ void set_round(bool);+private:+ virtual void paintEvent(QPaintEvent*) override;virtual void enterEvent(QEnterEvent*) override;virtual void leaveEvent(QEvent*) override;virtual void mouseMoveEvent(QMouseEvent*) override;@@ -43,7 +47,9 @@ private:void set_pressed_outside(bool);void update_pressed_position(QPoint const&);+ WindowControlButtonType m_type;bool m_tracking_press { false };+ bool m_is_round { false };};struct WindowControlButtons {diff --git a/UI/Qt/ladybird.qrc b/UI/Qt/ladybird.qrcindex 44ff682293b..99f309c504a 100644--- a/UI/Qt/ladybird.qrc+++ b/UI/Qt/ladybird.qrc@@ -1,6 +1,7 @@<!DOCTYPE RCC><RCC version="1.0"><qresource><file>../Icons/ladybird.png</file>+ <file>../Icons/ladybird-private.png</file><file>OrcaScripts/Ladybird/__init__.py</file><file>OrcaScripts/Ladybird/script.py</file><file>OrcaScripts/Ladybird/script_utilities.py</file>diff --git a/UI/Qt/main.cpp b/UI/Qt/main.cppindex 4b0897b8893..ee20bf082bf 100644--- a/UI/Qt/main.cpp+++ b/UI/Qt/main.cpp@@ -13,6 +13,8 @@#include <LibWebView/Utilities.h>#include <UI/Qt/Application.h>#include <UI/Qt/BrowserWindow.h>+#include <UI/Qt/ChromeStyle.h>+#include <UI/Qt/SystemAppearance.h>#if defined(LADYBIRD_QT_HAVE_POSITIONING)# include <UI/Qt/GeolocationProviderQt.h>#endif@@ -30,26 +32,6 @@# include <UI/Qt/SpellCheckerMac.h>#endif-namespace Ladybird {--// FIXME: Find a place to put this declaration (and other helper functions).-bool is_using_dark_system_theme(QWidget&);-bool is_using_dark_system_theme(QWidget& widget)-{- // Use the explicitly set or system default color scheme whenever available- auto color_scheme = QGuiApplication::styleHints()->colorScheme();- if (color_scheme != Qt::ColorScheme::Unknown)- return color_scheme == Qt::ColorScheme::Dark;-- // Calculate luma based on Rec. 709 coefficients- // https://en.wikipedia.org/wiki/Rec._709#Luma_coefficients- auto color = widget.palette().color(widget.backgroundRole());- auto luma = 0.2126f * color.redF() + 0.7152f * color.greenF() + 0.0722f * color.blueF();- return luma <= 0.5f;-}--}-ErrorOr<int> ladybird_main(Main::Arguments arguments){AK::set_rich_debug_enabled(true);@@ -75,6 +57,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)#endifauto app = TRY(Ladybird::Application::create(arguments));+ Ladybird::ChromeStyle::install_application_style();#if defined(AK_OS_MACOS)app->set_spell_checker(Ladybird::create_platform_spell_checker());#endif@@ -89,6 +72,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)#if defined(AK_OS_MACOS)Ladybird::set_profile_application_icon(Ladybird::Application::profile());#endif+ Ladybird::SystemAppearance::the().apply_interface_theme(Ladybird::Application::settings().appearance().interface_theme);app->on_open_file = [&](auto const& file_url) {if (auto* window = app->non_private_window_if_any()) {@@ -138,9 +122,11 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)auto restored_everything = app->launch_restore_policy() == WebView::SessionLaunchPolicy::Everything;if (!restored_everything || !browser_options.raw_urls.is_empty())app->open_startup_tabs(*restored_window, browser_options.urls);+ app->offer_to_restore_unexpectedly_closed_tabs(*restored_window);} else {auto& window = app->new_window(browser_options.urls, configuration);window.setWindowTitle("Ladybird");+ app->offer_to_restore_unexpectedly_closed_tabs(window);}app->offer_newest_pending_crash_report();