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.

Site Control Center: captures go to the clipboard with Arc's Save toast, Share stays open, the lock shows the certificate (#90) (#116)

Victor Kildahl9b855931c8b4
diff --git a/Packages/CraCore/Sources/CraCore/ConnectionSecurity.swift b/Packages/CraCore/Sources/CraCore/ConnectionSecurity.swift
new file mode 100644
index 0000000..b99aa18
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/ConnectionSecurity.swift
@@ -0,0 +1,37 @@
+import Foundation
+
+/// The Site Control Center's connection badge, "Secure" or "Not Secure" (GitHub #90): Chrome's
+/// security level, read from the page's SSL status rather than its URL, in Arc's two states.
+///
+/// An https page whose certificate has an error (the user went past the warning, or the warning
+/// page itself) or that showed or ran http content is not secure. Chromium's own pages are.
+public enum ConnectionSecurity {
+ /// Chromium's SSL status of the page on screen (CefSSLStatus).
+ public struct Status: Equatable, Sendable {
+ /// The page came over a connection with a certificate.
+ public var secureConnection: Bool
+ /// net::CertStatus bits.
+ public var certStatus: UInt
+ /// net::SSLStatus::ContentStatus bits.
+ public var contentStatus: UInt
+
+ public init(secureConnection: Bool, certStatus: UInt, contentStatus: UInt) {
+ self.secureConnection = secureConnection
+ self.certStatus = certStatus
+ self.contentStatus = contentStatus
+ }
+ }
+
+ /// net::CERT_STATUS_ALL_ERRORS, less the two minor errors Chrome ignores
+ /// (CERT_STATUS_NO_REVOCATION_MECHANISM, CERT_STATUS_UNABLE_TO_CHECK_REVOCATION).
+ static let certErrors: UInt = 0xFF00_FFFF & ~UInt(1 << 4 | 1 << 5)
+ /// SSL_CONTENT_DISPLAYED_INSECURE_CONTENT, SSL_CONTENT_RAN_INSECURE_CONTENT.
+ static let insecureContent: UInt = 1 << 0 | 1 << 1
+
+ /// `status` is nil before a page has committed (or with no page at all): the URL decides.
+ public static func isSecure(url: String, status: Status?) -> Bool {
+ if url.hasPrefix("chrome://") || url.hasPrefix("chrome-extension://") { return true }
+ guard let status else { return url.hasPrefix("https://") }
+ return status.secureConnection && status.certStatus & certErrors == 0 && status.contentStatus & insecureContent == 0
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/ConnectionSecurityTests.swift b/Packages/CraCore/Tests/CraCoreTests/ConnectionSecurityTests.swift
new file mode 100644
index 0000000..36b763d
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/ConnectionSecurityTests.swift
@@ -0,0 +1,48 @@
+import CraCore
+import Testing
+
+/// The Site Control Center's "Secure" badge follows the connection, not the URL (GitHub #90).
+struct ConnectionSecurityTests {
+ private func status(_ secure: Bool = true, cert: UInt = 0, content: UInt = 0) -> ConnectionSecurity.Status {
+ ConnectionSecurity.Status(secureConnection: secure, certStatus: cert, contentStatus: content)
+ }
+
+ @Test func aValidCertificateIsSecure() {
+ #expect(ConnectionSecurity.isSecure(url: "https://example.com/", status: status()))
+ // CERT_STATUS_IS_EV and CERT_STATUS_REV_CHECKING_ENABLED are notes, not errors.
+ #expect(ConnectionSecurity.isSecure(url: "https://example.com/", status: status(cert: 1 << 16 | 1 << 17)))
+ }
+
+ /// An https page the user reached past a certificate warning reads "Not Secure".
+ @Test func aCertificateErrorIsNotSecure() {
+ #expect(!ConnectionSecurity.isSecure(url: "https://expired.badssl.com/", status: status(cert: 1 << 1)))
+ #expect(!ConnectionSecurity.isSecure(url: "https://self-signed.badssl.com/", status: status(cert: 1 << 2)))
+ #expect(!ConnectionSecurity.isSecure(url: "https://revoked.badssl.com/", status: status(cert: 1 << 6)))
+ }
+
+ /// Chrome ignores the two minor revocation errors.
+ @Test func revocationThatCannotBeCheckedIsNotAnError() {
+ #expect(ConnectionSecurity.isSecure(url: "https://example.com/", status: status(cert: 1 << 4 | 1 << 5)))
+ }
+
+ @Test func mixedContentIsNotSecure() {
+ #expect(!ConnectionSecurity.isSecure(url: "https://example.com/", status: status(content: 1 << 0)))
+ #expect(!ConnectionSecurity.isSecure(url: "https://example.com/", status: status(content: 1 << 1)))
+ }
+
+ @Test func plainHTTPIsNotSecure() {
+ #expect(!ConnectionSecurity.isSecure(url: "http://example.com/", status: status(false)))
+ #expect(!ConnectionSecurity.isSecure(url: "file:///tmp/a.html", status: status(false)))
+ }
+
+ /// Before a page commits (or for a sleeping tab) the scheme is all there is.
+ @Test func withoutAStatusTheSchemeDecides() {
+ #expect(ConnectionSecurity.isSecure(url: "https://example.com/", status: nil))
+ #expect(!ConnectionSecurity.isSecure(url: "http://example.com/", status: nil))
+ }
+
+ @Test func chromiumsOwnPagesAreSecure() {
+ #expect(ConnectionSecurity.isSecure(url: "chrome://extensions", status: status(false)))
+ #expect(ConnectionSecurity.isSecure(url: "chrome-extension://abc/options.html", status: nil))
+ }
+}
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index c415b4a..a080867 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -76,6 +76,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
NSApp.activate(ignoringOtherApps: true)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in self?.installURLEventHandler() }
+ // The Site Control Center's Share would otherwise pay for finding the share extensions.
+ DispatchQueue.main.asyncAfter(deadline: .now() + 5) { SharePicker.warmUp() }
// Extension welcome pages and chrome.tabs.create land in Cra, not in a Chrome window.
// --load-extension extensions count as freshly installed on every launch, so their
// onInstalled welcome pages come back each time: right after launch, drop them unless
diff --git a/Sources/Cra/UI/SiteControlCenter.swift b/Sources/Cra/UI/SiteControlCenter.swift
index 93650bc..efcb58b 100644
--- a/Sources/Cra/UI/SiteControlCenter.swift
+++ b/Sources/Cra/UI/SiteControlCenter.swift
@@ -8,7 +8,8 @@ import AppKit
/// with the connection state and a More menu. A tile's 14 pt badge pins it to the toolbar:
/// filled for pinned extensions, grey on hover for the others.
struct SiteControlCenterActions {
- var share: () -> Void = {}
+ /// Gets the Share button, to hang the share list from.
+ var share: (NSView) -> Void = { _ in }
var copyURL: () -> Void = {}
var capture: () -> Void = {}
var captureFullPage: () -> Void = {}
@@ -18,6 +19,8 @@ struct SiteControlCenterActions {
var clearCache: () -> Void = {}
var clearCookies: () -> Void = {}
var siteSettings: () -> Void = {}
+ /// The lock: the page's certificate. nil without one (http, Chromium's pages).
+ var showCertificate: (() -> Void)?
}
enum SiteControlCenterMetrics {
@@ -33,6 +36,8 @@ enum SiteControlCenterMetrics {
final class SiteControlCenterView: NSView {
private typealias M = SiteControlCenterMetrics
private let url: String
+ /// The connection badge (ConnectionSecurity).
+ private let secure: Bool
private let colors: SiteControlCenterColors
private let actions: SiteControlCenterActions
private let store: SidebarStore
@@ -40,8 +45,9 @@ final class SiteControlCenterView: NSView {
private let profile: String
private var extensions: ExtensionStore { .shared }
- init(url: String, dark: Bool, profile: String, actions: SiteControlCenterActions, store: SidebarStore) {
+ init(url: String, secure: Bool, dark: Bool, profile: String, actions: SiteControlCenterActions, store: SidebarStore) {
self.url = url
+ self.secure = secure
self.profile = profile
colors = SiteControlCenterColors(dark: dark)
self.actions = actions
@@ -58,8 +64,6 @@ final class SiteControlCenterView: NSView {
var onResize: (NSSize) -> Void = { _ in }
- private var isSecure: Bool { url.hasPrefix("https://") || url.hasPrefix("chrome://") || url.hasPrefix("chrome-extension://") }
-
/// Arc: pinned extensions in toolbar order, then the rest by name.
private var orderedExtensions: [ExtensionStore.Entry] {
let entries = extensions.entries(inProfile: profile)
@@ -85,10 +89,12 @@ final class SiteControlCenterView: NSView {
let x = M.inset, w = M.width - 2 * M.inset
var y: CGFloat = 9
// The four raised action buttons.
- for (i, (symbol, help, run)) in [("square.and.arrow.up", "Share", actions.share), ("link", "Copy URL", actions.copyURL),
+ let share = actions.share
+ for (i, (symbol, help, run)) in [("square.and.arrow.up", "Share", {}), ("link", "Copy URL", actions.copyURL),
("camera", "Capture this page", actions.capture),
("text.viewfinder", "Capture the full page", actions.captureFullPage)].enumerated() {
let b = SiteActionButton(symbol: symbol, help: help, colors: colors, action: run)
+ if i == 0 { b.onClick = { [weak b] in if let b { share(b) } } }
b.frame = NSRect(x: x + CGFloat(i) * (M.tile.width + M.gap), y: y, width: M.tile.width, height: M.tile.height)
addSubview(b)
}
@@ -140,7 +146,7 @@ final class SiteControlCenterView: NSView {
addSubview(divider)
y += 1 + 12
// Footer: the connection state, the More menu.
- let secure = SiteSecurityPill(secure: isSecure, colors: colors)
+ let secure = SiteSecurityPill(secure: secure, colors: colors, action: actions.showCertificate)
secure.frame.origin = NSPoint(x: x, y: y)
addSubview(secure)
let more = SiteMoreButton(colors: colors, actions: actions)
@@ -206,6 +212,12 @@ private class SiteHoverView: NSView {
override func mouseUp(with event: NSEvent) {
if bounds.contains(convert(event.locationInWindow, from: nil)) { onClick() }
}
+
+ /// VoiceOver's press is a click.
+ override func accessibilityPerformPress() -> Bool {
+ onClick()
+ return true
+ }
}
/// A titled section; hovering it shows `hoverText` at the header's right end (Arc: "Manage").
@@ -387,6 +399,9 @@ private final class SiteActionButton: SiteHoverView {
glyph.imageScaling = .scaleNone
addSubview(glyph)
_ = ArcTooltipAnchorView.attach(to: self, help: help)
+ setAccessibilityElement(true)
+ setAccessibilityLabel(help)
+ setAccessibilityRole(.button)
refresh()
}
@@ -452,9 +467,16 @@ private final class SiteSettingRow: SiteHoverView {
override func refresh() { alphaValue = hovered ? 0.85 : 1 }
}
-private final class SiteSecurityPill: NSView {
- init(secure: Bool, colors: SiteControlCenterColors) {
+/// Pressed, it shows the page's certificate (Arc closes the control center and opens it).
+private final class SiteSecurityPill: SiteHoverView {
+ private let colors: SiteControlCenterColors
+ private let clickable: Bool
+
+ init(secure: Bool, colors: SiteControlCenterColors, action: (() -> Void)?) {
+ self.colors = colors
+ clickable = action != nil
super.init(frame: .zero)
+ if let action { onClick = action }
wantsLayer = true
layer?.cornerRadius = 8
layer?.cornerCurve = .continuous
@@ -474,9 +496,19 @@ private final class SiteSecurityPill: NSView {
addSubview(lock)
addSubview(label)
_ = ArcTooltipAnchorView.attach(to: self, help: secure ? "Your connection to this site is secure" : "Your connection to this site is not secure")
+ setAccessibilityElement(true)
+ setAccessibilityLabel(secure ? "Secure" : "Not Secure")
+ setAccessibilityRole(clickable ? .button : .staticText)
}
required init?(coder: NSCoder) { fatalError() }
+
+ override func refresh() {
+ // The More button's hover: SwiftUI's .brightness(0.04).
+ let c = colors.footerFill.usingColorSpace(.sRGB) ?? colors.footerFill
+ layer?.backgroundColor = (hovered && clickable ? NSColor(srgbRed: min(1, c.redComponent + 0.04), green: min(1, c.greenComponent + 0.04),
+ blue: min(1, c.blueComponent + 0.04), alpha: c.alphaComponent) : c).cgColor
+ }
}
/// Arc's footer "…": Clear Cache, Clear Cookies, Manage Extensions, Add Extension, All Site Settings.
@@ -541,7 +573,8 @@ final class SiteControlCenterPopover: NSObject, NSPopoverDelegate {
var isShown: Bool { popover?.isShown == true }
- func show(relativeTo rect: NSRect, of view: NSView, url: String, dark: Bool, profile: String, store: SidebarStore, actions: SiteControlCenterActions) {
+ func show(relativeTo rect: NSRect, of view: NSView, url: String, secure: Bool, dark: Bool, profile: String, store: SidebarStore,
+ actions: SiteControlCenterActions) {
// A transient popover closes on the mouse-down outside it; the button fires on that
// click's mouse-up. The same click on the sliders button closes it, as in Arc,
// however long the press took (GitHub #42): the latest mouse-down is the closing one.
@@ -558,9 +591,9 @@ final class SiteControlCenterPopover: NSObject, NSPopoverDelegate {
p.delegate = self
p.appearance = NSAppearance(named: dark ? .darkAqua : .aqua)
var acts = actions
- // Every action ends the popover, as in Arc (pinning keeps it open).
+ // Every action ends the popover, as in Arc (pinning keeps it open, and the share list
+ // opens over it).
func closing(_ f: @escaping () -> Void) -> () -> Void { { [weak p] in p?.performClose(nil); f() } }
- acts.share = closing(actions.share)
acts.copyURL = closing(actions.copyURL)
acts.capture = closing(actions.capture)
acts.captureFullPage = closing(actions.captureFullPage)
@@ -570,7 +603,8 @@ final class SiteControlCenterPopover: NSObject, NSPopoverDelegate {
acts.siteSettings = closing(actions.siteSettings)
acts.clearCache = closing(actions.clearCache)
acts.clearCookies = closing(actions.clearCookies)
- let content = SiteControlCenterView(url: url, dark: dark, profile: profile, actions: acts, store: store)
+ acts.showCertificate = actions.showCertificate.map(closing)
+ let content = SiteControlCenterView(url: url, secure: secure, dark: dark, profile: profile, actions: acts, store: store)
let host = NSViewController()
host.view = content
host.preferredContentSize = content.frame.size
@@ -582,9 +616,57 @@ final class SiteControlCenterPopover: NSObject, NSPopoverDelegate {
func close() { popover?.performClose(nil) }
+ /// While the share list is up the popover only closes when Cra closes it: a transient one
+ /// can go when a menu opens over it.
+ func holdOpen(_ hold: Bool) { popover?.behavior = hold ? .applicationDefined : .transient }
+
func popoverWillClose(_ notification: Notification) {
if let e = NSApp.currentEvent, e.type == .leftMouseDown { closingClick = e.timestamp }
}
func popoverDidClose(_ notification: Notification) { popover = nil }
}
+
+/// The Site Control Center's share list (GitHub #90). macOS finds the share extensions the
+/// first time a process asks, about 0.3 s on the main thread, so that happens once off it
+/// soon after launch. The list keeps the system's own services, as Arc's shorter one does.
+@MainActor
+final class SharePicker: NSObject, @preconcurrency NSSharingServicePickerDelegate {
+ static let shared = SharePicker()
+ private static let kept: [NSSharingService.Name] = [
+ .composeMessage, .composeEmail, .sendViaAirDrop, .init("com.apple.Notes.SharingExtension"),
+ .init("com.apple.reminders.sharingextension"),
+ ]
+ private var picker: NSSharingServicePicker?
+ private var done: (_ chose: Bool) -> Void = { _ in }
+
+ nonisolated static func warmUp() {
+ DispatchQueue.global(qos: .utility).async {
+ // Deprecated, but the only call that finds them without showing a menu.
+ _ = NSSharingService.sharingServices(forItems: [URL(string: "https://example.com")!])
+ }
+ }
+
+ /// `done` runs when the list goes, `chose` when a service was picked.
+ func show(_ url: URL, relativeTo anchor: NSView, done: @escaping (_ chose: Bool) -> Void) {
+ let picker = NSSharingServicePicker(items: [url])
+ picker.delegate = self
+ self.picker = picker
+ self.done = done
+ picker.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .minY)
+ }
+
+ func sharingServicePicker(_ sharingServicePicker: NSSharingServicePicker, sharingServicesForItems items: [Any],
+ proposedSharingServices proposedServices: [NSSharingService]) -> [NSSharingService] {
+ // NSSharingService has no public name: match the titles of the named services.
+ let titles = Set(Self.kept.compactMap { NSSharingService(named: $0)?.title })
+ let kept = proposedServices.filter { titles.contains($0.title) }
+ return kept.isEmpty ? proposedServices : kept
+ }
+
+ func sharingServicePicker(_ sharingServicePicker: NSSharingServicePicker, didChoose service: NSSharingService?) {
+ guard sharingServicePicker === picker else { return }
+ picker = nil
+ done(service != nil)
+ }
+}
diff --git a/Sources/Cra/UI/Windows/CertificateWindow.swift b/Sources/Cra/UI/Windows/CertificateWindow.swift
new file mode 100644
index 0000000..4839889
--- /dev/null
+++ b/Sources/Cra/UI/Windows/CertificateWindow.swift
@@ -0,0 +1,45 @@
+import AppKit
+import SecurityInterface
+
+/// The Site Control Center's lock (GitHub #90): the page's certificate chain in macOS's
+/// certificate sheet, trust evaluated for the host, as Arc opens Chromium's viewer from it.
+/// Like Chrome's SSLCertificateViewerMac, the sheet hangs off a clear window laid over the
+/// browser window, so the page's own child windows can't cover it.
+@MainActor
+final class CertificateWindow: NSObject {
+ private static var current: CertificateWindow?
+ private let overlay: NSWindow
+
+ /// `certificates`: DER, the server's first, then its issuers.
+ static func show(_ certificates: [Data], host: String, over window: NSWindow) {
+ let chain = certificates.compactMap { SecCertificateCreateWithData(nil, $0 as CFData) }
+ var trust: SecTrust?
+ guard current == nil, !chain.isEmpty,
+ SecTrustCreateWithCertificates(chain as CFArray, SecPolicyCreateSSL(true, host as CFString), &trust) == errSecSuccess,
+ let trust else { return }
+ // Only what Chromium already fetched; no revocation or issuer requests from here.
+ SecTrustSetNetworkFetchAllowed(trust, false)
+ let viewer = CertificateWindow(over: window)
+ current = viewer
+ SFCertificatePanel.shared().beginSheet(for: viewer.overlay, modalDelegate: viewer,
+ didEnd: #selector(sheetDidEnd(_:returnCode:contextInfo:)), contextInfo: nil,
+ trust: trust, showGroup: true)
+ }
+
+ private init(over window: NSWindow) {
+ overlay = NSWindow(contentRect: window.frame, styleMask: .borderless, backing: .buffered, defer: false)
+ overlay.isOpaque = false
+ overlay.backgroundColor = .clear
+ overlay.hasShadow = false
+ overlay.ignoresMouseEvents = true
+ overlay.isReleasedWhenClosed = false
+ super.init()
+ window.addChildWindow(overlay, ordered: .above)
+ }
+
+ @objc private func sheetDidEnd(_ sheet: NSWindow, returnCode: Int, contextInfo: UnsafeMutableRawPointer?) {
+ overlay.parent?.removeChildWindow(overlay)
+ overlay.orderOut(nil)
+ Self.current = nil
+ }
+}
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index 97153b0..61b5d31 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -1356,25 +1356,13 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
b.setZoomLevel(b.zoomLevel() + delta)
}
- /// Arc's Capture: save a PNG of the page area to ~/Downloads.
+ /// Arc's Capture: the visible page as a PNG. Chromium draws it (Page.captureScreenshot), so
+ /// it holds the page whatever display the window is on and whatever is in front of it.
func capturePage() {
- guard let window else { return }
- let rectInWindow = shell.webContainer.convert(shell.webContainer.bounds, to: nil)
- var screenRect = window.convertToScreen(rectInWindow)
- // CGWindowList uses top-left origin.
- if let screen = NSScreen.screens.first {
- screenRect.origin.y = screen.frame.height - screenRect.maxY
- }
- let captureWindow = browsers.visibleRuntime?.hostWindow ?? window
- guard let image = CGWindowListCreateImage(screenRect, .optionIncludingWindow, CGWindowID(captureWindow.windowNumber), [.bestResolution]) else { return }
- let rep = NSBitmapImageRep(cgImage: image)
- guard let png = rep.representation(using: .png, properties: [:]) else { return }
- let f = DateFormatter()
- f.dateFormat = "yyyy-MM-dd 'at' HH.mm.ss"
- let url = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0]
- .appendingPathComponent("Cra Capture \(f.string(from: Date())).png")
- try? png.write(to: url)
- NSWorkspace.shared.activateFileViewerSelecting([url])
+ guard let b = currentBrowser else { return }
+ b.sendDevToolsMethod("Page.captureScreenshot", params: #"{"format":"png","captureBeyondViewport":false}"#) { [weak self] shot, error in
+ MainActor.assumeIsolated { self?.finishCapture(shot, error: error) }
+ }
}
// MARK: Sidebar
@@ -1958,7 +1946,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
let rect = content.convert(window.convertFromScreen(onScreen), from: nil)
let url = selectedTabID.flatMap { store.item($0)?.tab?.url } ?? ""
var actions = SiteControlCenterActions()
- actions.share = { [weak self] in self?.shareCurrentPage(from: rect, in: content) }
+ actions.share = { [weak self] anchor in self?.shareCurrentPage(from: anchor) }
actions.copyURL = { [weak self] in self?.app.perform("copyURL") }
actions.capture = { [weak self] in self?.capturePage() }
actions.captureFullPage = { [weak self] in self?.captureFullPage() }
@@ -1967,12 +1955,17 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
actions.manageExtensions = { [weak self] in self?.openTab("chrome://extensions") }
actions.clearCache = { [weak self] in self?.currentBrowser?.clearSiteDataAndReload(cookies: false) }
actions.clearCookies = { [weak self] in self?.currentBrowser?.clearSiteDataAndReload(cookies: true) }
+ let ssl = currentBrowser?.sslStatus()
+ let secure = ConnectionSecurity.isSecure(url: url, status: ssl.map {
+ ConnectionSecurity.Status(secureConnection: $0.secureConnection, certStatus: $0.certStatus, contentStatus: $0.contentStatus)
+ })
+ if ssl?.certificates.isEmpty == false { actions.showCertificate = { [weak self] in self?.showCertificate() } }
actions.siteSettings = { [weak self] in
guard let origin = URL(string: url).flatMap({ u in u.host.map { "\(u.scheme ?? "https")://\($0)" } }) else { return }
self?.openTab("chrome://settings/content/siteDetails?site=" + (origin.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? origin))
}
siteControlCenterSpaceID = focusedSpaceID
- siteControlCenter.show(relativeTo: rect, of: content, url: url, dark: focusedSpace.theme.palette.isDark,
+ siteControlCenter.show(relativeTo: rect, of: content, url: url, secure: secure, dark: focusedSpace.theme.palette.isDark,
profile: profileDirectoryName, store: store, actions: actions)
}
@@ -1981,33 +1974,84 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
showWindow(nil)
}
- private func shareCurrentPage(from rect: NSRect, in view: NSView) {
+ /// The share list over the Site Control Center's Share button; the control center stays
+ /// open behind it, as in Arc.
+ private func shareCurrentPage(from anchor: NSView) {
guard let url = selectedTabID.flatMap({ store.item($0)?.tab?.url }).flatMap(URL.init(string:)) else { return }
- NSSharingServicePicker(items: [url]).show(relativeTo: rect, of: view, preferredEdge: .minY)
+ siteControlCenter.holdOpen(true)
+ SharePicker.shared.show(url, relativeTo: anchor) { [weak self] chose in
+ self?.siteControlCenter.holdOpen(false)
+ // The service's own window (Mail, AirDrop) takes over.
+ if chose { self?.siteControlCenter.close() }
+ }
+ }
+
+ /// The lock in the Site Control Center: the certificate of the page on screen.
+ private func showCertificate() {
+ guard let b = currentBrowser, let window else { return }
+ let host = URL(string: b.currentURL)?.host ?? ""
+ guard let certificates = b.sslStatus()?.certificates, !certificates.isEmpty else { return }
+ CertificateWindow.show(certificates, host: host, over: window)
}
- /// Arc's "Capture the full page": the whole document (beyond the viewport) as a PNG in Downloads.
+ /// Arc's "Capture the full page": the whole document, beyond the viewport, as a PNG.
func captureFullPage() {
guard let b = currentBrowser else { return }
- b.sendDevToolsMethod("Page.getLayoutMetrics", params: "{}") { result, _ in
+ showToast("Capture in Progress")
+ // Both completions come on the main queue.
+ b.sendDevToolsMethod("Page.getLayoutMetrics", params: "{}") { [weak self] result, error in
guard let result, let m = try? JSONSerialization.jsonObject(with: Data(result.utf8)) as? [String: Any],
let size = (m["cssContentSize"] ?? m["contentSize"]) as? [String: Any],
- let w = size["width"] as? Double, let h = size["height"] as? Double else { return }
+ let w = size["width"] as? Double, let h = size["height"] as? Double else {
+ MainActor.assumeIsolated { self?.finishCapture(nil, error: error) }
+ return
+ }
let params = #"{"format":"png","captureBeyondViewport":true,"clip":{"x":0,"y":0,"width":\#(w),"height":\#(min(h, 16384)),"scale":1}}"#
b.sendDevToolsMethod("Page.captureScreenshot", params: params) { shot, error in
- guard let shot, let o = try? JSONSerialization.jsonObject(with: Data(shot.utf8)) as? [String: Any],
- let b64 = o["data"] as? String, let png = Data(base64Encoded: b64) else {
- NSLog("Cra: full-page capture failed: %@", error ?? "no data")
- return
- }
- DispatchQueue.main.async {
- let f = DateFormatter()
- f.dateFormat = "yyyy-MM-dd 'at' HH.mm.ss"
- let url = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0]
- .appendingPathComponent("Cra Capture \(f.string(from: Date())).png")
- try? png.write(to: url)
- NSWorkspace.shared.activateFileViewerSelecting([url])
- }
+ MainActor.assumeIsolated { self?.finishCapture(shot, error: error) }
+ }
+ }
+ }
+
+ /// As Arc does with a capture: the image goes on the clipboard with the shutter sound, and
+ /// the toast's Save puts it in a file. Finder stays where it is (GitHub #90).
+ private func finishCapture(_ shot: String?, error: String?) {
+ guard let shot, let o = try? JSONSerialization.jsonObject(with: Data(shot.utf8)) as? [String: Any],
+ let b64 = o["data"] as? String, let png = Data(base64Encoded: b64), let image = NSImage(data: png) else {
+ NSLog("Cra: capture failed: %@", error ?? "no data")
+ showToast("Capture Failed")
+ return
+ }
+ let pasteboard = NSPasteboard.general
+ pasteboard.declareTypes([.png, .tiff], owner: nil)
+ pasteboard.setData(png, forType: .png)
+ if let tiff = image.tiffRepresentation { pasteboard.setData(tiff, forType: .tiff) }
+ Self.shutter?.stop()
+ Self.shutter?.play()
+ showToast("Screenshot Copied to Clipboard", action: ShinyToast.Action(title: "Save") { [weak self] in self?.saveCapture(png) })
+ }
+
+ /// macOS's own screenshot sound.
+ private static let shutter = NSSound(contentsOfFile: "/System/Library/Components/CoreAudio.component/Contents/SharedSupport/SystemSounds/system/Screen Capture.aif",
+ byReference: true)
+
+ /// The toast's Save: Arc's "Save Capture Image" panel, in Downloads.
+ private func saveCapture(_ png: Data) {
+ guard let window else { return }
+ let f = DateFormatter()
+ f.dateFormat = "yyyy-MM-dd 'at' HH.mm.ss"
+ let panel = NSSavePanel()
+ panel.title = "Save Capture Image"
+ panel.nameFieldStringValue = "Cra Capture \(f.string(from: Date())).png"
+ panel.allowedContentTypes = [.png]
+ panel.directoryURL = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first
+ panel.beginSheetModal(for: window) { [weak self] response in
+ guard response == .OK, let url = panel.url else { return }
+ do {
+ try png.write(to: url)
+ } catch {
+ NSLog("Cra: saving a capture failed: %@", error.localizedDescription)
+ self?.showToast("Failed to Save Capture")
}
}
}
@@ -2194,10 +2238,10 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
/// Arc's toast at the top right of the page (ShinyToast): Cra's confirmations.
- func showToast(_ text: String) {
+ func showToast(_ text: String, action: ShinyToast.Action? = nil) {
guard let window else { return }
let page = shell.webContainer.convert(shell.webContainer.bounds, to: nil)
- toast.show(text, page: page, in: window, theme: focusedSpace.theme)
+ toast.show(text, action: action, page: page, in: window, theme: focusedSpace.theme)
}
/// Navigate the focused tab (an empty split pane gets its first page here).
diff --git a/Sources/Cra/UI/Windows/ShinyToast.swift b/Sources/Cra/UI/Windows/ShinyToast.swift
index 9428316..dfdba72 100644
--- a/Sources/Cra/UI/Windows/ShinyToast.swift
+++ b/Sources/Cra/UI/Windows/ShinyToast.swift
@@ -8,9 +8,16 @@ import QuartzCore
/// page and 9 pt in from its right edge, 14 pt medium black text with 12 pt either side, a fill
/// from the space's colours with a 1 pt darker outline. It springs in from its top centre
/// (≈0.3 s response, 4 % overshoot), stays 4.85 s after the last tab it announced (another one
-/// bumps it by 4 %) and shrinks back into its top in 80 ms.
+/// bumps it by 4 %) and shrinks back into its top in 80 ms. Some of Arc's carry a button
+/// ("Screenshot Copied to Clipboard" offers Save): a capsule after the text, and the toast stays
+/// up while the pointer is on it.
@MainActor
final class ShinyToast {
+ struct Action {
+ let title: String
+ let run: () -> Void
+ }
+
static let height: CGFloat = 42
static let topInset: CGFloat = 8
static let trailingInset: CGFloat = 9
@@ -21,11 +28,22 @@ final class ShinyToast {
static let font = NSFont.systemFont(ofSize: 14, weight: .medium)
/// How long the toast stays up after the last message.
static let visibleFor: TimeInterval = 4.85
+ static let buttonFont = NSFont.systemFont(ofSize: 13, weight: .semibold)
+ static let buttonHeight: CGFloat = 26
+ static let buttonPadding: CGFloat = 10
+ /// Between the text and the button.
+ static let buttonGap: CGFloat = 10
private let panel: NSPanel
+ private let view = ToastView()
private let pill = CAGradientLayer()
private let label = CATextLayer()
+ private let button = CALayer()
+ private let buttonLabel = CATextLayer()
private var hide: DispatchWorkItem?
+ private var action: Action?
+ /// The text colour: the button is a wash of it.
+ private var buttonTint = NSColor.black
init() {
panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 140, height: Self.height),
@@ -35,7 +53,7 @@ final class ShinyToast {
panel.hasShadow = false
panel.ignoresMouseEvents = true
panel.hidesOnDeactivate = false
- let view = NSView(frame: panel.contentLayoutRect)
+ view.frame = panel.contentLayoutRect
view.wantsLayer = true
panel.contentView = view
pill.cornerRadius = Self.cornerRadius
@@ -46,14 +64,26 @@ final class ShinyToast {
label.alignmentMode = .center
label.foregroundColor = NSColor.black.cgColor
pill.addSublayer(label)
+ button.cornerRadius = Self.buttonHeight / 2
+ button.cornerCurve = .continuous
+ buttonLabel.font = Self.buttonFont
+ buttonLabel.fontSize = Self.buttonFont.pointSize
+ buttonLabel.alignmentMode = .center
+ button.addSublayer(buttonLabel)
+ pill.addSublayer(button)
view.layer?.addSublayer(pill)
+ view.onHover = { [weak self] inside in self?.hovered(inside) }
+ view.onClick = { [weak self] point in self?.clicked(at: point) }
}
var isShown: Bool { panel.parent != nil }
/// Shows `text` at the top right of `page` (window coordinates) over `window`'s pages.
- func show(_ text: String, page: NSRect, in window: NSWindow, theme: SpaceTheme) {
- let width = ceil((text as NSString).size(withAttributes: [.font: Self.font]).width) + 2 * Self.padding
+ func show(_ text: String, action: Action? = nil, page: NSRect, in window: NSWindow, theme: SpaceTheme) {
+ self.action = action
+ let textWidth = ceil((text as NSString).size(withAttributes: [.font: Self.font]).width)
+ let buttonWidth = action.map { ceil(($0.title as NSString).size(withAttributes: [.font: Self.buttonFont]).width) + 2 * Self.buttonPadding }
+ let width = textWidth + 2 * Self.padding + (buttonWidth.map { $0 + Self.buttonGap - Self.padding + (Self.height - Self.buttonHeight) / 2 } ?? 0)
let local = NSRect(x: page.maxX - Self.trailingInset - width, y: page.maxY - Self.topInset - Self.height,
width: width, height: Self.height)
panel.setFrame(window.convertToScreen(local.insetBy(dx: -Self.margin, dy: -Self.margin)), display: false)
@@ -72,8 +102,23 @@ final class ShinyToast {
label.contentsScale = scale
label.string = text
let lineHeight = ceil(Self.font.ascender - Self.font.descender)
- label.frame = CGRect(x: 0, y: (Self.height - lineHeight) / 2, width: width, height: lineHeight)
+ label.frame = CGRect(x: buttonWidth == nil ? 0 : Self.padding, y: (Self.height - lineHeight) / 2,
+ width: buttonWidth == nil ? width : textWidth, height: lineHeight)
+ button.isHidden = buttonWidth == nil
+ if let buttonWidth, let action {
+ let inset = (Self.height - Self.buttonHeight) / 2
+ button.frame = CGRect(x: width - inset - buttonWidth, y: inset, width: buttonWidth, height: Self.buttonHeight)
+ buttonTint = colors.text
+ button.backgroundColor = colors.text.withAlphaComponent(0.1).cgColor
+ buttonLabel.foregroundColor = colors.text.cgColor
+ buttonLabel.contentsScale = scale
+ buttonLabel.string = action.title
+ let buttonLine = ceil(Self.buttonFont.ascender - Self.buttonFont.descender)
+ buttonLabel.frame = CGRect(x: 0, y: (Self.buttonHeight - buttonLine) / 2, width: buttonWidth, height: buttonLine)
+ }
CATransaction.commit()
+ panel.ignoresMouseEvents = action == nil
+ view.hitRect = action == nil ? .zero : NSRect(x: Self.margin, y: Self.margin, width: width, height: Self.height)
if !isShown {
// Opening the tab's page holds the main thread for ~0.1 s, so the toast waits for the
// next turn, invisible: started now, its first frame showed it most of the way in.
@@ -86,12 +131,39 @@ final class ShinyToast {
// Another message while it is up: Arc bumps it (1 → 1.044 → 1 in ~0.2 s) and restarts its time.
DispatchQueue.main.async { [weak self] in self?.pulse() }
}
+ scheduleHide()
+ }
+
+ private func scheduleHide() {
hide?.cancel()
let work = DispatchWorkItem { [weak self] in self?.dismiss() }
hide = work
DispatchQueue.main.asyncAfter(deadline: .now() + Self.visibleFor, execute: work)
}
+ /// The pointer on a toast with a button holds it up; leaving starts its time again.
+ private func hovered(_ inside: Bool) {
+ guard isShown, action != nil else { return }
+ if inside {
+ hide?.cancel()
+ } else if hide?.isCancelled != false {
+ scheduleHide()
+ }
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ button.backgroundColor = buttonTint.withAlphaComponent(inside ? 0.16 : 0.1).cgColor
+ CATransaction.commit()
+ }
+
+ /// `point` in the content view: the button runs its action and the toast goes.
+ private func clicked(at point: NSPoint) {
+ guard let action, isShown else { return }
+ let local = NSPoint(x: point.x - Self.margin, y: point.y - Self.margin)
+ guard button.frame.insetBy(dx: -4, dy: -4).contains(local) else { return }
+ dismiss()
+ action.run()
+ }
+
private func springIn() {
guard isShown else { return }
let spring = CASpringAnimation(keyPath: "transform.scale")
@@ -131,6 +203,7 @@ final class ShinyToast {
hide?.cancel()
hide = nil
guard isShown else { return }
+ panel.ignoresMouseEvents = true
CATransaction.begin()
CATransaction.setCompletionBlock { [weak self] in
MainActor.assumeIsolated {
@@ -177,3 +250,29 @@ final class ShinyToast {
return (top, color(min(0.25, s * 1.3), 0.85), color(s, 0.61), .black)
}
}
+
+/// The toast's content: tracks the pointer over the pill and takes the click on its button
+/// without making Cra active first.
+private final class ToastView: NSView {
+ var hitRect: NSRect = .zero { didSet { updateTrackingAreas() } }
+ var onHover: (Bool) -> Void = { _ in }
+ var onClick: (NSPoint) -> Void = { _ in }
+
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+
+ override func hitTest(_ point: NSPoint) -> NSView? {
+ hitRect.contains(convert(point, from: superview)) ? self : nil
+ }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }
+ guard !hitRect.isEmpty else { return }
+ addTrackingArea(NSTrackingArea(rect: hitRect, options: [.mouseEnteredAndExited, .activeAlways], owner: self, userInfo: nil))
+ }
+
+ override func mouseEntered(with event: NSEvent) { onHover(true) }
+ override func mouseExited(with event: NSEvent) { onHover(false) }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) { onClick(convert(event.locationInWindow, from: nil)) }
+}
diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mm
index 33ebdc5..6d5249d 100644
--- a/Sources/CraCEF/CraCEF.mm
+++ b/Sources/CraCEF/CraCEF.mm
@@ -26,6 +26,7 @@
#include "include/cef_keyboard_handler.h"
#include "include/cef_life_span_handler.h"
#include "include/cef_load_handler.h"
+#include "include/cef_navigation_entry.h"
#include "include/cef_parser.h"
#include "include/cef_permission_handler.h"
#include "include/cef_request_context.h"
@@ -150,6 +151,9 @@ enum CraMenuCommand {
@implementation CraDownloadInfo
@end
+@implementation CraSSLStatus
+@end
+
// MARK: - CraBrowser private interface
class CraClient;
@@ -1912,6 +1916,32 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {
if (f) f->ExecuteJavaScript(CefStringFromNS(script), f->GetURL(), 0);
}
+- (CraSSLStatus*)sslStatus {
+ if (!_browser) return nil;
+ CefRefPtr<CefNavigationEntry> entry = _browser->GetHost()->GetVisibleNavigationEntry();
+ CefRefPtr<CefSSLStatus> ssl = entry ? entry->GetSSLStatus() : nullptr;
+ if (!ssl) return nil;
+ CraSSLStatus* status = [CraSSLStatus new];
+ status.secureConnection = ssl->IsSecureConnection();
+ status.certStatus = (NSUInteger)ssl->GetCertStatus();
+ status.contentStatus = (NSUInteger)ssl->GetContentStatus();
+ NSMutableArray<NSData*>* certificates = [NSMutableArray array];
+ auto add = [&](CefRefPtr<CefBinaryValue> der) {
+ if (!der || !der->GetSize()) return;
+ NSMutableData* data = [NSMutableData dataWithLength:der->GetSize()];
+ der->GetData(data.mutableBytes, data.length, 0);
+ [certificates addObject:data];
+ };
+ if (CefRefPtr<CefX509Certificate> cert = ssl->GetX509Certificate()) {
+ add(cert->GetDEREncoded());
+ CefX509Certificate::IssuerChainBinaryList chain;
+ cert->GetDEREncodedIssuerChain(chain);
+ for (auto& der : chain) add(der);
+ }
+ status.certificates = certificates;
+ return status;
+}
+
- (double)zoomLevel { return _browser ? _browser->GetHost()->GetZoomLevel() : 0; }
- (void)setZoomLevel:(double)level { if (_browser) _browser->GetHost()->SetZoomLevel(level); }
diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.h
index 63edf43..05e9ac9 100644
--- a/Sources/CraCEF/include/CraCEF.h
+++ b/Sources/CraCEF/include/CraCEF.h
@@ -24,6 +24,18 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
@property (nonatomic) CraDownloadState state;
@end
+/// The connection of the page on screen (Chromium's SSL status of the visible navigation entry).
+@interface CraSSLStatus : NSObject
+/// The page came over a connection with a certificate (https, whatever the certificate's errors).
+@property (nonatomic) BOOL secureConnection;
+/// net::CertStatus bits: the certificate's errors and notes.
+@property (nonatomic) NSUInteger certStatus;
+/// net::SSLStatus::ContentStatus bits: http content the page showed or ran.
+@property (nonatomic) NSUInteger contentStatus;
+/// The server's certificate, then its issuers, DER encoded; empty without a certificate.
+@property (nonatomic, copy) NSArray<NSData *> *certificates;
+@end
+
@protocol CraBrowserDelegate <NSObject>
- (void)browser:(CraBrowser *)browser didChangeTitle:(NSString *)title;
- (void)browser:(CraBrowser *)browser didChangeURL:(NSString *)url;
@@ -187,6 +199,8 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
/// `params` is a JSON object string; the completion gets the result JSON or an error.
- (void)sendDevToolsMethod:(NSString *)method params:(NSString *)params
completion:(void (^)(NSString * _Nullable result, NSString * _Nullable error))completion;
+/// The page on screen's connection; nil before anything has committed.
+- (nullable CraSSLStatus *)sslStatus;
- (void)notifyMoveOrResizeStarted;
/// Asynchronous. -browserDidClose: fires when Chromium is done.
- (void)close;