Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 20 additions & 15 deletions Sources/Early/BrowserApplication.swift
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate {
/// A fresh window shares saved organization/store identity, never another
/// window's Today tabs, split membership, live views, or command-bar state.
@discardableResult
func openNewWindow(from source: BrowserWindowModel? = nil) -> UUID? {
func openNewWindow(from source: BrowserWindowModel? = nil, opening urls: [URL] = []) -> UUID? {
guard canOpenWindow, let workspace else { return nil }
let template: BrowserSession
// New Window from a private window opens an ordinary one.
Expand All @@ -276,7 +276,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate {
guard let session = workspace.session(for: workspace.activeProfileID) else { return nil }
template = session
}
let id = addWindow(session: template.savedItemsOnly)
let id = addWindow(session: template.openingWindow(at: urls))
self.workspace?.activeProfileID = template.profileID
saveAll()
presentWindow?(id)
Expand All @@ -287,12 +287,13 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate {
/// no history, and nothing in it is saved, restored or kept on disk.
/// It fills passwords saved in the profile it was opened from.
@discardableResult
func openPrivateWindow(from source: BrowserWindowModel? = nil) -> UUID? {
func openPrivateWindow(from source: BrowserWindowModel? = nil, opening urls: [URL] = []) -> UUID? {
guard canOpenWindow else { return nil }
let profile = privateProfileID ?? UUID()
privateProfileID = profile
let passwordsFrom = source?.passwordsProfileID ?? workspace?.activeProfileID
let id = addWindow(session: .privateWindow(profileID: profile), passwordsFrom: passwordsFrom)
let session = BrowserSession.privateWindow(profileID: profile).openingWindow(at: urls)
let id = addWindow(session: session, passwordsFrom: passwordsFrom)
presentWindow?(id)
return id
}
Expand Down Expand Up @@ -343,7 +344,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate {
privateExtensionHosts.removeAll()
sitePermissionStores.removeValue(forKey: profile)
localFileStores.removeValue(forKey: profile)
downloadStores.removeValue(forKey: profile)?.cancelAll()
downloadStores.removeValue(forKey: profile)?.retire()
}

private func websiteDataStore(for id: UUID) -> WKWebsiteDataStore {
Expand Down Expand Up @@ -532,11 +533,11 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate {
if let owner = (window?.owner as? BrowserWindowModel) ?? self.extensionModels(of: host).first {
return owner.openExtensionTab(url, active: active)
}
return self.openExtensionWindow(for: host, url: url)?.activeTab
return (try? self.openExtensionWindow(for: host, urls: [url]))?.activeTab
}
host.openWindow = { [weak self, weak host] url in
host.openWindow = { [weak self, weak host] urls in
guard let self, let host else { return nil }
return self.openExtensionWindow(for: host, url: url)
return try self.openExtensionWindow(for: host, urls: urls)
}
host.presentPopup = { [weak self, weak host] action in
guard let self, let host,
Expand All @@ -557,23 +558,27 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate {

/// A window an extension asked for, in the host's profile (or private session).
@available(macOS 15.4, *)
private func openExtensionWindow(for host: ExtensionHost, url: URL?) -> ExtensionWindow? {
private func openExtensionWindow(for host: ExtensionHost, urls: [URL]) throws -> ExtensionWindow? {
// Validate the entire request before publishing a window or any tabs.
guard let urls = try? urls.map({ try input.validate($0) }) else { throw ExtensionHost.ExtensionError.invalidWindowURL }
let source = extensionModels(of: host).first
var id: UUID?
if host.isPrivate {
guard let source else { return nil }
id = openPrivateWindow(from: source)
id = openPrivateWindow(from: source, opening: urls)
} else if let source {
id = openNewWindow(from: source)
id = openNewWindow(from: source, opening: urls)
} else if canOpenWindow, let profile = extensionHosts.first(where: { $0.value === host })?.key,
let session = workspace?.session(for: profile) {
let window = addWindow(session: session.savedItemsOnly)
let window = addWindow(session: session.openingWindow(at: urls))
saveAll()
presentWindow?(window)
id = window
}
guard let id, let model = windowModel(id) else { return nil }
if let url { _ = model.openExtensionTab(url, active: true) }
for tab in model.coordinator.tabStore.tabs where tab.isOpen && tab.id != model.coordinator.activeTabID {
model.webViews.load(tab.currentURL, in: tab)
}
return model.extensionWindow as? ExtensionWindow
}

Expand All @@ -585,7 +590,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate {
owner.openExtensionTab(url, active: true)
owner.extensionFocusWindow()
} else {
_ = openExtensionWindow(for: host, url: url)
_ = try? openExtensionWindow(for: host, urls: [url])
}
}

Expand Down Expand Up @@ -1292,6 +1297,7 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate {
// its windows, credentials, extension data and permissions be removed.
workspace = draft
profileError = nil
downloadStores.removeValue(forKey: id)?.retire()
let closing = windows.filter { $0.model.coordinator.profileID == id }.map(\.id)
for windowID in closing {
nativeWindow(id: windowID)?.close()
Expand All @@ -1302,7 +1308,6 @@ final class EarlyAppDelegate: NSObject, NSApplicationDelegate {
closeWindow(nil)
}
dataStores.removeValue(forKey: id)
downloadStores.removeValue(forKey: id)?.cancelAll()
pullRequestFeeds.removeValue(forKey: id)?.stop()
if extensionsProfileID == id { extensionsProfileID = nil }
if passwordsProfileID == id { passwordsProfileID = nil }
Expand Down
2 changes: 1 addition & 1 deletion Sources/EarlyCore/BackgroundFileIO.swift
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,10 @@ public enum BackgroundFileIO {
defer { try? output.close() }
try write(output)
try output.synchronize()
try Task.checkCancellation()
if let mode = try? files.attributesOfItem(atPath: destination.path)[.posixPermissions] {
try files.setAttributes([.posixPermissions: mode], ofItemAtPath: staged.path)
}
try Task.checkCancellation()
guard Darwin.rename(staged.path, destination.path) == 0 else { throw fileError() }
}
}
Expand Down
21 changes: 11 additions & 10 deletions Sources/EarlyCore/BrowserSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -131,16 +131,17 @@ public struct BrowserSession: Codable, Equatable, Sendable {
/// A copied page is a new Today tab, even when opened from a saved pin.
/// Saved tabs start unloaded; no other window's live navigation is copied.
public func openingWindow(at url: URL, title: String? = nil) -> BrowserSession {
let saved = tabs.filter { $0.pinnedURL != nil }.map { tab in
var copy = tab
copy.currentURL = tab.pinnedURL!
copy.title = tab.pinnedTitle ?? tab.title
copy.isOpen = false
return copy
openingWindow(at: [url], firstTitle: title)
}

public func openingWindow(at urls: [URL], firstTitle: String? = nil) -> BrowserSession {
var window = savedItemsOnly
let pages = urls.enumerated().map { index, url in
BrowserTab(spaceID: activeSpaceID, profileID: profileID,
title: (index == 0 ? firstTitle : nil) ?? url.host ?? url.absoluteString, currentURL: url)
}
let page = BrowserTab(spaceID: activeSpaceID, profileID: profileID,
title: title ?? url.host ?? url.absoluteString, currentURL: url)
return BrowserSession(profileID: profileID, activeSpaceID: activeSpaceID,
tabs: saved + [page], selectionBySpace: [activeSpaceID: page.id], folders: folders, spaces: spaces)
window.tabs.append(contentsOf: pages)
window.selectionBySpace[activeSpaceID] = pages.first?.id
return window
}
}
11 changes: 8 additions & 3 deletions Sources/EarlyWeb/BrowserExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ public final class ExtensionHost: NSObject, WKWebExtensionControllerDelegate {
@ObservationIgnored public private(set) weak var focusedWindow: ExtensionWindow?
/// Opens a tab for an extension; the app decides where.
@ObservationIgnored public var openTab: ((URL, ExtensionWindow?, _ active: Bool) -> ExtensionTab?)?
@ObservationIgnored public var openWindow: ((URL?) -> ExtensionWindow?)?
@ObservationIgnored public var openWindow: (([URL]) throws -> ExtensionWindow?)?
/// Shows an extension's popup; false when it can't be shown now.
@ObservationIgnored public var presentPopup: ((WKWebExtension.Action) -> Bool)?
/// An extension loaded (or loaded again): tabs showing its pages reload.
Expand Down Expand Up @@ -245,13 +245,16 @@ public final class ExtensionHost: NSObject, WKWebExtensionControllerDelegate {
}

public enum ExtensionError: LocalizedError {
case missing, alreadyAdded, windowPrivacyMismatch, localFiles
case missing, alreadyAdded, windowPrivacyMismatch, localFiles, existingWindowTabs, invalidWindowURL, windowUnavailable
public var errorDescription: String? {
switch self {
case .missing: "Its files are missing. If it came with an app, the app may have moved or been deleted."
case .alreadyAdded: "This extension is already added."
case .windowPrivacyMismatch: "Extensions cannot create a window in a different privacy mode. Open the appropriate window in Early first."
case .localFiles: "This extension isn’t allowed to open files on this Mac. You can allow it in Settings › Extensions."
case .existingWindowTabs: "Extensions cannot move existing tabs into a new window."
case .invalidWindowURL: "A tab address requested for this window is unsupported or invalid."
case .windowUnavailable: "Early couldn’t open a window for this extension."
}
}
}
Expand Down Expand Up @@ -538,10 +541,12 @@ public final class ExtensionHost: NSObject, WKWebExtensionControllerDelegate {
// Each host owns one regular or private session. Never silently replace
// the requested mode with the host's mode, or cross their data stores.
guard configuration.shouldBePrivate == isPrivate else { throw ExtensionError.windowPrivacyMismatch }
guard configuration.tabs.isEmpty else { throw ExtensionError.existingWindowTabs }
guard !configuration.tabURLs.contains(where: \.isFileURL) || allowsLocalFiles(extensionContext) else {
throw ExtensionError.localFiles
}
return openWindow?(configuration.tabURLs.first)
guard let window = try openWindow?(configuration.tabURLs) else { throw ExtensionError.windowUnavailable }
return window
}

public func webExtensionController(_ controller: WKWebExtensionController,
Expand Down
28 changes: 28 additions & 0 deletions Sources/EarlyWeb/BrowserWebView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,40 @@ enum UnhandledPageKey {
@MainActor
final class BrowserWebView: WKWebView, @preconcurrency NSSharingServicePickerDelegate {
let initialPresentation = InitialPagePresentation()
private var fileDrop: (urls: [URL], expires: ContinuousClock.Instant)?

override func stopLoading() {
clearFileDrop()
initialPresentation.reveal()
super.stopLoading()
}

override func performDragOperation(_ sender: any NSDraggingInfo) -> Bool {
noteFileDrop(from: sender.draggingPasteboard)
// Let WebKit deliver the drop to the document first, including uploads.
let accepted = super.performDragOperation(sender)
if !accepted { clearFileDrop() }
return accepted
}

func noteFileDrop(from pasteboard: NSPasteboard, now: ContinuousClock.Instant = .now) {
let files = pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []
fileDrop = files.isEmpty ? nil : (files, now.advanced(by: .seconds(5)))
}

func clearFileDrop() { fileDrop = nil }

/// WebKit reports unhandled file drops as ordinary navigation actions.
/// Take the actual native file URL once, only on the view that received it.
func takeDroppedFile(matching url: URL, now: ContinuousClock.Instant = .now) -> URL? {
guard let fileDrop else { return nil }
guard now < fileDrop.expires else { clearFileDrop(); return nil }
let path = url.standardizedFileURL.path
guard let file = fileDrop.urls.first(where: { $0.standardizedFileURL.path == path }) else { return nil }
clearFileDrop()
return file
}

/// What a trusted right-click landed on, already validated by the manager.
struct ContextTarget: Equatable {
var link: URL?
Expand Down
38 changes: 26 additions & 12 deletions Sources/EarlyWeb/DownloadStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ public final class DownloadStore: NSObject, WKDownloadDelegate {
@ObservationIgnored private var tracked: [ObjectIdentifier: DownloadItem] = [:]
@ObservationIgnored private var reserved: Set<String> = []
@ObservationIgnored private var automaticReservations: Set<UUID> = []
@ObservationIgnored private(set) var isRetired = false

/// Private windows' files keep their quarantine, which Gatekeeper needs,
/// but their addresses never reach LaunchServices' quarantine-event log.
Expand Down Expand Up @@ -117,7 +118,7 @@ public final class DownloadStore: NSObject, WKDownloadDelegate {
/// Shared by every window in the profile. Authorization and WebKit's
/// adoption callback are separate turns, so both need to hold a slot.
var canReserveAutomaticDownload: Bool {
activeTransferCount + automaticReservations.count < WebViewManager.automaticDownloadLimit
!isRetired && activeTransferCount + automaticReservations.count < WebViewManager.automaticDownloadLimit
}

func reserveAutomaticDownload() -> UUID? {
Expand Down Expand Up @@ -153,6 +154,11 @@ public final class DownloadStore: NSObject, WKDownloadDelegate {
@discardableResult
func adopt(_ download: WKDownload, source: URL?, origin: URL?, destination: URL? = nil, listed: Bool = true) -> DownloadItem {
let item = DownloadItem(source: source, origin: origin, requestedDestination: destination, listed: listed)
guard !isRetired else {
item.state = .cancelled
download.cancel { _ in }
return item
}
attach(download, to: item)
if listed {
items.insert(item, at: 0)
Expand Down Expand Up @@ -224,7 +230,7 @@ public final class DownloadStore: NSObject, WKDownloadDelegate {
/// Continues a stopped or interrupted transfer into its original file.
@discardableResult
public func resume(_ item: DownloadItem) -> Bool {
guard item.canResume, let resumeData = item.resumeData else { return false }
guard !isRetired, item.canResume, let resumeData = item.resumeData else { return false }
let configuration = WKWebViewConfiguration()
if let store = dataStoreProvider?() { configuration.websiteDataStore = store }
let host = WKWebView(frame: .zero, configuration: configuration)
Expand Down Expand Up @@ -284,6 +290,14 @@ public final class DownloadStore: NSObject, WKDownloadDelegate {
}
}

/// The owning profile was removed or its last private window closed.
public func retire() {
isRetired = true
dataStoreProvider = nil
automaticReservations.removeAll()
cancelAll()
}

/// Removes finished, failed and cancelled rows. Files are never deleted;
/// stopped transfers stay so they can resume.
public func clearInactive() {
Expand Down Expand Up @@ -419,21 +433,21 @@ public final class DownloadStore: NSObject, WKDownloadDelegate {
guard let item = tracked.removeValue(forKey: ObjectIdentifier(download)) else { return }
let nsError = error as NSError
synchronizeProgress(item)
releaseTransfer(item)
if nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorCancelled && resumeData == nil {
item.state = .cancelled
} else {
item.state = .failed
item.failureReason = nsError.localizedDescription
if let resumeData {
// An interrupted transfer keeps its partial file for Resume.
item.resumeData = resumeData
return
}
item.resumeData = resumeData
item.state = .failed
}
if resumeData == nil || !item.listed {
// Remove our partial file, but never a destination WebKit refused
// because another process had already created it. Unlisted
// transfers have no Resume action and don't keep partial files.
discardPartialFile(of: item)
item.resumeData = nil
}
// Remove our partial file, but never a destination WebKit refused
// because another process had already created it.
discardPartialFile(of: item)
releaseTransfer(item)
}

// MARK: Helpers
Expand Down
18 changes: 10 additions & 8 deletions Sources/EarlyWeb/PageDocuments.swift
Original file line number Diff line number Diff line change
Expand Up @@ -177,19 +177,21 @@ extension WebViewManager {

private func performDocumentSave(pageID: UUID?, to destination: URL, source: URL?, failure: String,
operation: @escaping @Sendable () async throws -> Void) {
let downloads = downloads
guard !downloads.isRetired else { return }
let token = UUID()
let task = Task { @MainActor [weak self] in
defer { self?.documentWrites[token] = nil }
guard !downloads.isRetired else { return }
do {
try Task.checkCancellation()
try await operation()
guard let self else { return }
self.documentWrites[token] = nil
guard !Task.isCancelled else { return }
self.downloads.recordSavedFile(at: destination, source: source)
// A successful write already renamed the file. Its profile
// owns the result even if the page or window closed meanwhile.
guard !downloads.isRetired else { return }
downloads.recordSavedFile(at: destination, source: source)
} catch {
guard let self else { return }
self.documentWrites[token] = nil
if !(error is CancellationError) { self.onNotice?(failure) }
if !downloads.isRetired && !Task.isCancelled && !(error is CancellationError) { self?.onNotice?(failure) }
}
}
documentWrites[token] = PendingDocumentWrite(pageID: pageID, task: task)
Expand Down Expand Up @@ -363,7 +365,7 @@ extension WebViewManager {
let started = startDownload(url, from: id, to: destination, listed: false) { [weak self] item in
defer { try? FileManager.default.removeItem(at: folder) }
guard item.state == .finished, let image = NSImage(contentsOf: destination) else {
if item.state == .failed { self?.onNotice?("The image could not be copied.") }
if item.state == .failed || item.state == .finished { self?.onNotice?("The image could not be copied.") }
return
}
NSPasteboard.general.clearContents()
Expand Down
Loading
Loading