The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.
Extension options pages: no fullscreen slide, and an open one is selected (#38) (#75)
Victor Kildahlef9dc7ca77b9
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swiftindex 8d9f323..caf3906 100644--- a/Sources/Cra/App/AppDelegate.swift+++ b/Sources/Cra/App/AppDelegate.swift@@ -95,7 +95,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {return}self.useNormalWindow()- self.store.createTab(url: url, select: true)+ self.openExtensionPage(url)self.main.showWindow(nil)}}@@ -286,6 +286,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {}}+ /// A page an extension opens as a tab. Its options page stays one tab, as in Chrome and+ /// Arc: opening it again selects the open one (GitHub #38).+ func openExtensionPage(_ url: String, window: UUID? = nil) {+ let page = { (u: String) in u.split(separator: "#", maxSplits: 1).first.map(String.init) ?? u }+ if ExtensionStore.shared.optionsPageOwner(url) != nil,+ let open = store.allTabs().first(where: { $0.tab.map { page($0.url) == page(url) } == true && !store.isIncognito(item: $0.id) }) {+ store.selectTab(open.id, window: window)+ } else {+ store.createTab(url: url, select: true, window: window)+ }+ }+/// The window links from other apps, the Library and Little Windows go to: the/// normal window in use last, never an incognito one.@discardableResultdiff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swiftindex 1d7bd29..0807129 100644--- a/Sources/Cra/Services/BrowserManager.swift+++ b/Sources/Cra/Services/BrowserManager.swift@@ -56,6 +56,8 @@ protocol BrowserManagerDelegate: AnyObject {func browserManagerFocusedBrowser(_ tabID: UUID)/// The page closed itself (window.close()).func browserManagerPageClosedTab(_ tabID: UUID)+ /// An extension asked for this tab to be in front (chrome.tabs.update with active: true).+ func browserManagerActivationRequested(_ tabID: UUID)/// Arc's Peek: a link the user clicked (or Shift-clicked) in `tabID`, whose page is at/// `pageURL`. Return true when it opens in a Peek instead.func browserManagerOpensPeek(url: String, fromTab tabID: UUID, pageURL: String, shiftClick: Bool) -> Bool@@ -873,6 +875,11 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {delegate?.browserManagerFocusedBrowser(id)}+ func browserRequestsActivation(_ browser: CraBrowser) {+ guard let id = tabID(of: browser) else { return }+ delegate?.browserManagerActivationRequested(id)+ }+func browserDidClose(_ browser: CraBrowser) {closingBrowsers[ObjectIdentifier(browser)] = nilguard let id = tabID(of: browser) else { return }diff --git a/Sources/Cra/Services/ExtensionStore.swift b/Sources/Cra/Services/ExtensionStore.swiftindex e8d0337..ae6e17a 100644--- a/Sources/Cra/Services/ExtensionStore.swift+++ b/Sources/Cra/Services/ExtensionStore.swift@@ -143,6 +143,19 @@ final class ExtensionStore {return ExtensionImporter.settings(inProfile: dir)}+ /// The extension whose options page `url` is (its options_ui/options_page, or Chrome's+ /// chrome://extensions page for it). Chrome keeps one such tab and opening it again selects it.+ func optionsPageOwner(_ url: String) -> String? {+ guard let u = URLComponents(string: url) else { return nil }+ if u.scheme == "chrome", u.host == "extensions" {+ return u.queryItems?.first(where: { $0.name == "options" || $0.name == "id" })?.value+ }+ guard u.scheme == "chrome-extension", let id = u.host,+ let options = entries.first(where: { $0.extensionID == id })?.optionsPath else { return nil }+ let path = options.split(separator: "?", maxSplits: 1).first.map(String.init) ?? options+ return u.path == "/" + path.trimmingCharacters(in: CharacterSet(charactersIn: "/")) ? id : nil+ }+private static func entry(id: String, folder dir: URL, extensionID: String?) -> Entry? {guard let data = try? Data(contentsOf: dir.appendingPathComponent("manifest.json")),let m = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swiftindex 7429e70..3f67e4b 100644--- a/Sources/Cra/UI/Windows/MainWindowController.swift+++ b/Sources/Cra/UI/Windows/MainWindowController.swift@@ -1253,6 +1253,13 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMfunc browserManagerPageClosedTab(_ tabID: UUID) { closeTab(tabID) }+ /// An extension brought one of this window's tabs to the front (SwitchyOmega's Options with+ /// its settings tab already open): selected, as in Arc (GitHub #38).+ func browserManagerActivationRequested(_ tabID: UUID) {+ store.selectTab(tabID, window: windowID)+ if NSApp.isActive, window?.isKeyWindow == false { showWindow(nil) }+ }+/// Arc's Peek (Settings ▸ Tabs ▸ Links): a link to another site clicked in a favorite or/// pinned tab (any tab with "In every tab" on), or any Shift-clicked link, opens over the/// window and the tab stays put.@@ -1737,7 +1744,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMlet fallback = window.map { NSPoint(x: $0.frame.maxX - 16, y: $0.frame.maxY - CraMetrics.toolbarHeight) } ?? .zeroExtensionPageWindow.open(url: url, anchor: anchor ?? fallback, app: app)case .openTab(let url):- store.createTab(url: url, select: true, window: windowID)+ app.openExtensionPage(url, window: windowID)}}diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mmindex ac0b07c..6f0b0f4 100644--- a/Sources/CraCEF/CraCEF.mm+++ b/Sources/CraCEF/CraCEF.mm@@ -203,7 +203,7 @@ static CraClient* AsCraClient(CefClient* c) {// extension's chrome.tabs.create / chrome.windows.create, or the welcome page an// extension opens once it is installed. CEF gives them GetDefaultClient(); without// one they appear in a stock Chrome window with a tab strip. Cra takes the URL as-// one of its own tabs and closes Chrome's browser before it is shown.+// one of its own tabs and closes Chrome's browser, whose window stays unseen (HideStrayWindow).//// Popup-type windows (windows.create({type: "popup"}): 1Password's detached window,// sign-in and approval windows) stay what the extension asked for, like Arc's@@ -213,6 +213,24 @@ static CraClient* AsCraClient(CefClient* c) {// and popups a plain titled window, which is how they are told apart here.static NSHashTable<NSWindow*>* g_extensionWindows = nil;+// Chrome shows a new tabbed window at the end of Navigate(), after this first navigation+// has started, so ordering it out here is not enough: shown, it pulled a full-screen Cra+// onto the desktop and back (GitHub #38). It is made unseeable instead: transparent, no+// clicks, and a full-screen auxiliary that opens in the current space without switching.+static void HideStrayWindow(NSWindow* window) {+ if (!window) return;+ window.alphaValue = 0;+ window.ignoresMouseEvents = YES;+ window.animationBehavior = NSWindowAnimationBehaviorNone;+ NSWindowCollectionBehavior behavior = window.collectionBehavior;+ behavior &= ~(NSWindowCollectionBehaviorFullScreenPrimary | NSWindowCollectionBehaviorFullScreenAllowsTiling+ | NSWindowCollectionBehaviorManaged);+ behavior |= NSWindowCollectionBehaviorFullScreenAuxiliary | NSWindowCollectionBehaviorMoveToActiveSpace+ | NSWindowCollectionBehaviorTransient | NSWindowCollectionBehaviorIgnoresCycle;+ window.collectionBehavior = behavior;+ [window orderOut:nil];+}+class StrayBrowserClient : public CefClient, public CefLifeSpanHandler, public CefRequestHandler {public:CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() override { return this; }@@ -235,7 +253,7 @@ public:[g_extensionWindows addObject:window];return false;}- [window orderOut:nil];+ HideStrayWindow(window);NSString* url = NSStringFromCef(request->GetURL());if (url.length == 0 || [url isEqualToString:@"about:blank"]) return false;// Chrome's own empty tab (the window it opens to show "extension added" after a@@ -1194,12 +1212,22 @@ public:}// Chromium's audible state, which CEF has no callback for: the engine sends it as a- // "Cra.audible" message (scripts/cef-patches/audible-state.patch).+ // "Cra.audible" message (scripts/cef-patches/audible-state.patch). "Cra.activate": an+ // extension asked for this tab to be in front (scripts/cef-patches/extension-tab-activate.patch).bool OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,CefProcessId source_process, CefRefPtr<CefProcessMessage> message) override {- if (source_process != PID_BROWSER || message->GetName() != "Cra.audible") return false;- if (CraBrowser* o = owner_) [o audibleChanged:message->GetArgumentList()->GetBool(0)];- return true;+ if (source_process != PID_BROWSER) return false;+ CraBrowser* o = owner_;+ if (message->GetName() == "Cra.audible") {+ if (o) [o audibleChanged:message->GetArgumentList()->GetBool(0)];+ return true;+ }+ if (message->GetName() == "Cra.activate") {+ if (o && [o.delegate respondsToSelector:@selector(browserRequestsActivation:)])+ [o.delegate browserRequestsActivation:o];+ return true;+ }+ return false;}void OnFaviconURLChange(CefRefPtr<CefBrowser> browser, const std::vector<CefString>& icon_urls) override {diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.hindex 7f55e15..2d88b69 100644--- a/Sources/CraCEF/include/CraCEF.h+++ b/Sources/CraCEF/include/CraCEF.h@@ -84,6 +84,9 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {- (void)browser:(CraBrowser *)browser didChangeMediaCapture:(BOOL)capturing;/// The page started or stopped playing sound (see `isAudible`).- (void)browser:(CraBrowser *)browser didChangeAudible:(BOOL)audible;+/// An extension asked to bring this page's tab to the front (chrome.tabs.update with+/// active: true; scripts/cef-patches/extension-tab-activate.patch).+- (void)browserRequestsActivation:(CraBrowser *)browser;/// Arc's Peek: a link the user clicked (`shiftClick` NO: before it navigates the page or/// opens as a target=_blank tab) or Shift-clicked (YES, instead of a new window). Return/// YES to show it in a Peek; the page then stays where it is.diff --git a/Tests/BrowserManagerLifecycleTests.swift b/Tests/BrowserManagerLifecycleTests.swiftindex f890747..b9fd70a 100644--- a/Tests/BrowserManagerLifecycleTests.swift+++ b/Tests/BrowserManagerLifecycleTests.swift@@ -33,6 +33,9 @@ enum BrowserManagerLifecycleTests {expect(manager.runtime(for: id) === replacement && manager.visibleTabID == id && manager.visibleTabIDs == [id],"late close cannot remove or deselect the replacement")expect(observer.closedTabs.isEmpty, "late page-close cannot archive the replacement tab")+ manager.browserRequestsActivation(old.browser)+ manager.browserRequestsActivation(replacement.browser)+ expect(observer.activatedTabs == [id], "an extension's tabs.update activation reaches only the live page's tab")let retainedID = store.createTab(url: "https://example.test/retained").idweak var retainedBrowser = manager.ensureRuntime(for: retainedID)?.browser@@ -358,6 +361,7 @@ enum BrowserManagerLifecycleTests {@MainActorprivate final class Observer: BrowserManagerDelegate {var closedTabs: [UUID] = []+ var activatedTabs: [UUID] = []var onPageWindowsChanged: (() -> Void)?func browserManagerDidUpdate(_ tabID: UUID) {}func browserManager(statusMessage: String) {}@@ -372,5 +376,6 @@ private final class Observer: BrowserManagerDelegate {func browserManagerHandleUnhandledKey(_ event: NSEvent) -> Bool { false }func browserManagerFocusedBrowser(_ tabID: UUID) {}func browserManagerPageClosedTab(_ tabID: UUID) { closedTabs.append(tabID) }+ func browserManagerActivationRequested(_ tabID: UUID) { activatedTabs.append(tabID) }func browserManagerOpensPeek(url: String, fromTab tabID: UUID, pageURL: String, shiftClick: Bool) -> Bool { false }}diff --git a/scripts/cef-patches/extension-tab-activate.patch b/scripts/cef-patches/extension-tab-activate.patchnew file mode 100644index 0000000..4e6cf6c--- /dev/null+++ b/scripts/cef-patches/extension-tab-activate.patch@@ -0,0 +1,87 @@+diff --git a/cef/libcef/browser/chrome/browser_delegate.h b/cef/libcef/browser/chrome/browser_delegate.h+index e65325e..5b56d3a 100644+--- a/cef/libcef/browser/chrome/browser_delegate.h++++ b/cef/libcef/browser/chrome/browser_delegate.h+@@ -194,6 +194,11 @@ class BrowserDelegate {+ // Returns true if this browser is Views-hosted.+ virtual bool IsViewsHosted() const { return false; }+++ // Cra: an extension asked to bring this browser's tab to the front++ // (chrome.tabs.update({active: true})). A Views-hosted browser has only that++ // tab, so Chrome's own activation changes nothing the client can see.++ virtual void TabActivationRequested() {}+++ // Returns true if this browser has a Views-hosted opener. Only+ // applicable for Browsers of type picture_in_picture and devtools.+ virtual bool HasViewsHostedOpener() const { return false; }+diff --git a/cef/libcef/browser/chrome/chrome_browser_delegate.cc b/cef/libcef/browser/chrome/chrome_browser_delegate.cc+index 3c4eead..8df4ecf 100644+--- a/cef/libcef/browser/chrome/chrome_browser_delegate.cc++++ b/cef/libcef/browser/chrome/chrome_browser_delegate.cc+@@ -605,6 +605,23 @@ bool ChromeBrowserDelegate::IsViewsHosted() const {+ create_params_.popup_with_views_hosted_opener;+ }+++// Cra: delivered as a "Cra.activate" message from PID_BROWSER (no arguments);++// the client selects the tab in its own UI.++void ChromeBrowserDelegate::TabActivationRequested() {++ auto browser = ChromeBrowserHostImpl::GetBrowserForBrowser(browser_);++ if (!browser) {++ return;++ }++ auto client = browser->GetClient();++ if (!client) {++ return;++ }++ CefRefPtr<CefProcessMessage> message =++ CefProcessMessage::Create("Cra.activate");++ client->OnProcessMessageReceived(browser.get(), browser->GetMainFrame(),++ PID_BROWSER, message);++}+++ CefWindowImpl* ChromeBrowserDelegate::GetCefWindowImpl() const {+ if (IsViewsHosted()) {+ if (auto* chrome_browser_view = static_cast<ChromeBrowserView*>(+diff --git a/cef/libcef/browser/chrome/chrome_browser_delegate.h b/cef/libcef/browser/chrome/chrome_browser_delegate.h+index 639ecc8..ca311b4 100644+--- a/cef/libcef/browser/chrome/chrome_browser_delegate.h++++ b/cef/libcef/browser/chrome/chrome_browser_delegate.h+@@ -87,6 +87,7 @@ class ChromeBrowserDelegate : public cef::BrowserDelegate {+ void WindowFullscreenStateChanged() override;+ bool IsViewsHosted() const override;+ bool HasViewsHostedOpener() const override;++ void TabActivationRequested() override;++ Browser* browser() const { return browser_; }++diff --git a/chrome/browser/extensions/api/tabs/tabs_api.cc b/chrome/browser/extensions/api/tabs/tabs_api.cc+index bd5ca46..1c96b36 100644+--- a/chrome/browser/extensions/api/tabs/tabs_api.cc++++ b/chrome/browser/extensions/api/tabs/tabs_api.cc+@@ -63,6 +63,11 @@+ #include "extensions/browser/extension_zoom_request_client.h"+ #include "extensions/browser/extensions_browser_client.h"+ #include "extensions/buildflags/buildflags.h"++#include "cef/libcef/features/features.h"++++#if BUILDFLAG(ENABLE_CEF)++#include "cef/libcef/browser/chrome/browser_delegate.h"++#endif+ #include "extensions/common/extension.h"+ #include "extensions/common/extension_features.h"+ #include "extensions/common/manifest_constants.h"+@@ -2866,6 +2871,14 @@ bool TabsUpdateFunction::UpdateActiveTab(+ tab_list.ActivateTab(tab_list.GetTab(tab_index)->GetHandle());+ DCHECK_EQ(tab_index, tab_list.GetActiveIndex());+ }++#if BUILDFLAG(ENABLE_CEF)++ // Cra: each page is a Views-hosted Browser with one, always active tab, so++ // the activation above never shows. Let the client select it (SwitchyOmega's++ // Options focuses its open settings tab this way).++ if (browser.cef_delegate() && browser.cef_delegate()->IsViewsHosted()) {++ browser.cef_delegate()->TabActivationRequested();++ }++#endif+ return true;+ }+diff --git a/scripts/fetch-cef.sh b/scripts/fetch-cef.shindex c96fabc..3e685ae 100755--- a/scripts/fetch-cef.sh+++ b/scripts/fetch-cef.sh@@ -13,7 +13,7 @@ CEF_VERSION="${CEF_VERSION:-156.0.15+gcf671c0+chromium-156.0.8078.80}"ARCH="${CEF_ARCH:-macosarm64}"NAME="cef_binary_${CEF_VERSION}_${ARCH}_minimal"# Bump the suffix (codecs2, …) when the build changes but CEF_VERSION does not.-CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs1}"+CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs2}"URL="${CEF_URL:-https://github.com/VictorKildahl/cra/releases/download/${CEF_RELEASE}/cef_binary_${ARCH}_minimal.tar.bz2}"mkdir -p vendor