From 63371089c0c84591fc72645b368fe40bb533765c Mon Sep 17 00:00:00 2001 From: Joshua Park Date: Fri, 27 Nov 2026 00:39:49 -0500 Subject: [PATCH 1/8] feat: add the tab switcher's engine calls and delete Chromium's Tab menu --- .../clair/window/clair_browser_bridge.mm | 36 +++++ .../clair/window/clair_browser_window.h | 23 ++- .../clair/window/clair_browser_window.mm | 143 +++++++++++++++--- .../clair/window/clair_native_window.mm | 8 - .../browser/clair/window/clair_peeks.mm | 18 --- .../browser/clair/window/clair_tab_preview.h | 53 +++++++ .../browser/clair/window/clair_tab_preview.mm | 75 +++++++++ .../browser/clair/window/clair_window_group.h | 7 +- .../clair/window/clair_window_group.mm | 11 +- .../clair/window/clair_window_hooks.mm | 8 + engine/patches/clair/native-window-hook.patch | 4 +- native/ClairHost.h | 22 +++ native/ClairUITests/FakeBrowser.swift | 21 +++ native/ClairUITests/FakeBrowserTests.swift | 79 ++++++++++ native/ClairUITests/FakeHost.swift | 3 + .../add-tab-switcher-and-tabs-menu/design.md | 6 +- 16 files changed, 457 insertions(+), 60 deletions(-) create mode 100644 engine/overlay/chrome/browser/clair/window/clair_tab_preview.h create mode 100644 engine/overlay/chrome/browser/clair/window/clair_tab_preview.mm diff --git a/engine/overlay/chrome/browser/clair/window/clair_browser_bridge.mm b/engine/overlay/chrome/browser/clair/window/clair_browser_bridge.mm index 0c31dad6..32e1bb6d 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_browser_bridge.mm +++ b/engine/overlay/chrome/browser/clair/window/clair_browser_bridge.mm @@ -752,6 +752,42 @@ - (void)setMuted:(BOOL)muted forTab:(ClairTabID)tabID { } } +// --- ClairBrowser: the tab switcher (add-tab-switcher-and-tabs-menu D1, D4) --- + +// A tab of any window, which the window decides whether it may show. +- (tabs::TabInterface*)anyTabWithID:(ClairTabID)tabID { + if (tabs::TabInterface* tab = [self tabWithID:tabID]) { + return tab; + } + return _browserWindow && tabID != ClairTabIDNone + ? tabs::TabHandle(static_cast(tabID)).Get() + : nullptr; +} + +- (void)showTab:(ClairTabID)tabID { + if (tabs::TabInterface* tab = [self anyTabWithID:tabID]) { + _browserWindow->ShowTab(tab); + } +} + +- (void)requestPreviewOfTab:(ClairTabID)tabID + size:(NSSize)size + completion:(void (^)(NSImage*))completion { + if (!completion) { + return; + } + tabs::TabInterface* tab = [self anyTabWithID:tabID]; + if (!tab || !ClairBrowserWindow::HolderOf(tab)) { + completion(nil); + return; + } + _browserWindow->RequestPreview( + tab, gfx::SizeF(size.width, size.height), + base::BindOnce(^(NSImage* preview) { + completion(preview); + })); +} + // --- ClairBrowser: Peek --- // The Peeks of the window holding `tab`. diff --git a/engine/overlay/chrome/browser/clair/window/clair_browser_window.h b/engine/overlay/chrome/browser/clair/window/clair_browser_window.h index e7f28f00..c0d4815b 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_browser_window.h +++ b/engine/overlay/chrome/browser/clair/window/clair_browser_window.h @@ -33,6 +33,7 @@ #include "components/web_modal/web_contents_modal_dialog_host.h" #include "ui/base/mojom/window_show_state.mojom.h" #include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/size_f.h" #include "ui/gfx/range/range.h" #if !defined(__OBJC__) @@ -339,7 +340,11 @@ class ClairBrowserWindow : public BrowserWindow { // its member for that profile (add-profiles D3). With `again`, a member // the group swaps in shows the Space even if it showed it already, as its // active tab may be its placeholder. - void ShowSpace(const std::string& space, bool again = false); + // With `tab`, a row of `space` or a favorite of its profile, the window + // shows that tab instead (add-tab-switcher-and-tabs-menu D1). + void ShowSpace(const std::string& space, + bool again = false, + tabs::TabInterface* tab = nullptr); // The tabs of the shown Space, in its order, whichever window of the // profile holds them: with Peeks, or only the rows the sidebar lists. An // incognito or guest window's are its own. @@ -478,6 +483,17 @@ class ClairBrowserWindow : public BrowserWindow { void FollowActiveTab(); // add-profiles D9: drops a take waiting for `tab`'s page copy. void DropPendingTakeOf(const tabs::TabInterface* tab); + // add-tab-switcher-and-tabs-menu D1: shows `tab`, of any of the window's + // Spaces or a favorite, as selecting its row or tile does, taking it from + // another window if need be. Another profile's tab is shown by the window's + // group, which swaps to its member for that profile. + void ShowTab(tabs::TabInterface* tab); + // D4: hands `done` a preview of `tab`'s page, `size` in points: the page as + // it is now while a window shows it, else the copy kept when it was last + // hidden, or nil. + void RequestPreview(tabs::TabInterface* tab, + const gfx::SizeF& size, + base::OnceCallback done); // D5: runs a tab command over the rows of the shown Space. Returns whether // it ran; otherwise Chromium runs it. bool ExecuteTabCommand(int command); @@ -695,6 +711,11 @@ class ClairBrowserWindow : public BrowserWindow { // D2: the copy of the still's page came after the tab left. void SetStillImage(tabs::TabHandle handle, const SkBitmap& copy); NSImage* StillImageFrom(const SkBitmap& copy) const; + // add-tab-switcher-and-tabs-menu D4: before `old_contents` and the pages + // shown with it are hidden, copies each one that stops being shown, + // `shown` being the pages shown from now on, and keeps it as its preview. + void KeepPreviews(content::WebContents* old_contents, + const std::set& shown); // D2: copies `row`'s page, waiting at most 250 ms, and hands `done` the // copy, or an empty bitmap. void CopyPage(tabs::TabInterface* row, diff --git a/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm b/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm index 425de716..b389e4f5 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm +++ b/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm @@ -12,6 +12,7 @@ #import #include +#include #include #include #include @@ -42,6 +43,7 @@ #import "chrome/browser/clair/window/clair_native_window.h" #include "chrome/browser/clair/window/clair_peeks.h" #include "chrome/browser/clair/window/clair_space_session.h" +#include "chrome/browser/clair/window/clair_tab_preview.h" #include "chrome/browser/clair/window/clair_window_group.h" #include "chrome/browser/clair/window/clair_window_hooks.h" #include "chrome/browser/clair/clair_profiles.h" @@ -1961,7 +1963,107 @@ void GiveBackToStill(tabs::TabHandle handle) { } } -void ClairBrowserWindow::ShowSpace(const std::string& space, bool again) { +// --- The tab switcher (add-tab-switcher-and-tabs-menu D1, D4) --- + +void ClairBrowserWindow::ShowTab(tabs::TabInterface* tab) { + ClairBrowserWindow* holder = HolderOf(tab); + if (!holder || ClairSpaceTabs::IsPlaceholder(tab->GetContents())) { + return; + } + // A Peek's row is its parent's; a split shows with its pane focused last. + tabs::TabInterface* row = RowOf(tab); + ClairSpaceTabs* lists = holder->space_tabs(); + if (holder == this || + (space_tabs_ && space_tabs_->is_regular() && lists == space_tabs_ && + space_tabs_->IsListed(row))) { + // A tab of another Space shows that Space as it becomes active, ClairUI + // hearing of the Space first (OnActiveTabChanged). + ActivateRow(row); + return; + } + // add-profiles D3: another profile's tab; the group swaps to its member. + if (!space_tabs_ || !space_tabs_->is_regular() || !lists || + !lists->is_regular() || !lists->IsListed(row)) { + return; + } + std::string space = lists->SpaceOf(row); + if (space.empty()) { + // A favorite belongs to its profile: the Space its window shows. + space = holder->shown_space(); + } + ShowSpace(space, /*again=*/false, row); +} + +void ClairBrowserWindow::RequestPreview( + tabs::TabInterface* tab, + const gfx::SizeF& size, + base::OnceCallback done) { + content::WebContents* contents = tab ? tab->GetContents() : nullptr; + if (!contents || contents->IsCrashed() || size.IsEmpty() || + ClairSpaceTabs::IsPlaceholder(contents)) { + std::move(done).Run(nil); + return; + } + const CGFloat scale = + ns_window_.backingScaleFactor > 0 ? ns_window_.backingScaleFactor : 1; + const int width = + std::max(1, static_cast(std::lround(size.width() * scale))); + // The copy, or else the preview kept, cut to the card, in points. + auto finish = [](tabs::TabHandle handle, gfx::SizeF size, int width, + base::OnceCallback done, + const SkBitmap& copy) { + tabs::TabInterface* tab = handle.Get(); + const SkBitmap& source = + copy.drawsNothing() && tab ? ClairTabPreview::Get(tab->GetContents()) + : copy; + const SkBitmap cut = ClairTabPreview::CutFromTop(source, size, width); + if (!tab || cut.drawsNothing()) { + std::move(done).Run(nil); + return; + } + NSImage* image = skia::SkBitmapToNSImage(cut); + image.size = NSMakeSize(size.width(), + size.width() * cut.height() / cut.width()); + std::move(done).Run(image); + }; + if (contents->GetVisibility() == content::Visibility::VISIBLE) { + // A page a window shows, as it is now. + CopyPage(tab, base::BindOnce(finish, tab->GetHandle(), size, width, + std::move(done))); + return; + } + finish(tab->GetHandle(), size, width, std::move(done), SkBitmap()); +} + +void ClairBrowserWindow::KeepPreviews( + content::WebContents* old_contents, + const std::set& shown) { + if (!old_contents || ClairSpaceTabs::IsPlaceholder(old_contents) || + !IsVisible()) { + return; + } + for (content::WebContents* page : PagesShownWith(old_contents)) { + tabs::TabInterface* tab = tabs::TabInterface::MaybeGetFromContents(page); + // Each pane of a split. A Peek's parent keeps its own page; the Peek, + // never a row, has none. + if (shown.contains(page) || !tab || page->IsCrashed() || + ClairSpaceTabs::IsPlaceholder(page) || + (peeks_ && peeks_->ParentOf(tab))) { + continue; + } + CopyPage(tab, base::BindOnce( + [](tabs::TabHandle handle, const SkBitmap& copy) { + if (tabs::TabInterface* tab = handle.Get()) { + ClairTabPreview::Keep(tab->GetContents(), copy); + } + }, + tab->GetHandle())); + } +} + +void ClairBrowserWindow::ShowSpace(const std::string& space, + bool again, + tabs::TabInterface* tab) { clair::ClairSpaceStore* store = clair::ClairSpaceStore::Get(); if (!space_tabs_ || !space_tabs_->is_regular() || !store->Contains(space) || (space == shown_space_ && !again)) { @@ -1971,10 +2073,20 @@ void GiveBackToStill(tabs::TabHandle handle) { if (store->ProfileOf(space) != clair::ClairProfiles::IDOf(browser_->GetProfile())) { if (ClairWindowGroup* group = ClairWindowGroup::Of(this)) { - group->ShowSpace(space); + group->ShowSpace(space, {}, + tab ? tab->GetHandle() : tabs::TabHandle::Null()); } return; } + // add-tab-switcher-and-tabs-menu D1: the switcher's tab, a row of the Space + // or a favorite, shows in place of the one Clair would pick, so no other + // tab shows on the way. + if (tab && space_tabs_->IsListed(tab) && + (space_tabs_->SpaceOf(tab) == space || space_tabs_->IsFavoriteTab(tab))) { + SetShownSpace(space); + ActivateRow(RowOf(tab)); + return; + } // Shown again: the active tab stays if it's a row of the Space. if (space == shown_space_) { tabs::TabInterface* active = browser_->tab_strip_model()->GetActiveTab(); @@ -2029,10 +2141,9 @@ void GiveBackToStill(tabs::TabHandle handle) { bool ClairBrowserWindow::ExecuteTabCommand(int command) { const bool select_index = command >= IDC_SELECT_TAB_0 && command <= IDC_SELECT_TAB_7; + // add-tab-switcher-and-tabs-menu D5a: Ctrl+Tab is ClairUI's switcher. const bool step = command == IDC_SELECT_NEXT_TAB || - command == IDC_SELECT_PREVIOUS_TAB || - command == IDC_CYCLE_TO_NEXT_TAB || - command == IDC_CYCLE_TO_PREV_TAB; + command == IDC_SELECT_PREVIOUS_TAB; TabStripModel* strip = browser_->tab_strip_model(); tabs::TabInterface* active = strip->GetActiveTab(); // While the window shows a still, the still's row stands for the active @@ -2089,8 +2200,7 @@ void GiveBackToStill(tabs::TabHandle handle) { (slot.tab == active_row || ClairSplits::PartnerOf(slot.tab) == active_row); }); - const bool forward = command == IDC_SELECT_NEXT_TAB || - command == IDC_CYCLE_TO_NEXT_TAB; + const bool forward = command == IDC_SELECT_NEXT_TAB; // From a favorite, the first or last row. const int position = it == slots.end() ? (forward ? -1 : count) @@ -2158,22 +2268,6 @@ void GiveBackToStill(tabs::TabHandle handle) { // a still, the still's row is the one closed. CloseTab(still_tab_.Get() ? still_tab_.Get() : active); return true; - case IDC_WINDOW_CLOSE_TABS_TO_RIGHT: - CloseTabsBelow(active_row); - return true; - case IDC_WINDOW_CLOSE_OTHER_TABS: { - std::vector others; - for (tabs::TabInterface* row : Rows()) { - if (row != active_row) { - others.push_back(row->GetHandle()); - } - } - // add-split-view: a split row closes both its panes. - for (const tabs::TabHandle& handle : others) { - CloseSplit(handle.Get()); - } - return true; - } default: return false; } @@ -3125,6 +3219,9 @@ void GiveBackToStill(tabs::TabHandle handle) { // window's visibility. A tab and its Peek show together (add-peek D4). const std::set shown = PagesShownWith(new_contents); if (old_contents) { + // add-tab-switcher-and-tabs-menu D4: the switcher's previews, while the + // pages leaving are still shown. + KeepPreviews(old_contents, shown); for (content::WebContents* page : PagesShownWith(old_contents)) { if (!shown.contains(page)) { page->UpdateWebContentsVisibility(content::Visibility::HIDDEN); diff --git a/engine/overlay/chrome/browser/clair/window/clair_native_window.mm b/engine/overlay/chrome/browser/clair/window/clair_native_window.mm index 3376f565..beb6a4ad 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_native_window.mm +++ b/engine/overlay/chrome/browser/clair/window/clair_native_window.mm @@ -45,18 +45,14 @@ bool ClairIsRemovedCommand(int command) { case IDC_SHOW_FULL_URLS: case IDC_SHOW_CUSTOMIZE_CHROME_SIDE_PANEL: case IDC_SHOW_CUSTOMIZE_CHROME_TOOLBAR: - case IDC_TAB_SEARCH: case IDC_TAB_SEARCH_CLOSE: case IDC_CREATE_NEW_TAB_GROUP: - case IDC_WINDOW_GROUP_TAB: - case IDC_GROUP_TARGET_TAB: case IDC_SHOW_CHROME_LABS: case IDC_SHOW_READING_MODE: case IDC_READING_LIST_MENU_SHOW_UI: case IDC_TOGGLE_VERTICAL_TABS: case IDC_TOGGLE_VERTICAL_TABS_COLLAPSE: case IDC_SHOW_HISTORY_SIDE_PANEL: - case IDC_NEW_SPLIT_TAB: // Omnibox settings, with no omnibox to apply to, and Cast. case IDC_SHOW_GOOGLE_LENS_SHORTCUT: case IDC_SHOW_AI_MODE_OMNIBOX_BUTTON: @@ -223,12 +219,10 @@ - (BOOL)validateUserInterfaceItem:(id)item enable |= clair::CanRestoreLastClosed(browser_window); break; case IDC_BACK: - case IDC_DUPLICATE_TAB: case IDC_FOCUS_LOCATION: case IDC_FORWARD: case IDC_HOME: case IDC_MANAGE_EXTENSIONS: - case IDC_MOVE_TAB_TO_NEW_WINDOW: case IDC_NEW_TAB: case IDC_OPEN_FILE: case IDC_PRINT: @@ -238,8 +232,6 @@ - (BOOL)validateUserInterfaceItem:(id)item case IDC_SELECT_PREVIOUS_TAB: case IDC_SHOW_DOWNLOADS: case IDC_STOP: - case IDC_WINDOW_CLOSE_OTHER_TABS: - case IDC_WINDOW_CLOSE_TABS_TO_RIGHT: // Commands that would put up their own dialog are off while a modal // dialog is up. enable &= ![AppController.sharedController keyWindowIsModal]; diff --git a/engine/overlay/chrome/browser/clair/window/clair_peeks.mm b/engine/overlay/chrome/browser/clair/window/clair_peeks.mm index c263e38a..0b7c2042 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_peeks.mm +++ b/engine/overlay/chrome/browser/clair/window/clair_peeks.mm @@ -20,7 +20,6 @@ #include "chrome/browser/clair/window/clair_splits.h" #import "chrome/browser/clair/clair_space_tabs.h" #include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/navigator/browser_navigator.h" #include "chrome/browser/ui/navigator/browser_navigator_params.h" #include "chrome/browser/ui/tabs/tab_enums.h" @@ -628,7 +627,6 @@ void Unwatch() { // The tab commands over the rows are the window's, which knows the // Space's order (add-spaces D5). tabs::TabInterface* peek = ActivePeek(); - tabs::TabInterface* parent = peek ? ParentOf(peek) : nullptr; if (!peek) { return false; } @@ -641,22 +639,6 @@ void Unwatch() { // Cmd+O expands the Peek, as in Arc, instead of File > Open File. Expand(peek); return true; - case IDC_DUPLICATE_TAB: { - const int index = parent ? strip()->GetIndexOfTab(parent) - : TabStripModel::kNoTab; - if (index != TabStripModel::kNoTab && - chrome::CanDuplicateTabAt(window_->browser(), index)) { - chrome::DuplicateTabAt(window_->browser(), index); - } - return true; - } - case IDC_MOVE_TAB_TO_NEW_WINDOW: - // The parent moves without its Peek: Chromium moves the active tab, - // which this makes the parent. The Peek, left behind without it, closes - // once, with its leave-page confirmation (Repair). - BeginClosing(FindByPeek(peek)); - ActivateTab(parent); - return false; default: return false; } diff --git a/engine/overlay/chrome/browser/clair/window/clair_tab_preview.h b/engine/overlay/chrome/browser/clair/window/clair_tab_preview.h new file mode 100644 index 00000000..7d0d704c --- /dev/null +++ b/engine/overlay/chrome/browser/clair/window/clair_tab_preview.h @@ -0,0 +1,53 @@ +// Copyright 2026 The Clair Authors +// Use of this source code is governed by the GNU General Public License, +// version 3, found in the LICENSE file at the root of Clair's repository. + +#ifndef CHROME_BROWSER_CLAIR_WINDOW_CLAIR_TAB_PREVIEW_H_ +#define CHROME_BROWSER_CLAIR_WINDOW_CLAIR_TAB_PREVIEW_H_ + +#include "content/public/browser/web_contents_user_data.h" +#include "third_party/skia/include/core/SkBitmap.h" +#include "ui/gfx/geometry/size_f.h" + +namespace content { +class WebContents; +} // namespace content + +// The tab switcher's preview of a tab's page (add-tab-switcher-and-tabs-menu +// design D4): the page as it was when a window last hid it, kept on its +// WebContents, so it goes with the tab between windows and is freed with it. +// One per tab, replaced on each hide. +class ClairTabPreview : public content::WebContentsUserData { + public: + // The card's shape and the width a preview is kept at: 2× the card's + // 157.5 points, so it stays sharp on a Retina screen. + static constexpr int kWidth = 315; + static constexpr double kAspect = 3.0 / 2.0; + + ClairTabPreview(const ClairTabPreview&) = delete; + ClairTabPreview& operator=(const ClairTabPreview&) = delete; + ~ClairTabPreview() override; + + // Keeps `copy` of `contents`'s page as its preview: the page's top, cut to + // the card's shape and scaled to kWidth. An empty copy keeps the one before. + static void Keep(content::WebContents* contents, const SkBitmap& copy); + // The preview kept for `contents`, or an empty bitmap. + static SkBitmap Get(content::WebContents* contents); + + // `copy`'s top, cut to `shape`'s width-to-height ratio (all of it when it's + // wider than that), scaled down to `width` pixels when it's wider. Empty + // for an empty copy or shape. + static SkBitmap CutFromTop(const SkBitmap& copy, + const gfx::SizeF& shape, + int width); + + private: + friend class content::WebContentsUserData; + explicit ClairTabPreview(content::WebContents* contents); + + SkBitmap bitmap_; + + WEB_CONTENTS_USER_DATA_KEY_DECL(); +}; + +#endif // CHROME_BROWSER_CLAIR_WINDOW_CLAIR_TAB_PREVIEW_H_ diff --git a/engine/overlay/chrome/browser/clair/window/clair_tab_preview.mm b/engine/overlay/chrome/browser/clair/window/clair_tab_preview.mm new file mode 100644 index 00000000..01b935a3 --- /dev/null +++ b/engine/overlay/chrome/browser/clair/window/clair_tab_preview.mm @@ -0,0 +1,75 @@ +// Copyright 2026 The Clair Authors +// Use of this source code is governed by the GNU General Public License, +// version 3, found in the LICENSE file at the root of Clair's repository. + +#include "chrome/browser/clair/window/clair_tab_preview.h" + +#include +#include +#include + +#include "content/public/browser/web_contents.h" +#include "skia/ext/image_operations.h" +#include "third_party/skia/include/core/SkRect.h" + +ClairTabPreview::ClairTabPreview(content::WebContents* contents) + : content::WebContentsUserData(*contents) {} + +ClairTabPreview::~ClairTabPreview() = default; + +// static +void ClairTabPreview::Keep(content::WebContents* contents, + const SkBitmap& copy) { + if (!contents) { + return; + } + SkBitmap preview = CutFromTop( + copy, gfx::SizeF(static_cast(kAspect), 1.0f), kWidth); + if (preview.drawsNothing()) { + return; + } + GetOrCreateForWebContents(contents)->bitmap_ = std::move(preview); +} + +// static +SkBitmap ClairTabPreview::Get(content::WebContents* contents) { + ClairTabPreview* preview = contents ? FromWebContents(contents) : nullptr; + return preview ? preview->bitmap_ : SkBitmap(); +} + +// static +SkBitmap ClairTabPreview::CutFromTop(const SkBitmap& copy, + const gfx::SizeF& shape, + int width) { + if (copy.drawsNothing() || shape.IsEmpty() || width <= 0) { + return SkBitmap(); + } + // The page's top, fitted to the card's width (D4, `tab-switcher` "Cards"). + const int height = std::min( + copy.height(), + std::max(1, static_cast(std::lround(copy.width() * shape.height() / + shape.width())))); + SkBitmap top; + if (!copy.extractSubset(&top, SkIRect::MakeWH(copy.width(), height))) { + return SkBitmap(); + } + if (top.width() <= width) { + // A bitmap of its own, so the whole page's copy can go. + SkBitmap own; + if (!own.tryAllocPixels(top.info()) || + !top.readPixels(own.pixmap(), 0, 0)) { + return SkBitmap(); + } + own.setImmutable(); + return own; + } + const int scaled_height = std::max( + 1, static_cast(std::lround(static_cast(height) * width / + top.width()))); + SkBitmap scaled = skia::ImageOperations::Resize( + top, skia::ImageOperations::RESIZE_GOOD, width, scaled_height); + scaled.setImmutable(); + return scaled; +} + +WEB_CONTENTS_USER_DATA_KEY_IMPL(ClairTabPreview); diff --git a/engine/overlay/chrome/browser/clair/window/clair_window_group.h b/engine/overlay/chrome/browser/clair/window/clair_window_group.h index 8fc67d39..7bce1020 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_window_group.h +++ b/engine/overlay/chrome/browser/clair/window/clair_window_group.h @@ -69,9 +69,12 @@ class ClairWindowGroup { // Shows `space`, of any profile: the shown member shows it, or the group // swaps to its member for the Space's profile, created hidden if need be. // `then` runs with the member showing it, once it does, which may wait for - // the profile to load; with null if it can't. + // the profile to load; with null if it can't. With `tab`, a row of `space` + // or a favorite of its profile, the member shows that tab + // (add-tab-switcher-and-tabs-menu D1). void ShowSpace(const std::string& space, - base::OnceCallback then = {}); + base::OnceCallback then = {}, + tabs::TabHandle tab = tabs::TabHandle::Null()); // Runs `done` with the member for `profile_id`, created hidden if the group // has none; with null when the profile can't be loaded. void EnsureMember(const std::string& profile_id, diff --git a/engine/overlay/chrome/browser/clair/window/clair_window_group.mm b/engine/overlay/chrome/browser/clair/window/clair_window_group.mm index 2fb7eef9..13471b4e 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_window_group.mm +++ b/engine/overlay/chrome/browser/clair/window/clair_window_group.mm @@ -346,7 +346,8 @@ void SetCoverBehavior(NSWindow* window, bool covering) { void ClairWindowGroup::ShowSpace( const std::string& space, - base::OnceCallback then) { + base::OnceCallback then, + tabs::TabHandle tab) { clair::ClairSpaceStore* store = clair::ClairSpaceStore::Get(); if (!is_regular() || !store->Contains(space)) { if (then) { @@ -358,7 +359,7 @@ void SetCoverBehavior(NSWindow* window, bool covering) { // The group switches on purpose: start-up's shows are over for it. holds_startup_show_.clear(); if (ProfileIDOf(shown_) == profile) { - shown_->ShowSpace(space); + shown_->ShowSpace(space, /*again=*/false, tab.Get()); if (then) { std::move(then).Run(shown_); } @@ -371,7 +372,7 @@ void SetCoverBehavior(NSWindow* window, bool covering) { [](base::WeakPtr group, std::string space, std::string previous, base::OnceCallback then, - ClairBrowserWindow* member) { + tabs::TabHandle tab, ClairBrowserWindow* member) { if (!group || !member) { if (then) { std::move(then).Run(nullptr); @@ -382,13 +383,13 @@ void SetCoverBehavior(NSWindow* window, bool covering) { // group's earlier Space, in place of the shown member, before // the member's tab shows it. member->BeginSwapIn(previous, group->shown_); - member->ShowSpace(space, /*again=*/true); + member->ShowSpace(space, /*again=*/true, tab.Get()); group->SwapTo(member, previous); if (then) { std::move(then).Run(member); } }, - weak_factory_.GetWeakPtr(), space, previous, std::move(then))); + weak_factory_.GetWeakPtr(), space, previous, std::move(then), tab)); } void ClairWindowGroup::EnsureMember( diff --git a/engine/overlay/chrome/browser/clair/window/clair_window_hooks.mm b/engine/overlay/chrome/browser/clair/window/clair_window_hooks.mm index a2c3e3a8..e91cc64d 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_window_hooks.mm +++ b/engine/overlay/chrome/browser/clair/window/clair_window_hooks.mm @@ -407,6 +407,14 @@ void InstallNativeWindowMenus() { if (NSMenuItem* profiles = [main_menu itemWithTag:IDC_PROFILE_MAIN_MENU]) { [main_menu removeItem:profiles]; } + // add-tab-switcher-and-tabs-menu D5: no Tab menu; ClairUI's Tabs menu takes + // its place. Deleted rather than hidden, as a hidden item still fires its + // key equivalent (Ctrl+Tab, Search Tabs). AppController looks it up by tag + // whenever a window becomes main: its TabMenuBridge then fills nil, and + // -onVerticalTabStripModeChanged: returns early. + if (NSMenuItem* tab_menu = [main_menu itemWithTag:IDC_TAB_MENU]) { + [main_menu removeItem:tab_menu]; + } // add-profiles D10: Settings › Advanced replaces "Warn Before Quitting", // which has no tag; it's found by its action, with the separator after it. if (NSMenu* app_menu = main_menu.itemArray.firstObject.submenu) { diff --git a/engine/patches/clair/native-window-hook.patch b/engine/patches/clair/native-window-hook.patch index e4e5ebb0..55b01462 100644 --- a/engine/patches/clair/native-window-hook.patch +++ b/engine/patches/clair/native-window-hook.patch @@ -468,7 +468,7 @@ ":global_keyboard_shortcuts_mac", "//chrome/browser/apps/app_shim", "//chrome/browser/mac", -@@ -5257,6 +5258,75 @@ +@@ -5257,6 +5258,77 @@ # is easy to catch in review. sources = [] } @@ -527,6 +527,8 @@ + "clair/window/clair_space_session.mm", + "clair/window/clair_splits.h", + "clair/window/clair_splits.mm", ++ "clair/window/clair_tab_preview.h", ++ "clair/window/clair_tab_preview.mm", + "clair/window/clair_window_group.h", + "clair/window/clair_window_group.mm", + "clair/window/clair_window_hooks.h", diff --git a/native/ClairHost.h b/native/ClairHost.h index 6d2f03d6..fdb8707c 100644 --- a/native/ClairHost.h +++ b/native/ClairHost.h @@ -1212,6 +1212,28 @@ NS_SWIFT_NAME(ClairBrowser) // Mutes or unmutes the tab. - (void)setMuted:(BOOL)muted forTab:(ClairTabID)tabID NS_SWIFT_NAME(setMuted(_:tab:)); +// --- The tab switcher (add-tab-switcher-and-tabs-menu design D1, D4) --- +// Shows a tab of any of the window's Spaces, or a favorite's, as selecting its +// row or tile does: a split shows as -showSplitOfTab: does, and a tab with a +// Peek shows its Peek. A tab of the shown Space is activated as -activateTab: +// does, taking it from another window. A tab of another Space of the window's +// profile shows that Space with the tab active, -[ClairWindow +// shownSpaceDidChange:…] coming before -activeTabDidChange:. A tab of another +// profile's Space goes through the window group's swap, as -showSpace: does +// for that Space, and the window swapped in activates the tab. Ignored for an +// unknown tab and the still's placeholder. +- (void)showTab:(ClairTabID)tabID NS_SWIFT_NAME(show(tab:)); +// A preview of the tab's page for the tab switcher, `size` in points: the +// shown tab's page as it is now; any other tab's as it was when this or +// another window last hid it, cut from its top to `size`'s shape; nil when +// there is none (never shown, crashed, or a copy that failed). A Peek's parent +// gets its own page, without the Peek. `completion` runs once, on the main +// thread, maybe before this returns. +- (void)requestPreviewOfTab:(ClairTabID)tabID + size:(NSSize)size + completion:(void (^)(NSImage *_Nullable preview))completion + NS_SWIFT_NAME(requestPreview(of:size:completion:)); + // --- Pins (add-pinned-tabs-and-favorites design D4, D5) --- // Selects a pinned tab or favorite of the window's profile: activates its // bound tab as -activateTab: does, or opens its pinned URL in a new tab bound diff --git a/native/ClairUITests/FakeBrowser.swift b/native/ClairUITests/FakeBrowser.swift index 0c4c947e..dd1562a3 100644 --- a/native/ClairUITests/FakeBrowser.swift +++ b/native/ClairUITests/FakeBrowser.swift @@ -1452,6 +1452,27 @@ final class FakeBrowser: NSObject, ClairBrowser { func duplicate(tab tabID: TabID) { record("duplicate \(tabID)") } func setMuted(_ muted: Bool, tab tabID: TabID) { record("\(muted ? "mute" : "unmute") \(tabID)") } + + // MARK: The tab switcher (add-tab-switcher-and-tabs-menu D1, D4) + + func show(tab tabID: TabID) { + host.operation { + record("show \(tabID)") + guard tabID != placeholderID, let tab = rowTab(tabID) else { return } + // A split shows as its row does; a tab with a Peek shows its Peek. + // Activating a tab of another Space shows that Space first (setActive). + if tab.splitPartnerID != ClairTabIDNone { + showSplit(of: tabID) + } else { + activateRow(tab.peekParentID != ClairTabIDNone ? tab.peekParentID : tabID) + } + } + } + + func requestPreview(of tabID: TabID, size: NSSize, completion: @escaping (NSImage?) -> Void) { + record("preview \(tabID)") + completion(rowTab(tabID) != nil ? host.previews[tabID] : nil) + } func goBack() { record("back") } func goForward() { record("forward") } func reload() { record("reload") } diff --git a/native/ClairUITests/FakeBrowserTests.swift b/native/ClairUITests/FakeBrowserTests.swift index 2063ff0f..0b8a1508 100644 --- a/native/ClairUITests/FakeBrowserTests.swift +++ b/native/ClairUITests/FakeBrowserTests.swift @@ -2,6 +2,7 @@ // You can use, redistribute, and/or modify this source code under // the terms of the GPL-3.0 license that can be found in the LICENSE file. +import AppKit import ClairHost import Foundation import Testing @@ -635,3 +636,81 @@ struct FakeFolderTests { #expect(host.folderRecords(inSpace: work).isEmpty) } } + +/// The tab switcher's calls (add-tab-switcher-and-tabs-menu D1, D4). +@MainActor +struct FakeSwitcherCallTests { + @Test func showingATabOfAnotherSpaceShowsTheSpaceFirst() { + let host = FakeHost() + let work = host.addSpaces("Work")[0] + let browser = FakeBrowser(host: host) + let window = RecordingWindow() + browser.clairWindow = window + let mail = browser.addTab(title: "Mail") + browser.showSpace(work) + let recipes = browser.addTab(title: "Recipes") + let before = window.calls.count + browser.show(tab: mail.tabID) + #expect(browser.shownSpaceID == FakeHost.homeID) + #expect(browser.activeTabID == mail.tabID) + #expect(Array(window.calls[before...]) == ["space \(FakeHost.homeID) from \(work)", "active \(mail.tabID)"]) + #expect(recipes.spaceID == work) + } + + @Test func showingATabWithAPeekShowsThePeek() { + let browser = FakeBrowser() + let docs = browser.addTab(title: "Docs") + let peek = browser.openPeek(of: docs.tabID, title: "Peek")! + browser.addTab(title: "Mail") + browser.show(tab: docs.tabID) + #expect(browser.activeTabID == peek.tabID) + } + + @Test func showingASplitsPaneShowsTheSplit() { + let browser = FakeBrowser() + let news = browser.addTab(title: "News") + let docs = browser.addTab(title: "Docs") + browser.makeSplit(news.tabID, with: docs.tabID) + browser.activate(tab: news.tabID) + browser.addTab(title: "Mail") + browser.show(tab: docs.tabID) + #expect(browser.commands.contains("showSplit \(docs.tabID)")) + // The pane focused last. + #expect(browser.activeTabID == news.tabID) + } + + @Test func showingAFavoriteKeepsTheShownSpace() { + let host = FakeHost() + let mail = host.addPin(url: "https://mail.example/", title: "Mail", inSpace: nil) + let browser = FakeBrowser(host: host) + browser.addTab(title: "Docs") + browser.openPin(mail) + let favorite = host.boundTab(of: mail)!.tabID + browser.addTab(title: "News") + browser.show(tab: favorite) + #expect(browser.activeTabID == favorite) + #expect(browser.shownSpaceID == FakeHost.homeID) + } + + @Test func showingAnUnknownTabDoesNothing() { + let browser = FakeBrowser() + let docs = browser.addTab(title: "Docs") + browser.show(tab: 999) + #expect(browser.activeTabID == docs.tabID) + } + + @Test func previewsAreNilUntilATestSetsThem() { + let browser = FakeBrowser() + let docs = browser.addTab(title: "Docs") + var got: [NSImage?] = [] + browser.requestPreview(of: docs.tabID, size: NSSize(width: 157.5, height: 105)) { got.append($0) } + let image = NSImage(size: NSSize(width: 4, height: 4)) + browser.host.previews[docs.tabID] = image + browser.requestPreview(of: docs.tabID, size: NSSize(width: 157.5, height: 105)) { got.append($0) } + browser.requestPreview(of: 999, size: NSSize(width: 157.5, height: 105)) { got.append($0) } + #expect(got.count == 3) + #expect(got[0] == nil) + #expect(got[1] === image) + #expect(got[2] == nil) + } +} diff --git a/native/ClairUITests/FakeHost.swift b/native/ClairUITests/FakeHost.swift index ac66ec2f..a5425700 100644 --- a/native/ClairUITests/FakeHost.swift +++ b/native/ClairUITests/FakeHost.swift @@ -155,6 +155,9 @@ final class FakeHost: NSObject, ClairHost { /// Every tab's page view, which moves with it between windows. var pageViews: [TabID: NSView] = [:] + /// Each tab's page preview for the tab switcher (add-tab-switcher-and-tabs-menu + /// D4), set by tests; none by default, as for a tab never shown. + var previews: [TabID: NSImage] = [:] /// Unique across browsers, as Chromium's tab handles are. private var nextTabID: TabID = 1 /// When each tab was last active, as a count. diff --git a/openspec/changes/add-tab-switcher-and-tabs-menu/design.md b/openspec/changes/add-tab-switcher-and-tabs-menu/design.md index 9335dd2d..7cf58bd9 100644 --- a/openspec/changes/add-tab-switcher-and-tabs-menu/design.md +++ b/openspec/changes/add-tab-switcher-and-tabs-menu/design.md @@ -74,7 +74,7 @@ The contract (`ClairHost.h`, `ClairBrowser`): ``` - **Capture.** The engine copies a tab's page with `CopyPage` as the tab stops being shown. That happens in `ClairBrowserWindow`'s active-tab change, before Chromium hides it, which is where `TabStripModel` asks `ThumbnailTabHelper` for its own. The copy is scaled to 2× the card's width, cut to the card's 3:2 shape from the top, and kept on the tab as `WebContents` user data (`ClairTabPreview`). -- **Lifetime and memory.** One image per tab, replaced on each hide, freed with the tab: about 100 KB each. +- **Lifetime and memory.** One bitmap per tab, 315 × 210 pixels, replaced on each hide, freed with the tab: about 260 KB each. - **The shown tab** is copied live on request. - **Peeks.** A tab with a Peek gets the parent's page; the still's convention is followed. @@ -82,6 +82,8 @@ Turning on `kTabHoverCardImages` was rejected: it needs a patch to a Chromium de A split's card asks for both panes and draws them side by side in pane order. +**Showing a tab of another profile.** `-showTab:` passes the tab through the window group's swap (`ClairWindowGroup::ShowSpace`), and the member swapped in shows it in place of the tab `ShowSpace` would pick. Otherwise the Space's last tab would show first, and enter the recents. + ### D5. Delete Chromium's Tab menu, add Clair's Tabs menu The engine deletes Chromium's Tab menu (the main menu item tagged `IDC_TAB_MENU`) in `clair_window_hooks.mm`, where it already reworks the main menu at start-up, before any window becomes main. ClairUI's new `TabsMenu` inserts its "Tabs" menu before the Window menu (`IDC_WINDOW_MENU`), where Chromium's sat. @@ -131,7 +133,7 @@ With Chromium's Tab menu deleted, nothing Clair did to it or for it is needed. E **Docs:** `docs/native-window.md`'s "Rows and commands" stops listing Ctrl+Tab among the row commands. -Before deleting each engine case, the implementation greps the Chromium tree for other senders of the command (extension APIs, context menus Clair shows). A command with another sender keeps its case. +Before deleting each engine case, the implementation greps the Chromium tree for other senders of the command (extension APIs, context menus Clair shows). A command with another sender keeps its case. None has one that reaches a native window: on macOS their accelerators are only the Tab menu's key equivalents (`accelerators_cocoa.mm`), `global_keyboard_shortcuts_mac.mm` lists none of them, the app menu and the Views tab strip's context menu aren't shown, and DevTools' `Browser.executeBrowserCommand` (Open Tab Search) calls `chrome::ExecuteCommand` directly, past Clair's handler, as it did before. ### D6. Context menus in groups From 08bf5144483f54f686c2adbe94d98b2421ce95ae Mon Sep 17 00:00:00 2001 From: Joshua Park Date: Fri, 27 Nov 2026 00:56:52 -0500 Subject: [PATCH 2/8] feat: add the tab switcher, the Tabs menu and grouped tab menus to ClairUI --- .../BrowserWindowController+Pins.swift | 17 +- .../BrowserWindowController+Switcher.swift | 85 ++++ native/ClairUI/BrowserWindowController.swift | 41 +- native/ClairUI/NativeLayer.swift | 7 + native/ClairUI/PinsLogic.swift | 148 +++--- native/ClairUI/PinsMenu.swift | 53 +-- native/ClairUI/PinsViews.swift | 14 +- native/ClairUI/SidebarView.swift | 1 - native/ClairUI/SplitMenu.swift | 95 +--- native/ClairUI/TabSwitcher.swift | 391 ++++++++++++++++ native/ClairUI/TabSwitcherLogic.swift | 212 +++++++++ native/ClairUI/TabsMenu.swift | 238 ++++++++++ native/ClairUITests/FoldersTests.swift | 13 +- native/ClairUITests/PinsTests.swift | 140 ++++-- native/ClairUITests/SpacesTests.swift | 3 +- native/ClairUITests/SplitTests.swift | 20 +- native/ClairUITests/TabSwitcherTests.swift | 425 ++++++++++++++++++ native/ClairUITests/TabsMenuTests.swift | 160 +++++++ .../add-tab-switcher-and-tabs-menu/design.md | 2 +- .../add-tab-switcher-and-tabs-menu/tasks.md | 2 +- 20 files changed, 1780 insertions(+), 287 deletions(-) create mode 100644 native/ClairUI/BrowserWindowController+Switcher.swift create mode 100644 native/ClairUI/TabSwitcher.swift create mode 100644 native/ClairUI/TabSwitcherLogic.swift create mode 100644 native/ClairUI/TabsMenu.swift create mode 100644 native/ClairUITests/TabSwitcherTests.swift create mode 100644 native/ClairUITests/TabsMenuTests.swift diff --git a/native/ClairUI/BrowserWindowController+Pins.swift b/native/ClairUI/BrowserWindowController+Pins.swift index e7e6a58f..6e4649e4 100644 --- a/native/ClairUI/BrowserWindowController+Pins.swift +++ b/native/ClairUI/BrowserWindowController+Pins.swift @@ -59,7 +59,7 @@ extension BrowserWindowController { } } - /// What the Tabs and View menus' Clair items act on. + /// What the Tabs menu's pin items and View › Collapse Pinned Tabs act on. var pinMenuState: PinsLogic.MenuState { guard model.showsPins else { return PinsLogic.MenuState(showsPins: false) } // The row's highlight stays on a split's leading pane; the commands are @@ -72,12 +72,11 @@ extension BrowserWindowController { showsPins: true, activeIsToday: pin == nil && rows.contains { $0.tabID == highlighted || $0.tabID == commandTab }, activePinIsFavorite: pin?.isFavorite, - activePinIsNavigatedAway: pin.map(PinsLogic.isNavigatedAway) ?? false, todayRowCount: TabListLogic.rowCount(model.tabs), isCollapsed: model.isPinnedSectionCollapsed) } - /// One of the main menu's Clair items. + /// One of the Tabs menu's pin items, or View › Collapse Pinned Tabs. func perform(_ command: PinsLogic.MainMenuCommand) { let highlighted = model.commandTab switch command { @@ -89,13 +88,13 @@ extension BrowserWindowController { } else if highlighted != ClairTabIDNone { pin(tab: highlighted) } - case .backToPinnedURL: + case .pinToFavorites: if let pin = model.pin(ofTab: highlighted) { - returnToPinnedURL(pin.pinID) - } - case .closeKeepingPin: - if let pin = model.pin(ofTab: highlighted) { - closeKeepingPin(pin.pinID) + if !pin.isFavorite { + pinToFavorites(pin: pin.pinID) + } + } else if highlighted != ClairTabIDNone { + pinToFavorites(tab: highlighted) } case .clearToday: clearToday() diff --git a/native/ClairUI/BrowserWindowController+Switcher.swift b/native/ClairUI/BrowserWindowController+Switcher.swift new file mode 100644 index 00000000..5817cc4c --- /dev/null +++ b/native/ClairUI/BrowserWindowController+Switcher.swift @@ -0,0 +1,85 @@ +// Copyright 2026 The Clair Authors +// You can use, redistribute, and/or modify this source code under +// the terms of the GPL-3.0 license that can be found in the LICENSE file. + +import AppKit +import ClairHost + +/// The window's recent tabs and Ctrl+Tab's switcher +/// (add-tab-switcher-and-tabs-menu design D1 to D4). +extension BrowserWindowController: TabSwitcherHost { + /// Every tab the window can show from the switcher, by ID: every Space's + /// tabs, pinned tabs and favorites, of every profile, as the recents span + /// Spaces and follow a profile swap; an incognito or guest window's own. + var switcherTabs: [TabID: any ClairTab] { + var tabs: [TabID: any ClairTab] = [:] + let spaces = model.spaces + if model.showsSpaces { + for space in spaces.spaces { + for tab in spaces.tabs(inSpace: space.spaceID) { tabs[tab.tabID] = tab } + for pin in spaces.pins(inSpace: space.spaceID) { + for tab in pin.tabs { tabs[tab.tabID] = tab } + } + } + for profile in spaces.profiles { + for pin in spaces.favorites(ofProfile: profile.profileID) { + for tab in pin.tabs { tabs[tab.tabID] = tab } + } + } + } + // The window's own, as last reported. + for tab in model.allTabs { tabs[tab.tabID] = tab } + return tabs + } + + /// D1: the window showed another tab; its row moves to the front, or + /// waits for the list that adds it. The still's placeholder never comes. + func noteShownTab() { + let tabID = model.activeTabID + guard tabID != ClairTabIDNone else { return } + pendingRecent = recents.show(tabID, in: switcherTabs) ? ClairTabIDNone : tabID + } + + /// D1: tabs or pins changed somewhere: closed pages leave the recents, and + /// the switcher closes when the shown tab did. + func recentTabsChanged() { + let tabs = switcherTabs + recents.prune(in: tabs) + if pendingRecent != ClairTabIDNone, pendingRecent == model.activeTabID, recents.show(pendingRecent, in: tabs) { + pendingRecent = ClairTabIDNone + } + tabSwitcher.tabsDidChange(open: Set(tabs.keys)) + } + + // MARK: TabSwitcherHost + + var switcherWindow: NSWindow { window } + + var switcherMayAct: Bool { + browser != nil && window.isKeyWindow && dialogs.showing == nil && window.attachedSheet == nil + } + + /// The recents as the rows they are now: a tab that joined a split since + /// counts as the split, which a tab's own update, not a list's, says. + var recentTabIDs: [TabID] { + recents.prune(in: switcherTabs) + return recents.ids + } + + func switcherCards(for entries: [TabID]) -> [SwitcherCard] { + let tabs = switcherTabs + return entries.compactMap { SwitcherCard.make($0, in: tabs) } + } + + func requestSwitcherPreview(of tabID: TabID, size: NSSize, completion: @escaping (NSImage?) -> Void) { + guard let browser else { + completion(nil) + return + } + browser.requestPreview(of: tabID, size: size, completion: completion) + } + + func showFromSwitcher(_ tabID: TabID) { + browser?.show(tab: tabID) + } +} diff --git a/native/ClairUI/BrowserWindowController.swift b/native/ClairUI/BrowserWindowController.swift index 1ddd60ba..4d9d92e7 100644 --- a/native/ClairUI/BrowserWindowController.swift +++ b/native/ClairUI/BrowserWindowController.swift @@ -77,6 +77,12 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over nonisolated(unsafe) var flagsMonitor: Any? /// A closed pin dropped on the page, which splits once its page opens. var pendingPinSplit: (pinID: PinID, then: (TabID) -> Void)? + /// The window's recent tabs, and a shown tab no list has yet + /// (add-tab-switcher-and-tabs-menu D1). + var recents = RecentTabs() + var pendingRecent: TabID = ClairTabIDNone + /// Ctrl+Tab's switcher (D2). + private(set) lazy var tabSwitcher = TabSwitcher(host: self) /// Add Split View and New Tab open the command bar on the new pane once /// it's active. var opensCommandBarOnNewPane = false @@ -190,6 +196,7 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over model.setDownloads(browser.downloads, progress: browser.downloadProgress) stillDidChange() activeTabDidChange(browser.activeTabID) + tabSwitcher.start() } /// Reads the toolbar preference again; only a change touches the model. @@ -208,6 +215,10 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over MainActor.assumeIsolated { guard let self else { return } self.model.isWindowKey = self.window.isKeyWindow + // Another window or app: the switcher closes without switching. + if !self.window.isKeyWindow { + self.tabSwitcher.cancel() + } self.offerCommandBarIfNew() } }) @@ -528,6 +539,12 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over model.renaming = nil model.setShownSpace(spaceID) refreshPinPreferences() + // add-tab-switcher-and-tabs-menu D1: the recents belong to the window as + // the user sees it. + if let outgoing { + recents = outgoing.recents + recentTabsChanged() + } tabsChanged() if let outgoing { takeManageSpaces(from: outgoing) @@ -576,9 +593,13 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over } func spaceTabsDidChange(_ spaceID: SpaceID) { - guard spaceID == model.shownSpaceID else { return } + guard spaceID == model.shownSpaceID else { + recentTabsChanged() + return + } model.reloadTabs() tabsChanged() + recentTabsChanged() } func spaceTabDidChange(_ tab: any ClairTab) { @@ -586,19 +607,29 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over tabChanged(tab) } - func spacesDidChange() {} + func spacesDidChange() { + recentTabsChanged() + } func spacePinsDidChange(_ spaceID: SpaceID) { - guard spaceID == model.shownSpaceID, model.showsPins else { return } + guard spaceID == model.shownSpaceID, model.showsPins else { + recentTabsChanged() + return + } pinsChanged() tabsChanged() + recentTabsChanged() finishPendingPinSplit() } func favoritesDidChange(_ profileID: ProfileID) { - guard profileID == model.profileID, model.showsPins else { return } + guard profileID == model.profileID, model.showsPins else { + recentTabsChanged() + return + } pinsChanged() tabsChanged() + recentTabsChanged() finishPendingPinSplit() } @@ -674,6 +705,7 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over model.commandBar?.cancel() } model.setActiveTab(tabID) + noteShownTab() if switched { model.reloadStop.tabSwitched(isLoading: model.activeTab?.isLoading == true) rootView.loadingIndicator.tabSwitched(isLoading: model.activeTab?.isLoading == true) @@ -978,6 +1010,7 @@ final class BrowserWindowController: NSObject, ClairWindow, SidebarActions, Over rootView.card.showStill(false, image: nil) removeSafetyNet() stopCommandBarKeyMonitor() + tabSwitcher.stop() rootView.card.show(devTools: nil, layout: DevToolsLayout(dockSide: .none, pageBounds: .zero, hidesPage: false)) browser = nil } diff --git a/native/ClairUI/NativeLayer.swift b/native/ClairUI/NativeLayer.swift index a9927c69..a3b57ddd 100644 --- a/native/ClairUI/NativeLayer.swift +++ b/native/ClairUI/NativeLayer.swift @@ -41,6 +41,8 @@ final class NativeLayer { private(set) var pinsMenu: PinsMenu? /// Split view's menu bar items (add-split-view D9). private(set) var splitMenu: SplitMenu? + /// The Tabs menu (add-tab-switcher-and-tabs-menu D5). + private(set) var tabsMenu: TabsMenu? /// View › Hide Toolbar's target (add-page-toolbar D8). let toolbarMenu = ToolbarMenuTarget() @@ -83,6 +85,11 @@ final class NativeLayer { let splitMenu = SplitMenu() splitMenu.install(in: NSApp.mainMenu) self.splitMenu = splitMenu + // add-tab-switcher-and-tabs-menu D5: in place of Chromium's Tab menu, + // which the engine deleted. + let tabsMenu = TabsMenu() + tabsMenu.install(in: NSApp.mainMenu) + self.tabsMenu = tabsMenu let updates = UpdateController(host: host, configuration: .current) updates.start() diff --git a/native/ClairUI/PinsLogic.swift b/native/ClairUI/PinsLogic.swift index ee8d762d..3a8731a5 100644 --- a/native/ClairUI/PinsLogic.swift +++ b/native/ClairUI/PinsLogic.swift @@ -471,6 +471,9 @@ enum PinsLogic { case pin case pinToFavorites case editPinnedPage + /// Edit Pinned Page › Back to Pinned URL (add-tab-switcher-and-tabs-menu + /// D6). + case backToPinnedURL case replacePinnedURL case editPinnedURL case moveToSpace @@ -494,77 +497,69 @@ enum PinsLogic { static let splitWithTab = MenuItem(title: "Split with Tab", command: .splitWithTab) static let separateTabs = MenuItem(title: "Separate Tabs", command: .separateTabs) - - /// A Today tab's menu: nil entries are separators. Incognito and guest - /// windows have neither pin item. A split row's chip (`inSplit`) has no - /// Split with Tab, and Separate Tabs (add-split-view, "The split row's - /// menu"). - static func todayMenu(isMuted: Bool, canMoveToSpace: Bool, canPin: Bool, inSplit: Bool = false) -> [MenuItem?] { - var items: [MenuItem?] = [ - MenuItem(title: "Copy Link", command: .copyLink), - MenuItem(title: "Rename…", command: .rename), - MenuItem(title: "Duplicate", command: .duplicate), - MenuItem(title: isMuted ? "Unmute" : "Mute", command: isMuted ? .unmute : .mute), - ] - items += inSplit ? [nil, separateTabs] : [splitWithTab] - if canPin { - items += [nil, MenuItem(title: "Pin Tab", command: .pin), MenuItem(title: "Pin to Favorites", command: .pinToFavorites)] - } - if canMoveToSpace { - items += [nil, MenuItem(title: "Move to Space", command: .moveToSpace)] + private static let copyLink = MenuItem(title: "Copy Link", command: .copyLink) + private static let duplicate = MenuItem(title: "Duplicate", command: .duplicate) + private static let rename = MenuItem(title: "Rename…", command: .rename) + private static let moveToSpace = MenuItem(title: "Move to Space", command: .moveToSpace) + private static let pinToFavorites = MenuItem(title: "Pin to Favorites", command: .pinToFavorites) + private static let closeTab = MenuItem(title: "Close Tab", command: .closeTab) + private static let editPinnedPage = MenuItem(title: "Edit Pinned Page", command: .editPinnedPage) + + private static func mute(_ isMuted: Bool, isEnabled: Bool = true) -> MenuItem { + MenuItem(title: isMuted ? "Unmute" : "Mute", command: isMuted ? .unmute : .mute, isEnabled: isEnabled) + } + + /// A menu of `groups`, with a divider (nil) between each; a group left + /// empty drops out with its divider (add-tab-switcher-and-tabs-menu D6). + static func joined(_ groups: [[MenuItem]]) -> [MenuItem?] { + var items: [MenuItem?] = [] + for group in groups where !group.isEmpty { + if !items.isEmpty { + items.append(nil) + } + items += group.map { Optional($0) } } - items += [ - nil, - MenuItem(title: "Close Tab", command: .closeTab), - MenuItem(title: "Close Tabs Below", command: .closeTabsBelow), - ] return items } - /// A pinned tab's menu; a pinned split's chip's has no Edit Pinned Page - /// or Split with Tab, and Separate Tabs. + /// A Today tab's menu (sidebar spec, "Today tab menu"): nil entries are + /// dividers. Incognito and guest windows (`canPin` false) have neither pin + /// item, nor Rename…. A split row's chip (`inSplit`) has Separate Tabs in + /// place of Split with Tab (add-split-view, "The split row's menu"). + static func todayMenu(isMuted: Bool, canMoveToSpace: Bool, canPin: Bool, inSplit: Bool = false) -> [MenuItem?] { + joined([ + canPin ? [MenuItem(title: "Pin Tab", command: .pin), pinToFavorites] : [], + [copyLink, duplicate], + [inSplit ? separateTabs : splitWithTab] + (canMoveToSpace ? [moveToSpace] : []), + (canPin ? [rename] : []) + [mute(isMuted)], + [closeTab, MenuItem(title: "Close Tabs Below", command: .closeTabsBelow)], + ]) + } + + /// A pinned tab's menu (pinned-tabs spec, "Pinned tab menu"), with Close + /// Tab while its page is open; a pinned split's chip's has Separate Tabs in + /// place of Split with Tab, and no Edit Pinned Page. static func pinnedMenu(isOpen: Bool, isMuted: Bool, canMoveToSpace: Bool, inSplit: Bool = false) -> [MenuItem?] { - var items: [MenuItem?] = [ - MenuItem(title: "Copy Link", command: .copyLink), - MenuItem(title: "Rename…", command: .rename), - MenuItem(title: isMuted ? "Unmute" : "Mute", command: isMuted ? .unmute : .mute, isEnabled: isOpen), - ] - if !inSplit { - items.append(MenuItem(title: "Edit Pinned Page", command: .editPinnedPage)) - } - items.append(MenuItem(title: "Duplicate", command: .duplicate)) - items += inSplit ? [nil, separateTabs] : [splitWithTab] - if canMoveToSpace { - items += [nil, MenuItem(title: "Move to Space", command: .moveToSpace)] - } - items += [ - nil, - MenuItem(title: "Pin to Favorites", command: .pinToFavorites), - MenuItem(title: "Unpin Tab", command: .unpin), - ] - return items - } - - /// A favorite's menu; Close Tab only while the window shows its page. A - /// favorited split's segment's has no Edit Pinned Page or Split with Tab, - /// and Separate Tabs. + joined([ + [MenuItem(title: "Unpin Tab", command: .unpin), pinToFavorites], + [copyLink, duplicate], + [inSplit ? separateTabs : splitWithTab] + (canMoveToSpace ? [moveToSpace] : []), + [rename, mute(isMuted, isEnabled: isOpen)] + (inSplit ? [] : [editPinnedPage]), + isOpen ? [closeTab] : [], + ]) + } + + /// A favorite's menu (favorites spec, "Favorite menu"), with Close Tab + /// only while the window shows its page. A favorited split's segment's has + /// Separate Tabs in place of Split with Tab, and no Edit Pinned Page. static func favoriteMenu(isShown: Bool, isOpen: Bool, isMuted: Bool, inSplit: Bool = false) -> [MenuItem?] { - var items: [MenuItem?] = [ - MenuItem(title: "Copy Link", command: .copyLink), - MenuItem(title: "Rename…", command: .rename), - MenuItem(title: isMuted ? "Unmute" : "Mute", command: isMuted ? .unmute : .mute, isEnabled: isOpen), - ] - if !inSplit { - items.append(MenuItem(title: "Edit Pinned Page", command: .editPinnedPage)) - } - items.append(MenuItem(title: "Duplicate", command: .duplicate)) - items += inSplit ? [nil, separateTabs] : [splitWithTab] - items.append(nil) - if isShown { - items.append(MenuItem(title: "Close Tab", command: .closeTab)) - } - items.append(MenuItem(title: "Remove Favorite", command: .removeFavorite)) - return items + joined([ + [MenuItem(title: "Remove Favorite", command: .removeFavorite)], + [copyLink, duplicate], + [inSplit ? separateTabs : splitWithTab], + [rename, mute(isMuted, isEnabled: isOpen)] + (inSplit ? [] : [editPinnedPage]), + isShown ? [closeTab] : [], + ]) } /// A folder's menu (tab-folders spec, "Folder menu"): Move to Space only @@ -608,10 +603,11 @@ enum PinsLogic { static let folderDeletionMessage = "Deleting this folder will remove the tabs inside it." static let folderDeletionButton = "Delete Folder" - /// Edit Pinned Page's items; Replace needs the page open away from its - /// pinned URL. + /// Edit Pinned Page's items; Back to Pinned URL and Replace need the page + /// open away from its pinned URL. static func editPinnedPageMenu(_ pin: any ClairPin) -> [MenuItem] { [ + MenuItem(title: "Back to Pinned URL", command: .backToPinnedURL, isEnabled: isNavigatedAway(pin)), MenuItem(title: "Replace Pinned URL with Current", command: .replacePinnedURL, isEnabled: isNavigatedAway(pin)), MenuItem(title: "Edit…", command: .editPinnedURL), ] @@ -626,15 +622,15 @@ enum PinsLogic { var activeIsToday = false /// The selected row is a pinned tab, or a favorite. var activePinIsFavorite: Bool? - var activePinIsNavigatedAway = false var todayRowCount = 0 var isCollapsed = false } enum MainMenuCommand: Int, CaseIterable { case togglePin = 1 - case backToPinnedURL - case closeKeepingPin + /// Tabs › Pin to Favorites (add-tab-switcher-and-tabs-menu D5). + case pinToFavorites + /// Tabs › Clear Unpinned Tabs. case clearToday case toggleCollapse /// Tabs › New Folder… (add-tab-folders D6). @@ -644,20 +640,20 @@ enum PinsLogic { static func title(of command: MainMenuCommand, in state: MenuState) -> String { switch command { case .togglePin: state.activePinIsFavorite == false ? "Unpin Tab" : "Pin Tab" - case .backToPinnedURL: "Back to Pinned URL" - case .closeKeepingPin: "Close and Keep Pinned" - case .clearToday: "Clear Today" + case .pinToFavorites: "Pin to Favorites" + case .clearToday: "Clear Unpinned Tabs" case .toggleCollapse: state.isCollapsed ? "Expand Pinned Tabs" : "Collapse Pinned Tabs" case .newFolder: newFolderDialogTitle } } + /// tabs-menu spec, "Pin items" and "Clear Unpinned Tabs": none in an + /// incognito or guest window; the pin items on a Today or pinned tab, not + /// a favorite. static func isEnabled(_ command: MainMenuCommand, in state: MenuState) -> Bool { guard state.showsPins else { return false } switch command { - case .togglePin: return state.activeIsToday || state.activePinIsFavorite == false - case .backToPinnedURL: return state.activePinIsFavorite != nil && state.activePinIsNavigatedAway - case .closeKeepingPin: return state.activePinIsFavorite != nil + case .togglePin, .pinToFavorites: return state.activeIsToday || state.activePinIsFavorite == false case .clearToday: return state.todayRowCount > 0 case .toggleCollapse: return true case .newFolder: return true diff --git a/native/ClairUI/PinsMenu.swift b/native/ClairUI/PinsMenu.swift index b265e38e..4d7e9024 100644 --- a/native/ClairUI/PinsMenu.swift +++ b/native/ClairUI/PinsMenu.swift @@ -5,16 +5,11 @@ import AppKit import ClairHost -/// Clair's items in Chromium's Tab menu and the View menu -/// (add-pinned-tabs-and-favorites design D11): Pin Tab (Cmd+D), New Folder… -/// (add-tab-folders D6), Back to Pinned URL, Close and Keep Pinned and Clear -/// Today (Shift+Cmd+K), and View › -/// Collapse Pinned Tabs. They act on the main window, which titles and -/// enables them. Chromium's own Pin Tab is hidden, and Cmd+D left its -/// bookmark item. +/// View › Collapse Pinned Tabs (add-pinned-tabs-and-favorites design D11), +/// which acts on the main window, which titles and enables it. The pin +/// items are the Tabs menu's (`TabsMenu`). final class PinsMenu: NSObject, NSMenuItemValidation { - /// Chromium's IDC_TAB_MENU and IDC_VIEW_MENU. - static let tabMenuTag = 57323 + /// Chromium's IDC_VIEW_MENU. static let viewMenuTag = 57327 /// Clair's tags, clear of Chromium's command IDs. static let baseTag = 0x436C_5000 @@ -28,47 +23,19 @@ final class PinsMenu: NSObject, NSMenuItemValidation { baseTag + command.rawValue } - /// Adds the items, once. + /// Adds the item, once. @discardableResult func install(in mainMenu: NSMenu?) -> Bool { - guard let mainMenu, items.isEmpty else { return false } - let tabMenu = mainMenu.items.first { $0.tag == Self.tabMenuTag }?.submenu - let viewMenu = mainMenu.items.first { $0.tag == Self.viewMenuTag }?.submenu - guard let tabMenu else { return false } - // Where Chromium's own Pin Tab (IDC_WINDOW_PIN_TAB) and its alternate - // (IDC_PIN_TARGET_TAB) were: Clair doesn't use Chromium's pinned tabs, so - // they're hidden, and have no key equivalent to fire. - let chromiumPinTags: Set = [35013, 35051] - for item in tabMenu.items where chromiumPinTags.contains(item.tag) { - item.isHidden = true - item.keyEquivalent = "" - } - let chromiumPin = tabMenu.items.lastIndex { chromiumPinTags.contains($0.tag) } - var index = chromiumPin.map { $0 + 1 } ?? tabMenu.numberOfItems - // add-tab-folders D6: New Folder… right after Pin Tab. - for command in [PinsLogic.MainMenuCommand.togglePin, .newFolder, .backToPinnedURL, .closeKeepingPin, .clearToday] { - tabMenu.insertItem(make(command), at: index) - index += 1 - } - if let viewMenu { - viewMenu.insertItem(make(.toggleCollapse), at: 0) - } + guard let mainMenu, items.isEmpty, + let viewMenu = mainMenu.items.first(where: { $0.tag == Self.viewMenuTag })?.submenu + else { return false } + viewMenu.insertItem(make(.toggleCollapse), at: 0) return true } private func make(_ command: PinsLogic.MainMenuCommand) -> NSMenuItem { let title = PinsLogic.title(of: command, in: PinsLogic.MenuState()) - let item: NSMenuItem - switch command { - case .togglePin: - item = NSMenuItem(title: title, action: #selector(choose(_:)), keyEquivalent: "d") - item.keyEquivalentModifierMask = [.command] - case .clearToday: - item = NSMenuItem(title: title, action: #selector(choose(_:)), keyEquivalent: "k") - item.keyEquivalentModifierMask = [.command, .shift] - default: - item = NSMenuItem(title: title, action: #selector(choose(_:)), keyEquivalent: "") - } + let item = NSMenuItem(title: title, action: #selector(choose(_:)), keyEquivalent: "") item.target = self item.tag = Self.tag(of: command) items[command] = item diff --git a/native/ClairUI/PinsViews.swift b/native/ClairUI/PinsViews.swift index a1b673bf..8569ba6e 100644 --- a/native/ClairUI/PinsViews.swift +++ b/native/ClairUI/PinsViews.swift @@ -592,10 +592,10 @@ enum PinMenus { PinsLogic.editPinnedPageMenu(pin).map { sub in guard sub.isEnabled else { return .disabled(sub.title) } return .action(sub.title) { [weak actions] in - if sub.command == .replacePinnedURL { - actions?.replacePinnedURL(pinID) - } else { - actions?.editPinnedURL(pinID) + switch sub.command { + case .backToPinnedURL: actions?.returnToPinnedURL(pinID) + case .replacePinnedURL: actions?.replacePinnedURL(pinID) + default: actions?.editPinnedURL(pinID) } } }) @@ -622,8 +622,8 @@ enum PinMenus { case .unpin: actions?.unpin(pinID) case .closeTab: actions?.closeKeepingPin(pinID) case .removeFavorite: actions?.removePin(pinID) - case .pin, .editPinnedPage, .replacePinnedURL, .editPinnedURL, .moveToSpace, .closeTabsBelow, .turnIntoSpace, - .deleteFolder, .splitWithTab, .separateTabs: + case .pin, .editPinnedPage, .backToPinnedURL, .replacePinnedURL, .editPinnedURL, .moveToSpace, .closeTabsBelow, + .turnIntoSpace, .deleteFolder, .splitWithTab, .separateTabs: break } } @@ -661,7 +661,7 @@ struct TodayDivider: View { } .buttonStyle(.plain) .onHover { isClearHovered = $0 } - .tooltip("Clear Today tabs", shortcut: ["⇧", "⌘", "K"]) + .tooltip("Clear unpinned tabs", shortcut: ["⇧", "⌘", "K"]) .accessibilityIdentifier("clair.clearToday") .transition(.opacity) } diff --git a/native/ClairUI/SidebarView.swift b/native/ClairUI/SidebarView.swift index 0d5fc4b7..50f3370e 100644 --- a/native/ClairUI/SidebarView.swift +++ b/native/ClairUI/SidebarView.swift @@ -1587,7 +1587,6 @@ extension TabRow { switch item.command { case .copyLink: return .action(item.title) { actions?.copyLink(of: tabID) } case .rename: - guard canPin else { return nil } return .action(item.title) { actions?.beginRenaming(RowRename(row: .tab(tabID), selectsAll: true, caret: nil)) } diff --git a/native/ClairUI/SplitMenu.swift b/native/ClairUI/SplitMenu.swift index ebb0b689..f4e6d9c6 100644 --- a/native/ClairUI/SplitMenu.swift +++ b/native/ClairUI/SplitMenu.swift @@ -5,31 +5,28 @@ import AppKit import ClairHost -/// Split view's items in the menu bar (add-split-view design D9): Tabs › -/// Split with Tab ›, and View › Add Split View (⌃⇧=), Close Split Pane (⌃⇧−) -/// and Separate Tabs. They act on the main window, which enables them. -final class SplitMenu: NSObject, NSMenuItemValidation, NSMenuDelegate { +/// Split view's items in the View menu (add-split-view design D9): Add Split +/// View (⌃⇧=), Close Split Pane (⌃⇧−) and Separate Tabs. They act on the main +/// window, which enables them. Split with Tab › is the Tabs menu's +/// (`TabsMenu`). +final class SplitMenu: NSObject, NSMenuItemValidation { enum Command: Int, CaseIterable { - case splitWithTab = 1 - case addSplitView + case addSplitView = 2 case closeSplitPane case separateTabs var title: String { switch self { - case .splitWithTab: SplitLogic.splitWithTabTitle case .addSplitView: "Add Split View" case .closeSplitPane: "Close Split Pane" case .separateTabs: "Separate Tabs" } } - /// Whether the item can be chosen: Split with Tab and Add Split View on - /// a single page (Add Split View then shows "Cannot Add New Pane"), the - /// others while split. + /// Whether the item can be chosen: Add Split View always (it shows + /// "Cannot Add New Pane" while split), the others while split. func isEnabled(isSplit: Bool) -> Bool { switch self { - case .splitWithTab: !isSplit case .addSplitView: true case .closeSplitPane, .separateTabs: isSplit } @@ -47,35 +44,22 @@ final class SplitMenu: NSObject, NSMenuItemValidation, NSMenuDelegate { /// Adds the items, once. @discardableResult func install(in mainMenu: NSMenu?) -> Bool { - guard let mainMenu, items.isEmpty else { return false } - let tabMenu = mainMenu.items.first { $0.tag == PinsMenu.tabMenuTag }?.submenu - let viewMenu = mainMenu.items.first { $0.tag == PinsMenu.viewMenuTag }?.submenu - guard let tabMenu else { return false } - // After Clair's pin items in Tabs. - let lastPinItem = tabMenu.items.lastIndex { $0.tag >= PinsMenu.baseTag && $0.tag < Self.baseTag } - tabMenu.insertItem(make(.splitWithTab), at: lastPinItem.map { $0 + 1 } ?? tabMenu.numberOfItems) - if let viewMenu { - // After Collapse Pinned Tabs, if it's there. - var index = viewMenu.items.firstIndex { $0.tag >= PinsMenu.baseTag && $0.tag < Self.baseTag }.map { $0 + 1 } ?? 0 - for command in [Command.addSplitView, .closeSplitPane, .separateTabs] { - viewMenu.insertItem(make(command), at: index) - index += 1 - } - viewMenu.insertItem(.separator(), at: index) + guard let mainMenu, items.isEmpty, + let viewMenu = mainMenu.items.first(where: { $0.tag == PinsMenu.viewMenuTag })?.submenu + else { return false } + // After Collapse Pinned Tabs, if it's there. + var index = viewMenu.items.firstIndex { $0.tag >= PinsMenu.baseTag && $0.tag < Self.baseTag }.map { $0 + 1 } ?? 0 + for command in Command.allCases { + viewMenu.insertItem(make(command), at: index) + index += 1 } + viewMenu.insertItem(.separator(), at: index) return true } private func make(_ command: Command) -> NSMenuItem { let item: NSMenuItem switch command { - case .splitWithTab: - // With an action, the menu asks validateMenuItem whether it's on; an - // item with a submenu and none is always on. - item = NSMenuItem(title: command.title, action: #selector(choose(_:)), keyEquivalent: "") - let submenu = NSMenu(title: command.title) - submenu.delegate = self - item.submenu = submenu case .addSplitView: item = NSMenuItem(title: command.title, action: #selector(choose(_:)), keyEquivalent: "=") item.keyEquivalentModifierMask = [.control, .shift] @@ -94,9 +78,6 @@ final class SplitMenu: NSObject, NSMenuItemValidation, NSMenuDelegate { private var isSplit: Bool { currentController()?.model.shownSplit != nil } func validateMenuItem(_ item: NSMenuItem) -> Bool { - if item.action == #selector(chooseTab(_:)) || item.action == #selector(chooseNewTab(_:)) { - return currentController() != nil && !isSplit - } guard let command = Command(rawValue: item.tag - Self.baseTag) else { return false } return currentController() != nil && command.isEnabled(isSplit: isSplit) } @@ -109,48 +90,6 @@ final class SplitMenu: NSObject, NSMenuItemValidation, NSMenuDelegate { case .addSplitView: controller.addSplitView() case .closeSplitPane: controller.closeSplitPane() case .separateTabs: controller.separateSplit(of: controller.focusedPaneTabID) - case .splitWithTab: break - } - } - - // MARK: Tabs › Split with Tab › - - /// Lists the main window's Today tabs as the split button's menu does, - /// with New Tab, for its shown tab. - func menuNeedsUpdate(_ menu: NSMenu) { - menu.removeAllItems() - guard let controller = currentController(), controller.model.shownSplit == nil else { return } - let shown = controller.shownRowTabID - let entries = SplitLogic.splitWithTabSubmenu(for: shown, today: controller.model.tabs) - let favicons = Dictionary( - controller.model.allTabs.map { ($0.tabID, $0.favicon) }, uniquingKeysWith: { first, _ in first }) - for entry in entries { - switch entry { - case .separator: - menu.addItem(.separator()) - case .tab(let other, let title): - let item = NSMenuItem(title: title, action: #selector(chooseTab(_:)), keyEquivalent: "") - item.target = self - item.tag = Int(truncatingIfNeeded: other) - item.setFavicon(favicons[other] ?? nil) - menu.addItem(item) - case .newTab: - let item = NSMenuItem(title: entry.title, action: #selector(chooseNewTab(_:)), keyEquivalent: "") - item.target = self - menu.addItem(item) - default: - break - } } } - - @objc func chooseTab(_ sender: NSMenuItem) { - guard let controller = currentController(), controller.model.shownSplit == nil else { return } - controller.split(tab: controller.shownRowTabID, with: TabID(sender.tag), side: .trailing) - } - - @objc func chooseNewTab(_ sender: NSMenuItem) { - guard let controller = currentController(), controller.model.shownSplit == nil else { return } - controller.splitWithNewTab(controller.shownRowTabID) - } } diff --git a/native/ClairUI/TabSwitcher.swift b/native/ClairUI/TabSwitcher.swift new file mode 100644 index 00000000..aa91e96d --- /dev/null +++ b/native/ClairUI/TabSwitcher.swift @@ -0,0 +1,391 @@ +// Copyright 2026 The Clair Authors +// You can use, redistribute, and/or modify this source code under +// the terms of the GPL-3.0 license that can be found in the LICENSE file. + +import AppKit +import ClairHost +import SwiftUI + +/// What the switcher needs from its window (add-tab-switcher-and-tabs-menu +/// D1, D2). +@MainActor +protocol TabSwitcherHost: AnyObject { + /// The browser window the switcher sits over. + var switcherWindow: NSWindow { get } + /// Whether the switcher may take keys now: the window is key, with no + /// Clair dialog or sheet up. + var switcherMayAct: Bool { get } + /// The window's recent tabs, most recent first. + var recentTabIDs: [TabID] { get } + /// The cards for `entries`. + func switcherCards(for entries: [TabID]) -> [SwitcherCard] + /// Asks for a preview of `tabID`'s page, `size` in points. + func requestSwitcherPreview(of tabID: TabID, size: NSSize, completion: @escaping (NSImage?) -> Void) + /// Shows the tab chosen, as selecting its row or tile does. + func showFromSwitcher(_ tabID: TabID) +} + +/// Ctrl+Tab's switcher for one window: a local key monitor, a mouse monitor +/// while the panel shows, and the panel (add-tab-switcher-and-tabs-menu D2, +/// D3). The rules are `SwitcherState`'s; this is the glue. +@MainActor +final class TabSwitcher { + private static let tabKey: UInt16 = 48 + private static let escapeKey: UInt16 = 53 + + weak var host: (any TabSwitcherHost)? + private(set) var state = SwitcherState() + let panelModel = TabSwitcherPanelModel() + private(set) lazy var panel = TabSwitcherPanel(model: panelModel) + + /// The clock and the wait for the panel's delay, injected by tests. + var now: () -> ContinuousClock.Instant = { .now } + var wait: (Duration) async -> Void = { duration in try? await Task.sleep(for: duration) } + + private var keyMonitor: Any? + private var mouseMonitor: Any? + private var delay: Task? + /// The keys whose key-down the switcher took, whose key-up it takes too. + private var takenKeys: Set = [] + + init(host: any TabSwitcherHost) { + self.host = host + } + + isolated deinit { + stop() + } + + /// Installs the key monitor. + func start() { + guard keyMonitor == nil else { return } + keyMonitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .keyUp, .flagsChanged]) { [weak self] event in + let taken = MainActor.assumeIsolated { self?.handle(event) ?? false } + return taken ? nil : event + } + } + + func stop() { + cancel() + if let keyMonitor { + NSEvent.removeMonitor(keyMonitor) + self.keyMonitor = nil + } + } + + // MARK: Keys + + /// Whether the switcher takes `event`, which then goes no further: not to + /// the page, a field or Chromium. Costs one flag test for any other key + /// while the switcher is closed. + @discardableResult + func handle(_ event: NSEvent) -> Bool { + switch event.type { + case .flagsChanged: + // Releasing Ctrl chooses the selected card. The page keeps hearing the + // modifiers, so it never thinks Ctrl is still down. + if state.isOpen, !event.modifierFlags.contains(.control) { + commit() + } + return false + case .keyUp: + return takenKeys.remove(event.keyCode) != nil + case .keyDown: + break + default: + return false + } + let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask) + if !state.isOpen { + guard event.keyCode == Self.tabKey, flags.contains(.control), + flags.isDisjoint(with: [.command, .option]), host?.switcherMayAct == true + else { return false } + takenKeys.insert(event.keyCode) + open(forward: !flags.contains(.shift)) + return true + } + takenKeys.insert(event.keyCode) + switch event.keyCode { + case Self.tabKey: + state.step(forward: !flags.contains(.shift)) + render() + case Self.escapeKey: + cancel() + default: + break + } + return true + } + + private func open(forward: Bool) { + guard let host, state.open(recents: host.recentTabIDs, forward: forward, at: now()) else { return } + let cards = host.switcherCards(for: state.entries) + guard cards.count == state.entries.count else { + // A recent tab the window can't draw: no switcher rather than a wrong + // one. + state.cancel() + return + } + panelModel.cards = cards + panelModel.previews = [:] + requestPreviews(for: cards) + render() + let wait = self.wait + delay = Task { [weak self] in + await wait(SwitcherState.panelDelay) + guard !Task.isCancelled, let self else { return } + self.state.update(at: self.now()) + self.render() + } + } + + private func requestPreviews(for cards: [SwitcherCard]) { + for card in cards { + let width = SwitcherLayout.previewSize.width / CGFloat(card.paneIDs.count) + let size = NSSize(width: width, height: SwitcherLayout.previewSize.height) + for paneID in card.paneIDs { + host?.requestSwitcherPreview(of: paneID, size: size) { [weak self] image in + guard let self, self.state.isOpen, let image else { return } + // A preview arriving late replaces the placeholder in place. + self.panelModel.previews[paneID] = image + } + } + } + } + + // MARK: Choosing and cancelling + + /// Releasing Ctrl: shows the selected tab, unless it's the shown one. + func commit() { + finish(state.commit()) + } + + /// A click on card `index` while the panel shows. + func choose(card index: Int) { + guard state.isPanelShown else { return } + finish(state.commit(card: index)) + } + + /// Esc, the window resigning key, or the shown tab closing. + func cancel() { + guard state.isOpen else { return } + state.cancel() + finish(nil) + } + + /// The shown tab, the first card, is gone: the switcher closes. + func tabsDidChange(open: Set) { + if let shown = state.entries.first, !open.contains(shown) { + cancel() + } + } + + private func finish(_ chosen: TabID?) { + delay?.cancel() + delay = nil + render() + if let chosen { + host?.showFromSwitcher(chosen) + } + } + + // MARK: The panel + + /// Shows, updates or hides the panel as the state says, with no animation. + private func render() { + panelModel.selection = state.selection + guard state.isPanelShown, let window = host?.switcherWindow else { + hidePanel() + return + } + let visible = (window.screen ?? NSScreen.main)?.visibleFrame ?? window.frame + panel.setFrame( + SwitcherLayout.panelFrame(cards: panelModel.cards.count, window: window.frame, visible: visible), display: false) + if panel.parent == nil { + window.addChildWindow(panel, ordered: .above) + } + panel.orderFront(nil) + startMouseMonitor() + } + + private func hidePanel() { + stopMouseMonitor() + guard panel.parent != nil || panel.isVisible else { return } + panel.parent?.removeChildWindow(panel) + panel.orderOut(nil) + } + + /// A click on a card, Ctrl held, chooses it before AppKit can take the + /// Control-click for a secondary click (D2). No other mouse event. + private func startMouseMonitor() { + guard mouseMonitor == nil else { return } + mouseMonitor = NSEvent.addLocalMonitorForEvents(matching: .leftMouseDown) { [weak self] event in + let taken = MainActor.assumeIsolated { + guard let self, event.window === self.panel else { return false } + return self.click(at: event.locationInWindow) + } + return taken ? nil : event + } + } + + private func stopMouseMonitor() { + if let mouseMonitor { + NSEvent.removeMonitor(mouseMonitor) + self.mouseMonitor = nil + } + } + + /// A click at `point` in the panel, from its bottom left: chooses the card + /// under it. Returns whether one was. + @discardableResult + func click(at point: CGPoint) -> Bool { + let height = panel.frame.height + let fromTop = CGPoint(x: point.x, y: height - point.y) + guard state.isPanelShown, let index = SwitcherLayout.card(at: fromTop, cards: panelModel.cards.count) else { + return false + } + choose(card: index) + return true + } +} + +/// What the panel draws. +@MainActor +@Observable +final class TabSwitcherPanelModel { + var cards: [SwitcherCard] = [] + var selection = 0 + /// Each page's preview, by its tab, as it arrives. + var previews: [TabID: NSImage] = [:] +} + +/// The switcher's panel: borderless and non-activating, a child of the +/// browser window, hosting the cards (D3). It never becomes key, so the +/// window keeps its keys. +final class TabSwitcherPanel: NSPanel { + init(model: TabSwitcherPanelModel) { + super.init( + contentRect: CGRect(origin: .zero, size: SwitcherLayout.panelSize(cards: 2)), + styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: true) + isReleasedWhenClosed = false + isOpaque = false + backgroundColor = .clear + hasShadow = true + animationBehavior = .none + hidesOnDeactivate = false + collectionBehavior = [.transient, .ignoresCycle, .fullScreenAuxiliary] + contentView = NSHostingView(rootView: TabSwitcherView(model: model)) + } + + override var canBecomeKey: Bool { false } + override var canBecomeMain: Bool { false } +} + +/// The cards in one row, left to right, the selected one highlighted in the +/// accent colour, as in Arc (`tab-switcher` "Switcher panel", "Cards"). +struct TabSwitcherView: View { + let model: TabSwitcherPanelModel + + var body: some View { + HStack(spacing: 0) { + ForEach(Array(model.cards.enumerated()), id: \.element.id) { index, card in + TabSwitcherCardView( + card: card, previews: card.paneIDs.map { model.previews[$0] }, isSelected: index == model.selection) + } + } + .padding(.horizontal, SwitcherLayout.padding - SwitcherLayout.highlightInset) + .padding(.top, SwitcherLayout.padding - SwitcherLayout.highlightInset) + .frame( + width: SwitcherLayout.panelSize(cards: model.cards.count).width, height: SwitcherLayout.height, + alignment: .topLeading + ) + .background { + RoundedRectangle(cornerRadius: SwitcherLayout.cornerRadius, style: .continuous) + .fill(Color(nsColor: .windowBackgroundColor)) + .overlay { + RoundedRectangle(cornerRadius: SwitcherLayout.cornerRadius, style: .continuous) + .strokeBorder(Color.primary.opacity(0.12), lineWidth: 0.5) + } + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("clair.tabSwitcher") + } +} + +struct TabSwitcherCardView: View { + let card: SwitcherCard + let previews: [NSImage?] + let isSelected: Bool + + private var labelHeight: CGFloat { + SwitcherLayout.highlightHeight - SwitcherLayout.previewSize.height - 2 * SwitcherLayout.highlightInset + } + + var body: some View { + VStack(spacing: 0) { + preview + .frame(width: SwitcherLayout.previewSize.width, height: SwitcherLayout.previewSize.height) + .clipShape(RoundedRectangle(cornerRadius: SwitcherLayout.previewRadius, style: .continuous)) + .overlay { + RoundedRectangle(cornerRadius: SwitcherLayout.previewRadius, style: .continuous) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.5) + } + label.frame(width: SwitcherLayout.previewSize.width, height: labelHeight) + } + .padding(SwitcherLayout.highlightInset) + .frame(width: SwitcherLayout.pitch, height: SwitcherLayout.highlightHeight) + .background { + if isSelected { + RoundedRectangle(cornerRadius: SwitcherLayout.highlightRadius, style: .continuous) + .fill(Color.accentColor.opacity(0.18)) + } + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(card.label) + .accessibilityAddTraits(isSelected ? [.isButton, .isSelected] : .isButton) + .accessibilityIdentifier("clair.tabSwitcherCard") + } + + /// The page from its top, fitted to the card's width; a split's two side + /// by side in pane order; a blank card with the favicon while there's no + /// preview. + private var preview: some View { + HStack(spacing: 1) { + ForEach(previews.indices, id: \.self) { index in + page(previews[index], favicon: card.favicons.indices.contains(index) ? card.favicons[index] : nil) + } + } + .background(Color(nsColor: .textBackgroundColor)) + } + + @ViewBuilder + private func page(_ image: NSImage?, favicon: NSImage?) -> some View { + if let image { + Image(nsImage: image) + .resizable() + .interpolation(.high) + .aspectRatio(contentMode: .fill) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + .clipped() + } else { + Color(nsColor: .textBackgroundColor) + .overlay { PinIcon(icon: favicon, size: 24) } + } + } + + private var label: some View { + HStack(spacing: 6) { + ForEach(card.favicons.indices, id: \.self) { index in + PinIcon(icon: card.favicons[index], size: SwitcherLayout.faviconSize) + } + if !card.title.isEmpty { + Text(card.title) + .font(.system(size: 14, weight: isSelected ? .semibold : .medium)) + .foregroundStyle(isSelected ? .primary : .secondary) + .lineLimit(1) + .truncationMode(.tail) + } + } + .frame(maxWidth: .infinity) + } +} diff --git a/native/ClairUI/TabSwitcherLogic.swift b/native/ClairUI/TabSwitcherLogic.swift new file mode 100644 index 00000000..106a0dba --- /dev/null +++ b/native/ClairUI/TabSwitcherLogic.swift @@ -0,0 +1,212 @@ +// Copyright 2026 The Clair Authors +// You can use, redistribute, and/or modify this source code under +// the terms of the GPL-3.0 license that can be found in the LICENSE file. + +import AppKit +import ClairHost + +/// A window's tabs in the order it last showed them, most recent first, for +/// Ctrl+Tab's switcher (add-tab-switcher-and-tabs-menu design D1). An entry +/// is a row's tab: a tab and its Peek are one, as the two tabs of a split +/// are, through its leading pane. It holds only open tabs, so it needs no cap. +struct RecentTabs: Equatable { + private(set) var ids: [TabID] = [] + + init(_ ids: [TabID] = []) { + self.ids = ids + } + + /// The row `tabID` shows in, among `tabs`: its parent for a Peek, the + /// leading pane for a split's; nil when `tabs` doesn't list it, as for + /// the still's placeholder, which is in no Space. + static func row(of tabID: TabID, in tabs: [TabID: any ClairTab]) -> TabID? { + guard var tab = tabs[tabID] else { return nil } + if tab.peekParentID != ClairTabIDNone { + guard let parent = tabs[tab.peekParentID] else { return nil } + tab = parent + } + if tab.splitPartnerID != ClairTabIDNone, !tab.isLeadingPane, tabs[tab.splitPartnerID] != nil { + return tab.splitPartnerID + } + return tab.tabID + } + + /// The window showed `tabID`: its row moves to the front. Returns false, + /// changing nothing, when `tabs` doesn't list it yet. + @discardableResult + mutating func show(_ tabID: TabID, in tabs: [TabID: any ClairTab]) -> Bool { + guard let row = Self.row(of: tabID, in: tabs) else { return false } + ids.removeAll { $0 == row } + ids.insert(row, at: 0) + return true + } + + /// Keeps the entries whose tab is still open, each as the row it is now, + /// once: a closed page, a closed tab and a tab of a removed Space leave; a + /// tab that joined a split counts as the split. + mutating func prune(in tabs: [TabID: any ClairTab]) { + var seen: Set = [] + ids = ids.compactMap { id in + guard let row = Self.row(of: id, in: tabs), seen.insert(row).inserted else { return nil } + return row + } + } +} + +/// Ctrl+Tab's switcher while Ctrl is held (add-tab-switcher-and-tabs-menu +/// D2, D3): its cards, the selected one, and whether the panel shows yet. +struct SwitcherState: Equatable { + /// The cards the panel holds at most. + static let maxCards = 5 + /// How long Ctrl is held before the panel shows, as in Arc, whose delay + /// measured between 90 and 130 ms. + static let panelDelay: Duration = .milliseconds(100) + + /// The recent tabs the cards stand for, the shown tab first; empty while + /// the switcher is closed. + private(set) var entries: [TabID] = [] + private(set) var selection = 0 + private(set) var isPanelShown = false + private var openedAt: ContinuousClock.Instant? + + var isOpen: Bool { !entries.isEmpty } + var selectedTab: TabID? { entries.indices.contains(selection) ? entries[selection] : nil } + + /// Ctrl+Tab (`forward`) or Ctrl+Shift+Tab: opens on the window's first + /// recent tabs with the second card or the last selected. With fewer than + /// two, it stays closed and returns false. + @discardableResult + mutating func open(recents: [TabID], forward: Bool, at now: ContinuousClock.Instant) -> Bool { + guard recents.count >= 2 else { return false } + entries = Array(recents.prefix(Self.maxCards)) + selection = forward ? 1 : entries.count - 1 + isPanelShown = false + openedAt = now + return true + } + + /// When the panel is due, while the switcher is open and it isn't shown. + var panelDeadline: ContinuousClock.Instant? { + guard isOpen, !isPanelShown, let openedAt else { return nil } + return openedAt.advanced(by: Self.panelDelay) + } + + /// Shows the panel once its delay is over. + mutating func update(at now: ContinuousClock.Instant) { + if let deadline = panelDeadline, now >= deadline { + isPanelShown = true + } + } + + /// Tab or Shift+Tab, Ctrl still held: the next card or the previous one, + /// wrapping; the panel shows at once if it hadn't. + mutating func step(forward: Bool) { + guard isOpen else { return } + selection = (selection + (forward ? 1 : -1) + entries.count) % entries.count + isPanelShown = true + } + + /// Ends the switcher on the selected card, or on `card` when the pointer + /// chose it, and returns its tab; nil for the first card, the shown tab, + /// which leaves the window as it is. + mutating func commit(card: Int? = nil) -> TabID? { + guard isOpen else { return nil } + if let card, entries.indices.contains(card) { + selection = card + } + let chosen = selection == 0 ? nil : selectedTab + cancel() + return chosen + } + + /// Esc, another app, or the shown tab closing: closes without switching. + mutating func cancel() { + entries = [] + selection = 0 + isPanelShown = false + openedAt = nil + } +} + +/// The switcher panel's layout, from Arc's measurements +/// (add-tab-switcher-and-tabs-menu D3, `arc-reference/`), in points, from the +/// panel's top left. +enum SwitcherLayout { + /// A card's preview of its page, 3:2. + static let previewSize = CGSize(width: 157.5, height: 105) + /// From the panel's edge to a preview. + static let padding: CGFloat = 27 + /// Between two previews. + static let gap: CGFloat = 24 + /// The selection's highlight around a preview and its label. + static let highlightInset: CGFloat = 12 + static let highlightHeight: CGFloat = 157.5 + static let highlightRadius: CGFloat = 12 + static let height: CGFloat = 189 + static let cornerRadius: CGFloat = 22 + static let previewRadius: CGFloat = 5 + static let faviconSize: CGFloat = 16 + + /// From one card to the next. + static var pitch: CGFloat { previewSize.width + gap } + + static func panelSize(cards: Int) -> CGSize { + let count = CGFloat(max(cards, 1)) + return CGSize(width: 2 * padding + count * previewSize.width + (count - 1) * gap, height: height) + } + + /// The highlight of card `index`, which a click lands on. + static func cardFrame(_ index: Int) -> CGRect { + CGRect( + x: padding - highlightInset + CGFloat(index) * pitch, y: padding - highlightInset, + width: pitch, height: highlightHeight) + } + + /// The card under `point`, from the panel's top left, or nil. + static func card(at point: CGPoint, cards: Int) -> Int? { + (0.. CGRect { + let size = panelSize(cards: cards) + var frame = CGRect( + x: window.midX - size.width / 2, y: window.midY - size.height / 2, width: size.width, height: size.height) + frame.origin.x = max(min(frame.origin.x, visible.maxX - size.width), visible.minX) + frame.origin.y = min(max(frame.origin.y, visible.minY), visible.maxY - size.height) + return frame + } +} + +/// One card of the switcher: a tab, or a split's two in pane order. +struct SwitcherCard: Identifiable { + /// The row's tab, which choosing the card shows. + let id: TabID + /// The pages it shows, one, or a split's two in pane order. + let paneIDs: [TabID] + /// The title or custom name; empty for a split, whose card shows both + /// favicons with no title. + let title: String + let favicons: [NSImage?] + /// What VoiceOver and the runtime suite read: the title, or a split's + /// two. + let label: String + + /// The card of row `rowID`, from the tabs the window can show. + static func make(_ rowID: TabID, in tabs: [TabID: any ClairTab]) -> SwitcherCard? { + guard let tab = tabs[rowID] else { return nil } + let name = { (tab: any ClairTab) -> String in + if let name = tab.name, !name.isEmpty { return name } + return tab.title + } + if tab.splitPartnerID != ClairTabIDNone, let partner = tabs[tab.splitPartnerID] { + let panes = tab.isLeadingPane ? [tab, partner] : [partner, tab] + return SwitcherCard( + id: rowID, paneIDs: panes.map(\.tabID), title: "", favicons: panes.map(\.favicon), + label: panes.map(name).joined(separator: ", ")) + } + return SwitcherCard(id: rowID, paneIDs: [rowID], title: name(tab), favicons: [tab.favicon], label: name(tab)) + } +} diff --git a/native/ClairUI/TabsMenu.swift b/native/ClairUI/TabsMenu.swift new file mode 100644 index 00000000..a292f6ab --- /dev/null +++ b/native/ClairUI/TabsMenu.swift @@ -0,0 +1,238 @@ +// Copyright 2026 The Clair Authors +// You can use, redistribute, and/or modify this source code under +// the terms of the GPL-3.0 license that can be found in the LICENSE file. + +import AppKit +import ClairHost + +/// The menu bar's Tabs menu, in place of Chromium's Tab menu, which the +/// engine deletes (add-tab-switcher-and-tabs-menu design D5): Pin Tab (⌘D), +/// Pin to Favorites and New Folder…; Next Tab (⌥⌘↓) and Previous Tab (⌥⌘↑); +/// Split with Tab › and Move to Space ›; Clear Unpinned Tabs (⇧⌘K). The items +/// act on the main window and its shown tab, which enables them. +final class TabsMenu: NSObject, NSMenuItemValidation, NSMenuDelegate { + static let title = "Tabs" + /// Chromium's IDC_WINDOW_MENU, which the Tabs menu goes before. + static let windowMenuTag = 57321 + /// Chromium's IDC_SELECT_NEXT_TAB and IDC_SELECT_PREVIOUS_TAB, which its + /// own shortcut table runs first (space-shortcuts.patch): the items only + /// show them, and Chromium validates them. + static let nextTabTag = 34016 + static let previousTabTag = 34017 + /// Clair's tags, clear of Chromium's command IDs and the other menus'. + static let baseTag = 0x436C_5200 + + enum Command: Int, CaseIterable { + case pinTab = 1 + case pinToFavorites + case newFolder + case splitWithTab + case moveToSpace + case clearUnpinnedTabs + + /// The pin command it runs, for the pin items. + var pinCommand: PinsLogic.MainMenuCommand? { + switch self { + case .pinTab: .togglePin + case .pinToFavorites: .pinToFavorites + case .newFolder: .newFolder + case .clearUnpinnedTabs: .clearToday + case .splitWithTab, .moveToSpace: nil + } + } + } + + let menu = NSMenu(title: TabsMenu.title) + /// The window the items act on. + var currentController: () -> BrowserWindowController? = { BrowserWindowController.main } + + private(set) var items: [Command: NSMenuItem] = [:] + private(set) var nextTab: NSMenuItem? + private(set) var previousTab: NSMenuItem? + + override init() { + super.init() + build() + } + + /// Adds the menu just before the Window menu, once. + @discardableResult + func install(in mainMenu: NSMenu?) -> Bool { + guard let mainMenu, !mainMenu.items.contains(where: { $0.submenu === menu }) else { return false } + let item = NSMenuItem(title: Self.title, action: nil, keyEquivalent: "") + item.submenu = menu + let window = + mainMenu.items.firstIndex { $0.tag == Self.windowMenuTag } + ?? mainMenu.items.firstIndex { $0.submenu != nil && $0.submenu === NSApp?.windowsMenu } + mainMenu.insertItem(item, at: window ?? mainMenu.numberOfItems) + return true + } + + private func build() { + add(.pinTab, key: "d", modifiers: [.command]) + add(.pinToFavorites) + add(.newFolder) + menu.addItem(.separator()) + nextTab = addChromium("Next Tab", tag: Self.nextTabTag, arrow: NSDownArrowFunctionKey) + previousTab = addChromium("Previous Tab", tag: Self.previousTabTag, arrow: NSUpArrowFunctionKey) + menu.addItem(.separator()) + // With an action, the menu asks validateMenuItem whether a submenu's item + // is on; one with a submenu and none is always on. + for command in [Command.splitWithTab, .moveToSpace] { + let item = add(command) + let submenu = NSMenu(title: item.title) + submenu.delegate = self + item.submenu = submenu + } + menu.addItem(.separator()) + add(.clearUnpinnedTabs, key: "k", modifiers: [.command, .shift]) + } + + static func title(of command: Command, in state: PinsLogic.MenuState) -> String { + switch command { + case .splitWithTab: SplitLogic.splitWithTabTitle + case .moveToSpace: "Move to Space" + default: command.pinCommand.map { PinsLogic.title(of: $0, in: state) } ?? "" + } + } + + @discardableResult + private func add(_ command: Command, key: String = "", modifiers: NSEvent.ModifierFlags = []) -> NSMenuItem { + let item = NSMenuItem( + title: Self.title(of: command, in: PinsLogic.MenuState()), action: #selector(choose(_:)), keyEquivalent: key) + item.keyEquivalentModifierMask = modifiers + item.target = self + item.tag = Self.baseTag + command.rawValue + items[command] = item + menu.addItem(item) + return item + } + + /// One of Chromium's commands, sent down the responder chain to the key + /// window as Chromium's own menu items are. + private func addChromium(_ title: String, tag: Int, arrow: Int) -> NSMenuItem { + let item = NSMenuItem( + title: title, action: NSSelectorFromString("commandDispatch:"), + keyEquivalent: String(Character(UnicodeScalar(UInt16(arrow))!))) + item.keyEquivalentModifierMask = [.command, .option] + item.tag = tag + menu.addItem(item) + return item + } + + // MARK: Enabling + + /// The Spaces the shown tab can move to: every other Space, in the + /// switcher's order; none on a favorite or in an incognito or guest + /// window. + private func moveTargets(of controller: BrowserWindowController) -> [any ClairSpace] { + let model = controller.model + guard model.showsSpaces, model.pin(ofTab: model.commandTab)?.isFavorite != true, + model.highlightedTab != ClairTabIDNone + else { return [] } + return SpacesLogic.moveTargets(from: model.shownSpaceID, in: model.spaces.spaces) + } + + /// Whether `command` can be chosen in `controller`'s window. + func isEnabled(_ command: Command, in controller: BrowserWindowController) -> Bool { + if let pinCommand = command.pinCommand { + return PinsLogic.isEnabled(pinCommand, in: controller.pinMenuState) + } + switch command { + case .splitWithTab: + return controller.model.shownSplit == nil && controller.shownRowTabID != ClairTabIDNone + case .moveToSpace: + return !moveTargets(of: controller).isEmpty + default: + return false + } + } + + func validateMenuItem(_ item: NSMenuItem) -> Bool { + let controller = currentController() + if item.action == #selector(chooseTab(_:)) || item.action == #selector(chooseNewTab(_:)) { + return controller.map { isEnabled(.splitWithTab, in: $0) } ?? false + } + if item.action == #selector(chooseSpace(_:)) { + return controller.map { isEnabled(.moveToSpace, in: $0) } ?? false + } + guard let command = Command(rawValue: item.tag - Self.baseTag) else { return false } + item.title = Self.title(of: command, in: controller?.pinMenuState ?? PinsLogic.MenuState(showsPins: false)) + return controller.map { isEnabled(command, in: $0) } ?? false + } + + @objc func choose(_ sender: NSMenuItem) { + guard let command = Command(rawValue: sender.tag - Self.baseTag), let controller = currentController(), + isEnabled(command, in: controller), let pinCommand = command.pinCommand + else { return } + controller.perform(pinCommand) + } + + // MARK: The submenus + + func menuNeedsUpdate(_ submenu: NSMenu) { + submenu.removeAllItems() + guard let controller = currentController() else { return } + if submenu === items[.splitWithTab]?.submenu { + fillSplitWithTab(submenu, controller: controller) + } else if submenu === items[.moveToSpace]?.submenu { + for space in moveTargets(of: controller) { + let item = NSMenuItem(title: SpacesLogic.label(of: space), action: #selector(chooseSpace(_:)), keyEquivalent: "") + item.target = self + item.representedObject = space.spaceID + submenu.addItem(item) + } + } + } + + /// Split with Tab ›: the main window's Today tabs as the split button's + /// menu lists them, with New Tab, for its shown tab (add-split-view D9). + private func fillSplitWithTab(_ submenu: NSMenu, controller: BrowserWindowController) { + guard controller.model.shownSplit == nil else { return } + let entries = SplitLogic.splitWithTabSubmenu(for: controller.shownRowTabID, today: controller.model.tabs) + let favicons = Dictionary( + controller.model.allTabs.map { ($0.tabID, $0.favicon) }, uniquingKeysWith: { first, _ in first }) + for entry in entries { + switch entry { + case .separator: + submenu.addItem(.separator()) + case .tab(let other, let title): + let item = NSMenuItem(title: title, action: #selector(chooseTab(_:)), keyEquivalent: "") + item.target = self + item.tag = Int(truncatingIfNeeded: other) + item.setFavicon(favicons[other] ?? nil) + submenu.addItem(item) + case .newTab: + let item = NSMenuItem(title: entry.title, action: #selector(chooseNewTab(_:)), keyEquivalent: "") + item.target = self + submenu.addItem(item) + default: + break + } + } + } + + @objc func chooseTab(_ sender: NSMenuItem) { + guard let controller = currentController(), isEnabled(.splitWithTab, in: controller) else { return } + controller.split(tab: controller.shownRowTabID, with: TabID(sender.tag), side: .trailing) + } + + @objc func chooseNewTab(_ sender: NSMenuItem) { + guard let controller = currentController(), isEnabled(.splitWithTab, in: controller) else { return } + controller.splitWithNewTab(controller.shownRowTabID) + } + + /// Moves the shown tab, or the shown pinned tab, as its Move to Space does + /// (`spaces`). + @objc func chooseSpace(_ sender: NSMenuItem) { + guard let spaceID = sender.representedObject as? SpaceID, let controller = currentController(), + isEnabled(.moveToSpace, in: controller) + else { return } + let model = controller.model + if let pin = model.pin(ofTab: model.commandTab) { + controller.movePin(pin.pinID, toSpace: spaceID) + } else { + controller.moveTab(model.highlightedTab, toSpace: spaceID) + } + } +} diff --git a/native/ClairUITests/FoldersTests.swift b/native/ClairUITests/FoldersTests.swift index 2c13d508..a1eb4c47 100644 --- a/native/ClairUITests/FoldersTests.swift +++ b/native/ClairUITests/FoldersTests.swift @@ -184,16 +184,9 @@ struct FolderMenuTests { #expect(PinsLogic.folderNameChange(draft: "Untitled", current: "Untitled") == .unchanged) } - @Test func newFolderIsTheTabMenusItemAfterPinTab() { - let main = NSMenu() - let tabs = NSMenuItem(title: "Tab", action: nil, keyEquivalent: "") - tabs.tag = PinsMenu.tabMenuTag - tabs.submenu = NSMenu(title: "Tab") - main.addItem(tabs) - let menu = PinsMenu() - menu.install(in: main) - let titles = tabs.submenu?.items.map(\.title) ?? [] - #expect(Array(titles.prefix(2)) == ["Pin Tab", "New Folder…"]) + @Test func newFolderIsTheTabsMenusItemAfterThePinItems() { + let titles = TabsMenu().menu.items.map(\.title) + #expect(Array(titles.prefix(3)) == ["Pin Tab", "Pin to Favorites", "New Folder…"]) #expect(PinsLogic.title(of: .newFolder, in: PinsLogic.MenuState()) == "New Folder…") // Disabled in incognito and guest windows. #expect(!PinsLogic.isEnabled(.newFolder, in: PinsLogic.MenuState(showsPins: false))) diff --git a/native/ClairUITests/PinsTests.swift b/native/ClairUITests/PinsTests.swift index af8703b4..95427917 100644 --- a/native/ClairUITests/PinsTests.swift +++ b/native/ClairUITests/PinsTests.swift @@ -222,75 +222,114 @@ struct PinsLogicTests { #expect(SidebarDragItem(payload: SidebarDragItem.pin("p").payload) == .pin("p")) } - @Test func theMenusListTheirItemsInOrder() { - let today = PinsLogic.todayMenu(isMuted: false, canMoveToSpace: false, canPin: true).compactMap { $0?.title } + /// A menu's titles, "|" for each divider. + private func titles(_ menu: [PinsLogic.MenuItem?]) -> [String] { + menu.map { $0?.title ?? "|" } + } + + /// sidebar, "Today tab menu"; pinned-tabs, "Pinned tab menu"; favorites, + /// "Favorite menu" (add-tab-switcher-and-tabs-menu D6). + @Test func theMenusListTheirGroupsInOrder() { + #expect( + titles(PinsLogic.todayMenu(isMuted: false, canMoveToSpace: false, canPin: true)) == [ + "Pin Tab", "Pin to Favorites", "|", "Copy Link", "Duplicate", "|", "Split with Tab", "|", "Rename…", "Mute", + "|", "Close Tab", "Close Tabs Below", + ]) + // With another Space, Move to Space follows Split with Tab. #expect( - today == [ - "Copy Link", "Rename…", "Duplicate", "Mute", "Split with Tab", "Pin Tab", "Pin to Favorites", "Close Tab", - "Close Tabs Below", + titles(PinsLogic.todayMenu(isMuted: false, canMoveToSpace: true, canPin: true)) == [ + "Pin Tab", "Pin to Favorites", "|", "Copy Link", "Duplicate", "|", "Split with Tab", "Move to Space", "|", + "Rename…", "Mute", "|", "Close Tab", "Close Tabs Below", ]) - let pinned = PinsLogic.pinnedMenu(isOpen: true, isMuted: false, canMoveToSpace: true).compactMap { $0?.title } #expect( - pinned == [ - "Copy Link", "Rename…", "Mute", "Edit Pinned Page", "Duplicate", "Split with Tab", "Move to Space", - "Pin to Favorites", "Unpin Tab", + titles(PinsLogic.pinnedMenu(isOpen: true, isMuted: false, canMoveToSpace: false)) == [ + "Unpin Tab", "Pin to Favorites", "|", "Copy Link", "Duplicate", "|", "Split with Tab", "|", "Rename…", "Mute", + "Edit Pinned Page", "|", "Close Tab", ]) - let favorite = PinsLogic.favoriteMenu(isShown: true, isOpen: true, isMuted: false).compactMap { $0?.title } #expect( - favorite == [ - "Copy Link", "Rename…", "Mute", "Edit Pinned Page", "Duplicate", "Split with Tab", "Close Tab", - "Remove Favorite", + titles(PinsLogic.pinnedMenu(isOpen: true, isMuted: false, canMoveToSpace: true)) == [ + "Unpin Tab", "Pin to Favorites", "|", "Copy Link", "Duplicate", "|", "Split with Tab", "Move to Space", "|", + "Rename…", "Mute", "Edit Pinned Page", "|", "Close Tab", ]) - #expect(!PinsLogic.favoriteMenu(isShown: false, isOpen: false, isMuted: false).contains { $0?.title == "Close Tab" }) + #expect( + titles(PinsLogic.favoriteMenu(isShown: true, isOpen: true, isMuted: false)) == [ + "Remove Favorite", "|", "Copy Link", "Duplicate", "|", "Split with Tab", "|", "Rename…", "Mute", + "Edit Pinned Page", "|", "Close Tab", + ]) + // A favorite that isn't shown ends with Edit Pinned Page. + #expect(titles(PinsLogic.favoriteMenu(isShown: false, isOpen: true, isMuted: false)).last == "Edit Pinned Page") + } + + /// pinned-tabs, "A closed pinned tab": no Close Tab, no divider before + /// where it would be, and Mute disabled. + @Test func aClosedPinnedTabsMenuEndsWithEditPinnedPage() { + let menu = PinsLogic.pinnedMenu(isOpen: false, isMuted: false, canMoveToSpace: false) + #expect(titles(menu).suffix(4) == ["|", "Rename…", "Mute", "Edit Pinned Page"]) + #expect(menu.compactMap { $0 }.first { $0.command == .mute }?.isEnabled == false) } - /// add-split-view, "The split row's menu": a chip's menu has no Split - /// with Tab or Edit Pinned Page, and Separate Tabs. + /// add-split-view, "The split row's menu": a chip's menu has Separate Tabs + /// where Split with Tab would be, and no Edit Pinned Page. @Test func aSplitChipsMenusSeparateTheSplit() { - let today = PinsLogic.todayMenu(isMuted: false, canMoveToSpace: false, canPin: true, inSplit: true) - .compactMap { $0?.title } #expect( - today == [ - "Copy Link", "Rename…", "Duplicate", "Mute", "Separate Tabs", "Pin Tab", "Pin to Favorites", "Close Tab", - "Close Tabs Below", + titles(PinsLogic.todayMenu(isMuted: false, canMoveToSpace: false, canPin: true, inSplit: true)) == [ + "Pin Tab", "Pin to Favorites", "|", "Copy Link", "Duplicate", "|", "Separate Tabs", "|", "Rename…", "Mute", + "|", "Close Tab", "Close Tabs Below", + ]) + #expect( + titles(PinsLogic.pinnedMenu(isOpen: false, isMuted: false, canMoveToSpace: false, inSplit: true)) == [ + "Unpin Tab", "Pin to Favorites", "|", "Copy Link", "Duplicate", "|", "Separate Tabs", "|", "Rename…", "Mute", + ]) + #expect( + titles(PinsLogic.favoriteMenu(isShown: false, isOpen: false, isMuted: false, inSplit: true)) == [ + "Remove Favorite", "|", "Copy Link", "Duplicate", "|", "Separate Tabs", "|", "Rename…", "Mute", ]) - let pinned = PinsLogic.pinnedMenu(isOpen: false, isMuted: false, canMoveToSpace: false, inSplit: true) - .compactMap { $0?.title } - #expect(pinned == ["Copy Link", "Rename…", "Mute", "Duplicate", "Separate Tabs", "Pin to Favorites", "Unpin Tab"]) - let favorite = PinsLogic.favoriteMenu(isShown: false, isOpen: false, isMuted: false, inSplit: true) - .compactMap { $0?.title } - #expect(favorite == ["Copy Link", "Rename…", "Mute", "Duplicate", "Separate Tabs", "Remove Favorite"]) } + /// sidebar, "Incognito": the menu starts with Copy Link and Duplicate, + /// with no divider before them. @Test func privateWindowsMenusHaveNoPinItems() { - let today = PinsLogic.todayMenu(isMuted: true, canMoveToSpace: false, canPin: false).compactMap { $0?.title } - #expect(!today.contains("Pin Tab") && !today.contains("Pin to Favorites")) - #expect(today.contains("Unmute")) + let today = titles(PinsLogic.todayMenu(isMuted: true, canMoveToSpace: false, canPin: false)) + #expect( + today == ["Copy Link", "Duplicate", "|", "Split with Tab", "|", "Unmute", "|", "Close Tab", "Close Tabs Below"]) + } + + @Test func emptyGroupsDropOutWithTheirDividers() { + let a = PinsLogic.MenuItem(title: "A", command: .copyLink) + let b = PinsLogic.MenuItem(title: "B", command: .duplicate) + #expect(titles(PinsLogic.joined([[], [a], [], [b], []])) == ["A", "|", "B"]) + #expect(PinsLogic.joined([[], []]).isEmpty) } - @Test func aClosedPinCantMuteOrReplaceItsURL() { - let closed = pin("Docs") - #expect(PinsLogic.pinnedMenu(isOpen: false, isMuted: false, canMoveToSpace: false).compactMap { $0 } - .first { $0.command == .mute }?.isEnabled == false) - #expect(PinsLogic.editPinnedPageMenu(closed).first?.isEnabled == false) + /// pinned-tabs, "Editing the pinned URL": Back to Pinned URL first, then + /// Replace, both only while the page is away from its pinned URL. + @Test func editPinnedPageGoesBackOnlyWhenAway() { + let closed = PinsLogic.editPinnedPageMenu(pin("Docs")) + #expect(closed.map(\.title) == ["Back to Pinned URL", "Replace Pinned URL with Current", "Edit…"]) + #expect(closed.map(\.isEnabled) == [false, false, true]) + let atPinnedURL = PinsLogic.editPinnedPageMenu(pin("Docs", tab: FakeTab(id: 1, title: "Docs", pinID: "Docs"))) + #expect(atPinnedURL.map(\.isEnabled) == [false, false, true]) let guide = FakeTab(id: 1, title: "Guide", pinID: "Docs") - #expect(PinsLogic.editPinnedPageMenu(pin("Docs", tab: guide, atPinnedURL: false)).first?.isEnabled == true) + let away = PinsLogic.editPinnedPageMenu(pin("Docs", tab: guide, atPinnedURL: false)) + #expect(away.map(\.isEnabled) == [true, true, true]) + #expect(away.first?.command == .backToPinnedURL) } @Test func theMainMenuItemsFollowTheSelectedRow() { var state = PinsLogic.MenuState(activeIsToday: true, todayRowCount: 2) #expect(PinsLogic.title(of: .togglePin, in: state) == "Pin Tab") #expect(PinsLogic.isEnabled(.togglePin, in: state)) - #expect(!PinsLogic.isEnabled(.backToPinnedURL, in: state)) - #expect(!PinsLogic.isEnabled(.closeKeepingPin, in: state)) + #expect(PinsLogic.isEnabled(.pinToFavorites, in: state)) #expect(PinsLogic.isEnabled(.clearToday, in: state)) - state = PinsLogic.MenuState(activePinIsFavorite: false, activePinIsNavigatedAway: false, todayRowCount: 0) + #expect(PinsLogic.title(of: .clearToday, in: state) == "Clear Unpinned Tabs") + state = PinsLogic.MenuState(activePinIsFavorite: false, todayRowCount: 0) #expect(PinsLogic.title(of: .togglePin, in: state) == "Unpin Tab") - #expect(!PinsLogic.isEnabled(.backToPinnedURL, in: state)) - #expect(PinsLogic.isEnabled(.closeKeepingPin, in: state)) + #expect(PinsLogic.isEnabled(.pinToFavorites, in: state)) #expect(!PinsLogic.isEnabled(.clearToday, in: state)) - state.activePinIsNavigatedAway = true - #expect(PinsLogic.isEnabled(.backToPinnedURL, in: state)) + // tabs-menu, "On a favorite". + state = PinsLogic.MenuState(activePinIsFavorite: true, todayRowCount: 1) + #expect(!PinsLogic.isEnabled(.togglePin, in: state)) + #expect(!PinsLogic.isEnabled(.pinToFavorites, in: state)) state.isCollapsed = true #expect(PinsLogic.title(of: .toggleCollapse, in: state) == "Expand Pinned Tabs") } @@ -383,7 +422,7 @@ struct FakePinsTests { w.browser.setActive(news.tabID) w.controller.openPin(w.model.pins[0].pinID) #expect(w.model.activePin?.title == "Mail") - w.controller.perform(.closeKeepingPin) + w.controller.closeKeepingPin(w.model.pins[0].pinID) #expect(w.pinTitles == ["Mail"]) #expect(w.model.pins[0].tabID == ClairTabIDNone) #expect(w.model.activeTabID == news.tabID) @@ -421,8 +460,17 @@ struct FakePinsTests { // The engine posts the pins again once the navigation commits. w.host.rebind(pinID, to: w.host.boundTab(of: pinID)!) #expect(PinsLogic.isNavigatedAway(w.model.pins[0])) - #expect(w.controller.pinMenuState.activePinIsNavigatedAway) - w.controller.perform(.backToPinnedURL) + // From the menu's Edit Pinned Page › (add-tab-switcher-and-tabs-menu D6). + let pin = w.model.pins[0] + let items = PinMenus.pinnedItems(pin: pin, tab: w.model.tab(ofPin: pin), moveTargets: [], actions: w.controller) + guard case .submenu(_, let edit)? = items.first(where: { $0.title == "Edit Pinned Page" }), + case .action(let title, let back)? = edit.first + else { + Issue.record("Edit Pinned Page has no Back to Pinned URL") + return + } + #expect(title == "Back to Pinned URL") + back() #expect(!PinsLogic.isNavigatedAway(w.model.pins[0])) #expect(w.model.activeTab?.canGoBack == true) } diff --git a/native/ClairUITests/SpacesTests.swift b/native/ClairUITests/SpacesTests.swift index a8d9e8ac..76ded0d2 100644 --- a/native/ClairUITests/SpacesTests.swift +++ b/native/ClairUITests/SpacesTests.swift @@ -149,7 +149,8 @@ struct SpacesLogicTests { @Test func tabRowMenuHasNoMoveToSpaceWithOneSpace() { let row = TabRow(tab: FakeTab(id: 1, title: "One"), isActive: false, isWindowKey: true, moveTargets: []) #expect(!row.menuItems.contains { $0.title == "Move to Space" }) - #expect(row.menuItems.compactMap(\.title) == ["Copy Link", "Duplicate", "Mute", "Split with Tab", "Close Tab", "Close Tabs Below"]) + // Without pins, as in an incognito window: no pin items or Rename…. + #expect(row.menuItems.compactMap(\.title) == ["Copy Link", "Duplicate", "Split with Tab", "Mute", "Close Tab", "Close Tabs Below"]) } // MARK: Names and the form diff --git a/native/ClairUITests/SplitTests.swift b/native/ClairUITests/SplitTests.swift index 1ebbfb2c..340a7d79 100644 --- a/native/ClairUITests/SplitTests.swift +++ b/native/ClairUITests/SplitTests.swift @@ -364,23 +364,23 @@ struct SplitWindowTests { @Test func theMenuBarItemsFollowTheSplit() { let menu = SplitMenu() menu.currentController = { [controller] in controller } + let tabs = TabsMenu() + tabs.currentController = { [controller] in controller } let main = NSMenu() - for (title, tag) in [("Tab", PinsMenu.tabMenuTag), ("View", PinsMenu.viewMenuTag)] { - let item = NSMenuItem(title: title, action: nil, keyEquivalent: "") - item.tag = tag - item.submenu = NSMenu(title: title) - main.addItem(item) - } + let viewItem = NSMenuItem(title: "View", action: nil, keyEquivalent: "") + viewItem.tag = PinsMenu.viewMenuTag + viewItem.submenu = NSMenu(title: "View") + main.addItem(viewItem) #expect(menu.install(in: main)) - let view = main.items[1].submenu! - #expect(view.items.prefix(3).map(\.title) == ["Add Split View", "Close Split Pane", "Separate Tabs"]) + let view = main.items[0].submenu! + #expect(view.items.map(\.title) == ["Add Split View", "Close Split Pane", "Separate Tabs", ""]) let close = menu.items[.closeSplitPane]! #expect(close.keyEquivalent == "-" && close.keyEquivalentModifierMask == [.control, .shift]) #expect(!menu.validateMenuItem(close)) - #expect(menu.validateMenuItem(menu.items[.splitWithTab]!)) + #expect(tabs.validateMenuItem(tabs.items[.splitWithTab]!)) browser.split(tab: mail.tabID, with: docs.tabID, side: .trailing) #expect(menu.validateMenuItem(close)) - #expect(!menu.validateMenuItem(menu.items[.splitWithTab]!)) + #expect(!tabs.validateMenuItem(tabs.items[.splitWithTab]!)) // Close Split Pane closes the focused pane. menu.choose(close) #expect(!browser.tabs.contains { $0.tabID == docs.tabID }) diff --git a/native/ClairUITests/TabSwitcherTests.swift b/native/ClairUITests/TabSwitcherTests.swift new file mode 100644 index 00000000..827b2882 --- /dev/null +++ b/native/ClairUITests/TabSwitcherTests.swift @@ -0,0 +1,425 @@ +// Copyright 2026 The Clair Authors +// You can use, redistribute, and/or modify this source code under +// the terms of the GPL-3.0 license that can be found in the LICENSE file. + +import AppKit +import ClairHost +import Foundation +import Testing + +@testable import ClairUI + +// MARK: Recent tabs (tab-switcher, "Recent tabs"; design D1) + +/// A window's recents, read through its controller as Chromium drives it. +@MainActor +struct RecentTabsTests { + let window = PinWindow() + + private var recents: [String] { + let tabs = window.controller.switcherTabs + return window.controller.recentTabIDs.map { tabs[$0]?.title ?? "?\($0)" } + } + + @Test func theMostRecentComesFirst() { + let mail = window.browser.addTab(title: "Mail") + let news = window.browser.addTab(title: "News") + let docs = window.browser.addTab(title: "Docs") + window.browser.activate(tab: mail.tabID) + window.browser.activate(tab: news.tabID) + window.browser.activate(tab: docs.tabID) + #expect(recents == ["Docs", "News", "Mail"]) + } + + @Test func theyGoAcrossSpaces() { + let home = window.browser.shownSpaceID + let work = window.host.addSpaces("Work")[0] + window.browser.addTab(title: "Recipes") + window.browser.showSpace(work) + window.browser.addTab(title: "Mail") + // Home shows the tab last shown there. + window.browser.showSpace(home) + #expect(recents.prefix(2) == ["Recipes", "Mail"]) + } + + @Test func aPinnedTabLeavesWhenItsPageCloses() throws { + window.browser.addTab(title: "News") + let pinID = window.host.addPin(url: "https://mail.example/", title: "Mail") + window.browser.openPin(pinID) + window.browser.addTab(title: "Docs") + #expect(recents == ["Docs", "Mail", "News"]) + window.controller.closeKeepingPin(pinID) + #expect(recents == ["Docs", "News"]) + } + + @Test func aFavoriteCounts() { + let pinID = window.host.addPin(url: "https://calendar.example/", title: "Calendar", inSpace: nil) + window.browser.addTab(title: "News") + window.browser.openPin(pinID) + window.browser.addTab(title: "Docs") + #expect(recents == ["Docs", "Calendar", "News"]) + } + + /// A tab and its Peek are one entry (peek spec, "Ctrl+Tab across a Peek"). + @Test func aPeekCountsAsItsParent() throws { + window.browser.addTab(title: "Docs") + let mail = window.browser.addTab(title: "Mail") + let peek = try #require(window.browser.openPeek(of: mail.tabID, title: "Peek")) + window.browser.activate(tab: peek.tabID) + #expect(recents == ["Mail", "Docs"]) + #expect(window.controller.recents.ids.first == mail.tabID) + } + + /// A split is one entry, through its leading pane (split-view spec). + @Test func aSplitCountsOnce() { + let docs = window.browser.addTab(title: "Docs") + let news = window.browser.addTab(title: "News") + let mail = window.browser.addTab(title: "Mail") + window.browser.split(tab: news.tabID, with: docs.tabID, side: .trailing) + window.browser.activate(tab: news.tabID) + window.browser.activate(tab: mail.tabID) + window.browser.activate(tab: docs.tabID) + #expect(window.controller.recentTabIDs == [news.tabID, mail.tabID]) + } + + @Test func aClosedTabLeaves() { + let mail = window.browser.addTab(title: "Mail") + window.browser.addTab(title: "Docs") + window.browser.closeTabNow(mail.tabID) + #expect(recents == ["Docs"]) + } + + /// The still's placeholder is in no Space, and never enters the list. + @Test func theStillsPlaceholderNeverEnters() { + let w = SharedWindows() + w.a.activate(tab: w.notes.tabID) + w.a.activate(tab: w.docs.tabID) + w.b.activate(tab: w.docs.tabID) + #expect(w.controllerA.model.isShowingStill) + #expect(w.controllerA.recentTabIDs == [w.docs.tabID, w.notes.tabID]) + } + + /// The incoming window of a profile swap takes the outgoing one's list. + @Test func theIncomingWindowTakesTheList() { + let mail = window.browser.addTab(title: "Mail") + let docs = window.browser.addTab(title: "Docs") + let other = FakeBrowser(host: window.host) + let incoming = BrowserWindowController(browser: other, spaces: other.spaces) + other.clairWindow = incoming + incoming.shownSpaceDidChange( + window.browser.shownSpaceID, from: window.browser.shownSpaceID, swappedInFor: window.browser.browserID) + #expect(incoming.recentTabIDs.prefix(2) == [docs.tabID, mail.tabID]) + } + + @Test func rowsResolveFromThePeekAndTheTrailingPane() { + let parent = FakeTab(id: 1, title: "Parent", peekID: 2) + let peek = FakeTab(id: 2, title: "Peek", peekParentID: 1) + let lead = FakeTab(id: 3, title: "Lead", splitPartnerID: 4, isLeadingPane: true) + let trail = FakeTab(id: 4, title: "Trail", splitPartnerID: 3) + let tabs: [TabID: any ClairTab] = [1: parent, 2: peek, 3: lead, 4: trail] + #expect(RecentTabs.row(of: 2, in: tabs) == 1) + #expect(RecentTabs.row(of: 4, in: tabs) == 3) + #expect(RecentTabs.row(of: 3, in: tabs) == 3) + #expect(RecentTabs.row(of: 9, in: tabs) == nil) + var recents = RecentTabs([4, 1, 3, 9]) + recents.prune(in: tabs) + #expect(recents.ids == [3, 1]) + let unknown = recents.show(9, in: tabs) + #expect(!unknown) + let fromPeek = recents.show(2, in: tabs) + #expect(fromPeek) + #expect(recents.ids == [1, 3]) + } +} + +// MARK: The switcher's state (design D2, D3) + +struct SwitcherStateTests { + let t0 = ContinuousClock.now + let recents: [TabID] = [1, 2, 3, 4, 5, 6, 7] + + /// tab-switcher, "Seven recent tabs". + @Test func ctrlTabOpensOnTheFirstFiveWithTheSecondSelected() { + var state = SwitcherState() + let r1 = state.open(recents: recents, forward: true, at: t0) + #expect(r1) + #expect(state.entries == [1, 2, 3, 4, 5]) + #expect(state.selectedTab == 2) + } + + /// "Backwards". + @Test func ctrlShiftTabSelectsTheLast() { + var state = SwitcherState() + state.open(recents: recents, forward: false, at: t0) + #expect(state.selectedTab == 5) + } + + /// "Two recent tabs" and "One tab". + @Test func itNeedsTwoRecentTabs() { + var state = SwitcherState() + state.open(recents: [1, 2], forward: true, at: t0) + #expect(state.entries == [1, 2] && state.selectedTab == 2) + state.cancel() + let r2 = state.open(recents: [1], forward: true, at: t0) + #expect(!r2) + let r3 = state.open(recents: [], forward: true, at: t0) + #expect(!r3) + #expect(!state.isOpen) + } + + /// "Moving the selection": "Stepping" and "Wrapping". + @Test func tabStepsAndWraps() { + var state = SwitcherState() + state.open(recents: recents, forward: true, at: t0) + state.step(forward: true) + #expect(state.selectedTab == 3) + state.step(forward: true) + state.step(forward: true) + #expect(state.selectedTab == 5) + state.step(forward: true) + #expect(state.selectedTab == 1) + state.step(forward: false) + #expect(state.selectedTab == 5) + } + + /// "Choosing a tab": the selected tab, and nothing for the shown one. + @Test func releasingCtrlChoosesTheSelectedTab() { + var state = SwitcherState() + state.open(recents: recents, forward: true, at: t0) + state.step(forward: true) + let r4 = state.commit() + #expect(r4 == 3) + #expect(!state.isOpen) + state.open(recents: recents, forward: true, at: t0) + state.step(forward: false) + let r5 = state.commit() + #expect(r5 == nil) + let r6 = state.commit() + #expect(r6 == nil) + } + + @Test func aCardChosenWithThePointerWins() { + var state = SwitcherState() + state.open(recents: recents, forward: true, at: t0) + let r7 = state.commit(card: 3) + #expect(r7 == 4) + } + + /// "Cancelling the switcher". + @Test func escChoosesNothing() { + var state = SwitcherState() + state.open(recents: recents, forward: true, at: t0) + state.cancel() + let afterCancel = state.commit() + #expect(!state.isOpen && afterCancel == nil) + } + + /// "A quick Ctrl+Tab shows no panel", "Holding Ctrl" and "Two quick Tabs". + @Test func thePanelWaitsAHundredMilliseconds() { + var state = SwitcherState() + state.open(recents: recents, forward: true, at: t0) + #expect(!state.isPanelShown) + #expect(state.panelDeadline == t0.advanced(by: .milliseconds(100))) + state.update(at: t0.advanced(by: .milliseconds(99))) + #expect(!state.isPanelShown) + state.update(at: t0.advanced(by: .milliseconds(100))) + #expect(state.isPanelShown) + #expect(state.panelDeadline == nil) + // A quick tap: released before the panel is due. + state.open(recents: recents, forward: true, at: t0) + let r8 = state.commit() + #expect(r8 == 2) + #expect(!state.isPanelShown) + // A second Tab within the delay shows it at once, on the third card. + state.open(recents: recents, forward: true, at: t0) + state.step(forward: true) + #expect(state.isPanelShown && state.selectedTab == 3) + } +} + +// MARK: The keys and the pointer (design D2) + +/// A window the switcher sits over, standing in for the controller. +@MainActor +final class StubSwitcherHost: TabSwitcherHost { + let switcherWindow = NSWindow( + contentRect: CGRect(x: 100, y: 100, width: 1000, height: 700), styleMask: [.titled], backing: .buffered, + defer: true) + var switcherMayAct = true + var recentTabIDs: [TabID] = [1, 2, 3, 4] + private(set) var shown: [TabID] = [] + private(set) var previewRequests: [TabID] = [] + + init() { + switcherWindow.isReleasedWhenClosed = false + } + + func switcherCards(for entries: [TabID]) -> [SwitcherCard] { + entries.map { SwitcherCard(id: $0, paneIDs: [$0], title: "Tab \($0)", favicons: [nil], label: "Tab \($0)") } + } + + func requestSwitcherPreview(of tabID: TabID, size: NSSize, completion: @escaping (NSImage?) -> Void) { + previewRequests.append(tabID) + completion(NSImage(size: size)) + } + + func showFromSwitcher(_ tabID: TabID) { + shown.append(tabID) + } +} + +@MainActor +struct TabSwitcherKeyTests { + let host = StubSwitcherHost() + let switcher: TabSwitcher + + init() { + switcher = TabSwitcher(host: host) + // The panel's delay never ends on its own here; a second Tab shows it. + switcher.wait = { _ in try? await Task.sleep(for: .seconds(3600)) } + } + + private func key(_ code: UInt16, _ flags: NSEvent.ModifierFlags = [], type: NSEvent.EventType = .keyDown) -> NSEvent + { + let characters = code == 48 ? "\t" : (code == 53 ? "\u{1b}" : "a") + return NSEvent.keyEvent( + with: type, location: .zero, modifierFlags: flags, timestamp: 0, windowNumber: 0, context: nil, + characters: characters, charactersIgnoringModifiers: characters, isARepeat: false, keyCode: code)! + } + + private func flags(_ flags: NSEvent.ModifierFlags) -> NSEvent { + NSEvent.keyEvent( + with: .flagsChanged, location: .zero, modifierFlags: flags, timestamp: 0, windowNumber: 0, context: nil, + characters: "", charactersIgnoringModifiers: "", isARepeat: false, keyCode: 59)! + } + + @Test func ctrlTabIsTakenAndOtherKeysPassWhileClosed() { + #expect(!switcher.handle(key(48))) + #expect(!switcher.handle(key(0, .control))) + #expect(!switcher.handle(key(48, [.control, .command]))) + #expect(!switcher.state.isOpen) + #expect(switcher.handle(key(48, .control))) + #expect(switcher.state.isOpen) + // Its key-up goes no further either. + #expect(switcher.handle(key(48, .control, type: .keyUp))) + #expect(switcher.state.entries == [1, 2, 3, 4]) + #expect(host.previewRequests == [1, 2, 3, 4]) + switcher.cancel() + } + + @Test func releasingCtrlShowsTheSelectedTab() { + #expect(switcher.handle(key(48, .control))) + #expect(!switcher.state.isPanelShown) + #expect(!switcher.handle(flags([]))) + #expect(host.shown == [2]) + #expect(!switcher.state.isOpen) + } + + @Test func tabStepsAndEscCancels() { + switcher.handle(key(48, .control)) + #expect(switcher.handle(key(48, .control))) + #expect(switcher.state.isPanelShown && switcher.state.selectedTab == 3) + #expect(switcher.handle(key(48, [.control, .shift]))) + #expect(switcher.state.selectedTab == 2) + // Any other key is swallowed while it's open. + #expect(switcher.handle(key(0, .control))) + #expect(switcher.handle(key(53, .control))) + #expect(!switcher.state.isOpen) + switcher.handle(flags([])) + #expect(host.shown.isEmpty) + } + + @Test func clickingACardShowsItsTab() { + switcher.handle(key(48, .control)) + switcher.handle(key(48, .control)) + let card = SwitcherLayout.cardFrame(3) + // From the panel's bottom left. + #expect(switcher.click(at: CGPoint(x: card.midX, y: SwitcherLayout.height - card.midY))) + #expect(host.shown == [4]) + // Releasing Ctrl then changes nothing. + switcher.handle(flags([])) + #expect(host.shown == [4]) + #expect(!switcher.click(at: CGPoint(x: card.midX, y: 10))) + } + + @Test func nothingHappensWhileADialogIsUp() { + host.switcherMayAct = false + #expect(!switcher.handle(key(48, .control))) + #expect(!switcher.state.isOpen) + } + + @Test func oneRecentTabOpensNothingButCtrlTabIsStillTaken() { + host.recentTabIDs = [1] + #expect(switcher.handle(key(48, .control))) + #expect(!switcher.state.isOpen) + } + + @Test func theShownTabClosingCancels() { + switcher.handle(key(48, .control)) + switcher.tabsDidChange(open: [2, 3, 4]) + #expect(!switcher.state.isOpen) + } +} + +// MARK: The panel's layout (design D3) + +struct SwitcherLayoutTests { + /// tab-switcher, "Five cards": about 938 by 189 points. + @Test(arguments: [(1, 211.5), (2, 393.0), (3, 574.5), (4, 756.0), (5, 937.5)]) + func thePanelFitsItsCards(cards: Int, width: Double) { + #expect(SwitcherLayout.panelSize(cards: cards) == CGSize(width: width, height: 189)) + } + + @Test func eachCardsHighlightIsTwelvePointsAroundItsPreview() { + #expect(SwitcherLayout.cardFrame(0) == CGRect(x: 15, y: 15, width: 181.5, height: 157.5)) + #expect(SwitcherLayout.cardFrame(2).minX == 15 + 2 * 181.5) + #expect(SwitcherLayout.card(at: CGPoint(x: 20, y: 100), cards: 5) == 0) + #expect(SwitcherLayout.card(at: CGPoint(x: 200, y: 100), cards: 5) == 1) + #expect(SwitcherLayout.card(at: CGPoint(x: 5, y: 100), cards: 5) == nil) + #expect(SwitcherLayout.card(at: CGPoint(x: 200, y: 180), cards: 5) == nil) + } + + @Test func itsCentredOnTheWindow() { + let window = CGRect(x: 0, y: 30, width: 1400, height: 976) + let frame = SwitcherLayout.panelFrame(cards: 5, window: window, visible: CGRect(x: 0, y: 0, width: 1920, height: 1080)) + #expect(frame.midX == window.midX && frame.midY == window.midY) + } + + /// Kept on screen: a five-card panel over a narrow window at the screen's + /// edge moves inside the visible frame. + @Test func itStaysOnScreen() { + let visible = CGRect(x: 0, y: 0, width: 1920, height: 1050) + let left = SwitcherLayout.panelFrame(cards: 5, window: CGRect(x: 0, y: 30, width: 600, height: 976), visible: visible) + #expect(left.minX == 0) + let right = SwitcherLayout.panelFrame( + cards: 5, window: CGRect(x: 1500, y: 0, width: 420, height: 300), visible: visible) + #expect(right.maxX == 1920) + #expect(right.midY == 150) + let low = SwitcherLayout.panelFrame(cards: 2, window: CGRect(x: 0, y: -50, width: 600, height: 100), visible: visible) + #expect(low.minY == 0) + // Wider than the screen: its leading edge stays on it. + let narrow = SwitcherLayout.panelFrame( + cards: 5, window: CGRect(x: 0, y: 0, width: 800, height: 600), visible: CGRect(x: 0, y: 0, width: 800, height: 600)) + #expect(narrow.minX == 0) + } +} + +// MARK: Cards (tab-switcher, "Cards") + +struct SwitcherCardTests { + @Test func aRenamedTabReadsItsName() { + let mail = FakeTab(id: 1, title: "Mail", name: "Inbox") + let card = SwitcherCard.make(1, in: [1: mail]) + #expect(card?.title == "Inbox") + } + + @Test func aSplitShowsBothPagesInPaneOrderWithNoTitle() { + let news = FakeTab(id: 1, title: "News", splitPartnerID: 2, isLeadingPane: true) + let docs = FakeTab(id: 2, title: "Docs", splitPartnerID: 1) + let card = SwitcherCard.make(1, in: [1: news, 2: docs]) + #expect(card?.paneIDs == [1, 2]) + #expect(card?.title == "") + #expect(card?.favicons.count == 2) + #expect(card?.label == "News, Docs") + } +} diff --git a/native/ClairUITests/TabsMenuTests.swift b/native/ClairUITests/TabsMenuTests.swift new file mode 100644 index 00000000..aff5fc98 --- /dev/null +++ b/native/ClairUITests/TabsMenuTests.swift @@ -0,0 +1,160 @@ +// Copyright 2026 The Clair Authors +// You can use, redistribute, and/or modify this source code under +// the terms of the GPL-3.0 license that can be found in the LICENSE file. + +import AppKit +import ClairHost +import Testing + +@testable import ClairUI + +/// The menu bar's Tabs menu (add-tab-switcher-and-tabs-menu D5, `tabs-menu`). +@MainActor +struct TabsMenuTests { + let window = PinWindow() + let menu = TabsMenu() + + init() { + menu.currentController = { [controller = window.controller] in controller } + } + + private func item(_ command: TabsMenu.Command) -> NSMenuItem { menu.items[command]! } + + private func isEnabled(_ command: TabsMenu.Command) -> Bool { menu.validateMenuItem(item(command)) } + + /// tabs-menu, "The items". + @Test func itListsItsItemsInGroups() { + #expect( + menu.menu.items.map { $0.isSeparatorItem ? "|" : $0.title } == [ + "Pin Tab", "Pin to Favorites", "New Folder…", "|", "Next Tab", "Previous Tab", "|", "Split with Tab", + "Move to Space", "|", "Clear Unpinned Tabs", + ]) + #expect(item(.pinTab).keyEquivalent == "d" && item(.pinTab).keyEquivalentModifierMask == [.command]) + let clear = item(.clearUnpinnedTabs) + #expect(clear.keyEquivalent == "k" && clear.keyEquivalentModifierMask == [.command, .shift]) + #expect(item(.splitWithTab).submenu != nil && item(.moveToSpace).submenu != nil) + } + + /// Next and Previous Tab are Chromium's commands, sent to the key window + /// as its own items are. + @Test func nextAndPreviousTabAreChromiumsCommands() throws { + let next = try #require(menu.nextTab) + let previous = try #require(menu.previousTab) + #expect(next.action == NSSelectorFromString("commandDispatch:") && next.target == nil) + #expect(next.tag == 34016 && previous.tag == 34017) + #expect(next.keyEquivalent == String(Character(UnicodeScalar(UInt16(NSDownArrowFunctionKey))!))) + #expect(previous.keyEquivalent == String(Character(UnicodeScalar(UInt16(NSUpArrowFunctionKey))!))) + #expect(next.keyEquivalentModifierMask == [.command, .option]) + } + + /// tabs-menu, "Tabs menu items": just before the Window menu. + @Test func itGoesBeforeTheWindowMenu() { + let main = NSMenu() + for (title, tag) in [("File", 0), ("View", PinsMenu.viewMenuTag), ("Window", TabsMenu.windowMenuTag), ("Help", 0)] { + let item = NSMenuItem(title: title, action: nil, keyEquivalent: "") + item.tag = tag + item.submenu = NSMenu(title: title) + main.addItem(item) + } + #expect(menu.install(in: main)) + #expect(main.items.map(\.title) == ["File", "View", "Tabs", "Window", "Help"]) + #expect(!menu.install(in: main)) + } + + /// tabs-menu, "No window". + @Test func everyItemIsOffWithoutAWindow() { + menu.currentController = { nil } + for command in TabsMenu.Command.allCases { + #expect(!isEnabled(command), "\(command)") + } + } + + /// tabs-menu, "Pin Tab". + @Test func pinTabPinsTheShownTodayTab() { + let mail = window.browser.addTab(title: "Mail", url: "https://mail.example/") + #expect(item(.pinTab).title == "Pin Tab" && isEnabled(.pinTab)) + #expect(isEnabled(.pinToFavorites)) + menu.choose(item(.pinTab)) + #expect(window.pinTitles == ["Mail"]) + #expect(window.host.boundTab(of: window.model.pins[0].pinID)?.tabID == mail.tabID) + } + + /// tabs-menu, "On a pinned tab". + @Test func onAPinnedTabTheFirstItemReadsUnpinTab() { + let pinID = window.host.addPin(url: "https://docs.example/", title: "Docs") + window.browser.addTab(title: "News") + window.browser.openPin(pinID) + _ = menu.validateMenuItem(item(.pinTab)) + #expect(item(.pinTab).title == "Unpin Tab") + #expect(isEnabled(.pinToFavorites)) + menu.choose(item(.pinToFavorites)) + #expect(window.model.favorites.map(\.title) == ["Docs"]) + } + + /// tabs-menu, "On a favorite". + @Test func aFavoriteCantBePinnedOrMoved() { + window.host.addSpaces("Work") + let pinID = window.host.addPin(url: "https://mail.example/", title: "Mail", inSpace: nil) + window.browser.addTab(title: "News") + window.browser.openPin(pinID) + #expect(!isEnabled(.pinTab)) + #expect(!isEnabled(.pinToFavorites)) + #expect(!isEnabled(.moveToSpace)) + #expect(isEnabled(.newFolder)) + } + + /// tabs-menu, "Pin items" and "Move to Space submenu": nothing to pin or + /// move in an incognito window. + @Test func incognitoHasNoPinItems() { + let host = FakeHost() + host.addSpaces("Work") + let browser = FakeBrowser(host: host, profileKind: .incognito) + let controller = BrowserWindowController(browser: browser, spaces: browser.spaces) + browser.clairWindow = controller + browser.addTab(title: "Secret") + menu.currentController = { controller } + for command in [TabsMenu.Command.pinTab, .pinToFavorites, .newFolder, .moveToSpace, .clearUnpinnedTabs] { + #expect(!isEnabled(command), "\(command)") + } + #expect(isEnabled(.splitWithTab)) + } + + /// tabs-menu, "Moving the shown tab" and "One Space". + @Test func moveToSpaceListsTheOtherSpaces() throws { + let docs = window.browser.addTab(title: "Docs") + #expect(!isEnabled(.moveToSpace)) + let ids = window.host.addSpaces("Research", "Travel") + #expect(isEnabled(.moveToSpace)) + let submenu = try #require(item(.moveToSpace).submenu) + menu.menuNeedsUpdate(submenu) + #expect(submenu.items.map(\.title) == ["Research", "Travel"]) + #expect(menu.validateMenuItem(submenu.items[0])) + menu.chooseSpace(submenu.items[0]) + #expect(window.host.tab(docs.tabID)?.spaceID == ids[0]) + } + + /// tabs-menu, "Clearing". + @Test func clearUnpinnedTabsClosesTheTodayTabs() { + #expect(!isEnabled(.clearUnpinnedTabs)) + let pinID = window.host.addPin(url: "https://docs.example/", title: "Docs") + window.browser.addTab(title: "One") + window.browser.addTab(title: "Two") + window.browser.openPin(pinID) + #expect(isEnabled(.clearUnpinnedTabs)) + menu.choose(item(.clearUnpinnedTabs)) + #expect(window.todayTitles.isEmpty) + #expect(window.pinTitles == ["Docs"]) + } + + /// Split with Tab › lists the Today tabs, and is off while split. + @Test func splitWithTabFollowsTheSplit() throws { + let docs = window.browser.addTab(title: "Docs") + let mail = window.browser.addTab(title: "Mail") + let submenu = try #require(item(.splitWithTab).submenu) + menu.menuNeedsUpdate(submenu) + let docsItem = try #require(submenu.items.first { $0.title == "Docs" }) + menu.chooseTab(docsItem) + #expect(window.host.tab(mail.tabID)?.splitPartnerID == docs.tabID) + #expect(!isEnabled(.splitWithTab)) + } +} diff --git a/openspec/changes/add-tab-switcher-and-tabs-menu/design.md b/openspec/changes/add-tab-switcher-and-tabs-menu/design.md index 7cf58bd9..479735aa 100644 --- a/openspec/changes/add-tab-switcher-and-tabs-menu/design.md +++ b/openspec/changes/add-tab-switcher-and-tabs-menu/design.md @@ -42,7 +42,7 @@ Kept in the engine instead, the list would need a new observer call for somethin | Other keys, switcher open | Swallowed. | | `flagsChanged` without Control, switcher open | Commits. | -Every handled event returns nil, so the page, the command bar and Chromium never see it. The window resigning key or the shown tab closing cancels. A second monitor, active only while the panel shows, takes a left mouse down over a card, Control held, and commits that card, before AppKit can treat the Control-click as a secondary click. It takes no other mouse event. Arc lets a click choose a card too (the owner checked by hand). +Every handled key-down returns nil, so the page, the command bar and Chromium never see it, and so does the key-up of a key whose key-down it took. A `flagsChanged` event always goes on, even the one that commits, so the page never thinks Ctrl is still held. The window resigning key or the shown tab closing cancels. A second monitor, active only while the panel shows, takes a left mouse down over a card, Control held, and commits that card, before AppKit can treat the Control-click as a secondary click. It takes no other mouse event. Arc lets a click choose a card too (the owner checked by hand). With Chromium's Tab menu deleted (D5), Chromium no longer has Ctrl+Tab at all. diff --git a/openspec/changes/add-tab-switcher-and-tabs-menu/tasks.md b/openspec/changes/add-tab-switcher-and-tabs-menu/tasks.md index 67bb2b9a..6e3a6b0a 100644 --- a/openspec/changes/add-tab-switcher-and-tabs-menu/tasks.md +++ b/openspec/changes/add-tab-switcher-and-tabs-menu/tasks.md @@ -42,7 +42,7 @@ Suggested order: - a tab of another profile's Space goes through the profile swap of `ShowSpace`, and the incoming window activates the tab. Verify with the runtime test of 5.3. -- [ ] 2.5 Push the branch and build the engine (`gh workflow run engine.yml -f ref=`). Verify that `chromium-engine-` is published. +- [x] 2.5 Push the branch and build the engine (`gh workflow run engine.yml -f ref=`). Verify that `chromium-engine-` is published. ## 3. ClairUI From ba0bb25c93bc41d7727ac72cb3889cb011eabe5e Mon Sep 17 00:00:00 2001 From: Joshua Park Date: Fri, 27 Nov 2026 01:10:11 -0500 Subject: [PATCH 3/8] test: cover the tab switcher and Tabs menu; document them --- .../unreleased/Changed-20261127-011006.yaml | 3 + .changes/unreleased/New-20261124-222859.yaml | 2 +- .changes/unreleased/New-20261127-011005.yaml | 3 + docs/building.md | 2 + docs/native-window.md | 21 +- .../add-tab-switcher-and-tabs-menu/tasks.md | 6 +- tests/probe/README.md | 9 +- tests/probe/tools/keys.swift | 124 +++++++++++ .../ClairRuntimeTests/FoldersTests.swift | 6 +- .../runtime/ClairRuntimeTests/PinsTests.swift | 43 ++-- .../ClairRuntimeTests/SpacesTests.swift | 15 +- .../ClairRuntimeTests/SplitViewTests.swift | 6 +- .../ClairRuntimeTests/TabSwitcherTests.swift | 204 ++++++++++++++++++ 13 files changed, 407 insertions(+), 37 deletions(-) create mode 100644 .changes/unreleased/Changed-20261127-011006.yaml create mode 100644 .changes/unreleased/New-20261127-011005.yaml create mode 100644 tests/probe/tools/keys.swift create mode 100644 tests/runtime/ClairRuntimeTests/TabSwitcherTests.swift diff --git a/.changes/unreleased/Changed-20261127-011006.yaml b/.changes/unreleased/Changed-20261127-011006.yaml new file mode 100644 index 00000000..74b6a321 --- /dev/null +++ b/.changes/unreleased/Changed-20261127-011006.yaml @@ -0,0 +1,3 @@ +kind: Changed +body: 'The menu bar''s Tab menu is now Tabs, with Clair''s own items: Pin Tab, Pin to Favorites, New Folder…, Next and Previous Tab, Split with Tab, Move to Space and Clear Unpinned Tabs. Tab menus in the sidebar are grouped into sections, and Edit Pinned Page offers Back to Pinned URL.' +time: 2026-11-27T01:10:06.636702-05:00 diff --git a/.changes/unreleased/New-20261124-222859.yaml b/.changes/unreleased/New-20261124-222859.yaml index e400b5e2..11c86d63 100644 --- a/.changes/unreleased/New-20261124-222859.yaml +++ b/.changes/unreleased/New-20261124-222859.yaml @@ -1,3 +1,3 @@ kind: New -body: 'Folders in the pinned section, as in Arc: create them from the + menu, the Space''s menu or Tab › New Folder…, drag tabs into them, open and close them, and turn one into a Space.' +body: 'Folders in the pinned section, as in Arc: create them from the + menu, the Space''s menu or Tabs › New Folder…, drag tabs into them, open and close them, and turn one into a Space.' time: 2026-11-24T22:28:59.296124-05:00 diff --git a/.changes/unreleased/New-20261127-011005.yaml b/.changes/unreleased/New-20261127-011005.yaml new file mode 100644 index 00000000..b1614db4 --- /dev/null +++ b/.changes/unreleased/New-20261127-011005.yaml @@ -0,0 +1,3 @@ +kind: New +body: 'Ctrl+Tab goes back to the tab you used last, as in Arc: hold Ctrl to see your five most recent tabs, across Spaces, with previews of their pages, and press Tab to choose another.' +time: 2026-11-27T01:10:05.615797-05:00 diff --git a/docs/building.md b/docs/building.md index a0553faa..190d69d7 100644 --- a/docs/building.md +++ b/docs/building.md @@ -200,6 +200,8 @@ Check the Xcode that ungoogled-chromium-macos's CI builds that tag with (`BASE_X Fix the Clair patches the comment lists from the top, using ungoogled-chromium-macos's and Helium's updates as references: a skipped patch can make a later one that builds on it fail too. +Clair deletes Chromium's Tab menu at start-up (`add-tab-switcher-and-tabs-menu` design D5), and Chromium's code that looks it up today handles its absence. On each update, grep the new Chromium for `IDC_TAB_MENU` (`chrome/browser/app_controller_mac.mm`, `chrome/browser/ui/cocoa/`): a new user that doesn't check for nil would crash when a window becomes main, which the patch check can't see. + To move the pin by hand instead, for a tag the bot doesn't follow (ungoogled-chromium-macos doesn't tag every version: of 157, it skipped `157.0.8103.38` and `157.0.8103.50`): ```sh diff --git a/docs/native-window.md b/docs/native-window.md index eab5c04d..581bad57 100644 --- a/docs/native-window.md +++ b/docs/native-window.md @@ -27,7 +27,7 @@ The archived `add-spaces` change's `design.md` (`openspec/changes/archive/2026-1 - **The Space store (D1).** `ClairSpaceStore` keeps the Spaces in Chromium's Local State (`clair.spaces`, and `clair.last_space` for the Space a new window shows). It creates "Home" when none is stored and refuses to delete the last Space. `clair::RegisterLocalStatePrefs` registers both prefs from `browser_prefs.cc`. Each Space is a record with its own sort key, `order`, and the Spaces are sorted by it, then by ID, so moving one rewrites only its record (`add-tab-folders` D12); the keys come from `clair_order_key.{h,mm}` (see Pins and favorites below). A Space saves its profile by the ID of `clair.profiles` (see Profiles below). - **The tab lists (D2).** `ClairSpaceTabs`, one per profile (kept as the profile's user data), observes the tab strip of every native window of the profile and keeps one ordered list of tab handles per Space, across windows: its Today tabs. A tab bound to a pinned tab or favorite is in no list (see Pins and favorites below). Each tab carries its Space as `WebContents` user data. A new tab joins the Space its window shows, a restored one its saved Space at its saved place, and a Peek its parent's. The tab strip's order no longer means anything to the user, except that a Peek follows its parent. An incognito or guest profile has one Space of its own, which isn't in the store. `ClairSpaceTabs` also owns the tab snapshots and pushes each Space's list and each tab's changes to the host's `ClairSpacesObserver`, once per run-loop turn, before a window hears that its active tab changed. -- **The shown Space (D3, D4, D5).** Each `ClairBrowserWindow` shows one Space, and its active tab always belongs to it: when another tab becomes active for any reason, the window shows that tab's Space. Showing a Space activates the tab last active in it in that window, or opens a new tab page with the command bar. The window also keeps the tab the user came from and picks the next tab before a close Clair starts (that tab, else the row above, else the row below, over the open pinned tabs and then the Today rows; a favorite counts as came-from but isn't a row), or, for a page with unload handlers, once the page agrees to close (`ClairBrowserWindow::BeforeUnloadFired`). It runs the tab commands (Cmd+number, Next and Previous Tab, Ctrl+Shift+PageDown and PageUp, Close Tabs Below, Close Other Tabs) over its rows of the shown Space: every pinned tab, open or not (landing on one that isn't opens it), then the Today rows; PageDown and PageUp move a row within its own section, or its folder. A closed folder's pinned tabs are rows only while their page is open, as the sidebar lists them (`RowPins`, `add-tab-folders` D9). +- **The shown Space (D3, D4, D5).** Each `ClairBrowserWindow` shows one Space, and its active tab always belongs to it: when another tab becomes active for any reason, the window shows that tab's Space. Showing a Space activates the tab last active in it in that window, or opens a new tab page with the command bar. The window also keeps the tab the user came from and picks the next tab before a close Clair starts (that tab, else the row above, else the row below, over the open pinned tabs and then the Today rows; a favorite counts as came-from but isn't a row), or, for a page with unload handlers, once the page agrees to close (`ClairBrowserWindow::BeforeUnloadFired`). It runs the tab commands (Cmd+number, Next and Previous Tab, Ctrl+Shift+PageDown and PageUp, Close Tabs Below) over its rows of the shown Space: every pinned tab, open or not (landing on one that isn't opens it), then the Today rows; PageDown and PageUp move a row within its own section, or its folder. A closed folder's pinned tabs are rows only while their page is open, as the sidebar lists them (`RowPins`, `add-tab-folders` D9). - **Sessions (D6).** Each tab's Space and its index in the Space's list ride in its session extra data (`clair_space`, `clair_order`), so session restore and Reopen Closed Tab put it back. Session restore always runs, whatever `session.restore_on_startup` says (see Pins and favorites below, D12); which windows come back is the restore setting's (see Profiles below). - **`ClairUI` (D10).** `SpacesModel`, one per host, holds the Spaces and each Space's tabs; each window copies its shown Space's list into its `BrowserWindowModel`. The sidebar's content between the URL field and the footer is a pager that slides between Spaces. @@ -68,7 +68,7 @@ The `add-pinned-tabs-and-favorites` change's `design.md` (`openspec/changes/add- - **Folders (`add-tab-folders` D2, D7, D8, D11).** The host's folder calls create, rename, open and close, move, duplicate and delete folders (`clair_native_layer.mm`); those that reach tabs are in `clair_space_tabs.mm`: `MoveFolder` moves the bound tabs as Move to Space does, `DeleteFolder` removes the folder first and then closes its tabs, `CloseTabsInFolder` closes them through the close flow, and `TurnFolderIntoSpace` creates a Space and moves the folder's pins into it with `MovePin`. - **Peeks for other sites (D7).** `ClairPinnedLinkThrottle`, added to primary main frame navigations by `pinned-link-peek.patch`, turns a renderer-initiated link click with a gesture from a bound tab to another site (another scheme or host, as in Arc) into a Peek while the window's `opensPeekForOtherSites` is on. A URL entered from a favorite to another site opens a new Today tab (`LeavesFavorite`). A bound tab's Peek expands to the top of Today. - **The title (D8).** `ClairBrowserWindow::UpdateTitleBar` uses the active row's custom name when it has one. -- **`ClairUI` (D11).** `SpacesModel` caches each Space's pins and each profile's favorites; `BrowserWindowModel` copies the shown Space's and the profile's, and its `allTabs` adds their tabs to the Today tabs. The sidebar shows the favorites grid (`FavoritesGrid`, laid out by `FavoritesLayout`) above the Space pager, and one list of pinned rows (`PinRow`, and `FolderRow` with its tabs indented under it, flattened by `PinsLogic.pinnedRows`), the divider with Clear (`TodayDivider`), "New Tab" and the Today rows, which drag between sections (`TabList`'s `onMove` and `onInsert`, `SidebarDragItem`; `PinsLogic.listDrop` maps a gap to a place, in a folder or at the top level). A folder's row takes drops on its middle through an AppKit view (`FolderDropArea`), as the favorites do. Right-clicking the sidebar outside the rows, or the "New Tab" row, opens the Space header's menu (`SpaceHeaderView.menuItems`): a catcher behind the page, the "New Tab" row's own, and the list's table view's menu (`TableMenuInstaller`). Renaming is in place (`RenameField`) or, for favorites, a dialog (`PinDialogs`). `PinsMenu` adds Pin Tab (Cmd+D), New Folder… (its dialog is in `PinDialogs`), Back to Pinned URL, Close and Keep Pinned and Clear Today (Shift+Cmd+K) to Chromium's Tab menu, hiding Chromium's own Pin Tab, and Collapse Pinned Tabs to the View menu. The collapse and the empty favorites box are user defaults (`PinsPreferences`), and the Links toggle is `ClairPeekForOtherSites`. +- **`ClairUI` (D11).** `SpacesModel` caches each Space's pins and each profile's favorites; `BrowserWindowModel` copies the shown Space's and the profile's, and its `allTabs` adds their tabs to the Today tabs. The sidebar shows the favorites grid (`FavoritesGrid`, laid out by `FavoritesLayout`) above the Space pager, and one list of pinned rows (`PinRow`, and `FolderRow` with its tabs indented under it, flattened by `PinsLogic.pinnedRows`), the divider with Clear (`TodayDivider`), "New Tab" and the Today rows, which drag between sections (`TabList`'s `onMove` and `onInsert`, `SidebarDragItem`; `PinsLogic.listDrop` maps a gap to a place, in a folder or at the top level). A folder's row takes drops on its middle through an AppKit view (`FolderDropArea`), as the favorites do. Right-clicking the sidebar outside the rows, or the "New Tab" row, opens the Space header's menu (`SpaceHeaderView.menuItems`): a catcher behind the page, the "New Tab" row's own, and the list's table view's menu (`TableMenuInstaller`). Renaming is in place (`RenameField`) or, for favorites, a dialog (`PinDialogs`). The Tabs menu (`TabsMenu`, see The tab switcher and the Tabs menu below) has Pin Tab (Cmd+D), Pin to Favorites, New Folder… (its dialog is in `PinDialogs`) and Clear Unpinned Tabs (Shift+Cmd+K); `PinsMenu` adds Collapse Pinned Tabs to the View menu. The context menus are groups (`PinsLogic.joined`). The collapse and the empty favorites box are user defaults (`PinsPreferences`), and the Links toggle is `ClairPeekForOtherSites`. ## Link rules @@ -107,12 +107,21 @@ The archived `add-bookmarks-menu` change's `design.md` (`openspec/changes/archiv The `add-split-view` change's `design.md` (`openspec/changes/add-split-view/`) has the reasoning (D1–D13). A split is Chromium's own: two adjacent tabs of a `TabStripModel` in a split collection, with its `SplitTabId`, its ratio, and its pane order as the tabs' order. Session restore and tab restore keep splits without help. - **`ClairSplits` (D1, D4, D5, D12).** One per native window, beside `ClairPeeks`, in `clair_splits.{h,mm}`. It makes splits from two tabs (`Make`, after `ClairBrowserWindow::BringHere` has brought both into the window), from a tab and a new tab page (`MakeWithNewTab`), replaces a pane (`Replace`: Chromium's `kReplace` closes the replaced tab, so it ends the split and restores it with the same ID), swaps, separates and resizes, and observes `OnSplitTabChanged` to push the change to `ClairSpaceTabs` and `ClairPeeks`. A `FocusWatcher` on each pane activates it when its contents take focus, so a click in the other pane focuses it; the active tab's partner is marked visible with it (`UpdateVisibility`). When a pane closes, the other is activated. A split Chromium makes itself, as Open Link in Split View does, gets the clicked tab back in the leading pane (`LeadWith`), except while a session restores. -- **Rows and commands.** A split is one row: `ClairBrowserWindow::RowOf` maps a pane to the split's row tab, the leading pane in Today, the tab commands (Ctrl+Tab, Cmd+1…9, Close Tabs Below) count it once, and `ActivateRow` shows the pane focused last (`LastFocusedPane`). Cmd+W, a pane's × and a Today split chip's × close one pane (`CloseTab`); a pinned split's − closes both through `ExecuteCloseTabsCommand`, so tab restore records one split entry. A favorite's page in a split loads another site's URL from the command bar in its pane, not in a new Today tab (`clair::LeavesFavorite`). +- **Rows and commands.** A split is one row: `ClairBrowserWindow::RowOf` maps a pane to the split's row tab, the leading pane in Today, the tab commands (Next and Previous Tab, Cmd+1…9, Close Tabs Below) and the tab switcher count it once, and `ActivateRow` shows the pane focused last (`LastFocusedPane`). Cmd+W, a pane's × and a Today split chip's × close one pane (`CloseTab`); a pinned split's − closes both through `ExecuteCloseTabsCommand`, so tab restore records one split entry. A favorite's page in a split loads another site's URL from the command bar in its pane, not in a new Today tab (`clair::LeavesFavorite`). - **Peeks (D3, D11).** A pane's Peek sits after the whole split in the strip, since a tab inserted inside a split ends it (`ClairPeeks::PeekIndexFor`); focusing the other pane closes it. Open in Split View expands the Peek and splits it with its parent (`OpenPeekInSplit`). - **Option+click (D6).** `split-on-option-click.patch` makes Option without Shift give `NEW_SPLIT_VIEW` in Blink's `NavigationPolicyFromEventModifiers` and `ui::DispositionFromClick`, so a link isn't downloaded. `clair::MaybeOpenLink` (`clair_window_hooks.mm`, formerly `MaybeOpenPeek`) hands it to `ClairSplits::OpenLink`: a new background tab after the source and a split with it on a single page, the other pane on a split, the Peek itself in a Peek. The page's context menu keeps Chromium's Open Link in Split View. - **Across windows and Spaces (D7).** `ClairSpaceTabs` keeps a split's tabs together in the Space's list (`KeepSplitsTogether`, run for every changed list), and Move to Space moves both. Taking a split's row from another window moves the split collection whole (`MoveFamilyHere`, with `DetachSplitTabForInsertion` and `InsertDetachedSplitTabAt`), its Peeks with it. - **Pins (D10).** `clair::PinTab` pins a split as one item (`PinSplit`), and `OpenPin` on either of its pins opens the closed pages and shows them as a split with the saved ratio (`ShowPinnedSplit`). A restored split whose two tabs bind to one pinned split's pins is made again (`JoinPinnedSplit`). A ratio change of a pinned split is saved (`KeepPinnedRatio`). -- **`ClairUI` (D2, D3, D8, D9, D13).** `ClairTab` carries `splitPartnerID`, `isLeadingPane` and `splitRatio`; `TabListLogic.rows` folds the trailing pane into its leading pane's row, and `SplitLogic.shownSplit` gives the model's `shownSplit` (and `paneCount`). `BrowserRootView` lays out two `PageCardView`s with `SplitDividerView` between them, `PageDropView` over the page takes tabs dragged from the sidebar, and the overlays follow the focused pane. `PageToolbar` shows pane headers (`PageHeaderContent.pane`) and the split button (`SplitButton`), the sidebar shows `SplitRow` and the favorites `FavoriteSplitTile`, and `SplitMenu` adds Tabs › Split with Tab › and View › Add Split View (⌃⇧=), Close Split Pane (⌃⇧−) and Separate Tabs. The link status names a split or a Peek while Option or Shift is held (`SplitLogic.linkStatus`). +- **`ClairUI` (D2, D3, D8, D9, D13).** `ClairTab` carries `splitPartnerID`, `isLeadingPane` and `splitRatio`; `TabListLogic.rows` folds the trailing pane into its leading pane's row, and `SplitLogic.shownSplit` gives the model's `shownSplit` (and `paneCount`). `BrowserRootView` lays out two `PageCardView`s with `SplitDividerView` between them, `PageDropView` over the page takes tabs dragged from the sidebar, and the overlays follow the focused pane. `PageToolbar` shows pane headers (`PageHeaderContent.pane`) and the split button (`SplitButton`), the sidebar shows `SplitRow` and the favorites `FavoriteSplitTile`, `TabsMenu` has Tabs › Split with Tab ›, and `SplitMenu` adds View › Add Split View (⌃⇧=), Close Split Pane (⌃⇧−) and Separate Tabs. The link status names a split or a Peek while Option or Shift is held (`SplitLogic.linkStatus`). + +## The tab switcher and the Tabs menu + +The `add-tab-switcher-and-tabs-menu` change's `design.md` has the reasoning (D1–D8). + +- **Recents (D1).** Each window keeps `RecentTabs` in `BrowserWindowController+Switcher.swift`: row IDs, most recent first, a Peek counting as its parent and a split as its leading pane. `activeTabDidChange` moves the shown row to the front; a tab no list has yet waits for the list that adds it, so the still's placeholder never enters. Every list or pin change drops the tabs that closed, across Spaces and profiles (`switcherTabs`), and a window a profile swap brings in takes the outgoing window's list. +- **The keys (D2, D3).** `TabSwitcher` installs a local monitor for key-down, key-up and modifier changes. Ctrl+Tab and Ctrl+Shift+Tab open it while the window is key with no dialog or sheet; Tab and Shift+Tab step, Esc cancels, releasing Ctrl chooses the card (a modifier change always goes on to the page). `SwitcherState` holds the rules, the five cards and the panel's 100 ms delay. The panel (`TabSwitcherPanel`) is a borderless, non-activating child window laid out by `SwitcherLayout`; while it shows, a second monitor takes a left mouse down on a card. Choosing a tab calls `-[ClairBrowser showTab:]`, which activates the row (`ClairBrowserWindow::ShowTab`), switching Space, and for another profile's tab passes it through the group's swap (`ClairWindowGroup::ShowSpace`), so no other tab shows on the way. +- **Previews (D4).** As the active tab changes, `KeepPreviews` copies each page that stops being shown (`CopyPage`), cuts it to the card's 3:2 shape from the top at 315 pixels wide, and keeps it on its `WebContents` (`ClairTabPreview`). `-requestPreviewOfTab:size:completion:` copies a shown page live and returns the kept copy otherwise. +- **The Tabs menu (D5, D5a).** `InstallNativeWindowMenus` deletes Chromium's Tab menu (`IDC_TAB_MENU`) at start-up; `AppController`'s `TabMenuBridge` then fills nothing. `TabsMenu` goes before the Window menu: Pin Tab, Pin to Favorites, New Folder…, Next and Previous Tab (Chromium's `IDC_SELECT_NEXT_TAB` and `IDC_SELECT_PREVIOUS_TAB` through `commandDispatch:`), Split with Tab ›, Move to Space › and Clear Unpinned Tabs. The engine no longer handles commands only Chromium's Tab menu sent (Ctrl+Tab's cycle, Close Tabs to the Right, Close Other Tabs, a Peek's Duplicate Tab and Move Tab to New Window). ## Where each piece lives @@ -161,10 +170,12 @@ The `add-split-view` change's `design.md` (`openspec/changes/add-split-view/`) h | Profiles: the dialogs, Settings › Profiles, the Advanced toggles | `native/ClairUI/ProfileDialogs.swift`, `ProfilesSettingsView.swift`, `SettingsWindow.swift` | | Link rules: Settings › Links' card, the dialog and its checks | `native/ClairUI/SettingsWindow.swift`, `LinkRulesDialog.swift`, `LinkRulesLogic.swift` | | Split view: panes, divider, drops on the page, split row and tile, split button and menus | `native/ClairUI/SplitLogic.swift`, `SplitViews.swift`, `SplitMenu.swift`, `BrowserWindowController+Split.swift` | +| The tab switcher: recents, keys, panel and cards; the Tabs menu | `native/ClairUI/TabSwitcherLogic.swift`, `TabSwitcher.swift`, `BrowserWindowController+Switcher.swift`, `TabsMenu.swift` | +| Page previews for the tab switcher | `engine/overlay/chrome/browser/clair/window/clair_tab_preview.{h,mm}`, `clair_browser_window.{h,mm}` (`KeepPreviews`, `RequestPreview`) | | Command bar | `native/ClairUI/CommandBarModel.swift`, `OverlayViews.swift` | | The bookmark dialog, the Bookmarks Bar notice, Manage Bookmarks' title | `native/ClairUI/BookmarkDialog.swift`, `BookmarksBarNotice.swift`, `MainMenuTitles.swift` | | Unit tests against a fake Chromium | `native/ClairUITests/` (`FakeBrowser.swift`, `FakeHost.swift`) | -| Runtime tests on a packaged Clair | `tests/runtime/ClairRuntimeTests/NativeWindowTests.swift`, `SpacesTests.swift`, `SharedTabsTests.swift`, `ProfilesTests.swift`, `PinsTests.swift`, `LinkRulesTests.swift`, `BookmarksTests.swift`, `SplitViewTests.swift` | +| Runtime tests on a packaged Clair | `tests/runtime/ClairRuntimeTests/NativeWindowTests.swift`, `SpacesTests.swift`, `SharedTabsTests.swift`, `ProfilesTests.swift`, `PinsTests.swift`, `LinkRulesTests.swift`, `BookmarksTests.swift`, `SplitViewTests.swift`, `TabSwitcherTests.swift` | ## Working on it diff --git a/openspec/changes/add-tab-switcher-and-tabs-menu/tasks.md b/openspec/changes/add-tab-switcher-and-tabs-menu/tasks.md index 6e3a6b0a..775cea8f 100644 --- a/openspec/changes/add-tab-switcher-and-tabs-menu/tasks.md +++ b/openspec/changes/add-tab-switcher-and-tabs-menu/tasks.md @@ -68,7 +68,7 @@ Suggested order: ## 4. Probe tooling -- [ ] 4.1 Add `tests/probe/tools/keys.swift` (D8): steps `ctrldown`, `ctrlup`, `shiftdown`, `shiftup`, `tab`, `esc`, `sleep:` and `shot::`. Build it in `tools/build.sh`, and document it in the README beside `drag` and `mouse`. Verify by running `build/probe/bin/keys ctrldown tab sleep:0.5 shot:… ctrlup` against Arc and seeing the switcher in the shot. +- [x] 4.1 Add `tests/probe/tools/keys.swift` (D8): steps `ctrldown`, `ctrlup`, `shiftdown`, `shiftup`, `tab`, `esc`, `sleep:` and `shot::`. Build it in `tools/build.sh`, and document it in the README beside `drag` and `mouse`. Verify by running `build/probe/bin/keys ctrldown tab sleep:0.5 shot:… ctrlup` against Arc and seeing the switcher in the shot. ## 5. Runtime suite @@ -95,12 +95,12 @@ Suggested order: - no animation in a 60 fps recording. Record the numbers in `arc-reference/README.md` under "Clair", and fix any size or spacing more than 2 pt off Arc's. Check the panel's position against D3's rule (centred on the window, kept on screen), not Arc's absolute position. -- [ ] 6.2 Update the docs: +- [x] 6.2 Update the docs: - `docs/native-window.md`'s "Rows and commands" (Ctrl+Tab leaves the row commands; the switcher and its previews get a short section); - `docs/building.md`'s "Updating the engine" gains a note to grep Chromium for new `IDC_TAB_MENU` users (design "Risks"). Verify by reading both pages. -- [ ] 6.3 Add a Changie fragment (`changie new`) for the switcher, the Tabs menu and the tab menus. Verify that `.changes/unreleased/` holds it. +- [x] 6.3 Add a Changie fragment (`changie new`) for the switcher, the Tabs menu and the tab menus. Verify that `.changes/unreleased/` holds it. - [ ] 6.4 Run CI and `quality.yml` on the last push together, with every note in that push. Verify that both pass. ## Workflow follow-up diff --git a/tests/probe/README.md b/tests/probe/README.md index 36e86062..a72f529f 100644 --- a/tests/probe/README.md +++ b/tests/probe/README.md @@ -118,7 +118,8 @@ build/probe/bin/measure track build/probe/rec/peek/frames white 0 0 2400 2012 80 use (or by `tools/build.sh`); each describes its arguments at the top: `windows` (window IDs and frames, by app name or process ID), `drag` (a drag with real mouse events, in screen points), `mouse` (a real pointer move, double-click or - click, in screen points), `cdp` (DevTools + click, in screen points), `keys` (real key events with Ctrl and Shift held + across steps, and screenshots between them), `cdp` (DevTools protocol commands for the test copy), `frames` (a movie's frames), `sheet` (a labelled contact sheet), `crop` (a pixel rectangle; `sips --cropOffset` centres instead), and `measure`: @@ -206,6 +207,12 @@ These come from the add-peek change (its design.md has the numbers): coordinates (and `click-element.sh`'s) start at its corner, and its `hover` doesn't bring up a sidebar row's close button. Use `build/probe/bin/mouse move|click x y` in screen points instead. +- **Held modifiers**: the probe's `key` releases its modifiers after each key, + so it can't hold Ctrl across Tabs for the tab switcher. Use + `build/probe/bin/keys` after `activate`, for example + `keys ctrldown tab sleep:0.5 shot:build/probe/s.png:0,30,963,976 tab ctrlup`: + `shot:` captures a screen rectangle in points while Ctrl is still held, and + the tool lets go of Ctrl and Shift at the end. Arc takes these events. - **Read a frame before clicking**: a button can disappear after the click, failing a later query. - **The emoji picker takes typing.** A field that opens macOS's emoji picker, diff --git a/tests/probe/tools/keys.swift b/tests/probe/tools/keys.swift new file mode 100644 index 00000000..e61bcfe7 --- /dev/null +++ b/tests/probe/tools/keys.swift @@ -0,0 +1,124 @@ +// Copyright 2026 The Clair Authors +// You can use, redistribute, and/or modify this source code under +// the terms of the GPL-3.0 license that can be found in the LICENSE file. + +// keys ... +// +// Posts real key events, with Ctrl and Shift held across steps, which +// XCUITest's typeKey can't do: it lets go of its modifiers after each key. +// For Ctrl+Tab's switcher (add-tab-switcher-and-tabs-menu design D8), in Arc +// and in Clair. The steps run in order: +// +// ctrldown, ctrlup press or release Control +// shiftdown, shiftup press or release Shift +// tab, esc press and release Tab or Esc, with what's held +// sleep: wait, such as sleep:0.5 +// shot:: capture a screen rectangle in points to +// +// For example: keys ctrldown tab sleep:0.5 shot:build/probe/s.png:0,0,963,1006 ctrlup +// +// A step that holds a key and no step that lets it go leaves it held: the +// tool releases Control and Shift at the end. Like `drag` and `mouse`, the +// shell needs permission to post events (Privacy & Security > Accessibility). +// Bring the app forward first (`probe.sh send activate`): the keys go to +// whatever app is active. + +import CoreGraphics +import Foundation + +let controlKey: CGKeyCode = 59 +let shiftKey: CGKeyCode = 56 +let tabKey: CGKeyCode = 48 +let escapeKey: CGKeyCode = 53 + +func fail(_ message: String, status: Int32 = 2) -> Never { + FileHandle.standardError.write("keys: \(message)\n".data(using: .utf8)!) + exit(status) +} + +let steps = Array(CommandLine.arguments.dropFirst()) +guard !steps.isEmpty else { + fail("usage: keys ctrldown|ctrlup|shiftdown|shiftup|tab|esc|sleep:|shot::...") +} +guard CGPreflightPostEventAccess() else { + fail("this shell may not post events (Privacy & Security > Accessibility)", status: 1) +} + +// Every step is checked before any key goes, so a wrong one leaves nothing +// held. +func isValid(_ step: String) -> Bool { + if ["ctrldown", "ctrlup", "shiftdown", "shiftup", "tab", "esc"].contains(step) { return true } + if step.hasPrefix("sleep:") { return Double(step.dropFirst("sleep:".count)).map { $0 >= 0 } ?? false } + if step.hasPrefix("shot:") { + let parts = step.dropFirst("shot:".count).split(separator: ":", maxSplits: 1) + return parts.count == 2 && !parts[0].isEmpty && parts[1].split(separator: ",").compactMap { Double($0) }.count == 4 + } + return false +} +if let wrong = steps.first(where: { !isValid($0) }) { + fail("unknown step \(wrong)") +} + +var held: CGEventFlags = [] +let source = CGEventSource(stateID: .hidSystemState) + +func post(_ key: CGKeyCode, down: Bool) { + let event = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: down) + event?.flags = held + event?.post(tap: .cghidEventTap) + usleep(15_000) +} + +func modifier(_ key: CGKeyCode, _ flag: CGEventFlags, down: Bool) { + if down { held.insert(flag) } else { held.remove(flag) } + post(key, down: down) +} + +func press(_ key: CGKeyCode) { + post(key, down: true) + usleep(30_000) + post(key, down: false) +} + +/// screencapture's rectangle, from "x,y,w,h" in points. +func shoot(_ argument: Substring) { + let parts = argument.split(separator: ":", maxSplits: 1) + let numbers = parts.count == 2 ? parts[1].split(separator: ",").compactMap { Double($0) } : [] + guard parts.count == 2, !parts[0].isEmpty, numbers.count == 4 else { + fail("shot needs :, got \(argument)") + } + let rect = numbers.map { String(Int($0.rounded())) }.joined(separator: ",") + let capture = Process() + capture.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture") + capture.arguments = ["-x", "-R", rect, String(parts[0])] + do { + try capture.run() + capture.waitUntilExit() + } catch { + fail("screencapture didn't run: \(error)", status: 1) + } + guard capture.terminationStatus == 0 else { fail("screencapture failed", status: 1) } +} + +for step in steps { + switch step { + case "ctrldown": modifier(controlKey, .maskControl, down: true) + case "ctrlup": modifier(controlKey, .maskControl, down: false) + case "shiftdown": modifier(shiftKey, .maskShift, down: true) + case "shiftup": modifier(shiftKey, .maskShift, down: false) + case "tab": press(tabKey) + case "esc": press(escapeKey) + default: + if step.hasPrefix("sleep:"), let seconds = Double(step.dropFirst("sleep:".count)), seconds >= 0 { + usleep(useconds_t(seconds * 1_000_000)) + } else if step.hasPrefix("shot:") { + shoot(step.dropFirst("shot:".count)) + } else { + fail("unknown step \(step)") + } + } +} + +// Nothing stays held once the tool is done. +if held.contains(.maskShift) { modifier(shiftKey, .maskShift, down: false) } +if held.contains(.maskControl) { modifier(controlKey, .maskControl, down: false) } diff --git a/tests/runtime/ClairRuntimeTests/FoldersTests.swift b/tests/runtime/ClairRuntimeTests/FoldersTests.swift index 90fecb74..a0ca7dc4 100644 --- a/tests/runtime/ClairRuntimeTests/FoldersTests.swift +++ b/tests/runtime/ClairRuntimeTests/FoldersTests.swift @@ -193,7 +193,7 @@ extension Browser { /// Tabs › New Folder…, named `name` in its dialog. func newFolderFromTabMenu(_ name: String) throws { try tabMenuItem("New Folder…").click() - try require(dialog.waitForExistence(timeout: 10), "Tab › New Folder… opened no dialog") + try require(dialog.waitForExistence(timeout: 10), "Tabs › New Folder… opened no dialog") let field = element("clair.newFolderField", in: dialog) try require(field.waitForExistence(timeout: 5), "The New Folder dialog has no field") ui.typeText("\(name)\r") @@ -227,7 +227,7 @@ final class FoldersTests: NativeWindowTestCase { return tabs } - /// Creating through the plus menu and Tab › New Folder…, renaming, + /// Creating through the plus menu and Tabs › New Folder…, renaming, /// closing, and the tab commands over a closed and an open folder, across /// a relaunch (tab-folders spec, "Creating a folder in place", "New Folder /// dialog", "Opening and closing a folder", "Folders after a relaunch"; @@ -252,7 +252,7 @@ final class FoldersTests: NativeWindowTestCase { try browser.newFolderFromTabMenu("Inbox") let inbox = await browser.waitForPinnedSection { $0 == order + ["[Trip]", "[Inbox]"] } - try require(inbox, "Tab › New Folder… didn't add Inbox last: \(browser.pinnedSection)") + try require(inbox, "Tabs › New Folder… didn't add Inbox last: \(browser.pinnedSection)") try browser.choose("Rename…", inMenuOf: browser.folderRow("Inbox")) let field = browser.element("clair.renameField") diff --git a/tests/runtime/ClairRuntimeTests/PinsTests.swift b/tests/runtime/ClairRuntimeTests/PinsTests.swift index 4e43b74b..2054de47 100644 --- a/tests/runtime/ClairRuntimeTests/PinsTests.swift +++ b/tests/runtime/ClairRuntimeTests/PinsTests.swift @@ -43,14 +43,15 @@ extension Browser { await Harness.wait(for: seconds) { condition(self.favoriteTitles) } } - var tabMenu: XCUIElement { ui.menuBars.menuBarItems["Tab"] } + /// Clair's Tabs menu (add-tab-switcher-and-tabs-menu D5). + var tabMenu: XCUIElement { ui.menuBars.menuBarItems["Tabs"] } - /// A Tab menu item, opened and read; Esc closes the menu again. + /// A Tabs menu item, opened and read; Esc closes the menu again. func tabMenuItem(_ title: String) throws -> XCUIElement { - try require(tabMenu.waitForExistence(timeout: 30), "The menu bar has no Tab menu") + try require(tabMenu.waitForExistence(timeout: 30), "The menu bar has no Tabs menu") tabMenu.click() let item = tabMenu.menuItems[title] - try require(item.waitForExistence(timeout: 5), "The Tab menu has no \(title)") + try require(item.waitForExistence(timeout: 5), "The Tabs menu has no \(title)") return item } @@ -81,8 +82,8 @@ final class PinsTests: NativeWindowTestCase { } /// A pin's life: pinning keeps the page; Cmd+1 counts the pin first and - /// opens it when closed; Cmd+W closes its page and keeps it; Clear Today - /// leaves it; × removes it, open or closed, and Restore Last Closed Tab + /// opens it when closed; Cmd+W closes its page and keeps it; Clear + /// Unpinned Tabs leaves it; × removes it, open or closed, and Restore Last Closed Tab /// brings it back as it was; a tab's name survives navigation and pinning; /// and unpinning and Pin to Favorites keep the page. func testPinLifecycle() async throws { @@ -91,9 +92,11 @@ final class PinsTests: NativeWindowTestCase { XCTAssertFalse(browser.tabTitles.contains(pinsTitle), "The pinned tab stayed among the Today tabs") let open = try await browser.target(endingWith: "pins.html") XCTAssertNotNil(open, "Pinning closed the page") + // tabs-menu, "The menu bar": Clair's Tabs menu, and no Chromium Tab menu. let unpin = try browser.tabMenuItem("Unpin Tab") - XCTAssertTrue(unpin.isEnabled, "Tab › Unpin Tab is off on a pinned tab") + XCTAssertTrue(unpin.isEnabled, "Tabs › Unpin Tab is off on a pinned tab") browser.ui.typeKey(.escape, modifierFlags: []) + XCTAssertFalse(browser.ui.menuBars.menuBarItems["Tab"].exists, "The menu bar still has Chromium's Tab menu") // Cmd+1 counts the pinned tab first; Cmd+W closes its page, keeps the pin // and shows the tab it was selected from; Cmd+1 then opens it again. @@ -118,13 +121,13 @@ final class PinsTests: NativeWindowTestCase { let opened = await browser.waitForTarget("pins.html") XCTAssertTrue(opened, "Cmd+1 didn't open the pinned tab") - // Clear Today closes the Today tabs only. - let clear = try browser.tabMenuItem("Clear Today") - XCTAssertTrue(clear.isEnabled, "Clear Today is off with Today tabs") + // Clear Unpinned Tabs closes the Today tabs only. + let clear = try browser.tabMenuItem("Clear Unpinned Tabs") + XCTAssertTrue(clear.isEnabled, "Clear Unpinned Tabs is off with Today tabs") clear.click() let cleared = await browser.waitForTabs { !$0.contains("Counter a") && !$0.contains("Counter b") } - XCTAssertTrue(cleared, "Clear Today left Today tabs: \(browser.tabTitles)") - XCTAssertEqual(browser.pinTitles, [pinsTitle], "Clear Today touched the pinned tab") + XCTAssertTrue(cleared, "Clear Unpinned Tabs left Today tabs: \(browser.tabTitles)") + XCTAssertEqual(browser.pinTitles, [pinsTitle], "Clear Unpinned Tabs touched the pinned tab") browser.ui.typeKey("t", modifierFlags: [.command, .shift]) let one = await browser.waitForTabs { $0.contains("Counter a") || $0.contains("Counter b") } try require(one, "Restore Last Closed Tab didn't bring back a Today tab") @@ -228,7 +231,8 @@ final class PinsTests: NativeWindowTestCase { XCTAssertTrue(shown, "The navigated row doesn't show the page's title: \(browser.pinTitles)") XCTAssertTrue(browser.element("clair.backToPinnedURL").waitForExistence(timeout: 5), "No Back to Pinned URL") let history = try await tab.evaluate("history.length") as? Int ?? 0 - try browser.tabMenuItem("Back to Pinned URL").click() + // The row's icon. + browser.element("clair.backToPinnedURL").click() let returned = await Harness.wait(for: 15) { try await tab.evaluate("location.pathname") as? String == "/pages/pins.html" } @@ -264,7 +268,14 @@ final class PinsTests: NativeWindowTestCase { field.typeText(url("pins.html?edited")) browser.ui.buttons["clair.dialogDefault"].click() try await Task.sleep(for: .seconds(1)) - try browser.tabMenuItem("Back to Pinned URL").click() + // Edit Pinned Page › Back to Pinned URL (add-tab-switcher-and-tabs-menu + // D6). + browser.pinRow("Clair pins guide").rightClick() + browser.ui.menuItems["Edit Pinned Page"].hover() + let backItem = browser.ui.menuItems["Back to Pinned URL"] + try require(backItem.waitForExistence(timeout: 5), "Edit Pinned Page has no Back to Pinned URL") + XCTAssertTrue(backItem.isEnabled, "Back to Pinned URL is off on a page away from its pinned URL") + backItem.click() let edited = await browser.waitForTarget("pins.html?edited") try require(edited, "Back to Pinned URL didn't load the edited URL") @@ -308,7 +319,9 @@ final class PinsTests: NativeWindowTestCase { XCTAssertFalse(browser.peek.exists, "A scripted navigation opened a Peek") // With the toggle off on Settings' Links page, the pinned tab navigates. - try browser.tabMenuItem("Back to Pinned URL").click() + let away = browser.element("clair.backToPinnedURL") + try require(away.waitForExistence(timeout: 10), "The navigated pinned tab shows no Back to Pinned URL") + away.click() let returnedAgain = await Harness.wait(for: 15) { try await tab.evaluate("location.search") as? String == "?edited" } diff --git a/tests/runtime/ClairRuntimeTests/SpacesTests.swift b/tests/runtime/ClairRuntimeTests/SpacesTests.swift index 4fb0918c..833df33e 100644 --- a/tests/runtime/ClairRuntimeTests/SpacesTests.swift +++ b/tests/runtime/ClairRuntimeTests/SpacesTests.swift @@ -59,13 +59,8 @@ extension Browser { } } -/// Spaces (add-spaces task 3.11), driven through the sidebar, the menu bar -/// and the keyboard, with a counter page whose state shows that a tab kept -/// its page. @MainActor -final class SpacesTests: NativeWindowTestCase { - func counter(_ name: String) -> String { url("counter.html?\(name)") } - +extension NativeWindowTestCase { /// Creates a Space from the Spaces menu or the footer's plus menu. func createSpace(_ name: String, in browser: Browser, fromPlusMenu: Bool = false) async throws { if fromPlusMenu { @@ -90,6 +85,14 @@ final class SpacesTests: NativeWindowTestCase { // The new Space opens on a new tab page with the command bar; close it. browser.ui.typeKey(.escape, modifierFlags: []) } +} + +/// Spaces (add-spaces task 3.11), driven through the sidebar, the menu bar +/// and the keyboard, with a counter page whose state shows that a tab kept +/// its page. +@MainActor +final class SpacesTests: NativeWindowTestCase { + func counter(_ name: String) -> String { url("counter.html?\(name)") } /// The first launch has one Space and no switcher; a Space made from the /// plus menu joins the switcher; tab commands stay in the shown Space; and diff --git a/tests/runtime/ClairRuntimeTests/SplitViewTests.swift b/tests/runtime/ClairRuntimeTests/SplitViewTests.swift index 9c2c43e5..16e011c7 100644 --- a/tests/runtime/ClairRuntimeTests/SplitViewTests.swift +++ b/tests/runtime/ClairRuntimeTests/SplitViewTests.swift @@ -33,15 +33,15 @@ extension Browser { /// Chooses `title` in Tabs › Split with Tab ›. func splitWithTabFromMenuBar(_ title: String) throws { let submenu = try tabMenuItem("Split with Tab") - try require(submenu.isEnabled, "Tab › Split with Tab is off") + try require(submenu.isEnabled, "Tabs › Split with Tab is off") submenu.hover() let item = submenu.menuItems[title] - try require(item.waitForExistence(timeout: 5), "Tab › Split with Tab has no \(title)") + try require(item.waitForExistence(timeout: 5), "Tabs › Split with Tab has no \(title)") item.click() } /// Chooses `title` in a row's Split with Tab › menu: the context menu's, - /// not the Tab menu's item of the same title. + /// not the Tabs menu's item of the same title. func splitWithTab(_ title: String, inMenuOf row: XCUIElement) throws { row.rightClick() let found = visibleMenuItem("Split with Tab") diff --git a/tests/runtime/ClairRuntimeTests/TabSwitcherTests.swift b/tests/runtime/ClairRuntimeTests/TabSwitcherTests.swift new file mode 100644 index 00000000..e510a25f --- /dev/null +++ b/tests/runtime/ClairRuntimeTests/TabSwitcherTests.swift @@ -0,0 +1,204 @@ +// Copyright 2026 The Clair Authors +// You can use, redistribute, and/or modify this source code under +// the terms of the GPL-3.0 license that can be found in the LICENSE file. + +import AppKit +import Foundation +import XCTest + +extension Browser { + /// Ctrl+Tab's panel, a window of its own over the browser window + /// (add-tab-switcher-and-tabs-menu D7). + var tabSwitcher: XCUIElement { ui.descendants(matching: .any)["clair.tabSwitcher"].firstMatch } + + /// The switcher's cards, left to right. + var switcherCards: [XCUIElement] { + ui.descendants(matching: .any).matching(identifier: "clair.tabSwitcherCard").allElementsBoundByIndex + } + + /// A row's context menu's items, "|" for a divider, read and closed again. + func menuTitles(of row: XCUIElement) -> [String] { + row.rightClick() + defer { ui.typeKey(.escape, modifierFlags: []) } + let menu = ui.menus.containing(NSPredicate(format: "title == 'Copy Link'")).firstMatch + guard menu.waitForExistence(timeout: 5) else { return [] } + var titles = menu.children(matching: .menuItem).allElementsBoundByIndex.map { $0.title.isEmpty ? "|" : $0.title } + // AppKit appends a section of its own to a context menu, whose items + // are hidden but whose divider XCUITest lists. + while titles.last == "|" { titles.removeLast() } + return titles + } +} + +/// Ctrl+Tab's switcher and the tab menus (add-tab-switcher-and-tabs-menu +/// tasks 5.2 to 5.4), driven with Ctrl held through XCUITest. +@MainActor +final class TabSwitcherTests: NativeWindowTestCase { + func counter(_ name: String) -> String { url("counter.html?\(name)") } + + /// What the switcher shows while Ctrl is held after `tabs` Tabs: whether it + /// appeared, its cards' labels, and the selected card's index. `then` + /// runs before Ctrl is let go; a key it types must say Control too. + func holdingCtrl( + _ browser: Browser, tabs: Int = 1, then: (Browser) -> Void = { _ in } + ) -> (appeared: Bool, labels: [String], selected: Int?) { + var result: (appeared: Bool, labels: [String], selected: Int?) = (false, [], nil) + XCUIElement.perform(withKeyModifiers: .control) { + // Each key says Control itself: inside the block, a key typed with + // no modifiers lets go of Control first, which chooses the card. + for _ in 0.. 2 { cards[2].click() } + } + shown = await browser.waitForActiveRow("Counter a") + XCTAssertTrue(shown, "Clicking a card didn't show its tab: \(browser.activeRow ?? "none")") + + // Opt+Cmd+Down still steps through the rows (c, b, a top down), and the + // tab it shows becomes the most recent. + browser.tabRow("Counter c")?.click() + _ = await browser.waitForActiveRow("Counter c") + browser.ui.typeKey(.downArrow, modifierFlags: [.command, .option]) + shown = await browser.waitForActiveRow("Counter b") + XCTAssertTrue(shown, "Opt+Cmd+Down didn't select the next row") + browser.ui.typeKey(.upArrow, modifierFlags: [.command, .option]) + shown = await browser.waitForActiveRow("Counter c") + XCTAssertTrue(shown, "Opt+Cmd+Up didn't select the previous row") + browser.ui.typeKey(.tab, modifierFlags: .control) + shown = await browser.waitForActiveRow("Counter b") + XCTAssertTrue(shown, "Ctrl+Tab after Opt+Cmd+Up didn't go back to the row Next Tab showed") + browser.ui.typeKey("1", modifierFlags: .command) + shown = await browser.waitForActiveRow("Counter c") + XCTAssertTrue(shown, "Cmd+1 didn't select the first row") + + // Close Tabs Below, from the row's menu, still closes the rows below. + try browser.chooseOnScreen("Close Tabs Below", inMenuOf: try XCTUnwrap(browser.tabRow("Counter b"))) + let below = await browser.waitForTabs { !$0.contains("Counter a") } + XCTAssertTrue(below, "Close Tabs Below left Counter a: \(browser.tabTitles)") + } + + /// tab-switcher, "Another Space": a tab shown in another Space comes back + /// with Ctrl+Tab, and the window shows its Space. + func testCtrlTabGoesBackToAnotherSpace() async throws { + let (browser, home) = try await startWithPage("counter.html?home") + defer { home.close() } + _ = await browser.waitForActiveRow("Counter home") + try await createSpace("Work", in: browser) + let work = try await browser.open(counter("work")) + defer { work.close() } + _ = await browser.waitForActiveRow("Counter work") + // Work's new tab page goes, leaving Counter work and then Counter home. + browser.tabRow("New Tab")?.click() + if browser.tabTitles.contains("New Tab") { + browser.ui.typeKey("w", modifierFlags: .command) + } + let alone = await browser.waitForTabs { $0 == ["Counter work"] } + try require(alone, "Work doesn't list its one tab: \(browser.tabTitles)") + _ = await browser.waitForActiveRow("Counter work") + + browser.ui.typeKey(.tab, modifierFlags: .control) + let atHome = await browser.waitForSpace("Home") + XCTAssertTrue(atHome, "Ctrl+Tab didn't switch the window to Home: \(browser.spaceName)") + let shown = await browser.waitForActiveRow("Counter home") + XCTAssertTrue(shown, "Ctrl+Tab didn't show Counter home: \(browser.activeRow ?? "none")") + browser.ui.typeKey(.tab, modifierFlags: .control) + let back = await browser.waitForSpace("Work") + XCTAssertTrue(back, "A second Ctrl+Tab didn't go back to Work") + } + + /// sidebar, "Today tab's menu", and pinned-tabs, "From its menu": the + /// menus' groups in order, and a pinned tab's Close Tab keeps its row. + func testTabMenusAndClosingAPinnedTab() async throws { + let (browser, a) = try await startWithPage("counter.html?a") + let b = try await browser.open(counter("b")) + defer { + a.close() + b.close() + } + _ = await browser.waitForActiveRow("Counter b") + let today = try XCTUnwrap(browser.tabRow("Counter a"), "No row for Counter a") + XCTAssertEqual( + browser.menuTitles(of: today), + [ + "Pin Tab", "Pin to Favorites", "|", "Copy Link", "Duplicate", "|", "Split with Tab", "|", "Rename…", "Mute", + "|", "Close Tab", "Close Tabs Below", + ], + "The Today tab's menu isn't in its groups") + + // Pinned, open and not shown, its menu ends with Close Tab, which closes + // its page and keeps its row. + try browser.chooseOnScreen("Pin Tab", inMenuOf: today) + let pinned = await browser.waitForPins { $0 == ["Counter a"] } + try require(pinned, "Pin Tab didn't pin Counter a: \(browser.pinTitles)") + browser.tabRow("Counter b")?.click() + _ = await browser.waitForActiveRow("Counter b") + let pin = browser.pinRow("Counter a") + XCTAssertEqual( + browser.menuTitles(of: pin), + [ + "Unpin Tab", "Pin to Favorites", "|", "Copy Link", "Duplicate", "|", "Split with Tab", "|", "Rename…", "Mute", + "Edit Pinned Page", "|", "Close Tab", + ], + "The pinned tab's menu isn't in its groups") + try browser.chooseOnScreen("Close Tab", inMenuOf: pin) + let closed = await browser.waitForTarget("counter.html?a", open: false) + XCTAssertTrue(closed, "Close Tab didn't close the pinned tab's page") + XCTAssertEqual(browser.pinTitles, ["Counter a"], "Close Tab removed the pin") + XCTAssertEqual(browser.activeRow, "Counter b", "Closing a pinned tab that isn't shown changed the tab") + } +} From 69cd6f0e145797327f588958ceee62dab7797ddd Mon Sep 17 00:00:00 2001 From: Joshua Park Date: Fri, 27 Nov 2026 02:29:15 -0500 Subject: [PATCH 4/8] test: follow the Tabs menu and Ctrl+Tab's recents in the runtime suite --- .../ClairRuntimeTests/FoldersTests.swift | 6 ++--- .../runtime/ClairRuntimeTests/PeekTests.swift | 24 ++++++++----------- .../runtime/ClairRuntimeTests/PinsTests.swift | 8 +++---- .../ClairRuntimeTests/ProfilesTests.swift | 6 +++-- .../ClairRuntimeTests/SplitViewTests.swift | 9 +++---- 5 files changed, 25 insertions(+), 28 deletions(-) diff --git a/tests/runtime/ClairRuntimeTests/FoldersTests.swift b/tests/runtime/ClairRuntimeTests/FoldersTests.swift index a0ca7dc4..3d8d2c7c 100644 --- a/tests/runtime/ClairRuntimeTests/FoldersTests.swift +++ b/tests/runtime/ClairRuntimeTests/FoldersTests.swift @@ -392,8 +392,8 @@ final class FoldersTests: NativeWindowTestCase { browser.ui.typeKey("1", modifierFlags: .control) _ = await browser.waitForSpace("Home") browser.folderRow("Docs").rightClick() - let move = browser.ui.menuItems["Move to Space"] - try require(move.waitForExistence(timeout: 5), "The folder's menu has no Move to Space with two Spaces") + // The menu's own item: the Tabs menu has one of the same title. + let move = try XCTUnwrap(browser.visibleMenuItem("Move to Space"), "The folder's menu has no Move to Space with two Spaces") move.click() try require(browser.visibleMenuItem("Work") != nil, "Move to Space has no Work") browser.visibleMenuItem("Work")?.click() @@ -473,7 +473,7 @@ final class FoldersTests: NativeWindowTestCase { let up = await browser.waitForPinnedSection { $0.prefix(2) == ["Counter end4", "Counter end3"] } try require(up, "Ctrl+Shift+PageUp didn't move End 4 up: \(browser.pinnedSection)") browser.folderRow("Trip").rightClick() - browser.ui.menuItems["Move to Space"].click() + browser.visibleMenuItem("Move to Space")?.click() try require(browser.visibleMenuItem("Work") != nil, "Move to Space has no Work") browser.visibleMenuItem("Work")?.click() _ = await Harness.wait(for: 10) { browser.folderNames.isEmpty } diff --git a/tests/runtime/ClairRuntimeTests/PeekTests.swift b/tests/runtime/ClairRuntimeTests/PeekTests.swift index 31f78e61..1418ac35 100644 --- a/tests/runtime/ClairRuntimeTests/PeekTests.swift +++ b/tests/runtime/ClairRuntimeTests/PeekTests.swift @@ -120,11 +120,12 @@ final class PeekTests: NativeWindowTestCase { XCTAssertEqual(parentVisibility, "visible", "The parent page isn't visible behind its Peek") XCTAssertEqual(peekVisibility, "visible", "The Peek's page isn't visible") - // Ctrl+Tab moves on to the next row and leaves the Peek open; both pages - // are hidden, and selecting the parent's row shows the Peek again. + // Ctrl+Tab goes back to the tab shown before, the other page, and leaves + // the Peek open; both pages are hidden, and selecting the parent's row + // shows the Peek again. browser.ui.typeKey(.tab, modifierFlags: .control) let switched = await Harness.wait(for: 15) { try await browser.visibility(of: other) == "visible" } - XCTAssertTrue(switched, "Ctrl+Tab didn't select the next row") + XCTAssertTrue(switched, "Ctrl+Tab didn't go back to the tab shown before") parentVisibility = try await browser.visibility(of: links) peekVisibility = try await browser.visibility(of: peek) XCTAssertEqual(parentVisibility, "hidden", "The parent page is still visible behind another tab") @@ -215,7 +216,7 @@ final class PeekTests: NativeWindowTestCase { XCTAssertTrue(peekClosed, "Closing the parent left its Peek open") } - func testThePeekComesBackSurvivesACancelledCloseAndStaysBehindAMove() async throws { + func testThePeekComesBackSurvivesACancelledCloseAndMovesWithItsTab() async throws { let (browser, links, other) = try await startWithLinks() defer { links.close() @@ -261,18 +262,13 @@ final class PeekTests: NativeWindowTestCase { XCTAssertTrue(browser.peek.waitForExistence(timeout: 15), "The parent's row doesn't show its Peek after staying") _ = try await asking.evaluate("window.guard = false; 1") - // Move Tab to New Window moves the parent alone and closes its Peek. - browser.ui.menuItems["Move Tab to New Window"].click() - let moved = await Harness.wait(for: 15) { try await browser.windowCount() == 2 } - XCTAssertTrue(moved, "Move Tab to New Window didn't open a window") - let peekGone = await browser.waitForTarget("?plain", open: false) - XCTAssertTrue(peekGone, "The Peek stayed behind after its parent moved") - let parentOpen = try await browser.target(endingWith: "peek.html") != nil - XCTAssertTrue(parentOpen, "Moving the parent closed it") - // With another window open, closing the parent's window keeps the parent // and its Peek in the other (share-tabs-across-windows D4). - try await openPeek("plain", in: links, browser: browser, suffix: "?plain") + let second = try await browser.open(url("index.html?second"), newWindow: true) + defer { second.close() } + _ = try await browser.waitForNativeWindows(2) + _ = try await links.send("Page.bringToFront", [:]) + try await Task.sleep(for: .seconds(1)) browser.ui.typeKey("w", modifierFlags: [.command, .shift]) let oneWindow = await Harness.wait(for: 15) { try await browser.windowCount() == 1 } try require(oneWindow, "Cmd+Shift+W didn't close the parent's window") diff --git a/tests/runtime/ClairRuntimeTests/PinsTests.swift b/tests/runtime/ClairRuntimeTests/PinsTests.swift index 2054de47..25b6f663 100644 --- a/tests/runtime/ClairRuntimeTests/PinsTests.swift +++ b/tests/runtime/ClairRuntimeTests/PinsTests.swift @@ -55,12 +55,10 @@ extension Browser { return item } - /// Chooses an item of a row's context menu. + /// Chooses an item of a row's context menu, the one on screen: the Tabs + /// menu has items of the same titles, as Pin to Favorites. func choose(_ title: String, inMenuOf row: XCUIElement) throws { - row.rightClick() - let item = ui.menuItems[title] - try require(item.waitForExistence(timeout: 5), "The menu has no \(title)") - item.click() + try chooseOnScreen(title, inMenuOf: row) } } diff --git a/tests/runtime/ClairRuntimeTests/ProfilesTests.swift b/tests/runtime/ClairRuntimeTests/ProfilesTests.swift index 6ce7453d..00651221 100644 --- a/tests/runtime/ClairRuntimeTests/ProfilesTests.swift +++ b/tests/runtime/ClairRuntimeTests/ProfilesTests.swift @@ -333,8 +333,10 @@ final class ProfilesTests: NativeWindowTestCase { func moveRow(_ title: String, to space: String, in browser: Browser) async throws { browser.tabRow(title)?.rightClick() - let move = browser.ui.menuItems["Move to Space"] - try require(move.waitForExistence(timeout: 5), "\(title) has no Move to Space") + // The row's menu's own item: the Tabs menu has one of the same title. + let found = browser.visibleMenuItem("Move to Space") + try require(found != nil, "\(title) has no Move to Space") + let move = try XCTUnwrap(found) move.hover() // The submenu's own item: the Spaces menu has one of the same title. let item = move.menuItems[space] diff --git a/tests/runtime/ClairRuntimeTests/SplitViewTests.swift b/tests/runtime/ClairRuntimeTests/SplitViewTests.swift index 16e011c7..6fd05c22 100644 --- a/tests/runtime/ClairRuntimeTests/SplitViewTests.swift +++ b/tests/runtime/ClairRuntimeTests/SplitViewTests.swift @@ -159,8 +159,9 @@ final class SplitViewTests: NativeWindowTestCase { let pagesAfter = try await browser.pageCount() XCTAssertEqual(pagesAfter, pages, "Add Split View opened a page while split") - // Ctrl+Tab leaves the split, both pages hidden, and Ctrl+Shift+Tab comes - // back to it in one stop, both visible. + // Ctrl+Tab leaves the split for the tab shown before it, both pages + // hidden, and Ctrl+Tab again comes back to it in one stop, both visible + // (split-view, "Tab commands treat a split as one row"). browser.ui.typeKey(.tab, modifierFlags: .control) let left = await Harness.wait(for: 15) { let leading = try await browser.visibility(of: links) @@ -168,13 +169,13 @@ final class SplitViewTests: NativeWindowTestCase { return leading == "hidden" && trailing == "hidden" } XCTAssertTrue(left, "Ctrl+Tab didn't leave the split, or left a pane visible") - browser.ui.typeKey(.tab, modifierFlags: [.control, .shift]) + browser.ui.typeKey(.tab, modifierFlags: .control) let back = await Harness.wait(for: 15) { let leading = try await browser.visibility(of: links) let trailing = try await browser.visibility(of: counter) return leading == "visible" && trailing == "visible" } - XCTAssertTrue(back, "Ctrl+Shift+Tab didn't come back to the split in one stop") + XCTAssertTrue(back, "Ctrl+Tab didn't come back to the split in one stop") // Separate Tabs from the View menu: two rows in pane order. try browser.chooseViewItem("Separate Tabs") From 644794d382f05bb19fbe68f878dcd905f7296689 Mon Sep 17 00:00:00 2001 From: Joshua Park Date: Fri, 27 Nov 2026 02:32:06 -0500 Subject: [PATCH 5/8] fix: copy a page for its preview before ClairUI takes it out of the card --- .../browser/clair/window/clair_browser_window.mm | 14 +++++++++----- .../add-tab-switcher-and-tabs-menu/design.md | 2 +- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm b/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm index b389e4f5..fb54d201 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm +++ b/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm @@ -3213,15 +3213,19 @@ void GiveBackToStill(tabs::TabHandle handle) { FROM_HERE, base::BindOnce(&GiveBackToStill, old_row->GetHandle())); } } + // A tab and its Peek show together (add-peek D4). + const std::set shown = PagesShownWith(new_contents); + // add-tab-switcher-and-tabs-menu D4: the switcher's previews, while the + // pages leaving are still in the card: once ClairUI takes a page's view out + // of the window, its surface can't be copied. + if (old_contents) { + KeepPreviews(old_contents, shown); + } // ClairUI swaps the page in the card now, before visibility changes. [bridge_ activeTabChanged]; // As WebUIBrowserWindow: the old page reports hidden, the new one the - // window's visibility. A tab and its Peek show together (add-peek D4). - const std::set shown = PagesShownWith(new_contents); + // window's visibility. if (old_contents) { - // add-tab-switcher-and-tabs-menu D4: the switcher's previews, while the - // pages leaving are still shown. - KeepPreviews(old_contents, shown); for (content::WebContents* page : PagesShownWith(old_contents)) { if (!shown.contains(page)) { page->UpdateWebContentsVisibility(content::Visibility::HIDDEN); diff --git a/openspec/changes/add-tab-switcher-and-tabs-menu/design.md b/openspec/changes/add-tab-switcher-and-tabs-menu/design.md index 479735aa..bc189abd 100644 --- a/openspec/changes/add-tab-switcher-and-tabs-menu/design.md +++ b/openspec/changes/add-tab-switcher-and-tabs-menu/design.md @@ -73,7 +73,7 @@ The contract (`ClairHost.h`, `ClairBrowser`): completion:(void (^)(NSImage *_Nullable preview))completion; ``` -- **Capture.** The engine copies a tab's page with `CopyPage` as the tab stops being shown. That happens in `ClairBrowserWindow`'s active-tab change, before Chromium hides it, which is where `TabStripModel` asks `ThumbnailTabHelper` for its own. The copy is scaled to 2× the card's width, cut to the card's 3:2 shape from the top, and kept on the tab as `WebContents` user data (`ClairTabPreview`). +- **Capture.** The engine copies a tab's page with `CopyPage` as the tab stops being shown. That happens in `ClairBrowserWindow`'s active-tab change, before ClairUI takes the page out of the card and Chromium hides it, which is where `TabStripModel` asks `ThumbnailTabHelper` for its own. The copy is scaled to 2× the card's width, cut to the card's 3:2 shape from the top, and kept on the tab as `WebContents` user data (`ClairTabPreview`). - **Lifetime and memory.** One bitmap per tab, 315 × 210 pixels, replaced on each hide, freed with the tab: about 260 KB each. - **The shown tab** is copied live on request. - **Peeks.** A tab with a Peek gets the parent's page; the still's convention is followed. From 05ad20ae2468c47a66c8f2b02514ee544fda61ef Mon Sep 17 00:00:00 2001 From: Joshua Park Date: Fri, 27 Nov 2026 02:44:32 -0500 Subject: [PATCH 6/8] fix: keep a page painting until its preview is copied --- .../browser/clair/window/clair_browser_window.mm | 14 ++++++++++++-- native/ClairUI/TabSwitcher.swift | 2 +- native/ClairUI/TabSwitcherLogic.swift | 6 ++++++ .../add-tab-switcher-and-tabs-menu/design.md | 4 ++-- 4 files changed, 21 insertions(+), 5 deletions(-) diff --git a/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm b/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm index fb54d201..c55a77a9 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm +++ b/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm @@ -22,6 +22,7 @@ #include "base/auto_reset.h" #include "base/check.h" #include "base/functional/bind.h" +#include "base/functional/callback_helpers.h" #include "base/location.h" #include "base/logging.h" #include "base/memory/ref_counted.h" @@ -2051,13 +2052,22 @@ void GiveBackToStill(tabs::TabHandle handle) { (peeks_ && peeks_->ParentOf(tab))) { continue; } + // Hidden, a page gives up its compositor, and viz never draws the + // surface the copy waits for. As Chromium's background thumbnails do, a + // hidden capture keeps it painting, the page told it's hidden, until the + // copy is back. + base::ScopedClosureRunner painting = page->IncrementCapturerCount( + gfx::Size(), /*stay_hidden=*/true, /*stay_awake=*/false, + /*is_activity=*/false); CopyPage(tab, base::BindOnce( - [](tabs::TabHandle handle, const SkBitmap& copy) { + [](tabs::TabHandle handle, + base::ScopedClosureRunner painting, + const SkBitmap& copy) { if (tabs::TabInterface* tab = handle.Get()) { ClairTabPreview::Keep(tab->GetContents(), copy); } }, - tab->GetHandle())); + tab->GetHandle(), std::move(painting))); } } diff --git a/native/ClairUI/TabSwitcher.swift b/native/ClairUI/TabSwitcher.swift index aa91e96d..0ee2f256 100644 --- a/native/ClairUI/TabSwitcher.swift +++ b/native/ClairUI/TabSwitcher.swift @@ -301,7 +301,7 @@ struct TabSwitcherView: View { ) .background { RoundedRectangle(cornerRadius: SwitcherLayout.cornerRadius, style: .continuous) - .fill(Color(nsColor: .windowBackgroundColor)) + .fill(Color(nsColor: SwitcherLayout.background)) .overlay { RoundedRectangle(cornerRadius: SwitcherLayout.cornerRadius, style: .continuous) .strokeBorder(Color.primary.opacity(0.12), lineWidth: 0.5) diff --git a/native/ClairUI/TabSwitcherLogic.swift b/native/ClairUI/TabSwitcherLogic.swift index 106a0dba..023e9073 100644 --- a/native/ClairUI/TabSwitcherLogic.swift +++ b/native/ClairUI/TabSwitcherLogic.swift @@ -146,6 +146,12 @@ enum SwitcherLayout { static let cornerRadius: CGFloat = 22 static let previewRadius: CGFloat = 5 static let faviconSize: CGFloat = 16 + /// Arc's #F2F2F2 in Light Mode; the system's dark window background in + /// Dark Mode, where Arc wasn't probed. The system's light one is white. + static let background = NSColor(name: "clair.tabSwitcher") { appearance in + appearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua + ? .windowBackgroundColor : NSColor(srgbRed: 0xF2 / 255, green: 0xF2 / 255, blue: 0xF2 / 255, alpha: 1) + } /// From one card to the next. static var pitch: CGFloat { previewSize.width + gap } diff --git a/openspec/changes/add-tab-switcher-and-tabs-menu/design.md b/openspec/changes/add-tab-switcher-and-tabs-menu/design.md index bc189abd..d48dc68a 100644 --- a/openspec/changes/add-tab-switcher-and-tabs-menu/design.md +++ b/openspec/changes/add-tab-switcher-and-tabs-menu/design.md @@ -52,7 +52,7 @@ The open/step/commit/cancel state is a pure `SwitcherState` with unit tests. The A borderless, non-activating `NSPanel`, a child window of the browser window, hosting SwiftUI. It is laid out from Arc's measurements: -- **Panel:** 27 pt padding, cards 157.5 × 105 pt with a 24 pt pitch gap, label row below each card. About 938 × 189 pt for five cards. Light background (`windowBackgroundColor` at Arc's #F2F2F2 in light mode), about 22 pt corner radius, hairline border and shadow. +- **Panel:** 27 pt padding, cards 157.5 × 105 pt with a 24 pt pitch gap, label row below each card. About 938 × 189 pt for five cards. Arc's #F2F2F2 background in light mode (the system's light `windowBackgroundColor` is white), about 22 pt corner radius, hairline border and shadow. - **Selection:** a 12 pt inset rounded highlight, about 12 pt radius, in the accent colour at the sidebar's selection opacity. The selected title is in the primary colour, the others secondary. - **Labels:** favicon 16 pt, then the title or custom name at the sidebar's title size, medium weight, one line, with an ellipsis. - **Position:** centred on the window, then moved inside the screen's visible frame. Arc centred a two-card panel on the window, but its five-card panel sat about 29 pt right of centre in a 963 pt window; centring is the simpler rule. @@ -73,7 +73,7 @@ The contract (`ClairHost.h`, `ClairBrowser`): completion:(void (^)(NSImage *_Nullable preview))completion; ``` -- **Capture.** The engine copies a tab's page with `CopyPage` as the tab stops being shown. That happens in `ClairBrowserWindow`'s active-tab change, before ClairUI takes the page out of the card and Chromium hides it, which is where `TabStripModel` asks `ThumbnailTabHelper` for its own. The copy is scaled to 2× the card's width, cut to the card's 3:2 shape from the top, and kept on the tab as `WebContents` user data (`ClairTabPreview`). +- **Capture.** The engine copies a tab's page with `CopyPage` as the tab stops being shown. That happens in `ClairBrowserWindow`'s active-tab change, before ClairUI takes the page out of the card and Chromium hides it, which is where `TabStripModel` asks `ThumbnailTabHelper` for its own. A hidden page gives up its compositor at once, so viz would never draw the surface the copy waits for: as Chromium's background thumbnails do, a hidden capture (`IncrementCapturerCount` with `stay_hidden`) keeps the page painting, told it's hidden, until the copy is back. The copy is scaled to 2× the card's width, cut to the card's 3:2 shape from the top, and kept on the tab as `WebContents` user data (`ClairTabPreview`). - **Lifetime and memory.** One bitmap per tab, 315 × 210 pixels, replaced on each hide, freed with the tab: about 260 KB each. - **The shown tab** is copied live on request. - **Peeks.** A tab with a Peek gets the parent's page; the still's convention is followed. From 04f44e19e8b8e547a2cebcb2d026c0fbb3565dfe Mon Sep 17 00:00:00 2001 From: Joshua Park Date: Fri, 27 Nov 2026 02:56:35 -0500 Subject: [PATCH 7/8] docs: record the tab switcher's hand check against Arc --- .../arc-reference/README.md | 21 +++++++++++++++++++ .../add-tab-switcher-and-tabs-menu/tasks.md | 6 +++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/openspec/changes/add-tab-switcher-and-tabs-menu/arc-reference/README.md b/openspec/changes/add-tab-switcher-and-tabs-menu/arc-reference/README.md index 905ff8be..2fad8129 100644 --- a/openspec/changes/add-tab-switcher-and-tabs-menu/arc-reference/README.md +++ b/openspec/changes/add-tab-switcher-and-tabs-menu/arc-reference/README.md @@ -44,3 +44,24 @@ Only two are kept. The rest of what was probed (stepping, Shift+Tab, Esc, a clos |---|---| | switcher-whole-panel.jpg | The whole panel from a screen capture, overhanging the window's right edge, with MDN selected: corners, border, highlight and the full card row | | switcher-across-spaces.jpg | From "Probe A": the split's card (two favicons, no title), Weather.com of "Probe B" selected, AP News (pinned), Reuters (favorite), BBC | + +## Clair + +Checked on 2026-11-27 with `tests/probe/launch-clair.sh` and the `keys` tool, Light Mode, a 1200 × 932 pt window at (22, 52) on the same 1920 × 1080 pt screen, 2 px per point, with Apple, GitHub, Hacker News, Wikipedia "Cat", MDN, Example Domain and BBC opened in that order (engine `chromium-engine-a6215d3cdeceef07`). + +| What | Clair | Arc | +|---|---|---| +| Panel, five cards | 937 × 189, centred on the window (the window's and the panel's centres within 0.5) | 938 × 189, about 29 right of centre | +| Panel padding | 27 to a preview; the highlight 15 from the panel's edges | 27; 15–16 | +| Panel background | #F2F2F2, hairline border, shadow | #F2F2F2 | +| Card preview | 157.5 × 105, the page's top, fitted to width | 157.5 × 105 | +| Card pitch | 181.5 | 181.5 | +| Selection highlight | 181.5 × 157.5, 12 around the preview, the accent colour at 18 % | 181.5 × 157.5, the Space's light accent | +| Label | 16 favicon, the title at 14 pt; selected semibold and primary, others medium and secondary | the same, selected darker and bolder | + +- **Previews.** Background tabs show their page as they were left, the shown tab its page as it is, and a split both pages side by side with both favicons and no title. +- **Keys.** Each Tab selects the next card, Tab on the last wraps to the first, and Esc with Ctrl held closes the panel and keeps the tab. +- **Timing.** In 60 fps recordings, Ctrl released right after Tab (about 60 ms) showed no panel in any frame; held about 165 ms, the panel showed. +- **Animation.** None: the panel appears at full size and opacity between two frames, the highlight moves between two frames, and the panel is gone in the frame after Ctrl is released. + +The hand check found two differences, both fixed: the panel's background was white (macOS 27's light `windowBackgroundColor`), and background tabs had no preview, because a hidden page stopped painting before its copy (design D4). diff --git a/openspec/changes/add-tab-switcher-and-tabs-menu/tasks.md b/openspec/changes/add-tab-switcher-and-tabs-menu/tasks.md index 775cea8f..30967a30 100644 --- a/openspec/changes/add-tab-switcher-and-tabs-menu/tasks.md +++ b/openspec/changes/add-tab-switcher-and-tabs-menu/tasks.md @@ -30,7 +30,7 @@ Suggested order: - `IDC_TAB_SEARCH`, `IDC_WINDOW_GROUP_TAB`, `IDC_GROUP_TARGET_TAB` and `IDC_NEW_SPLIT_TAB` from `ClairIsRemovedCommand`. Before each, grep the Chromium tree (`/Volumes/My Shared Files/clair/build/src`) for other senders of the command, and keep any case that has one, noting why in D5a. Verify that the engine compiles (2.5), and that Opt+Cmd+Down and Up, Cmd+1…9 and Close Tabs Below still work in the runtime suite (5.2). -- [ ] 2.3 Add `ClairTabPreview` (`engine/overlay/chrome/browser/clair/window/`), as D4 describes: +- [x] 2.3 Add `ClairTabPreview` (`engine/overlay/chrome/browser/clair/window/`), as D4 describes: - on each active-tab change, `CopyPage` copies the outgoing row's page (each pane of a split), scales it to 2× the card width and cuts it to 3:2 from the top; - the copy is kept as `WebContents` user data and replaced on each hide; - `-requestPreviewOfTab:size:completion:` returns it, or copies the shown tab live, or nil. @@ -64,7 +64,7 @@ Suggested order: Verify with `grep -rn "tabMenuTag\|35013\|35051" native/` finding nothing, and the unit tests passing in CI. - [ ] 3.7 Rebuild `PinsLogic`'s menus as groups (D6): the Today, pinned and favorite menus, Close Tab on an open pinned tab (as Close and Keep Pinned), and the split chip's Separate Tabs in Split with Tab's place. Add Back to Pinned URL to Edit Pinned Page ›. Verify with unit tests in CI for each menu scenario in the `sidebar`, `pinned-tabs`, `favorites` and `split-view` deltas, including incognito and one Space. -- [ ] 3.8 Rename the sidebar Clear button's tooltip to "Clear unpinned tabs" (`PinsViews`). Verify with `grep -rn '"[^"]*Today[^"]*"' native/ClairUI` finding no user-facing string. +- [x] 3.8 Rename the sidebar Clear button's tooltip to "Clear unpinned tabs" (`PinsViews`). Verify with `grep -rn '"[^"]*Today[^"]*"' native/ClairUI` finding no user-facing string. ## 4. Probe tooling @@ -86,7 +86,7 @@ Suggested order: ## 6. Hand check, docs and release notes -- [ ] 6.1 Hand check with `tests/probe/launch-clair.sh` and the `keys` tool, against `arc-reference/`, with the same tabs: +- [x] 6.1 Hand check with `tests/probe/launch-clair.sh` and the `keys` tool, against `arc-reference/`, with the same tabs: - the panel's size and position; - card and highlight sizes; - previews of background and shown tabs, and of a split; From 229b871aaba459122f226ddb0a0783b3a0a215d2 Mon Sep 17 00:00:00 2001 From: Joshua Park Date: Fri, 27 Nov 2026 03:23:09 -0500 Subject: [PATCH 8/8] fix: address review of the tab switcher --- .../clair/window/clair_browser_window.mm | 9 +++++++- native/ClairUI/TabSwitcher.swift | 12 ++++++++-- native/ClairUITests/TabSwitcherTests.swift | 18 ++++++++++++--- .../add-tab-switcher-and-tabs-menu/design.md | 3 ++- tests/probe/tools/keys.swift | 23 +++++++++++++++---- 5 files changed, 53 insertions(+), 12 deletions(-) diff --git a/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm b/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm index c55a77a9..62ad9b02 100644 --- a/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm +++ b/engine/overlay/chrome/browser/clair/window/clair_browser_window.mm @@ -1808,6 +1808,9 @@ void GiveBackToStill(tabs::TabHandle handle) { CancelPendingTake(); if (content::WebContents* active = browser_->tab_strip_model()->GetActiveWebContents()) { + // add-tab-switcher-and-tabs-menu D4: the pages leave without an active + // tab change; the switcher's previews are taken here too. + KeepPreviews(active, {}); for (content::WebContents* page : PagesShownWith(active)) { page->UpdateWebContentsVisibility(content::Visibility::HIDDEN); } @@ -2094,7 +2097,11 @@ void GiveBackToStill(tabs::TabHandle handle) { if (tab && space_tabs_->IsListed(tab) && (space_tabs_->SpaceOf(tab) == space || space_tabs_->IsFavoriteTab(tab))) { SetShownSpace(space); - ActivateRow(RowOf(tab)); + // The group reveals this member right after: the tab moves here at once, + // a window that showed it getting its still's image when the copy comes. + ClairTakeOptions options; + options.wait_for_copy = false; + ActivateRow(RowOf(tab), std::move(options)); return; } // Shown again: the active tab stays if it's a row of the Space. diff --git a/native/ClairUI/TabSwitcher.swift b/native/ClairUI/TabSwitcher.swift index 0ee2f256..2c9f7607 100644 --- a/native/ClairUI/TabSwitcher.swift +++ b/native/ClairUI/TabSwitcher.swift @@ -100,11 +100,11 @@ final class TabSwitcher { guard event.keyCode == Self.tabKey, flags.contains(.control), flags.isDisjoint(with: [.command, .option]), host?.switcherMayAct == true else { return false } - takenKeys.insert(event.keyCode) + take(event) open(forward: !flags.contains(.shift)) return true } - takenKeys.insert(event.keyCode) + take(event) switch event.keyCode { case Self.tabKey: state.step(forward: !flags.contains(.shift)) @@ -117,6 +117,14 @@ final class TabSwitcher { return true } + /// The key's release is the switcher's too, unless the key was down + /// before: a repeat's release belongs to whoever had its first press. + private func take(_ event: NSEvent) { + if !event.isARepeat { + takenKeys.insert(event.keyCode) + } + } + private func open(forward: Bool) { guard let host, state.open(recents: host.recentTabIDs, forward: forward, at: now()) else { return } let cards = host.switcherCards(for: state.entries) diff --git a/native/ClairUITests/TabSwitcherTests.swift b/native/ClairUITests/TabSwitcherTests.swift index 827b2882..cc483a1d 100644 --- a/native/ClairUITests/TabSwitcherTests.swift +++ b/native/ClairUITests/TabSwitcherTests.swift @@ -279,12 +279,13 @@ struct TabSwitcherKeyTests { switcher.wait = { _ in try? await Task.sleep(for: .seconds(3600)) } } - private func key(_ code: UInt16, _ flags: NSEvent.ModifierFlags = [], type: NSEvent.EventType = .keyDown) -> NSEvent - { + private func key( + _ code: UInt16, _ flags: NSEvent.ModifierFlags = [], type: NSEvent.EventType = .keyDown, repeat: Bool = false + ) -> NSEvent { let characters = code == 48 ? "\t" : (code == 53 ? "\u{1b}" : "a") return NSEvent.keyEvent( with: type, location: .zero, modifierFlags: flags, timestamp: 0, windowNumber: 0, context: nil, - characters: characters, charactersIgnoringModifiers: characters, isARepeat: false, keyCode: code)! + characters: characters, charactersIgnoringModifiers: characters, isARepeat: `repeat`, keyCode: code)! } private func flags(_ flags: NSEvent.ModifierFlags) -> NSEvent { @@ -342,6 +343,17 @@ struct TabSwitcherKeyTests { #expect(!switcher.click(at: CGPoint(x: card.midX, y: 10))) } + /// A key held down before the switcher opened keeps its release: the + /// switcher swallows its repeats, but its key-up goes on to the page. + @Test func aKeyPressedBeforeKeepsItsRelease() { + switcher.handle(key(48, .control)) + #expect(switcher.handle(key(125, .control, repeat: true))) + switcher.handle(key(53, .control)) + #expect(!switcher.handle(key(125, type: .keyUp))) + // Esc, pressed inside the switcher, has its release taken. + #expect(switcher.handle(key(53, type: .keyUp))) + } + @Test func nothingHappensWhileADialogIsUp() { host.switcherMayAct = false #expect(!switcher.handle(key(48, .control))) diff --git a/openspec/changes/add-tab-switcher-and-tabs-menu/design.md b/openspec/changes/add-tab-switcher-and-tabs-menu/design.md index d48dc68a..3d3a806a 100644 --- a/openspec/changes/add-tab-switcher-and-tabs-menu/design.md +++ b/openspec/changes/add-tab-switcher-and-tabs-menu/design.md @@ -74,6 +74,7 @@ The contract (`ClairHost.h`, `ClairBrowser`): ``` - **Capture.** The engine copies a tab's page with `CopyPage` as the tab stops being shown. That happens in `ClairBrowserWindow`'s active-tab change, before ClairUI takes the page out of the card and Chromium hides it, which is where `TabStripModel` asks `ThumbnailTabHelper` for its own. A hidden page gives up its compositor at once, so viz would never draw the surface the copy waits for: as Chromium's background thumbnails do, a hidden capture (`IncrementCapturerCount` with `stay_hidden`) keeps the page painting, told it's hidden, until the copy is back. The copy is scaled to 2× the card's width, cut to the card's 3:2 shape from the top, and kept on the tab as `WebContents` user data (`ClairTabPreview`). +- **Profile swaps.** A window the group conceals hides its pages without an active-tab change, so `Conceal` keeps their previews first. - **Lifetime and memory.** One bitmap per tab, 315 × 210 pixels, replaced on each hide, freed with the tab: about 260 KB each. - **The shown tab** is copied live on request. - **Peeks.** A tab with a Peek gets the parent's page; the still's convention is followed. @@ -82,7 +83,7 @@ Turning on `kTabHoverCardImages` was rejected: it needs a patch to a Chromium de A split's card asks for both panes and draws them side by side in pane order. -**Showing a tab of another profile.** `-showTab:` passes the tab through the window group's swap (`ClairWindowGroup::ShowSpace`), and the member swapped in shows it in place of the tab `ShowSpace` would pick. Otherwise the Space's last tab would show first, and enter the recents. +**Showing a tab of another profile.** `-showTab:` passes the tab through the window group's swap (`ClairWindowGroup::ShowSpace`), and the member swapped in shows it in place of the tab `ShowSpace` would pick. Otherwise the Space's last tab would show first, and enter the recents. It takes the tab without waiting for its page's copy, so the tab is active before the group reveals the member; a window that showed it gets its still's image when the copy comes. ### D5. Delete Chromium's Tab menu, add Clair's Tabs menu diff --git a/tests/probe/tools/keys.swift b/tests/probe/tools/keys.swift index e61bcfe7..1c9e664c 100644 --- a/tests/probe/tools/keys.swift +++ b/tests/probe/tools/keys.swift @@ -74,6 +74,17 @@ func modifier(_ key: CGKeyCode, _ flag: CGEventFlags, down: Bool) { post(key, down: down) } +/// Lets go of what's held, so a failure leaves no key down. +func releaseHeld() { + if held.contains(.maskShift) { modifier(shiftKey, .maskShift, down: false) } + if held.contains(.maskControl) { modifier(controlKey, .maskControl, down: false) } +} + +func releaseAndFail(_ message: String) -> Never { + releaseHeld() + fail(message, status: 1) +} + func press(_ key: CGKeyCode) { post(key, down: true) usleep(30_000) @@ -85,7 +96,7 @@ func shoot(_ argument: Substring) { let parts = argument.split(separator: ":", maxSplits: 1) let numbers = parts.count == 2 ? parts[1].split(separator: ",").compactMap { Double($0) } : [] guard parts.count == 2, !parts[0].isEmpty, numbers.count == 4 else { - fail("shot needs :, got \(argument)") + releaseAndFail("shot needs :, got \(argument)") } let rect = numbers.map { String(Int($0.rounded())) }.joined(separator: ",") let capture = Process() @@ -95,9 +106,12 @@ func shoot(_ argument: Substring) { try capture.run() capture.waitUntilExit() } catch { - fail("screencapture didn't run: \(error)", status: 1) + releaseAndFail("screencapture didn't run: \(error)") + } + // screencapture exits 0 when it can't write the file. + guard capture.terminationStatus == 0, FileManager.default.fileExists(atPath: String(parts[0])) else { + releaseAndFail("screencapture didn't write \(parts[0])") } - guard capture.terminationStatus == 0 else { fail("screencapture failed", status: 1) } } for step in steps { @@ -120,5 +134,4 @@ for step in steps { } // Nothing stays held once the tool is done. -if held.contains(.maskShift) { modifier(shiftKey, .maskShift, down: false) } -if held.contains(.maskControl) { modifier(controlKey, .maskControl, down: false) } +releaseHeld()