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.

Arc parity: Library ▸ Media, the address menu's capture and extension items, Capture in Portrait Mode

Victor2294e1353f6c
diff --git a/Packages/CraCore/Sources/CraCore/MediaLibrary.swift b/Packages/CraCore/Sources/CraCore/MediaLibrary.swift
new file mode 100644
index 0000000..b2ceaf7
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/MediaLibrary.swift
@@ -0,0 +1,57 @@
+import Foundation
+
+/// Arc's Library ▸ Media (HomeButton/Pages/Media, Arc 1.172.1): the images and videos in a few
+/// of the Mac's folders, newest first, in a two-column grid, searched by file name. Arc reads the
+/// folders itself (no Spotlight) and shows nothing until "Show Media" is pressed, since reading
+/// Desktop and Documents asks macOS for access. The right-click menu on the Library button picks
+/// the folders ("Show media": Documents, Desktop, Screenshots, Arc Captures, Downloads; Cra saves
+/// captures where you choose, so it has no captures folder).
+public enum MediaLibrary {
+ public enum Folder: String, Codable, CaseIterable, Sendable {
+ case documents, desktop, screenshots, downloads
+
+ public var title: String {
+ switch self {
+ case .documents: "Documents"
+ case .desktop: "Desktop"
+ case .screenshots: "Screenshots"
+ case .downloads: "Downloads"
+ }
+ }
+ }
+
+ public struct File: Equatable, Sendable {
+ public var path: String
+ public var date: Date
+ public init(path: String, date: Date) {
+ self.path = path
+ self.date = date
+ }
+ public var name: String { (path as NSString).lastPathComponent }
+ }
+
+ /// What counts as media: pictures and videos Quick Look can draw.
+ static let extensions: Set<String> = ["png", "jpg", "jpeg", "gif", "heic", "heif", "webp", "tiff", "tif", "bmp", "avif",
+ "mov", "mp4", "m4v"]
+
+ public static func isMedia(_ path: String) -> Bool {
+ extensions.contains((path as NSString).pathExtension.lowercased()) && !(path as NSString).lastPathComponent.hasPrefix(".")
+ }
+
+ /// The grid's files: media only, each path once (Screenshots is often the Desktop), newest
+ /// first, those whose name holds the query, at most `limit`.
+ public static func shown(_ files: [File], query: String, limit: Int = 500) -> [File] {
+ let needle = query.trimmingCharacters(in: .whitespaces).lowercased()
+ var seen = Set<String>()
+ return files
+ .filter { isMedia($0.path) && seen.insert($0.path).inserted }
+ .filter { needle.isEmpty || $0.name.lowercased().contains(needle) }
+ .sorted { $0.date != $1.date ? $0.date > $1.date : $0.path < $1.path }
+ .prefix(limit).map { $0 }
+ }
+
+ /// Two to a row, as Arc's grid lays them out.
+ public static func rows(_ files: [File]) -> [[File]] {
+ stride(from: 0, to: files.count, by: 2).map { Array(files[$0..<min($0 + 2, files.count)]) }
+ }
+}
diff --git a/Packages/CraCore/Sources/CraCore/SidebarModel.swift b/Packages/CraCore/Sources/CraCore/SidebarModel.swift
index 1c246e1..2c9b70b 100644
--- a/Packages/CraCore/Sources/CraCore/SidebarModel.swift
+++ b/Packages/CraCore/Sources/CraCore/SidebarModel.swift
@@ -513,6 +513,10 @@ public struct AppSettings: Codable, Equatable {
public var websiteAppearance: WebsiteAppearance = .automatic
/// Arc's Settings ▸ Advanced "Play Arc sound effects" (the capture shutter), on by default.
public var soundEffects: Bool = true
+ /// Arc's Library ▸ Media: off until "Show Media" is pressed (reading Desktop and Documents
+ /// asks macOS for access), then the folders the Library button's "Show media" menu ticks.
+ public var mediaLibraryEnabled: Bool = false
+ public var mediaFolders: [MediaLibrary.Folder] = MediaLibrary.Folder.allCases
/// Arc's searchSuggestEnabled: the command bar asks the search engine for suggestions
/// as you type and fills its rows with them.
public var searchSuggestions: Bool = true
@@ -718,6 +722,8 @@ extension AppSettings {
httpsOnly = try c.decodeIfPresent(Bool.self, forKey: .httpsOnly) ?? false
websiteAppearance = (try? c.decodeIfPresent(WebsiteAppearance.self, forKey: .websiteAppearance)) ?? .automatic
soundEffects = try c.decodeIfPresent(Bool.self, forKey: .soundEffects) ?? true
+ mediaLibraryEnabled = try c.decodeIfPresent(Bool.self, forKey: .mediaLibraryEnabled) ?? false
+ mediaFolders = (try? c.decodeIfPresent([MediaLibrary.Folder].self, forKey: .mediaFolders)) ?? MediaLibrary.Folder.allCases
searchSuggestions = try c.decodeIfPresent(Bool.self, forKey: .searchSuggestions) ?? true
showSpaceHeaderOnSingleSpace = try c.decodeIfPresent(Bool.self, forKey: .showSpaceHeaderOnSingleSpace) ?? true
sharedFavorites = try c.decodeIfPresent(Bool.self, forKey: .sharedFavorites) ?? false
diff --git a/Packages/CraCore/Tests/CraCoreTests/MediaLibraryTests.swift b/Packages/CraCore/Tests/CraCoreTests/MediaLibraryTests.swift
new file mode 100644
index 0000000..1e6a629
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/MediaLibraryTests.swift
@@ -0,0 +1,37 @@
+import CraCore
+import Foundation
+import Testing
+
+/// Arc's Library ▸ Media (Arc 1.172.1, offline Arc on a fake home, 7 Nov 2026): screenshots on
+/// the Desktop and photos in Downloads, newest first, two to a row, no date headers.
+struct MediaLibraryTests {
+ static func file(_ path: String, _ minutesAgo: Double) -> MediaLibrary.File {
+ .init(path: path, date: Date(timeIntervalSince1970: 1_800_000_000 - minutesAgo * 60))
+ }
+
+ @Test func newestFirstAndOnlyMedia() {
+ let files = [Self.file("/d/Screenshot 1.png", 30), Self.file("/d/notes.txt", 1), Self.file("/dl/photo.JPG", 5),
+ Self.file("/dl/clip.mov", 60), Self.file("/d/.hidden.png", 0), Self.file("/doc/report.pdf", 2)]
+ #expect(MediaLibrary.shown(files, query: "").map(\.name) == ["photo.JPG", "Screenshot 1.png", "clip.mov"])
+ }
+
+ @Test func aFolderListedTwiceShowsItsFilesOnce() {
+ let shot = Self.file("/Users/me/Desktop/Screenshot.png", 3)
+ #expect(MediaLibrary.shown([shot, shot], query: "").count == 1)
+ }
+
+ @Test func searchesFileNames() {
+ let files = [Self.file("/d/Screenshot 1.png", 30), Self.file("/dl/photo.jpg", 5)]
+ #expect(MediaLibrary.shown(files, query: " SCREEN ").map(\.name) == ["Screenshot 1.png"])
+ }
+
+ @Test func twoToARow() {
+ let files = (0..<5).map { Self.file("/d/\($0).png", Double($0)) }
+ #expect(MediaLibrary.rows(files).map(\.count) == [2, 2, 1])
+ }
+
+ @Test func keepsTheNewestWhenThereAreTooMany() {
+ let files = (0..<10).map { Self.file("/d/\($0).png", Double($0)) }
+ #expect(MediaLibrary.shown(files, query: "", limit: 3).map(\.name) == ["0.png", "1.png", "2.png"])
+ }
+}
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index 0fb9f05..e8cc3e8 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -1074,7 +1074,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
case "stayOnTop": item.state = main.staysOnTop ? .on : .off
case "appearanceAutomatic", "appearanceLight", "appearanceDark":
item.state = "appearance" + store.settings.websiteAppearance.title == item.representedObject as? String ? .on : .off
- case "copyURLQuote", "savePageAs", "captureFullPage", "revealTab": return store.selectedTabID != nil
+ case "copyURLQuote", "savePageAs", "captureFullPage", "capturePortrait", "revealTab": return store.selectedTabID != nil
case "clearArchive": return !store.archive.isEmpty
case "resetSpaceTabs": return !main.isStandalone
case "toggleDeveloperMode":
@@ -1267,12 +1267,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
case "copyURLQuote": main.copyURLAsQuote()
case "savePageAs": main.savePageAs()
case "captureFullPage": main.captureFullPage()
+ case "capturePortrait": main.capturePortrait()
case "collapsePinned": if !main.isStandalone { store.togglePinnedCollapsed(main.focusedSpaceID) }
case "revealTab": main.revealSelectedTab()
case "resetSpaceTabs": main.resetAllPinnedTabs()
case "collapseAllFolders": store.setAllFoldersExpanded(false, inSpace: main.focusedSpaceID)
case "expandAllFolders": store.setAllFoldersExpanded(true, inSpace: main.focusedSpaceID)
case "openExtensions": main.showSiteControlsFromTheirButton()
+ case "manageExtensions": main.openExtensionsPage()
case "showArchive": main.showLibrary(.archive)
case "clearArchive": store.clearArchive()
case "stayOnTop": main.toggleStayOnTop()
@@ -1313,6 +1315,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
case "openLibrary": main.toggleLibrary()
case "viewArchive": main.showLibrary(.archive)
case "viewDownloads": main.showLibrary(.downloads)
+ case "viewMedia": main.showLibrary(.media)
case "goBack": main.currentBrowser?.goBack()
case "goForward": main.currentBrowser?.goForward()
case "pinTab": if let c = current, !main.isBlank { store.togglePinned(c) }
@@ -1483,7 +1486,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
file.addItem(item("closeWindow")); file.addItem(item("closeTab"))
file.addItem(.separator())
// Arc: Capture…, Capture Full Page, Save Page As, Print.
- for id in ["capturePage", "captureFullPage", "savePageAs", "print"] { file.addItem(item(id)) }
+ for id in ["capturePage", "captureFullPage", "capturePortrait", "savePageAs", "print"] { file.addItem(item(id)) }
menubar.addItem(submenu: file, title: "File")
let edit = NSMenu(title: "Edit")
@@ -1567,7 +1570,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
window.addItem(std("Minimize Window", #selector(NSWindow.performMiniaturize(_:)), "m"))
window.addItem(std("Zoom", #selector(NSWindow.performZoom(_:))))
window.addItem(.separator())
- window.addItem(item("openLibrary")); window.addItem(item("viewDownloads"))
+ window.addItem(item("openLibrary")); window.addItem(item("viewDownloads")); window.addItem(item("viewMedia"))
window.addItem(.separator())
window.addItem(item("promoteLittleWindow")); window.addItem(item("closeLittleWindows"))
window.addItem(.separator())
diff --git a/Sources/Cra/App/KeyBindings.swift b/Sources/Cra/App/KeyBindings.swift
index a48b669..137880e 100644
--- a/Sources/Cra/App/KeyBindings.swift
+++ b/Sources/Cra/App/KeyBindings.swift
@@ -144,6 +144,7 @@ final class KeyBindingRegistry {
KeyAction(id: "capturePage", name: "Capture…", section: .file, shortcuts: [Shortcut("2", cmdShift)], triggers: ["capture", "screenshot"]),
// Arc: File ▸ Capture Full Page, Save Page As ⇧⌘S.
KeyAction(id: "captureFullPage", name: "Capture Full Page", section: .file, shortcuts: [], triggers: ["full page", "screenshot"]),
+ KeyAction(id: "capturePortrait", name: "Capture in Portrait Mode", section: .file, shortcuts: [], triggers: ["portrait", "mobile screenshot"]),
KeyAction(id: "savePageAs", name: "Save Page As…", section: .file, shortcuts: [Shortcut("s", cmdShift)], triggers: ["save page", "download page"]),
KeyAction(id: "print", name: "Print", section: .file, shortcuts: [Shortcut("p", cmd)]),
// Edit
@@ -213,6 +214,7 @@ final class KeyBindingRegistry {
// Arc lists these in Settings ▸ Shortcuts and the command bar only.
KeyAction(id: "collapseAllFolders", name: "Collapse All Folders", section: .none, shortcuts: [], triggers: ["collapse folders", "close folders"]),
KeyAction(id: "expandAllFolders", name: "Expand All Folders", section: .none, shortcuts: [], triggers: ["expand folders", "open folders"]),
+ KeyAction(id: "manageExtensions", name: "Manage Extensions…", section: .none, shortcuts: [], triggers: ["manage extensions", "chrome extensions"], symbol: "puzzlepiece.extension"),
KeyAction(id: "openExtensions", name: "Open Extensions", section: .none, shortcuts: [Shortcut("e", cmd)], triggers: ["extensions", "site controls"]),
// Archive
KeyAction(id: "goBack", name: "Go Back", section: .archive, shortcuts: [Shortcut("[", cmd), Shortcut(Shortcut.left, cmd)]),
@@ -224,6 +226,8 @@ final class KeyBindingRegistry {
// Window
KeyAction(id: "openLibrary", name: "Open Library…", section: .window, shortcuts: [Shortcut("l", cmdShift)], triggers: ["library"]),
KeyAction(id: "viewDownloads", name: "View Downloads…", section: .window, shortcuts: [Shortcut("j", cmdShift)], triggers: ["downloads"]),
+ // Arc: Window ▸ View Media….
+ KeyAction(id: "viewMedia", name: "View Media…", section: .window, shortcuts: [], triggers: ["media", "screenshots", "photos"]),
// Arc: Window ▸ Stay On Top.
KeyAction(id: "stayOnTop", name: "Stay On Top", section: .window, shortcuts: [], triggers: ["stay on top", "float", "always on top", "pin window"]),
// Arc's Little Arc "Open in Space" button (LittleBrowserMoveButton) and "Close Little Arc Windows".
diff --git a/Sources/Cra/UI/PaneToolbarView.swift b/Sources/Cra/UI/PaneToolbarView.swift
index 298c8dd..f6b394d 100644
--- a/Sources/Cra/UI/PaneToolbarView.swift
+++ b/Sources/Cra/UI/PaneToolbarView.swift
@@ -488,18 +488,27 @@ final class PaneToolbarView: NSView {
actions.performAction("copyURL")
}
- /// Arc's menu on the toolbar address: Copy URL, and Show Full URL / Hide Full URL for the
- /// normal bar (the developer bar always shows it).
+ /// Arc's menu on the toolbar address (Arc 1.172.1): Copy URL, Capture…, Capture Full Page,
+ /// Manage Extensions…, then Show Full URL / Hide Full URL for the normal bar (the developer
+ /// bar always shows it) and Hide Toolbar. Arc's Share ▸ is in the Site Control Center here, and
+ /// Shared Quotes go through arc.net, so neither is listed.
private func addressMenu() -> NSMenu? {
guard model.kind == .normal || model.kind == .developer else { return nil }
let menu = NSMenu()
+ let focus = { [weak self] in if let id = self?.paneTabID { self?.actions.focusPane(id) } }
menu.addItem(ToolbarMenuAction.item("Copy URL", shortcut: "copyURL", { [weak self] in self?.copyURL() }))
+ menu.addItem(ToolbarMenuAction.item("Capture…", shortcut: "capturePage", { [weak self] in focus(); self?.actions.performAction("capturePage") }))
+ menu.addItem(ToolbarMenuAction.item("Capture Full Page", shortcut: "captureFullPage", { [weak self] in focus(); self?.actions.performAction("captureFullPage") }))
+ menu.addItem(.separator())
+ menu.addItem(ToolbarMenuAction.item("Manage Extensions…", { [weak self] in self?.actions.performAction("manageExtensions") }))
+ menu.addItem(.separator())
if model.kind == .normal {
let full = store.settings.toolbarShowsFullURL
menu.addItem(ToolbarMenuAction.item(full ? "Hide Full URL" : "Show Full URL", { [weak self] in
self?.store.settings.toolbarShowsFullURL.toggle()
}))
}
+ menu.addItem(ToolbarMenuAction.item("Hide Toolbar", shortcut: "toggleToolbar", { [weak self] in self?.store.settings.showToolbar = false }))
return menu
}
diff --git a/Sources/Cra/UI/Sidebar/LibraryMedia.swift b/Sources/Cra/UI/Sidebar/LibraryMedia.swift
new file mode 100644
index 0000000..0b98397
--- /dev/null
+++ b/Sources/Cra/UI/Sidebar/LibraryMedia.swift
@@ -0,0 +1,252 @@
+import AppKit
+import Observation
+import QuickLookThumbnailing
+import SwiftUI
+
+/// Library ▸ Media's files (MediaLibrary): the folders read off the main thread, top level only,
+/// as Arc reads them. Reading Desktop and Documents asks macOS for access the first time.
+@MainActor
+@Observable
+final class MediaScanner {
+ static let shared = MediaScanner()
+ private(set) var files: [MediaLibrary.File] = []
+ @ObservationIgnored private var scanning = false
+ @ObservationIgnored private var thumbnails = NSCache<NSString, NSImage>()
+
+ static func url(_ folder: MediaLibrary.Folder) -> URL? {
+ let fm = FileManager.default
+ switch folder {
+ case .documents: return fm.urls(for: .documentDirectory, in: .userDomainMask).first
+ case .desktop: return fm.urls(for: .desktopDirectory, in: .userDomainMask).first
+ case .downloads: return fm.urls(for: .downloadsDirectory, in: .userDomainMask).first
+ case .screenshots:
+ // macOS's screenshot folder (Screenshot ▸ Options ▸ Save to), the Desktop by default.
+ let set = UserDefaults(suiteName: "com.apple.screencapture")?.string(forKey: "location")
+ return set.map { URL(fileURLWithPath: ($0 as NSString).expandingTildeInPath, isDirectory: true) }
+ ?? fm.urls(for: .desktopDirectory, in: .userDomainMask).first
+ }
+ }
+
+ @ObservationIgnored private var pending: [MediaLibrary.Folder]?
+
+ func rescan(_ folders: [MediaLibrary.Folder]) {
+ // One scan at a time; the folders asked for meanwhile are read next.
+ guard !scanning else { pending = folders; return }
+ scanning = true
+ let urls = folders.compactMap(Self.url)
+ Task.detached(priority: .utility) {
+ var found: [MediaLibrary.File] = []
+ let keys: [URLResourceKey] = [.contentModificationDateKey, .isRegularFileKey]
+ for dir in urls {
+ let items = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: keys,
+ options: [.skipsHiddenFiles])) ?? []
+ for u in items where MediaLibrary.isMedia(u.path) {
+ let v = try? u.resourceValues(forKeys: Set(keys))
+ guard v?.isRegularFile == true else { continue }
+ found.append(.init(path: u.path, date: v?.contentModificationDate ?? .distantPast))
+ }
+ }
+ let result = MediaLibrary.shown(found, query: "")
+ await MainActor.run {
+ self.scanning = false
+ if result != self.files { self.files = result }
+ if let next = self.pending { self.pending = nil; self.rescan(next) }
+ }
+ }
+ }
+
+ /// A Quick Look thumbnail, cached; nil until it is drawn, then `done` runs on the main thread.
+ func thumbnail(_ file: MediaLibrary.File, size: CGFloat, done: @escaping @MainActor (NSImage) -> Void) -> NSImage? {
+ let key = "\(file.path)|\(file.date.timeIntervalSince1970)" as NSString
+ if let image = thumbnails.object(forKey: key) { return image }
+ let scale = NSScreen.main?.backingScaleFactor ?? 2
+ let request = QLThumbnailGenerator.Request(fileAt: URL(fileURLWithPath: file.path), size: CGSize(width: size, height: size),
+ scale: scale, representationTypes: .thumbnail)
+ QLThumbnailGenerator.shared.generateBestRepresentation(for: request) { [weak self] rep, _ in
+ guard let image = rep?.nsImage else { return }
+ DispatchQueue.main.async {
+ MainActor.assumeIsolated {
+ self?.thumbnails.setObject(image, forKey: key)
+ done(image)
+ }
+ }
+ }
+ return nil
+ }
+}
+
+/// Arc's Media grid (measured at 2x on Arc 1.172.1): tiles 138 pt square, 10 pt apart in two
+/// columns from 7 pt in, a faint fill (darker under the pointer) with 10 pt corners; the picture
+/// fitted inside 12 pt in, framed in 4 pt of white with a soft shadow.
+enum MediaGridMetrics {
+ static let tile: CGFloat = 138
+ static let gap: CGFloat = 10
+ static let inset: CGFloat = 7
+ static let rowHeight: CGFloat = tile + 4
+ static let padding: CGFloat = 12
+ static let frame: CGFloat = 4
+}
+
+final class MediaRowCell: NSView {
+ private var tiles: [MediaTile] = []
+ var open: (MediaLibrary.File) -> Void = { _ in }
+
+ override var isFlipped: Bool { true }
+
+ func show(_ files: [MediaLibrary.File], ink: NSColor) {
+ while tiles.count < 2 {
+ let t = MediaTile()
+ t.open = { [weak self] in self?.open($0) }
+ tiles.append(t)
+ addSubview(t)
+ }
+ for (i, t) in tiles.enumerated() {
+ t.isHidden = i >= files.count
+ if i < files.count { t.show(files[i], ink: ink) }
+ }
+ needsLayout = true
+ }
+
+ override func layout() {
+ super.layout()
+ let m = MediaGridMetrics.self
+ let w = min(m.tile, (bounds.width - 2 * m.inset - m.gap) / 2)
+ for (i, t) in tiles.enumerated() {
+ t.frame = NSRect(x: m.inset + CGFloat(i) * (w + m.gap), y: 0, width: w, height: w)
+ }
+ }
+}
+
+final class MediaTile: NSView, NSDraggingSource {
+ var open: (MediaLibrary.File) -> Void = { _ in }
+ private var file: MediaLibrary.File?
+ private var ink: NSColor = .white
+ private let picture = CALayer()
+ private var hovering = false { didSet { refresh() } }
+ private var downAt: NSPoint?
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ wantsLayer = true
+ layer?.cornerRadius = 10
+ layer?.cornerCurve = .continuous
+ picture.borderColor = NSColor.white.cgColor
+ picture.borderWidth = MediaGridMetrics.frame
+ picture.backgroundColor = NSColor.white.cgColor
+ picture.contentsGravity = .resizeAspectFill
+ picture.masksToBounds = false
+ picture.shadowColor = NSColor.black.cgColor
+ picture.shadowOpacity = 0.18
+ picture.shadowRadius = 3
+ picture.shadowOffset = CGSize(width: 0, height: -1)
+ layer?.addSublayer(picture)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ func show(_ file: MediaLibrary.File, ink: NSColor) {
+ self.ink = ink
+ toolTip = file.name
+ guard file != self.file else { refresh(); return }
+ self.file = file
+ picture.contents = nil
+ if let image = MediaScanner.shared.thumbnail(file, size: MediaGridMetrics.tile, done: { [weak self] image in
+ guard self?.file == file else { return }
+ self?.picture.contents = image
+ self?.needsLayout = true
+ }) {
+ picture.contents = image
+ }
+ refresh()
+ needsLayout = true
+ }
+
+ private func refresh() {
+ layer?.backgroundColor = ink.withAlphaComponent(hovering ? 0.08 : 0.04).cgColor
+ }
+
+ override func layout() {
+ super.layout()
+ let box = bounds.insetBy(dx: MediaGridMetrics.padding, dy: MediaGridMetrics.padding)
+ var size = (picture.contents as? NSImage)?.size ?? NSSize(width: 4, height: 3)
+ if size.width <= 0 || size.height <= 0 { size = NSSize(width: 4, height: 3) }
+ let scale = min(box.width / size.width, box.height / size.height)
+ let w = (size.width * scale).rounded(), h = (size.height * scale).rounded()
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ picture.frame = NSRect(x: box.midX - w / 2, y: box.midY - h / 2, width: w, height: h)
+ picture.shadowPath = CGPath(rect: picture.bounds, transform: nil)
+ CATransaction.commit()
+ }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ trackingAreas.forEach(removeTrackingArea)
+ addTrackingArea(NSTrackingArea(rect: bounds, options: [.mouseEnteredAndExited, .activeInActiveApp, .inVisibleRect], owner: self))
+ }
+
+ override func mouseEntered(with event: NSEvent) { hovering = true }
+ override func mouseExited(with event: NSEvent) { hovering = false }
+ override func mouseDown(with event: NSEvent) { downAt = event.locationInWindow }
+
+ /// Dragging a tile out hands the file over, as dragging a download does: into a page's upload
+ /// field, a message, the Finder.
+ override func mouseDragged(with event: NSEvent) {
+ guard let file, let start = downAt, hypot(event.locationInWindow.x - start.x, event.locationInWindow.y - start.y) > 4 else { return }
+ downAt = nil
+ let item = NSDraggingItem(pasteboardWriter: URL(fileURLWithPath: file.path) as NSURL)
+ item.setDraggingFrame(picture.frame, contents: (picture.contents as? NSImage) ?? NSWorkspace.shared.icon(forFile: file.path))
+ beginDraggingSession(with: [item], event: event, source: self)
+ }
+
+ override func mouseUp(with event: NSEvent) {
+ defer { downAt = nil }
+ guard downAt != nil, let file, bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
+ open(file)
+ }
+
+ func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
+ context == .outsideApplication ? .copy : [.copy, .generic]
+ }
+}
+
+/// Arc's card over the Media page until it is turned on: "Your Media in the Library", what it
+/// does, a Show Media button and the privacy line under it (Arc 1.172.1).
+struct MediaOptInCard: View {
+ let dark: Bool
+ let show: () -> Void
+
+ var body: some View {
+ VStack(spacing: 8) {
+ Image(systemName: "photo.on.rectangle.angled")
+ .font(.system(size: 28, weight: .medium))
+ .foregroundStyle(Color(red: 0.55, green: 0.47, blue: 0.93))
+ .padding(.top, 4)
+ Text("Your Media in the Library").font(.system(size: 13, weight: .semibold))
+ Text("Quickly grab screenshots, images, and videos from your computer by showing them in the Cra Library!")
+ .font(.system(size: 11.5)).multilineTextAlignment(.center).foregroundStyle(.primary.opacity(0.8))
+ .fixedSize(horizontal: false, vertical: true)
+ Button(action: show) {
+ Text("Show Media").font(.system(size: 13, weight: .medium)).foregroundStyle(.white)
+ .frame(maxWidth: .infinity).frame(height: 32)
+ .background(RoundedRectangle(cornerRadius: 8, style: .continuous)
+ .fill(LinearGradient(colors: [Color(red: 0.85, green: 0.55, blue: 0.80), Color(red: 0.40, green: 0.42, blue: 0.95)],
+ startPoint: .leading, endPoint: .trailing)))
+ }
+ .buttonStyle(.plain)
+ .padding(.top, 4)
+ HStack(alignment: .top, spacing: 4) {
+ Image(systemName: "lock.fill").font(.system(size: 8))
+ Text("Media never leaves your computer and is not viewable by anyone but you.").font(.system(size: 10))
+ }
+ .foregroundStyle(.secondary)
+ }
+ .padding(16)
+ .frame(width: 222)
+ .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(dark ? Color(white: 0.18) : .white)
+ .shadow(color: .black.opacity(0.15), radius: 10, y: 3))
+ .environment(\.colorScheme, dark ? .dark : .light)
+ }
+}
diff --git a/Sources/Cra/UI/Sidebar/LibraryView.swift b/Sources/Cra/UI/Sidebar/LibraryView.swift
index 81ef31c..99078ec 100644
--- a/Sources/Cra/UI/Sidebar/LibraryView.swift
+++ b/Sources/Cra/UI/Sidebar/LibraryView.swift
@@ -1,11 +1,13 @@
import AppKit
+import SwiftUI
-/// The Library's pages Cra has, in the order of Arc's rail (which also lists Media, Easels and Boosts).
+/// The Library's pages Cra has, in the order of Arc's rail (which also lists Easels and Boosts).
enum LibraryPage: String, CaseIterable {
- case downloads, spaces, archive
+ case media, downloads, spaces, archive
var title: String {
switch self {
+ case .media: "Media"
case .downloads: "Downloads"
case .spaces: "Spaces"
case .archive: "Archived Tabs"
@@ -13,13 +15,20 @@ enum LibraryPage: String, CaseIterable {
}
var symbol: String {
switch self {
+ case .media: "photo.on.rectangle"
case .downloads: "arrow.down.circle"
case .spaces: "square.on.square"
case .archive: "archivebox"
}
}
- var selectedSymbol: String { symbol + ".fill" }
- var searchPrompt: String { self == .downloads ? "Search Downloads…" : "Search Archive…" }
+ var selectedSymbol: String { self == .media ? "photo.fill.on.rectangle.fill" : symbol + ".fill" }
+ var searchPrompt: String {
+ switch self {
+ case .media: "Search Media…"
+ case .downloads: "Search Downloads…"
+ default: "Search Archive…"
+ }
+ }
}
/// Arc's Library: not a window but a mode of the sidebar (WindowState+Library, HomeButton/*),
@@ -266,6 +275,7 @@ private final class LibraryRailButton: NSView {
private final class LibraryListView: NSView, NSTextFieldDelegate, NSTableViewDataSource, NSTableViewDelegate {
enum Row {
case header(String)
+ case media([MediaLibrary.File])
case download(DownloadHistory.Entry)
case archived(ArchivedItem)
}
@@ -286,6 +296,7 @@ private final class LibraryListView: NSView, NSTextFieldDelegate, NSTableViewDat
private let scroll = NSScrollView()
private let table = NSTableView()
private let empty = LibraryEmptyView()
+ private var mediaCard: NSHostingView<MediaOptInCard>?
init(page: LibraryPage, store: SidebarStore, actions: SidebarActions, favicons: FaviconCache) {
self.page = page
@@ -357,6 +368,9 @@ private final class LibraryListView: NSView, NSTextFieldDelegate, NSTableViewDat
_ = store.archive
_ = DownloadHistory.shared.entries
_ = DownloadHistory.shared.thumbnails.count
+ _ = MediaScanner.shared.files
+ _ = store.settings.mediaLibraryEnabled
+ _ = store.settings.mediaFolders
} onChange: { [weak self] in
Task { @MainActor in self?.observe() }
}
@@ -367,7 +381,22 @@ private final class LibraryListView: NSView, NSTextFieldDelegate, NSTableViewDat
private func reload() {
var out: [Row] = []
+ mediaCard?.isHidden = true
switch page {
+ case .media:
+ guard store.settings.mediaLibraryEnabled else {
+ showMediaCard()
+ empty.show(symbol: "photo.on.rectangle", title: "", detail: nil)
+ break
+ }
+ // Read again whenever the page shows, a search changes or the folders change; the scan is
+ // cheap, off the main thread, and reads only the folders ticked.
+ MediaScanner.shared.rescan(store.settings.mediaFolders)
+ let all = MediaScanner.shared.files
+ let shown = MediaLibrary.shown(all, query: query)
+ out = MediaLibrary.rows(shown).map { .media($0) }
+ empty.show(symbol: "photo.on.rectangle", title: all.isEmpty ? "Nothing here yet!" : "No matches",
+ detail: all.isEmpty ? "Screenshots, pictures and videos in the folders you show appear here." : nil)
case .downloads:
let all = DownloadHistory.shared.entries.reversed().filter { FileManager.default.fileExists(atPath: $0.path) }
let shown = needle.isEmpty ? all : all.filter { ($0.path as NSString).lastPathComponent.lowercased().contains(needle) }
@@ -391,7 +420,7 @@ private final class LibraryListView: NSView, NSTextFieldDelegate, NSTableViewDat
detail: store.archive.isEmpty ? "Tabs you close end up here." : nil)
}
rows = out
- empty.isHidden = !out.isEmpty
+ empty.isHidden = !out.isEmpty || (page == .media && !store.settings.mediaLibraryEnabled)
scroll.isHidden = out.isEmpty
table.reloadData()
refresh()
@@ -407,6 +436,18 @@ private final class LibraryListView: NSView, NSTextFieldDelegate, NSTableViewDat
empty.ink = ink
}
+ /// Arc's opt-in card, over the page until Show Media is pressed.
+ private func showMediaCard() {
+ let card = MediaOptInCard(dark: colors.isDark) { [store] in store.settings.mediaLibraryEnabled = true }
+ if let mediaCard { mediaCard.rootView = card } else {
+ let host = NSHostingView(rootView: card)
+ addSubview(host)
+ mediaCard = host
+ }
+ mediaCard?.isHidden = false
+ needsLayout = true
+ }
+
private static func grouped<T>(_ items: [T], date: KeyPath<T, Date>) -> [(String, [T])] {
let cal = Calendar.current
let df = DateFormatter()
@@ -436,6 +477,11 @@ private final class LibraryListView: NSView, NSTextFieldDelegate, NSTableViewDat
scroll.frame = NSRect(x: 0, y: 46, width: w, height: max(0, bounds.height - 46))
table.tableColumns.first?.width = w
empty.frame = scroll.frame
+ if let card = mediaCard {
+ let size = card.fittingSize
+ card.frame = NSRect(x: ((w - size.width) / 2).rounded(), y: max(56, ((bounds.height - size.height) / 2).rounded()),
+ width: size.width, height: size.height)
+ }
}
// MARK: Search
@@ -458,6 +504,22 @@ private final class LibraryListView: NSView, NSTextFieldDelegate, NSTableViewDat
let menu = NSMenu()
menu.autoenablesItems = false
switch page {
+ case .media:
+ // Arc's "Show media" folders (its Library button's right-click menu).
+ let store = store
+ let header = NSMenuItem(title: "Show media", action: nil, keyEquivalent: "")
+ header.isEnabled = false
+ menu.addItem(header)
+ for f in MediaLibrary.Folder.allCases {
+ let on = store.settings.mediaFolders.contains(f)
+ MenuItems.add(menu, f.title, on: on) {
+ if on { store.settings.mediaFolders.removeAll { $0 == f } } else { store.settings.mediaFolders.append(f) }
+ }
+ }
+ if store.settings.mediaLibraryEnabled {
+ menu.addItem(.separator())
+ MenuItems.add(menu, "Hide Media") { store.settings.mediaLibraryEnabled = false }
+ }
case .downloads:
// The folder the window's profile downloads to (#190).
let profile = (window?.windowController as? MainWindowController)?.profileDirectoryName
@@ -479,6 +541,7 @@ private final class LibraryListView: NSView, NSTextFieldDelegate, NSTableViewDat
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
if case .header = rows[row] { return 40 }
+ if case .media = rows[row] { return MediaGridMetrics.rowHeight }
return 56
}
@@ -489,6 +552,16 @@ private final class LibraryListView: NSView, NSTextFieldDelegate, NSTableViewDat
v.identifier = .init("header")
v.show(label, ink: colors.isDark ? .white : .black)
return v
+ case .media(let files):
+ let v = tableView.makeView(withIdentifier: .init("media"), owner: nil) as? MediaRowCell ?? MediaRowCell()
+ v.identifier = .init("media")
+ v.open = { [store, actions] file in
+ // Arc opens a picked picture in a tab, and the Library steps aside.
+ _ = store.createTab(url: URL(fileURLWithPath: file.path).absoluteString, select: true)
+ actions.closeLibrary()
+ }
+ v.show(files, ink: colors.isDark ? .white : .black)
+ return v
case .download(let e):
let v = tableView.makeView(withIdentifier: .init("item"), owner: nil) as? LibraryItemCell ?? LibraryItemCell()
v.identifier = .init("item")
@@ -512,7 +585,7 @@ extension LibraryListView: NSMenuDelegate {
let row = table.clickedRow
guard rows.indices.contains(row) else { return }
switch rows[row] {
- case .header: break
+ case .header, .media: break
case .archived(let e):
let actions = actions, store = store
MenuItems.add(menu, "Restore") { actions.restoreArchived(e.id) }
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index ac39cd2..07236de 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -2690,6 +2690,9 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
store.selectTab(panes[n - 1], window: windowID)
}
+ /// Chrome's extensions page, as the Site Control Center's Manage Extensions… opens it.
+ func openExtensionsPage() { openTab("chrome://extensions") }
+
/// Arc's Open Extensions (⌘E): the Site Control Center, as if its sliders were clicked.
func openSiteControls() { showSiteControlsFromTheirButton() }
@@ -2768,6 +2771,27 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
}
+ /// Arc's File ▸ Capture in Portrait Mode: the page laid out at a phone's width (390 × 844 pt,
+ /// the layout a site gives an iPhone 15) and captured at 3x, then put back as it was.
+ func capturePortrait() {
+ captureOverlay?.close()
+ guard let b = currentBrowser else { return }
+ showToast("Capture in Progress")
+ let metrics = #"{"width":390,"height":844,"deviceScaleFactor":3,"mobile":true}"#
+ b.sendDevToolsMethod("Emulation.setDeviceMetricsOverride", params: metrics) { [weak self] _, error in
+ MainActor.assumeIsolated {
+ guard error == nil else { self?.finishCapture(nil, error: error); return }
+ // A layout pass and a paint at the new width before the shot.
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
+ b.sendDevToolsMethod("Page.captureScreenshot", params: #"{"format":"png"}"#) { shot, error in
+ b.sendDevToolsMethod("Emulation.clearDeviceMetricsOverride", params: "{}") { _, _ in }
+ 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?) {