Open your Mac app from a link (myapp://)
A Mac app can have its own kind of link, myapp://…, that opens it from a web page, an email, another app or open in Terminal. Sign-in callbacks (OAuth redirects) and “open this item” links work this way. In Ferrokit it takes two pieces.
1. Declare the scheme in Cargo.toml:
[package.metadata.ferrokit]
url-schemes = ["notes"]
cargo ferrokit bundle (and cargo ferrokit run, which builds a bundle too) writes it into the app’s Info.plist (CFBundleURLTypes). macOS learns which app opens notes:// links the first time the bundled app runs; after that, a link starts the app if it isn’t running. A misspelt scheme, such as "notes://" or one with a space, stops the build and says what’s wrong.
2. Handle the links with App::on_open_url:
use ferrokit::*;
fn main() {
let opened = Signal::new(String::from("No link yet"));
App::new("Notes")
// Every notes://… link, whether it launched the app or came while it ran.
.on_open_url(move |url| match url.strip_prefix("notes://open/") {
Some(id) if !id.is_empty() && id.chars().all(|c| c.is_ascii_digit()) => {
opened.set(format!("Opening note {id}"));
}
// Anyone can send the app a link: ignore what you don't recognise.
_ => opened.set(format!("Ignored {url}")),
})
.window(Window::new("Notes").size(360.0, 120.0).view(text(move || opened.get()).padding(20.0)))
.run();
}
on_open_url gets every link, whether it launched the app or arrived while the app was running, after the windows are up.
Try it:
cargo ferrokit run
open "notes://open/42"
Things to know
- Only a bundled app that has run once gets links. A bundle that’s built but never run isn’t known to macOS yet (
opensays no application can open the link), and a barecargo runnever gets links. Usecargo ferrokit run. - Several copies, one winner. When more than one copy of the app declares the scheme (an old build, a copy in
/Applications), macOS picks one of them, not necessarily the one you just built. - Links arrive percent-encoded, as macOS gives them (
notes://open/my%20note). Decode them with a crate such asurlif you need to. - Treat a link as untrusted input. Any web page or app can send your app one. Check it before acting on it, and ask before doing anything destructive.
The guide has it too: Links into the app, with all of the [package.metadata.ferrokit] settings in cargo ferrokit’s README.