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 */;
diff --git a/iOS/SceneCoordinator.swift b/iOS/SceneCoordinator.swift
index 961194a45..9f7348796 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() {