This commit is contained in:
Brent Simmons committed 2026-08-03 10:50:36 -07:00
commit 02dc71f85e
7 files changed
+93 -231

No files matched your search

@@ -1,30 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="11134" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="11134"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="SafariExtensionViewController" customModuleProvider="target">
<connections>
<outlet property="view" destination="c22-O7-iKe" id="vwT-Xx-Aiz"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<customView id="c22-O7-iKe">
<rect key="frame" x="0.0" y="0.0" width="330" height="119"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<subviews>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="4Iy-aV-wGF">
<rect key="frame" x="103" y="82" width="124" height="17"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="Subscribe to Feed" id="2Ec-kd-q2K">
<font key="font" metaFont="system"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
</subviews>
</customView>
</objects>
</document>
-7
View File
@@ -30,13 +30,6 @@
<string>com.apple.Safari.extension</string>
<key>NSExtensionPrincipalClass</key>
<string>$(PRODUCT_MODULE_NAME).SafariExtensionHandler</string>
<key>SFSafariContentScript</key>
<array>
<dict>
<key>Script</key>
<string>netnewswire-subscribe-to-feed.js</string>
</dict>
</array>
<key>SFSafariToolbarItem</key>
<dict>
<key>Action</key>
+68 -113
View File
@@ -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.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4208>
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)
}
}
}
@@ -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
}()
}
@@ -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)
}
});
-6
View File
@@ -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 */;
+25 -10
View File
@@ -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.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4352>
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.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4352>
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.
// <https://github.com/Ranchero-Software/NetNewsWire/issues/4352>
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() {