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
2 changes: 1 addition & 1 deletion Annotate/AnnotateCommand.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Cocoa

/// An action other apps can trigger: Shortcuts actions today, `annotate://` links next (#134).
/// An action other apps can trigger, from Shortcuts actions or `annotate://` links.
/// Each command runs the same `AppDelegate` code the menu and shortcuts do, then shows the
/// on-screen HUD on any open overlay.
enum AnnotateCommand: Hashable, Sendable {
Expand Down
7 changes: 7 additions & 0 deletions Annotate/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem
var localMouseUpMonitor: Any?
var localFlagsChangedMonitor: Any?

/// Links that arrive before launch finishes, run once it does.
var pendingCommandURLs: [URL] = []
private(set) var hasFinishedLaunching = false

override init() {
self.settings = .standard
super.init()
Expand Down Expand Up @@ -92,6 +96,9 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem
setupCursorHighlightWindows()
setupGlobalMouseMonitors()
setupCursorHighlightObservers()

hasFinishedLaunching = true
runPendingCommandURLs()
}

func applicationWillTerminate(_ notification: Notification) {
Expand Down
7 changes: 7 additions & 0 deletions Annotate/GeneralSettingsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ struct GeneralSettingsView: View {
private var defaultToolOption: DefaultToolOption
@AppStorage(.fadeDelay)
private var fadeDelay: Double
@AppStorage(.urlCommandsEnabled)
private var urlCommandsEnabled: Bool

/// Tools offered in the Default Tool picker, excluding Select and Eraser since neither
/// is a sensible tool to land on when the overlay opens.
Expand Down Expand Up @@ -148,6 +150,11 @@ struct GeneralSettingsView: View {
Text("Default Tool")
Text("Tool selected each time the overlay is activated")
}

Toggle(isOn: $urlCommandsEnabled) {
Text("Allow URL commands")
Text("Run \(AnnotateCommand.urlScheme):// links from other apps, scripts, and the browser")
}
} header: {
SettingsHeader(
icon: "macwindow",
Expand Down
13 changes: 13 additions & 0 deletions Annotate/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,19 @@
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>CFBundleURLName</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleURLSchemes</key>
<array>
<string>$(ANNOTATE_URL_SCHEME)</string>
</array>
</dict>
</array>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleVersion</key>
Expand Down
2 changes: 2 additions & 0 deletions Annotate/SettingsStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ extension SettingKey<Bool> {
static var toolbarShowsShortcuts: Self { .bool("ToolbarShowsShortcuts", default: true) }
static var soundsEnabled: Self { .bool("SoundsEnabled") }
static var enableBoard: Self { .bool("EnableBoard") }
/// Whether `annotate://` links run commands. When off, links are ignored.
static var urlCommandsEnabled: Self { .bool("URLCommandsEnabled", default: true) }

static var textBackground: Self { .bool("TextBackgroundOn") }
/// Whether committing a label switches to the Select tool with that label selected.
Expand Down
93 changes: 93 additions & 0 deletions Annotate/URLCommands.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import Cocoa
import os

// `annotate://` links. Each link names an `AnnotateCommand` in its path form, so
// `annotate://tool/arrow` runs `.tool(.arrow)` the same way the Select Tool action does.

extension AnnotateCommand {
/// The scheme this build opens. Debug builds register their own, so a development copy never
/// takes links meant for the installed app. Keep in sync with `ANNOTATE_URL_SCHEME` in
/// `project.yml`, which puts the scheme in `Info.plist`.
#if DEBUG
static let urlScheme = "annotate-debug"
#else
static let urlScheme = "annotate"
#endif

/// Parses a link such as `annotate://show` or `annotate://tool/arrow`: the host is the command
/// and the path its value, matched like `init?(path:)`. Returns nil for another scheme, a
/// missing command, a user, password, port, query, or fragment, or a path `init?(path:)`
/// rejects.
init?(url: URL, scheme: String = AnnotateCommand.urlScheme) {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
components.scheme?.lowercased() == scheme.lowercased(),
let host = components.host, !host.isEmpty,
components.user == nil, components.password == nil, components.port == nil,
components.query == nil, components.fragment == nil
else { return nil }
self.init(path: host + components.path)
}

/// A link with only its scheme, host, and path, safe to log in the clear. Drops the user,
/// password, port, query, and fragment, where a pasted or forwarded link could carry a token
/// or other private data, and names which of them were there. Keeps percent-encoding, so the
/// result is one line however the link was built.
static func logDescription(of url: URL) -> String {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
return "<unparseable link>"
}
let host = components.percentEncodedHost.map { "//" + $0 } ?? ""
let link = (components.scheme.map { $0 + ":" } ?? "") + host + components.percentEncodedPath
let parts: [(name: String, isPresent: Bool)] = [
("user", components.percentEncodedUser != nil),
("password", components.percentEncodedPassword != nil),
("port", components.port != nil),
("query", components.percentEncodedQuery != nil),
("fragment", components.percentEncodedFragment != nil),
]
let dropped = parts.filter(\.isPresent).map(\.name)
return dropped.isEmpty ? link : "\(link) (dropped \(dropped.joined(separator: ", ")))"
}
}

private let log = Logger(subsystem: "com.epilande.Annotate", category: "URLCommands")

extension AppDelegate {
func application(_ application: NSApplication, open urls: [URL]) {
// A link that launches the app can arrive before launch finishes, when there is no
// overlay to open yet.
guard hasFinishedLaunching else {
pendingCommandURLs += urls
return
}
urls.forEach { openCommandURL($0) }
}

/// Runs a link's command and shows its HUD. Returns nil without doing anything when URL
/// commands are off in Settings or the link isn't a command.
@discardableResult
func openCommandURL(_ url: URL) -> AnnotateCommand.Outcome? {
guard settings[.urlCommandsEnabled] else {
let link = AnnotateCommand.logDescription(of: url)
log.info("Ignored a link because URL commands are off: \(link, privacy: .public)")
return nil
}
guard let command = AnnotateCommand(url: url) else {
let link = AnnotateCommand.logDescription(of: url)
log.info("Ignored a link that isn't a command: \(link, privacy: .public)")
return nil
}
return command.run(on: self)
}

/// Runs the links that arrived during launch on the next run-loop pass, after the Always-On
/// restore that launch queues.
func runPendingCommandURLs() {
guard !pendingCommandURLs.isEmpty else { return }
let urls = pendingCommandURLs
pendingCommandURLs = []
DispatchQueue.main.async {
urls.forEach { self.openCommandURL($0) }
}
}
}
2 changes: 1 addition & 1 deletion AnnotateTests/AnnotateCommandTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ final class AnnotateCommandTests: XCTestCase {

// MARK: - Path form

private static let everyCommand: [AnnotateCommand] =
static let everyCommand: [AnnotateCommand] =
[.toggle, .show, .hide, .clear]
+ ToolType.allCases.map(AnnotateCommand.tool)
+ PaletteColor.allCases.map(AnnotateCommand.color)
Expand Down
195 changes: 195 additions & 0 deletions AnnotateTests/URLCommandTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
import XCTest

@testable import Annotate

@MainActor
final class URLCommandTests: XCTestCase {
var appDelegate: AppDelegate!
var testDefaults: UserDefaults!
var screen: NSScreen!

override func setUp() {
super.setUp()
TestWindows.recordOpenWindows()
testDefaults = TestUserDefaults.create()
BoardManager.shared = BoardManager(userDefaults: testDefaults)
ShortcutManager.shared = ShortcutManager(userDefaults: testDefaults)

appDelegate = AppDelegate(userDefaults: testDefaults)
// Commands that open the overlay use the display under the pointer.
screen = NSScreen.screens.first
appDelegate.pointerLocationOverride = NSPoint(x: screen.frame.midX, y: screen.frame.midY)
}

override func tearDown() {
appDelegate.overlayWindows.values.forEach { $0.stopFadeLoop() }
appDelegate.tearDownAfterLaunch()
appDelegate = nil
screen = nil
assertNoLeakedWindows()
TestUserDefaults.removeSuite()
testDefaults = nil
super.tearDown()
}

private func launch() {
appDelegate.applicationDidFinishLaunching(
Notification(name: NSApplication.didFinishLaunchingNotification))
}

private var overlay: OverlayWindow? { appDelegate.overlayWindows[screen] }

private var visibleOverlays: [OverlayWindow] {
appDelegate.overlayWindows.values.filter(\.isVisible)
}

private func link(_ string: String) throws -> URL {
try XCTUnwrap(URL(string: string), string)
}

/// Opens links the way Launch Services delivers them.
private func open(_ strings: String...) throws {
appDelegate.application(NSApplication.shared, open: try strings.map(link))
}

// MARK: - Parsing

func testDebugBuildsUseTheirOwnScheme() {
// `swift test` and Xcode's test action both build Debug.
XCTAssertEqual(AnnotateCommand.urlScheme, "annotate-debug")
}

func testEveryCommandRoundTripsThroughALink() throws {
for command in AnnotateCommandTests.everyCommand {
for scheme in ["annotate", "annotate-debug"] {
let url = try link("\(scheme):/\(command.path)")
XCTAssertEqual(AnnotateCommand(url: url, scheme: scheme), command, url.absoluteString)
}
}
}

func testLinksUseTheHostAsTheCommand() throws {
XCTAssertEqual(AnnotateCommand(url: try link("annotate://show"), scheme: "annotate"), .show)
XCTAssertEqual(AnnotateCommand(url: try link("annotate://show/"), scheme: "annotate"), .show)
XCTAssertEqual(AnnotateCommand(url: try link("annotate://tool/arrow"), scheme: "annotate"), .tool(.arrow))
XCTAssertEqual(AnnotateCommand(url: try link("annotate://toolbar/off"), scheme: "annotate"), .toolbar(.off))
XCTAssertEqual(AnnotateCommand(url: try link("ANNOTATE://Color/Red"), scheme: "annotate"), .color(.red))
}

func testLinksOnlyMatchTheBuildsScheme() throws {
XCTAssertNil(AnnotateCommand(url: try link("annotate-debug://show"), scheme: "annotate"))
XCTAssertNil(AnnotateCommand(url: try link("annotate://show"), scheme: "annotate-debug"))
XCTAssertNil(AnnotateCommand(url: try link("annotate://show")), "Debug builds ignore release links")
XCTAssertEqual(AnnotateCommand(url: try link("annotate-debug://show")), .show)
}

func testMalformedLinksParseAsNothing() throws {
let invalid = [
"annotate://", "annotate:///show", "annotate:show", "annotate://nope",
"annotate://tool", "annotate://tool/brush", "annotate://color/purple",
"annotate://toolbar/maybe", "annotate://show/now", "annotate://tool/arrow/extra",
"annotate://show?now=1", "annotate://show?", "annotate://show#top",
"annotate://user@show", "annotate://user:pass@show", "annotate://show:80",
"https://show", "file:///show", "annotatex://show",
]
for string in invalid {
XCTAssertNil(AnnotateCommand(url: try link(string), scheme: "annotate"), string)
}
}

// MARK: - Logging

func testLogDescriptionKeepsOnlyTheSchemeAndCommand() throws {
XCTAssertEqual(AnnotateCommand.logDescription(of: try link("annotate://tool/arrow")), "annotate://tool/arrow")
XCTAssertEqual(AnnotateCommand.logDescription(of: try link("annotate:show")), "annotate:show")
XCTAssertEqual(
AnnotateCommand.logDescription(of: try link("annotate://show?token=s3cret#frag")),
"annotate://show (dropped query, fragment)")
XCTAssertEqual(
AnnotateCommand.logDescription(of: try link("annotate://me:hunter2@show:8080/now")),
"annotate://show/now (dropped user, password, port)")
}

func testLogDescriptionKeepsPercentEncodingOnOneLine() throws {
XCTAssertEqual(
AnnotateCommand.logDescription(of: try link("annotate://tool/arr%0Aow")), "annotate://tool/arr%0Aow")
}

// MARK: - Opening links

func testURLCommandsAreOnByDefault() {
XCTAssertTrue(testDefaults.settings[.urlCommandsEnabled])
}

func testToolLinkOpensTheOverlayWithItsHUD() throws {
launch()
let overlay = try XCTUnwrap(overlay)

try open("annotate-debug://tool/arrow")

XCTAssertTrue(overlay.isVisible)
XCTAssertEqual(overlay.overlayView.currentTool, .arrow)
let hud = overlay.currentFeedbackView?.subviews.lazy.compactMap { $0 as? NSTextField }.first
XCTAssertEqual(hud?.stringValue.contains("Arrow"), true)
}

func testColorAndToolbarLinksDoNotOpenTheOverlay() throws {
launch()

try open("annotate-debug://color/green", "annotate-debug://toolbar/off")

XCTAssertTrue(visibleOverlays.isEmpty)
XCTAssertEqual(appDelegate.currentColor, .systemGreen)
XCTAssertFalse(appDelegate.toolbarVisible)
}

func testOpeningALinkReportsWhatItsCommandDid() throws {
launch()

XCTAssertEqual(appDelegate.openCommandURL(try link("annotate-debug://show")), .ran)
XCTAssertEqual(appDelegate.openCommandURL(try link("annotate-debug://show")), .noOp)
}

func testLinksAreIgnoredWhenURLCommandsAreOff() throws {
testDefaults.settings[.urlCommandsEnabled] = false
launch()
let colorBefore = appDelegate.currentColor

XCTAssertNil(appDelegate.openCommandURL(try link("annotate-debug://show")))
try open("annotate-debug://tool/arrow", "annotate-debug://color/green", "annotate-debug://toolbar/off")

XCTAssertTrue(visibleOverlays.isEmpty)
XCTAssertEqual(appDelegate.currentColor, colorBefore)
XCTAssertTrue(appDelegate.toolbarVisible)

testDefaults.settings[.urlCommandsEnabled] = true
try open("annotate-debug://show")
XCTAssertEqual(overlay?.isVisible, true, "Links run again once the setting is back on")
}

func testMalformedLinksChangeNothing() throws {
launch()
let colorBefore = appDelegate.currentColor

XCTAssertNil(appDelegate.openCommandURL(try link("annotate-debug://tool/brush")))
try open("annotate-debug://", "annotate-debug://show?x=1", "annotate://show", "https://example.com")

XCTAssertTrue(visibleOverlays.isEmpty)
XCTAssertEqual(appDelegate.currentColor, colorBefore)
XCTAssertTrue(appDelegate.toolbarVisible)
}

func testALinkThatLaunchesTheAppRunsOnceLaunchFinishes() throws {
// Launch Services can deliver the link that launched the app before launch finishes.
try open("annotate-debug://tool/rectangle")
XCTAssertTrue(appDelegate.overlayWindows.isEmpty)

launch()
wait(for: 0.05)

let overlay = try XCTUnwrap(overlay)
XCTAssertTrue(overlay.isVisible)
XCTAssertEqual(overlay.overlayView.currentTool, .rectangle)
XCTAssertTrue(appDelegate.pendingCommandURLs.isEmpty)
}
}
Loading
Loading