macOS Services: the first right-click did nothing
Purrchiver adds five items to the Finder right-click Services menu: Open, Extract, Archive, Compress, and Encrypt. Two bugs made them feel broken. If Purrchiver wasn’t already running, the first time you picked one, the app launched to an empty welcome window and nothing else happened. And Extract on an archive in a folder like the Desktop failed with a permission error, even though the folder was plainly writable in Finder.
How in-process Services work
There are two ways to put an item in the Services menu: an app extension,
or an NSServices array in the app’s own Info.plist. Purrchiver uses the
second, so the service runs inside the app and can hand files straight to
the code that opens windows. Each entry names a message:
<key>NSMessage</key>
<string>extractUsingPurrchiver</string>AppKit turns that into a selector, extractUsingPurrchiver:userData:error:,
and calls it on whatever object you assign to NSApp.servicesProvider:
@objc func extractUsingPurrchiver(_ pasteboard: NSPasteboard,
userData: String,
error: AutoreleasingUnsafeMutablePointer<NSString>) {
let urls = pasteboard.readObjects(forClasses: [NSURL.self],
options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []
deliver(urls, intent: .extract)
}If the name in the plist and the method name drift apart, the menu item just
does nothing. Purrchiver now has a unit test that reads every NSMessage
from the bundled Info.plist and checks that the provider responds(to:)
the matching selector. It’s cheap, and it catches a typo before a user does.
Bug 1: the delivery arrived before anything could receive it
An archive utility usually isn’t running when you right-click an archive. Choosing a Service launches it, and AppKit calls the provider method during that launch. In Purrchiver, the provider passes files to a router that decides what window to open, and the router wasn’t wired in until the first window appeared. A Service call that arrived first found no router, and the code returned without doing anything. The files were dropped. You got the welcome window and had to pick the Service a second time, when it worked because the app was already up.
The fix is to buffer instead of dropping, and flush when the router appears:
var router: FileOpenRouter? {
didSet {
guard let router else { return }
for pending in buffer.drain() {
router.deliver(urls: pending.urls, intent: pending.intent)
}
NSApp.activate(ignoringOtherApps: true)
}
}
private func deliver(_ urls: [URL], intent: Intent) {
guard let router else {
buffer.enqueue(urls: urls, intent: intent) // capped, FIFO
return
}
router.deliver(urls: urls, intent: intent)
NSApp.activate(ignoringOtherApps: true)
}The buffer keeps order and keeps each delivery’s verb, so an Extract stays an Extract, and it’s capped so a burst of files can’t grow it without limit. I made it a plain value type so tests can check order, draining, and the cap without a pasteboard or a running app. Finder open requests were already buffered during launch the same way. The Services path had simply never gotten the same treatment.
If your Services, URL handler, or Apple Event handler routes into anything that’s set up after launch, check what happens on a cold start. That’s the normal case for a utility, and it’s the one you never test, because the app is always running while you develop it.
Bug 2: Extract couldn’t write next to the archive
Extract using Purrchiver puts the files in a folder next to the archive.
In the App Sandbox, the Service gives the app access to the archive it was
handed. It doesn’t give access to the folder the archive is in. Purrchiver
could read ~/Desktop/photos.zip and couldn’t create ~/Desktop/photos/.
The extract started, then failed with a permission error.
The tempting check is to look at the folder’s permissions first. That doesn’t work: POSIX permission bits describe what Unix permissions allow, and the sandbox is a separate layer on top. Your account can write to the Desktop, and the sandboxed process still can’t.
The only check I trust is to try:
static func canWrite(to dir: URL) -> Bool {
let started = dir.startAccessingSecurityScopedResource()
defer { if started { dir.stopAccessingSecurityScopedResource() } }
let probe = dir.appendingPathComponent(".write-probe-\(UUID().uuidString)")
do {
try Data().write(to: probe)
try? FileManager.default.removeItem(at: probe)
return true
} catch {
return false
}
}If the probe succeeds, Purrchiver extracts without asking. If it fails, it shows a folder picker that starts in that same folder. Usually one click on Choose is enough. That choice is what grants the sandbox write access. The same check covers opening an archive from Finder when your default is to extract next to it, which has the same problem.
The probe writes an empty hidden file and deletes it straight away, and
startAccessingSecurityScopedResource() returns false for a URL with no
scope, so it’s safe to call on any folder. Tests check that it reports a
writable folder as writable and a missing folder as not, and that it leaves
nothing behind. The decision between extracting and asking is a separate
pure function with its own tests.
What to take away
NSMessagemaps to<message>:userData:error:. Test that every plist entry has a method, because a mismatch fails silently.- A Service, like any launch-time entry point, can fire before your app has finished setting up. Buffer it; don’t drop it.
- In the sandbox, being given a file doesn’t give you its folder. To know whether you can write somewhere, write a probe file. Permission bits won’t tell you.
- When you can’t write, ask with a picker that defaults to the folder you wanted. The user’s click grants the access.