Skip to content

armgit / cra

Public Imported from GitHub
0

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.

Window drags from the URL and floating sidebar, extension popup fixes (#15, #16)

Victor37a87aad49c6
diff --git a/Sources/Cra/Services/ExtensionActions.swift b/Sources/Cra/Services/ExtensionActions.swift
index ba1d69a..bab8e90 100644
--- a/Sources/Cra/Services/ExtensionActions.swift
+++ b/Sources/Cra/Services/ExtensionActions.swift
@@ -25,9 +25,9 @@ final class ExtensionActions {
}
}
- /// Where a popup Cra did not ask for hangs (screen top-right point), nil to leave it where
- /// Chrome put it.
- private var defaultAnchor: () -> NSPoint? = { nil }
+ /// Where a popup Cra did not ask for hangs (screen top-right point) for an extension ID, nil
+ /// to leave it where Chrome put it.
+ private var defaultAnchor: (String) -> NSPoint? = { _ in nil }
/// True while `run` waits for its own popup.
private var placingOwnPopup = false
@@ -35,7 +35,7 @@ final class ExtensionActions {
/// ⌘⇧X) or chrome.action.openPopup() (1Password's inline menu). Arc hosts every popup
/// under its toolbar (ArcCore hands it over in browser:didOpenExtensionPopup:webContents:);
/// Cra watches for popup pages being created and moves those under `anchor` too.
- func watchPopups(anchor: @escaping () -> NSPoint?) {
+ func watchPopups(anchor: @escaping (String) -> NSPoint?) {
defaultAnchor = anchor
guard isAvailable else { return }
Task { _ = try? await call("Target.setDiscoverTargets", ["discover": true]) }
@@ -46,10 +46,12 @@ final class ExtensionActions {
@discardableResult
func run(_ extensionID: String, on browser: CraBrowser, anchor: NSPoint) async -> Bool {
guard isAvailable else { return false }
+ var triggered = false
do {
let tab = try await tabTarget(for: browser)
let before = visibleWindows()
placingOwnPopup = true
+ triggered = true
_ = try await call("Extensions.triggerAction", ["id": extensionID, "targetId": tab])
placePopup(appearingAfter: before, anchor: anchor)
return true
@@ -57,7 +59,9 @@ final class ExtensionActions {
placingOwnPopup = false
NSLog("Cra: extension action %@ failed: %@", extensionID, String(describing: error))
tabTargets[ObjectIdentifier(browser)] = nil
- return false
+ // The action may still run after its reply timed out; a fallback page would be a
+ // second popup.
+ return triggered && error is ExtensionProtocolTimeout
}
}
@@ -149,34 +153,42 @@ final class ExtensionActions {
let popup = ExtensionStore.shared.entries.first(where: { $0.extensionID == id })?.popupPath,
url.path == "/" + popup.trimmingCharacters(in: CharacterSet(charactersIn: "/")),
seenPopupTargets.insert(target).inserted, !placingOwnPopup,
- let anchor = defaultAnchor() else { return }
+ let anchor = defaultAnchor(id) else { return }
placePopup(appearingAfter: visibleWindows(), anchor: anchor)
}
// MARK: Protocol calls
+ // Chromium can leave a request unanswered (its target went away meanwhile). Without a
+ // deadline `placingOwnPopup` stayed set and no later shortcut popup was placed.
private func call(_ method: String, _ params: [String: Any] = [:], session: String? = nil) async throws -> [String: Any] {
let json = String(decoding: try JSONSerialization.data(withJSONObject: params), as: UTF8.self)
return try await withCheckedThrowingContinuation { cont in
- CraCEFRuntime.sendBrowserDevToolsMethod(method, params: json, sessionID: session) { result, error in
- if let result, let obj = try? JSONSerialization.jsonObject(with: Data(result.utf8)) as? [String: Any] {
- cont.resume(returning: obj)
- } else {
- cont.resume(throwing: Failure.protocolError(error ?? "bad reply to \(method)"))
+ let reply = ExtensionProtocolReply<[String: Any]>(method: method, timeout: 5, onLateReply: { result in
+ // An attach that answers after its caller gave up still leaves a session open.
+ if method == "Target.attachToTarget", case let .success(object) = result,
+ let session = object["sessionId"] as? String {
+ CraCEFRuntime.sendBrowserDevToolsMethod("Target.detachFromTarget", params: #"{"sessionId":"\#(session)"}"#,
+ sessionID: nil) { _, _ in }
}
+ }) { cont.resume(with: $0) }
+ CraCEFRuntime.sendBrowserDevToolsMethod(method, params: json, sessionID: session) { result, error in
+ MainActor.assumeIsolated { reply.resolve(Self.result(result, error: error, method: method)) }
}
}
}
private func pageCall(_ browser: CraBrowser, _ method: String) async throws -> [String: Any] {
try await withCheckedThrowingContinuation { cont in
+ let reply = ExtensionProtocolReply<[String: Any]>(method: method, timeout: 5) { cont.resume(with: $0) }
browser.sendDevToolsMethod(method, params: "{}") { result, error in
- if let result, let obj = try? JSONSerialization.jsonObject(with: Data(result.utf8)) as? [String: Any] {
- cont.resume(returning: obj)
- } else {
- cont.resume(throwing: Failure.protocolError(error ?? "bad reply to \(method)"))
- }
+ MainActor.assumeIsolated { reply.resolve(Self.result(result, error: error, method: method)) }
}
}
}
+
+ private nonisolated static func result(_ result: String?, error: String?, method: String) -> Result<[String: Any], Error> {
+ if let result, let obj = try? JSONSerialization.jsonObject(with: Data(result.utf8)) as? [String: Any] { return .success(obj) }
+ return .failure(Failure.protocolError(error ?? "bad reply to \(method)"))
+ }
}
diff --git a/Sources/Cra/Services/ExtensionProtocolReply.swift b/Sources/Cra/Services/ExtensionProtocolReply.swift
new file mode 100644
index 0000000..522b634
--- /dev/null
+++ b/Sources/Cra/Services/ExtensionProtocolReply.swift
@@ -0,0 +1,44 @@
+import Foundation
+
+struct ExtensionProtocolTimeout: Error {
+ let method: String
+}
+
+/// CEF may never reply after its renderer closes. Bound an asynchronous service call
+/// and complete its continuation once; a late attach can still release its session.
+/// This main-queue deadline cannot interrupt a synchronous block inside the CEF bridge.
+@MainActor
+final class ExtensionProtocolReply<Value> {
+ private var completion: ((Result<Value, Error>) -> Void)?
+ private let onLateReply: ((Result<Value, Error>) -> Void)?
+ private var deadline: DispatchWorkItem?
+ private var expired = false
+ private var handledLateReply = false
+
+ init(method: String, timeout: TimeInterval, onLateReply: ((Result<Value, Error>) -> Void)? = nil,
+ completion: @escaping (Result<Value, Error>) -> Void) {
+ self.completion = completion
+ self.onLateReply = onLateReply
+ let work = DispatchWorkItem { [weak self] in
+ guard let self, self.completion != nil else { return }
+ self.expired = true
+ self.resolve(.failure(ExtensionProtocolTimeout(method: method)))
+ }
+ deadline = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + timeout, execute: work)
+ }
+
+ func resolve(_ result: Result<Value, Error>) {
+ guard let completion else {
+ if expired, !handledLateReply {
+ handledLateReply = true
+ onLateReply?(result)
+ }
+ return
+ }
+ self.completion = nil
+ deadline?.cancel()
+ deadline = nil
+ completion(result)
+ }
+}
diff --git a/Sources/Cra/UI/PaneToolbarView.swift b/Sources/Cra/UI/PaneToolbarView.swift
index 4a2cd46..b3b9310 100644
--- a/Sources/Cra/UI/PaneToolbarView.swift
+++ b/Sources/Cra/UI/PaneToolbarView.swift
@@ -51,7 +51,7 @@ final class PaneToolbarView: NSView {
private let placeholderLabel = NSTextField.sidebarLabel(size: 13)
private let hairline = NSView()
private let devDivider = NSView()
- private var press: NSEvent?
+ private var press = WindowDragGesture()
init(paneTabID: UUID?, store: SidebarStore, ui: SidebarUIState, actions: SidebarActions) {
self.paneTabID = paneTabID
@@ -144,6 +144,12 @@ final class PaneToolbarView: NSView {
return m
}
+ /// A pinned extension's button (screen rect), for popups opened from the menu bar or a shortcut.
+ func extensionButtonFrameOnScreen(_ id: String) -> NSRect? {
+ guard let b = buttons["ext:" + id], !b.isHiddenOrHasHiddenAncestor, let window else { return nil }
+ return window.convertToScreen(b.convert(b.bounds, to: nil))
+ }
+
// MARK: Views
private func button(_ key: String, _ make: () -> ToolbarGlyphButton) -> ToolbarGlyphButton {
@@ -339,18 +345,10 @@ final class PaneToolbarView: NSView {
// A click anywhere on the bar edits the URL (a pane's click also focuses it); a drag moves
// the window, as on Arc's toolbar.
override var mouseDownCanMoveWindow: Bool { false }
- override func mouseDown(with event: NSEvent) { press = event }
- override func mouseDragged(with event: NSEvent) {
- guard let p = press else { return }
- if hypot(event.locationInWindow.x - p.locationInWindow.x, event.locationInWindow.y - p.locationInWindow.y) > 3 {
- press = nil
- window?.performDrag(with: p)
- }
- }
+ override func mouseDown(with event: NSEvent) { press.begin(event) }
+ override func mouseDragged(with event: NSEvent) { press.drag(event) }
override func mouseUp(with event: NSEvent) {
- guard press != nil else { return }
- press = nil
- editURL()
+ if press.finish() { editURL() }
}
}
@@ -450,6 +448,7 @@ final class ToolbarGlyphButton: NSView {
/// monospace after a lock in developer mode), or the nav-bar status in its place.
final class ToolbarURLButton: NSView {
var action: () -> Void = {}
+ private var press = WindowDragGesture()
private let content = NSView()
private let icon = NSImageView()
private let label = NSTextField.sidebarLabel(size: 13)
@@ -541,8 +540,10 @@ final class ToolbarURLButton: NSView {
override func mouseEntered(with event: NSEvent) { hovering = true }
override func mouseExited(with event: NSEvent) { hovering = false }
- override func mouseDown(with event: NSEvent) {}
+ // Part of the bar: a click edits the URL, a drag moves the window like the rest of it.
+ override func mouseDown(with event: NSEvent) { press.begin(event) }
+ override func mouseDragged(with event: NSEvent) { press.drag(event) }
override func mouseUp(with event: NSEvent) {
- if bounds.contains(convert(event.locationInWindow, from: nil)) { action() }
+ if press.finish(), bounds.contains(convert(event.locationInWindow, from: nil)) { action() }
}
}
diff --git a/Sources/Cra/UI/Sidebar/List/SidebarView.swift b/Sources/Cra/UI/Sidebar/List/SidebarView.swift
index adf04f3..b6bb0fb 100644
--- a/Sources/Cra/UI/Sidebar/List/SidebarView.swift
+++ b/Sources/Cra/UI/Sidebar/List/SidebarView.swift
@@ -310,25 +310,19 @@ final class SidebarTopBarView: NSView {
}
// A double click on the empty strip does the title bar's double-click action; a drag moves
- // the window.
+ // the window (from the floating sidebar too, without tearing its panel off).
override var mouseDownCanMoveWindow: Bool { false }
- private var press: NSEvent?
+ private var press = WindowDragGesture()
override func mouseDown(with event: NSEvent) {
if event.clickCount == 2, convert(event.locationInWindow, from: nil).y < CraMetrics.titleAreaHeight {
- press = nil
+ _ = press.finish()
actions.titleBarDoubleClick()
return
}
- press = event
+ press.begin(event)
}
- override func mouseDragged(with event: NSEvent) {
- guard let p = press else { return }
- if hypot(event.locationInWindow.x - p.locationInWindow.x, event.locationInWindow.y - p.locationInWindow.y) > 3 {
- press = nil
- window?.performDrag(with: p)
- }
- }
- override func mouseUp(with event: NSEvent) { press = nil }
+ override func mouseDragged(with event: NSEvent) { press.drag(event) }
+ override func mouseUp(with event: NSEvent) { _ = press.finish() }
override func updateTrackingAreas() {
super.updateTrackingAreas()
diff --git a/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift b/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift
index e6ac465..a884a46 100644
--- a/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift
+++ b/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift
@@ -132,7 +132,7 @@ final class ExtensionPopupWindow: NSWindow {
let size = NSSize(width: bubble.frame.width - 2 * inset, height: bubble.frame.height - 2 * inset + Self.titleBarHeight)
// Right edge on the anchor whatever width the page reports (Bitwarden grows after it loads).
var topLeft = NSPoint(x: anchor.x - size.width + offset.x, y: anchor.y + offset.y)
- if let screen = (bubble.screen ?? NSScreen.main)?.visibleFrame {
+ if let screen = (Self.screen(at: anchor) ?? bubble.screen ?? NSScreen.main)?.visibleFrame {
topLeft.x = min(max(topLeft.x, screen.minX + 4), screen.maxX - size.width - 4)
topLeft.y = min(max(topLeft.y, screen.minY + size.height + 4), screen.maxY)
}
@@ -160,6 +160,12 @@ final class ExtensionPopupWindow: NSWindow {
return NSPoint(x: anchor.x - width + offset.x, y: anchor.y + offset.y)
}
+ /// The display the anchor (the button) is on. Chrome's bubble starts out by its hidden
+ /// toolbar, which can be on another display than the browser window.
+ static func screen(at anchor: NSPoint) -> NSScreen? {
+ NSScreen.screens.first { $0.frame.insetBy(dx: -1, dy: -1).contains(anchor) }
+ }
+
private static var savedOffset: NSPoint? {
get {
guard let s = UserDefaults.standard.string(forKey: savedOffsetKey) else { return nil }
@@ -314,7 +320,7 @@ final class ExtensionPageWindow: NSWindow, NSWindowDelegate, @preconcurrency Cra
private func frame(for page: NSSize) -> NSRect {
let h = page.height + ExtensionPopupWindow.titleBarHeight
var tl = NSPoint(x: topRight.x - page.width, y: topRight.y)
- if let screen = (screen ?? NSScreen.main)?.visibleFrame {
+ if let screen = (ExtensionPopupWindow.screen(at: topRight) ?? screen ?? NSScreen.main)?.visibleFrame {
tl.x = min(max(tl.x, screen.minX + 4), screen.maxX - page.width - 4)
tl.y = min(max(tl.y, screen.minY + h + 4), screen.maxY)
}
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index f1ac175..c31216d 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -236,11 +236,11 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
sidebarActions.runExtension = { [weak self] id in self?.runExtensionAction(id, buttonRightX: Self.extensionButtonRightX()) }
sidebarActions.showExtensionsMenu = { [weak self] in self?.showToolbarExtensionsMenu() }
// Popups from an extension's shortcut or chrome.action.openPopup() hang where the
- // menu bar's do: under the toolbar at the card's right end of the window in use.
- ExtensionActions.shared.watchPopups { [weak app] in
- guard let main = app?.main, let window = main.window, let key = NSApp.keyWindow, key === window || key.parent === window,
- let bar = main.toolbarBottomOnScreen() else { return nil }
- return NSPoint(x: bar.cardMaxX - 8, y: bar.y)
+ // menu bar's do: under the extension's toolbar button, else at the card's right end.
+ // Arc puts every popup in one place, whatever opened it.
+ ExtensionActions.shared.watchPopups { [weak app] id in
+ guard let main = app?.main, let window = main.window, let key = NSApp.keyWindow, key === window || key.parent === window else { return nil }
+ return main.extensionPopupAnchor(id)
}
sidebarActions.performAction = { [weak self] id in
if id.hasPrefix("muteTab:"), let uuid = UUID(uuidString: String(id.dropFirst(8))) {
@@ -1513,13 +1513,23 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
return rect.maxY - CraMetrics.titleAreaHeight - 2 - 36
}
+ /// Under the extension's pinned toolbar button when the toolbar shows one, else under the
+ /// toolbar at the card's right end.
+ fileprivate func extensionPopupAnchor(_ id: String) -> NSPoint? {
+ guard let bar = toolbarBottomOnScreen() else { return nil }
+ if store.settings.showToolbar, let button = (shell.focusedCard?.toolbarHost as? PaneToolbarView)?.extensionButtonFrameOnScreen(id) {
+ return NSPoint(x: button.maxX, y: bar.y)
+ }
+ return NSPoint(x: bar.cardMaxX - 8, y: bar.y)
+ }
+
/// Runs an extension's toolbar action on the focused page, like Arc's toolbar buttons and
/// Dia's Extensions menu. The popup hangs under the toolbar, its right edge at `buttonRightX`
- /// (screen x; nil = the card's right end, for the menu bar).
+ /// (screen x of the clicked button; nil = the extension's toolbar button or the card's right end).
func runExtensionAction(_ id: String, buttonRightX: CGFloat? = nil) {
guard let bar = toolbarBottomOnScreen() else { openExtensionPopupPage(id, anchor: nil); return }
- let y = buttonRightX != nil ? (urlBarBottomOnScreen() ?? bar.y) : bar.y
- let anchor = NSPoint(x: buttonRightX ?? bar.cardMaxX - 8, y: y)
+ let anchor = buttonRightX.map { NSPoint(x: $0, y: urlBarBottomOnScreen() ?? bar.y) }
+ ?? extensionPopupAnchor(id) ?? NSPoint(x: bar.cardMaxX - 8, y: bar.y)
guard let browser = currentBrowser else { openExtensionPopupPage(id, anchor: anchor); return }
Task {
if await !ExtensionActions.shared.run(id, on: browser, anchor: anchor) { self.openExtensionPopupPage(id, anchor: anchor) }
diff --git a/Sources/Cra/UI/Windows/WindowDragGesture.swift b/Sources/Cra/UI/Windows/WindowDragGesture.swift
new file mode 100644
index 0000000..cfe0fb8
--- /dev/null
+++ b/Sources/Cra/UI/Windows/WindowDragGesture.swift
@@ -0,0 +1,43 @@
+import AppKit
+
+/// A press on Arc's title-bar stand-ins (the toolbar, its URL, the sidebar's top strip): a
+/// click acts, a drag past 3 pt moves the browser window. In the floating sidebar the press
+/// lands in its child panel, and `performDrag` there tears the panel off the window, so the
+/// browser window is moved by hand instead (the panel follows it as a child window).
+@MainActor
+struct WindowDragGesture {
+ private var press: NSEvent?
+ private var dragging = false
+ private var lastMouse = NSPoint.zero
+
+ mutating func begin(_ event: NSEvent) {
+ press = event
+ dragging = false
+ }
+
+ mutating func drag(_ event: NSEvent) {
+ guard let press, let window = press.window else { return }
+ if !dragging {
+ guard hypot(event.locationInWindow.x - press.locationInWindow.x,
+ event.locationInWindow.y - press.locationInWindow.y) > 3 else { return }
+ dragging = true
+ guard window.parent != nil else {
+ // A panel the sidebar has left meanwhile is no browser window.
+ if !(window is NSPanel) { window.performDrag(with: press) }
+ return
+ }
+ lastMouse = window.convertPoint(toScreen: press.locationInWindow)
+ }
+ guard let owner = window.parent, owner.isMovable, !owner.styleMask.contains(.fullScreen) else { return }
+ let mouse = NSEvent.mouseLocation
+ owner.setFrameOrigin(NSPoint(x: owner.frame.minX + mouse.x - lastMouse.x, y: owner.frame.minY + mouse.y - lastMouse.y))
+ lastMouse = mouse
+ }
+
+ /// True when the press ended as a click. `performDrag` can swallow the mouse-up; the next
+ /// `begin` starts over then.
+ mutating func finish() -> Bool {
+ defer { press = nil; dragging = false }
+ return press != nil && !dragging
+ }
+}