From 84b176d0b6435fe94bd0d6ee286d0817facc48d5 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Mon, 3 Aug 2026 09:48:24 -0700 Subject: [PATCH 1/2] =?UTF-8?q?Keep=20the=20current=20article=20when=20add?= =?UTF-8?q?ing=20a=20feed=20on=20iOS=20=E2=80=94=20don't=20clear=20the=20s?= =?UTF-8?q?election=20to=20show=20the=20Add=20Feed=20sheet,=20and=20disclo?= =?UTF-8?q?se=20the=20new=20feed=20only=20when=20nothing=20is=20selected.?= =?UTF-8?q?=20Fixes=20#4352.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- iOS/SceneCoordinator.swift | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/iOS/SceneCoordinator.swift b/iOS/SceneCoordinator.swift index 373ba0a0b..e538e1d36 100644 --- a/iOS/SceneCoordinator.swift +++ b/iOS/SceneCoordinator.swift @@ -452,21 +452,28 @@ struct SidebarItemNode: Hashable, Sendable { } func handle(_ activity: NSUserActivity) { + guard let activityType = ActivityType(rawValue: activity.activityType) else { + return + } + + // Add Feed just presents a sheet — unlike the activities below, it doesn't navigate, + // so it must not clear the current selection. + // + if activityType == .addFeedIntent { + showAddFeed() + return + } + selectSidebarItem(indexPath: nil) { - guard let activityType = ActivityType(rawValue: activity.activityType) else { - return - } switch activityType { - case .restoration: - break case .selectFeed: self.handleSelectFeed(activity.userInfo) case .nextUnread: self.selectFirstUnreadInAllUnread() case .readArticle: self.handleReadArticle(activity.userInfo) - case .addFeedIntent: - self.showAddFeed() + case .restoration, .addFeedIntent: + break } } } @@ -608,6 +615,14 @@ struct SidebarItemNode: Hashable, Sendable { guard let feed = notification.userInfo?[UserInfoKey.feed] as? Feed else { return } + + // Disclosing navigates away from whatever the user was reading, so do it only when + // nothing is selected — otherwise adding a feed would cost them their place. + // + guard timelineFeed == nil else { + return + } + discloseFeed(feed, animations: [.scroll, .navigation]) } @@ -1465,8 +1480,8 @@ struct SidebarItemNode: Hashable, Sendable { func showAddFeed(initialFeed: String? = nil, initialFeedName: String? = nil) { - // Since Add Feed can be opened from anywhere with a keyboard shortcut, we have to deselect any currently selected feeds - selectFeed(nil) + // The sheet appears over the current screen, so the feed and article selection stay as they are. + // let addNavViewController = UIStoryboard.add.instantiateViewController(withIdentifier: "AddFeedViewControllerNav") as! UINavigationController @@ -1476,7 +1491,7 @@ struct SidebarItemNode: Hashable, Sendable { addNavViewController.modalPresentationStyle = .formSheet addNavViewController.preferredContentSize = AddFeedViewController.preferredContentSizeForFormSheetDisplay - mainFeedCollectionViewController.present(addNavViewController, animated: true) + rootSplitViewController.present(addNavViewController, animated: true) } func showAddFolder() { From f997c22abdf55f9f352ced6e63f0f727ce854e3c Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Mon, 3 Aug 2026 10:45:33 -0700 Subject: [PATCH 2/2] =?UTF-8?q?Get=20the=20page=20URL=20from=20Safari=20in?= =?UTF-8?q?stead=20of=20an=20injected=20content=20script,=20so=20the=20ext?= =?UTF-8?q?ension=E2=80=99s=20button=20works=20without=20reloading=20the?= =?UTF-8?q?=20page.=20Fixes=20#4208.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SafariExtensionViewController.xib | 30 --- Mac/SafariExtension/Info.plist | 7 - .../SafariExtensionHandler.swift | 181 +++++++----------- .../SafariExtensionViewController.swift | 20 -- .../netnewswire-subscribe-to-feed.js | 45 ----- NetNewsWire.xcodeproj/project.pbxproj | 6 - 6 files changed, 68 insertions(+), 221 deletions(-) delete mode 100644 Mac/SafariExtension/Base.lproj/SafariExtensionViewController.xib delete mode 100644 Mac/SafariExtension/SafariExtensionViewController.swift delete mode 100644 Mac/SafariExtension/netnewswire-subscribe-to-feed.js diff --git a/Mac/SafariExtension/Base.lproj/SafariExtensionViewController.xib b/Mac/SafariExtension/Base.lproj/SafariExtensionViewController.xib deleted file mode 100644 index 6c80db684..000000000 --- a/Mac/SafariExtension/Base.lproj/SafariExtensionViewController.xib +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Mac/SafariExtension/Info.plist b/Mac/SafariExtension/Info.plist index 6ac1693ba..2440fe5c9 100644 --- a/Mac/SafariExtension/Info.plist +++ b/Mac/SafariExtension/Info.plist @@ -30,13 +30,6 @@ com.apple.Safari.extension NSExtensionPrincipalClass $(PRODUCT_MODULE_NAME).SafariExtensionHandler - SFSafariContentScript - - - Script - netnewswire-subscribe-to-feed.js - - SFSafariToolbarItem Action diff --git a/Mac/SafariExtension/SafariExtensionHandler.swift b/Mac/SafariExtension/SafariExtensionHandler.swift index 65f97a7ec..1b1b69e6b 100644 --- a/Mac/SafariExtension/SafariExtensionHandler.swift +++ b/Mac/SafariExtension/SafariExtensionHandler.swift @@ -8,135 +8,90 @@ @preconcurrency import SafariServices +// The extension needs nothing from a page but its URL, which Safari reports directly — +// NetNewsWire's FeedFinder does all feed discovery. Asking Safari rather than an injected +// script means the button also works on pages that were already open when the user granted +// access to the site, which a script can never reach. +// + final class SafariExtensionHandler: SFSafariExtensionHandler { - // Safari App Extensions don't support any reasonable means of detecting whether a - // specific Safari page was loaded with the benefit of the extension's injected - // JavaScript. For this reason a condition can easily be reached where the toolbar - // icon is active for a page, but the expected supporting code is not loaded into - // the page. To detect this and disable our icon, we use a kind of "ping" trick - // to verify whether our code is installed. - - // I tried to use a NSMapTable from String to the closure directly, but Swift - // complains that the object has to be a class type. - typealias ValidationHandler = (Bool, String) -> Void - final class ValidationWrapper { - let validationHandler: ValidationHandler - - init(validationHandler: @escaping ValidationHandler) { - self.validationHandler = validationHandler + override func toolbarItemClicked(in window: SFSafariWindow) { + SafariExtensionHandler.activePageURL(in: window) { pageURL in + guard let pageURL else { + return + } + SafariExtensionHandler.openFeedURL("feed:" + pageURL.absoluteString) } } - // Maps from UUID to a validation wrapper - nonisolated(unsafe) static var gPingPongMap = [String: ValidationWrapper]() - static let validationQueue = DispatchQueue(label: "Toolbar Validation") + override func validateToolbarItem(in window: SFSafariWindow, validationHandler: @escaping ((Bool, String) -> Void)) { + // Safari calls back on a Sendable closure, and the validation handler isn't Sendable. + nonisolated(unsafe) let validationHandler = validationHandler - // Bottleneck for calling through to a validation handler we have saved, and removing it from the list. - static func callValidationHandler(forHandlerID handlerID: String, withShouldValidate shouldValidate: Bool) { - if let validationWrapper = gPingPongMap[handlerID] { - validationWrapper.validationHandler(shouldValidate, "") - gPingPongMap.removeValue(forKey: handlerID) + SafariExtensionHandler.activePageURL(in: window) { pageURL in + validationHandler(SafariExtensionHandler.isSubscribablePageURL(pageURL), "") } } +} - override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String: Any]?) { - if messageName == "subscribeToFeed" { - if var feedURLString = userInfo?["url"] as? String { - var openInDefaultBrowser = false +private extension SafariExtensionHandler { - // Ask for the user's choice for whether to open the feed URL using whatever the system - // configured default is, or to always hard-code it to have NetNewsWire handle it itself. - if let appGroupID = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as? String { - if let groupDefaults = UserDefaults(suiteName: appGroupID) { - openInDefaultBrowser = groupDefaults.bool(forKey: "subscribeToFeedsInDefaultBrowser") - } - } - - if openInDefaultBrowser == false { - if feedURLString.hasPrefix("feeds:") { - feedURLString = "x-netnewswire-feed:" + feedURLString.dropFirst("feeds:".count) - } else if feedURLString.hasPrefix("feed:") { - feedURLString = "x-netnewswire-feed:" + feedURLString.dropFirst("feed:".count) - } - } - - if let feedURL = URL(string: feedURLString) { - NSWorkspace.shared.open(feedURL) - } + // Calls completion with the active page's URL, or with nil when there isn't one. + static func activePageURL(in window: SFSafariWindow, completion: @escaping @Sendable (URL?) -> Void) { + window.getActiveTab { activeTab in + guard let activeTab else { + completion(nil) + return } - } else if messageName == "pong" { - if let validationIDString = userInfo?["validationID"] as? String { - // Should we validate the button? - let shouldValidate = userInfo?["shouldValidate"] as? Bool ?? false - SafariExtensionHandler.callValidationHandler(forHandlerID: validationIDString, withShouldValidate: shouldValidate) - } - } - } - - override func toolbarItemClicked(in window: SFSafariWindow) { - window.getActiveTab { (activeTab) in - activeTab?.getActivePage(completionHandler: { (activePage) in - activePage?.dispatchMessageToScript(withName: "toolbarButtonClicked", userInfo: nil) - }) - } - } - - override func validateToolbarItem(in window: SFSafariWindow, validationHandler: @escaping ((Bool, String) -> Void)) { - - let uniqueValidationID = NSUUID().uuidString - - SafariExtensionHandler.validationQueue.sync { - - // Save it right away to eliminate any doubt of whether the handler gets deallocated while - // we are waiting for a callback from the getActiveTab or getActivatePage methods below. - let validationWrapper = ValidationWrapper(validationHandler: validationHandler) - SafariExtensionHandler.gPingPongMap[uniqueValidationID] = validationWrapper - - // To avoid problems with validation handlers dispatched after we've, for example, - // switched to a new tab, we aggressively clear out the map of any pending validations, - // and focus only on the newest validation request we've been asked for. - for thisValidationID in SafariExtensionHandler.gPingPongMap.keys { - if thisValidationID != uniqueValidationID { - // Default to valid ... we'll know soon enough whether the latest state - // is actually still valid or not... - SafariExtensionHandler.callValidationHandler(forHandlerID: thisValidationID, withShouldValidate: true) - - } - } - - // See comments above where gPingPongMap is declared. Upon being asked to validate the - // toolbar icon for a specific page, we save the validationHandler and postpone calling - // it until we have either received a response from our installed JavaScript, or until - // a timeout period has elapsed - window.getActiveTab { (activeTab) in - guard let activeTab = activeTab else { - SafariExtensionHandler.callValidationHandler(forHandlerID: uniqueValidationID, withShouldValidate: false) + activeTab.getActivePage { activePage in + guard let activePage else { + completion(nil) return } - - activeTab.getActivePage { (activePage) in - guard let activePage = activePage else { - SafariExtensionHandler.callValidationHandler(forHandlerID: uniqueValidationID, withShouldValidate: false) + activePage.getPropertiesWithCompletionHandler { pageProperties in + guard let pageProperties, pageProperties.isActive else { + completion(nil) return } - - activePage.getPropertiesWithCompletionHandler { pageProperties in - if let isActive = pageProperties?.isActive { - if isActive { - // Capture the uniqueValidationID to ensure it doesn't change out from under us on a future call - activePage.dispatchMessageToScript(withName: "ping", userInfo: ["validationID": uniqueValidationID]) - - let pongTimeoutInNanoseconds = Int(Double(NSEC_PER_SEC) * 0.5) - let timeoutDeadline = DispatchTime.now() + DispatchTimeInterval.nanoseconds(pongTimeoutInNanoseconds) - DispatchQueue.main.asyncAfter(deadline: timeoutDeadline, execute: { [timedOutValidationID = uniqueValidationID] in - SafariExtensionHandler.callValidationHandler(forHandlerID: timedOutValidationID, withShouldValidate: false) - }) - } - } - } + completion(pageProperties.url) } } } - } + } + + // True when the page is one we can look for a feed on. + static func isSubscribablePageURL(_ url: URL?) -> Bool { + guard let scheme = url?.scheme?.lowercased() else { + return false + } + return scheme == "http" || scheme == "https" + } + + // Rewrites the scheme so NetNewsWire handles the URL, unless the user would rather it went + // to the default news reader, and opens it. + static func openFeedURL(_ urlString: String) { + var feedURLString = urlString + var openInDefaultBrowser = false + + // Ask for the user's choice for whether to open the feed URL using whatever the system + // configured default is, or to always hard-code it to have NetNewsWire handle it itself. + if let appGroupID = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as? String { + if let groupDefaults = UserDefaults(suiteName: appGroupID) { + openInDefaultBrowser = groupDefaults.bool(forKey: "subscribeToFeedsInDefaultBrowser") + } + } + + if openInDefaultBrowser == false { + if feedURLString.hasPrefix("feeds:") { + feedURLString = "x-netnewswire-feed:" + feedURLString.dropFirst("feeds:".count) + } else if feedURLString.hasPrefix("feed:") { + feedURLString = "x-netnewswire-feed:" + feedURLString.dropFirst("feed:".count) + } + } + + if let feedURL = URL(string: feedURLString) { + NSWorkspace.shared.open(feedURL) + } + } } diff --git a/Mac/SafariExtension/SafariExtensionViewController.swift b/Mac/SafariExtension/SafariExtensionViewController.swift deleted file mode 100644 index 8da1fed4f..000000000 --- a/Mac/SafariExtension/SafariExtensionViewController.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// SafariExtensionViewController.swift -// Subscribe to Feed -// -// Created by Daniel Jalkut on 6/11/18. -// Copyright © 2018 Ranchero Software. All rights reserved. -// - -import SafariServices - -final class SafariExtensionViewController: SFSafariExtensionViewController { - - // This would be the place to handle a popover that could, for example, list the possibly multiple feeds offered by a site. - static let shared: SafariExtensionViewController = { - let shared = SafariExtensionViewController() - shared.preferredContentSize = NSSize(width: 320, height: 240) - return shared - }() - -} diff --git a/Mac/SafariExtension/netnewswire-subscribe-to-feed.js b/Mac/SafariExtension/netnewswire-subscribe-to-feed.js deleted file mode 100644 index e615c3207..000000000 --- a/Mac/SafariExtension/netnewswire-subscribe-to-feed.js +++ /dev/null @@ -1,45 +0,0 @@ -// The button is enabled on every web page. Clicking sends the page URL to the app, -// whose FeedFinder module does all feed discovery — head links, page scanning, -// URL guessing, special cases — so the logic lives in exactly one place. - -function subscribeToPage() { - safari.extension.dispatchMessage("subscribeToFeed", { "url": "feed:" + document.location.href }); -} - -function messageHandler(event) { - if (event.name === "toolbarButtonClicked") - { - // Workaround Radar #31182842, in which residual copies of our - // app extension may remain loaded in context of pages in Safari, - // causing multiple responses to broadcast message about toolbar - // button being clicked. In the case of the "extra" injections, - // the document location is null, so we can avoid doing on anything. - if (document.location != null) - { - subscribeToPage(); - } - } - else if (event.name === "ping") - { - // Just a hack to get the toolbar icon validation to work as expected. - // If we don't pong back, the extension knows we are not loaded in a page. - - // There is a bug in Safari where the messageHandler is apparently held on to by Safari - // even after an extension is disabled. So an effort to "ping" an extension's scripts will - // succeed even if its been disabled and the page reloaded. Checking for the existence of - // document.location seems to ensure we have enough of a handle still on the document that - // we can do something useful with it. - var shouldValidate = (document.location != null); - - // Pass back the same validationID we were handed so they can look up the correlated validationHandler - safari.extension.dispatchMessage("pong", { "validationID": event.message.validationID, "shouldValidate": shouldValidate }); - } -} - -document.addEventListener("DOMContentLoaded", function(event) { - // Prevent injecting the JavaScript in IFRAMES, and from acting before Safari is ready... - if ((window.top === window) && (typeof safari != 'undefined') && (document.location != null)) - { - safari.self.addEventListener("message", messageHandler, false) - } -}); diff --git a/NetNewsWire.xcodeproj/project.pbxproj b/NetNewsWire.xcodeproj/project.pbxproj index dbc57a42e..78145ff87 100644 --- a/NetNewsWire.xcodeproj/project.pbxproj +++ b/NetNewsWire.xcodeproj/project.pbxproj @@ -315,7 +315,6 @@ 842E25332DB9F9B800FF7DD8 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = { isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = ( - /Localized/SafariExtension/SafariExtensionViewController.xib, /Localized/ShareExtension/ShareViewController.xib, Resources/Info.plist, Resources/NetNewsWire.provisionprofile, @@ -324,9 +323,7 @@ "Resources/org.sparkle-project.InstallerLauncher.xpc", "Resources/org.sparkle-project.InstallerStatus.xpc", SafariExtension/Info.plist, - "SafariExtension/netnewswire-subscribe-to-feed.js", SafariExtension/SafariExtensionHandler.swift, - SafariExtension/SafariExtensionViewController.swift, SafariExtension/ToolbarItemIcon.pdf, ShareExtension/icon.icns, ShareExtension/Info.plist, @@ -337,10 +334,7 @@ 842E25352DB9F9B800FF7DD8 /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = { isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = ( - /Localized/SafariExtension/SafariExtensionViewController.xib, - "SafariExtension/netnewswire-subscribe-to-feed.js", SafariExtension/SafariExtensionHandler.swift, - SafariExtension/SafariExtensionViewController.swift, SafariExtension/ToolbarItemIcon.pdf, ); target = 6581C73220CED60000F4AD34 /* Subscribe to Feed */;