Skip to content

AI-native design editor. Open-source Figma alternative.

feat: draw SF Symbols from the Mac as icon outlines (#1472)

Danila Poyarkov2c92b864b68e
diff --git a/.gitignore b/.gitignore
index 4b3d2e409..16ab84c88 100644
--- a/.gitignore
+++ b/.gitignore
@@ -99,3 +99,6 @@ packages/cloud/deploy/generated/
packages/cloud/dist-standalone/
dist-cloud/
dist-metrics/
+
+# SwiftPM output of desktop Swift packages built by hand
+desktop/swift/*/.build/
diff --git a/changes/1472/added.md b/changes/1472/added.md
new file mode 100644
index 000000000..cb55d0707
--- /dev/null
+++ b/changes/1472/added.md
@@ -0,0 +1 @@
+- On macOS 14 and later, the desktop app's icon picker offers SF Symbols, drawn by the Mac itself at a chosen weight, scale, and monochrome or hierarchical rendering; documents keep the outlines, so they draw on every platform.
diff --git a/desktop/AGENTS.md b/desktop/AGENTS.md
index d098ff6d6..2338ca703 100644
--- a/desktop/AGENTS.md
+++ b/desktop/AGENTS.md
@@ -17,3 +17,4 @@ Check `desktop/Cargo.toml`, `desktop/capabilities/**`, and `desktop/tauri.conf.j
- The embedded WebDriver plugin compiles only with the `native-test` Cargo feature and must never be enabled in development or production binaries. Native tests use `bun run test:native` (`tests/AGENTS.md`).
- The editor opens external links through the `open_external_url` command, which allows only `http`, `https`, and `mailto`; native-test builds record them for `take_native_test_opened_urls` instead of launching a browser (`system::opener` unit tests, `tests/e2e/native/cloud-links.spec.ts`).
- `openpencil://` links are parsed in `desktop/src/launch/links.rs` and queued in `desktop/src/launch/mod.rs`: `open` queues files through `take_pending_open`, `join` queues validated room IDs through `take_pending_rooms`, `cloud` queues Cloud invitations and shared links (UUID, hex secret, `http(s)` server) through `take_pending_cloud_links`; second launches forward their link arguments through the single-instance handler (`launch::links` unit tests).
+- SF Symbols are drawn by SwiftUI through the Swift package `desktop/swift/sf-symbols`, linked by `build.rs` on macOS; they are never bundled, served, or read from Apple's font files. `sf_symbols_render` stays a synchronous command so Tauri runs it on the main thread SwiftUI needs, and both commands answer null below macOS 14, which lacks the path operations that cut badge knockouts (`packages/core/tests/icons/sf-symbols/provider.test.ts`).
diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock
index 74730a91d..bc183c7c2 100644
--- a/desktop/Cargo.lock
+++ b/desktop/Cargo.lock
@@ -3267,6 +3267,7 @@ dependencies = [
"semver",
"serde",
"serde_json",
+ "swift-rs",
"tauri",
"tauri-build",
"tauri-plugin-clipboard-manager",
diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml
index 9aef8d867..374d10b4f 100644
--- a/desktop/Cargo.toml
+++ b/desktop/Cargo.toml
@@ -22,6 +22,9 @@ crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
+[target.'cfg(target_os = "macos")'.build-dependencies]
+swift-rs = { version = "1.0.8", features = ["build"] }
+
[dependencies]
tauri = { version = "2", features = ["devtools"] }
tauri-plugin-opener = "2"
diff --git a/desktop/build.rs b/desktop/build.rs
index d860e1e6a..b9caf1106 100644
--- a/desktop/build.rs
+++ b/desktop/build.rs
@@ -1,3 +1,12 @@
fn main() {
+ // SF Symbols are drawn by SwiftUI, through a Swift library linked into the macOS app.
+ #[cfg(target_os = "macos")]
+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
+ swift_rs::SwiftLinker::new("13.0")
+ .with_package("SFSymbols", "swift/sf-symbols")
+ .link();
+ // The Swift runtime the library uses ships with macOS.
+ println!("cargo:rustc-link-arg=-Wl,-rpath,/usr/lib/swift");
+ }
tauri_build::build()
}
diff --git a/desktop/src/icons/mod.rs b/desktop/src/icons/mod.rs
new file mode 100644
index 000000000..7d185dd30
--- /dev/null
+++ b/desktop/src/icons/mod.rs
@@ -0,0 +1,30 @@
+//! Tauri commands that draw SF Symbols as outlines. Apple licenses the symbols for use on its
+//! own platforms, so they are drawn by the Mac the app runs on, never bundled or served.
+
+#[cfg(target_os = "macos")]
+mod sf_symbols;
+
+/// The SF Symbols this Mac draws, as JSON, or nothing where they cannot be drawn as outlines.
+#[tauri::command]
+pub async fn sf_symbols_catalogue() -> Option<String> {
+ #[cfg(target_os = "macos")]
+ return tauri::async_runtime::spawn_blocking(sf_symbols::catalogue)
+ .await
+ .ok()
+ .flatten();
+ #[cfg(not(target_os = "macos"))]
+ None
+}
+
+/// The symbols a JSON request names, drawn as it asks, as JSON. Not async, so Tauri runs it on
+/// the main thread, which SwiftUI draws on.
+#[tauri::command]
+pub fn sf_symbols_render(request: String) -> Option<String> {
+ #[cfg(target_os = "macos")]
+ return sf_symbols::render(&request);
+ #[cfg(not(target_os = "macos"))]
+ {
+ let _ = request;
+ None
+ }
+}
diff --git a/desktop/src/icons/sf_symbols.rs b/desktop/src/icons/sf_symbols.rs
new file mode 100644
index 000000000..ca0d829bb
--- /dev/null
+++ b/desktop/src/icons/sf_symbols.rs
@@ -0,0 +1,34 @@
+//! The Swift library in `swift/sf-symbols`, which reads the symbols macOS has and draws them with
+//! SwiftUI. Requests and answers are JSON in C strings.
+
+use std::ffi::{c_char, CStr, CString};
+
+extern "C" {
+ fn op_sf_symbols_catalogue() -> *mut c_char;
+ fn op_sf_symbols_render(request: *const c_char) -> *mut c_char;
+ fn op_sf_symbols_free(answer: *mut c_char);
+}
+
+fn take(answer: *mut c_char) -> Option<String> {
+ if answer.is_null() {
+ return None;
+ }
+ // SAFETY: the library answers with a NUL-terminated string it allocated, freed once here.
+ let text = unsafe { CStr::from_ptr(answer) }
+ .to_string_lossy()
+ .into_owned();
+ unsafe { op_sf_symbols_free(answer) };
+ Some(text)
+}
+
+pub fn catalogue() -> Option<String> {
+ // SAFETY: the catalogue takes no arguments and may run on any thread.
+ take(unsafe { op_sf_symbols_catalogue() })
+}
+
+/// Must run on the main thread.
+pub fn render(request: &str) -> Option<String> {
+ let request = CString::new(request).ok()?;
+ // SAFETY: the request is a NUL-terminated string that outlives the call.
+ take(unsafe { op_sf_symbols_render(request.as_ptr()) })
+}
diff --git a/desktop/src/lib.rs b/desktop/src/lib.rs
index dda8cb085..4c6a2d76d 100644
--- a/desktop/src/lib.rs
+++ b/desktop/src/lib.rs
@@ -2,6 +2,7 @@ mod agents;
mod credentials;
mod files;
mod fonts;
+mod icons;
mod launch;
mod menu;
mod network;
@@ -84,6 +85,8 @@ pub fn run() {
launch::paths::path_matches_suffix,
list_system_fonts,
load_system_font,
+ icons::sf_symbols_catalogue,
+ icons::sf_symbols_render,
proxy_http_request,
cancel_http_request,
files::recent::set_recent_files,
diff --git a/desktop/swift/sf-symbols/Package.swift b/desktop/swift/sf-symbols/Package.swift
new file mode 100644
index 000000000..03dffd99a
--- /dev/null
+++ b/desktop/swift/sf-symbols/Package.swift
@@ -0,0 +1,9 @@
+// swift-tools-version:5.9
+import PackageDescription
+
+let package = Package(
+ name: "SFSymbols",
+ platforms: [.macOS(.v13)],
+ products: [.library(name: "SFSymbols", type: .static, targets: ["SFSymbols"])],
+ targets: [.target(name: "SFSymbols")]
+)
diff --git a/desktop/swift/sf-symbols/Sources/SFSymbols/Bridge.swift b/desktop/swift/sf-symbols/Sources/SFSymbols/Bridge.swift
new file mode 100644
index 000000000..66ab94716
--- /dev/null
+++ b/desktop/swift/sf-symbols/Sources/SFSymbols/Bridge.swift
@@ -0,0 +1,42 @@
+import Foundation
+
+/// The C functions the desktop app calls. Requests and answers are JSON in C strings, and every
+/// answer is freed with `op_sf_symbols_free`.
+
+private func json<T: Encodable>(_ value: T?) -> String? {
+ guard let value, let data = try? JSONEncoder().encode(value) else { return nil }
+ return String(decoding: data, as: UTF8.self)
+}
+
+private func answer(_ text: String?) -> UnsafeMutablePointer<CChar>? {
+ text.flatMap { strdup($0) }
+}
+
+/// The symbols this Mac draws, or null when it cannot draw them as outlines.
+@_cdecl("op_sf_symbols_catalogue")
+public func opSFSymbolsCatalogue() -> UnsafeMutablePointer<CChar>? {
+ guard #available(macOS 14, *) else { return nil }
+ return answer(json(catalogue()))
+}
+
+/// Each named symbol this Mac has, drawn as the request asks. Must run on the main thread.
+@_cdecl("op_sf_symbols_render")
+public func opSFSymbolsRender(_ request: UnsafePointer<CChar>) -> UnsafeMutablePointer<CChar>? {
+ guard #available(macOS 14, *),
+ let request = try? JSONDecoder().decode(
+ RenderRequest.self, from: Data(String(cString: request).utf8))
+ else { return nil }
+ let icons = MainActor.assumeIsolated {
+ var icons: [String: Icon] = [:]
+ for name in request.names {
+ if let icon = icon(name, request) { icons[name] = icon }
+ }
+ return json(icons)
+ }
+ return answer(icons)
+}
+
+@_cdecl("op_sf_symbols_free")
+public func opSFSymbolsFree(_ answer: UnsafeMutablePointer<CChar>?) {
+ free(answer)
+}
diff --git a/desktop/swift/sf-symbols/Sources/SFSymbols/Catalogue.swift b/desktop/swift/sf-symbols/Sources/SFSymbols/Catalogue.swift
new file mode 100644
index 000000000..31c4909db
--- /dev/null
+++ b/desktop/swift/sf-symbols/Sources/SFSymbols/Catalogue.swift
@@ -0,0 +1,45 @@
+import Foundation
+
+/// The symbols this Mac draws, from the metadata macOS keeps beside its own symbol images.
+struct Catalogue: Encodable {
+ /// Every name, in the order Apple lists them.
+ var names: [String]
+ /// Search keywords by name, for the names that have them.
+ var keywords: [String: [String]]
+}
+
+private let metadata = URL(
+ fileURLWithPath: "/System/Library/CoreServices/CoreGlyphs.bundle/Contents/Resources")
+
+private func plist(_ name: String) -> Any? {
+ guard let data = try? Data(contentsOf: metadata.appendingPathComponent("\(name).plist")) else {
+ return nil
+ }
+ return try? PropertyListSerialization.propertyList(from: data, format: nil)
+}
+
+private func version(_ text: String) -> OperatingSystemVersion {
+ let parts = text.split(separator: ".").map { Int($0) ?? 0 }
+ return OperatingSystemVersion(
+ majorVersion: parts.first ?? 0,
+ minorVersion: parts.count > 1 ? parts[1] : 0,
+ patchVersion: parts.count > 2 ? parts[2] : 0)
+}
+
+/// The catalogue, or nil when macOS keeps no symbol metadata where it is read from.
+func catalogue() -> Catalogue? {
+ guard
+ let order = plist("symbol_order") as? [String],
+ let availability = plist("name_availability") as? [String: Any],
+ let released = availability["symbols"] as? [String: String],
+ let releases = availability["year_to_release"] as? [String: [String: String]]
+ else { return nil }
+ let running = ProcessInfo.processInfo
+ // A symbol is drawn from the macOS release its year shipped in.
+ let names = order.filter { name in
+ guard let year = released[name], let macOS = releases[year]?["macOS"] else { return false }
+ return running.isOperatingSystemAtLeast(version(macOS))
+ }
+ let keywords = (plist("symbol_search") as? [String: [String]]) ?? [:]
+ return Catalogue(names: names, keywords: keywords.filter { released[$0.key] != nil })
+}
diff --git a/desktop/swift/sf-symbols/Sources/SFSymbols/Outlines.swift b/desktop/swift/sf-symbols/Sources/SFSymbols/Outlines.swift
new file mode 100644
index 000000000..441041ec6
--- /dev/null
+++ b/desktop/swift/sf-symbols/Sources/SFSymbols/Outlines.swift
@@ -0,0 +1,247 @@
+import CoreGraphics
+import Foundation
+
+/// One filled shape of a drawing, in the PDF page's coordinates.
+struct Outline {
+ var path: CGPath
+ var opacity: CGFloat
+ /// The fill's lightness, which is what a soft mask reads.
+ var gray: CGFloat
+}
+
+/// What `q` saves and `Q` restores.
+private struct GraphicsState {
+ var transform = CGAffineTransform.identity
+ var gray: CGFloat = 0
+ var opacity: CGFloat = 1
+ /// Where a soft mask hides what is drawn, cut out of every later fill.
+ var knockout: CGPath?
+}
+
+/// The fills a PDF content stream draws, read operator by operator.
+@available(macOS 14, *)
+private final class Reader {
+ var states = [GraphicsState()]
+ var path = CGMutablePath()
+ var outlines: [Outline] = []
+
+ var state: GraphicsState {
+ get { states[states.count - 1] }
+ set { states[states.count - 1] = newValue }
+ }
+
+ func point(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
+ CGPoint(x: x, y: y).applying(state.transform)
+ }
+
+ func fill(_ rule: CGPathFillRule) {
+ var shape: CGPath = path.normalized(using: rule)
+ if let knockout = state.knockout { shape = shape.subtracting(knockout) }
+ if !shape.isEmpty { outlines.append(Outline(path: shape, opacity: state.opacity, gray: state.gray)) }
+ path = CGMutablePath()
+ }
+}
+
+private func numbers(_ scanner: CGPDFScannerRef, _ count: Int) -> [CGFloat] {
+ var values = [CGFloat](repeating: 0, count: count)
+ for index in (0..<count).reversed() {
+ var value: CGPDFReal = 0
+ CGPDFScannerPopNumber(scanner, &value)
+ values[index] = value
+ }
+ return values
+}
+
+private func name(_ scanner: CGPDFScannerRef) -> String? {
+ var value: UnsafePointer<CChar>?
+ guard CGPDFScannerPopName(scanner, &value), let value else { return nil }
+ return String(cString: value)
+}
+
+@available(macOS 14, *)
+private func reader(_ info: UnsafeMutableRawPointer?) -> Reader {
+ Unmanaged<Reader>.fromOpaque(info!).takeUnretainedValue()
+}
+
+/// A form's matrix, which maps its space into the space it is drawn in.
+private func matrix(_ form: CGPDFStreamRef) -> CGAffineTransform {
+ guard let dictionary = CGPDFStreamGetDictionary(form) else { return .identity }
+ var array: CGPDFArrayRef?
+ guard CGPDFDictionaryGetArray(dictionary, "Matrix", &array), let array,
+ CGPDFArrayGetCount(array) == 6
+ else { return .identity }
+ let values = (0..<6).map { index -> CGFloat in
+ var value: CGPDFReal = 0
+ CGPDFArrayGetNumber(array, index, &value)
+ return value
+ }
+ return CGAffineTransform(
+ a: values[0], b: values[1], c: values[2], d: values[3], tx: values[4], ty: values[5])
+}
+
+/// The fills of a form, drawn with `transform`, read with a reader of their own.
+@available(macOS 14, *)
+private func formOutlines(
+ _ form: CGPDFStreamRef, parent: CGPDFContentStreamRef, transform: CGAffineTransform
+) -> [Outline] {
+ let nested = Reader()
+ nested.state.transform = matrix(form).concatenating(transform)
+ guard let dictionary = CGPDFStreamGetDictionary(form) else { return [] }
+ var resources: CGPDFDictionaryRef?
+ CGPDFDictionaryGetDictionary(dictionary, "Resources", &resources)
+ // A form without resources of its own finds them in the stream that draws it.
+ let stream = CGPDFContentStreamCreateWithStream(form, resources ?? dictionary, parent)
+ scan(stream, nested)
+ return nested.outlines
+}
+
+/// The stream a resource names, such as a form XObject.
+private func resourceStream(
+ _ scanner: CGPDFScannerRef, _ category: String, _ key: String
+) -> CGPDFStreamRef? {
+ let content = CGPDFScannerGetContentStream(scanner)
+ guard let object = CGPDFContentStreamGetResource(content, category, key) else { return nil }
+ var stream: CGPDFStreamRef?
+ return CGPDFObjectGetValue(object, .stream, &stream) ? stream : nil
+}
+
+@available(macOS 14, *)
+private let operators: CGPDFOperatorTableRef = {
+ let table = CGPDFOperatorTableCreate()!
+ func on(_ name: String, _ callback: @escaping CGPDFOperatorCallback) {
+ CGPDFOperatorTableSetCallback(table, name, callback)
+ }
+ on("q") { _, info in
+ let reader = reader(info)
+ reader.states.append(reader.state)
+ }
+ on("Q") { _, info in
+ let reader = reader(info)
+ if reader.states.count > 1 { reader.states.removeLast() }
+ }
+ on("cm") { scanner, info in
+ let reader = reader(info)
+ let n = numbers(scanner, 6)
+ reader.state.transform = CGAffineTransform(
+ a: n[0], b: n[1], c: n[2], d: n[3], tx: n[4], ty: n[5]
+ ).concatenating(reader.state.transform)
+ }
+ on("m") { scanner, info in
+ let reader = reader(info)
+ let n = numbers(scanner, 2)
+ reader.path.move(to: reader.point(n[0], n[1]))
+ }
+ on("l") { scanner, info in
+ let reader = reader(info)
+ let n = numbers(scanner, 2)
+ reader.path.addLine(to: reader.point(n[0], n[1]))
+ }
+ on("c") { scanner, info in
+ let reader = reader(info)
+ let n = numbers(scanner, 6)
+ reader.path.addCurve(
+ to: reader.point(n[4], n[5]), control1: reader.point(n[0], n[1]),
+ control2: reader.point(n[2], n[3]))
+ }
+ on("v") { scanner, info in
+ let reader = reader(info)
+ let n = numbers(scanner, 4)
+ reader.path.addCurve(
+ to: reader.point(n[2], n[3]), control1: reader.path.currentPoint,
+ control2: reader.point(n[0], n[1]))
+ }
+ on("y") { scanner, info in
+ let reader = reader(info)
+ let n = numbers(scanner, 4)
+ let end = reader.point(n[2], n[3])
+ reader.path.addCurve(to: end, control1: reader.point(n[0], n[1]), control2: end)
+ }
+ on("h") { _, info in reader(info).path.closeSubpath() }
+ on("re") { scanner, info in
+ let reader = reader(info)
+ let n = numbers(scanner, 4)
+ reader.path.addLines(between: [
+ reader.point(n[0], n[1]), reader.point(n[0] + n[2], n[1]),
+ reader.point(n[0] + n[2], n[1] + n[3]), reader.point(n[0], n[1] + n[3]),
+ ])
+ reader.path.closeSubpath()
+ }
+ // Clips here only bound a form to its box, so the path they end is dropped.
+ on("n") { _, info in reader(info).path = CGMutablePath() }
+ on("f") { _, info in reader(info).fill(.winding) }
+ on("F") { _, info in reader(info).fill(.winding) }
+ on("f*") { _, info in reader(info).fill(.evenOdd) }
+ // A soft mask's gray is all that matters: black hides, white shows.
+ on("g") { scanner, info in reader(info).state.gray = numbers(scanner, 1)[0] }
+ // A gray colour space sets one component, an RGB one three.
+ on("sc") { scanner, info in
+ let reader = reader(info)
+ var n: [CGFloat] = []
+ var value: CGPDFReal = 0
+ while CGPDFScannerPopNumber(scanner, &value) { n.insert(value, at: 0) }
+ switch n.count {
+ case 1: reader.state.gray = n[0]
+ case 3: reader.state.gray = 0.2126 * n[0] + 0.7152 * n[1] + 0.0722 * n[2]
+ default: break
+ }
+ }
+ on("gs") { scanner, info in
+ let reader = reader(info)
+ guard let key = name(scanner) else { return }
+ let content = CGPDFScannerGetContentStream(scanner)
+ var dictionary: CGPDFDictionaryRef?
+ guard let object = CGPDFContentStreamGetResource(content, "ExtGState", key),
+ CGPDFObjectGetValue(object, .dictionary, &dictionary), let dictionary
+ else { return }
+ var opacity: CGPDFReal = 1
+ if CGPDFDictionaryGetNumber(dictionary, "ca", &opacity) { reader.state.opacity = opacity }
+ var mask: CGPDFDictionaryRef?
+ var group: CGPDFStreamRef?
+ if CGPDFDictionaryGetDictionary(dictionary, "SMask", &mask), let mask,
+ CGPDFDictionaryGetStream(mask, "G", &group), let group
+ {
+ // The mask is drawn over white, so what it fills in black is hidden.
+ let hidden = formOutlines(group, parent: content, transform: reader.state.transform)
+ .filter { $0.gray < 0.5 }
+ .reduce(CGMutablePath()) { union, outline in
+ union.addPath(outline.path)
+ return union
+ }
+ reader.state.knockout = hidden.normalized()
+ } else {
+ var none: UnsafePointer<CChar>?
+ if CGPDFDictionaryGetName(dictionary, "SMask", &none) { reader.state.knockout = nil }
+ }
+ }
+ on("Do") { scanner, info in
+ let reader = reader(info)
+ guard let key = name(scanner), let form = resourceStream(scanner, "XObject", key) else {
+ return
+ }
+ let content = CGPDFScannerGetContentStream(scanner)
+ for var outline in formOutlines(form, parent: content, transform: reader.state.transform) {
+ if let knockout = reader.state.knockout { outline.path = outline.path.subtracting(knockout) }
+ outline.opacity *= reader.state.opacity
+ reader.outlines.append(outline)
+ }
+ }
+ return table
+}()
+
+@available(macOS 14, *)
+private func scan(_ stream: CGPDFContentStreamRef, _ reader: Reader) {
+ let scanner = CGPDFScannerCreate(stream, operators, Unmanaged.passUnretained(reader).toOpaque())
+ CGPDFScannerScan(scanner)
+ CGPDFScannerRelease(scanner)
+}
+
+/// The fills of a one-page PDF, in its page's coordinates.
+@available(macOS 14, *)
+func outlines(ofPDF data: Data) -> [Outline] {
+ guard let provider = CGDataProvider(data: data as CFData),
+ let page = CGPDFDocument(provider)?.page(at: 1)
+ else { return [] }
+ let reader = Reader()
+ scan(CGPDFContentStreamCreateWithPage(page), reader)
+ return reader.outlines
+}
diff --git a/desktop/swift/sf-symbols/Sources/SFSymbols/Render.swift b/desktop/swift/sf-symbols/Sources/SFSymbols/Render.swift
new file mode 100644
index 000000000..a37c07dbc
--- /dev/null
+++ b/desktop/swift/sf-symbols/Sources/SFSymbols/Render.swift
@@ -0,0 +1,98 @@
+import AppKit
+import SwiftUI
+
+/// How a set of symbols is asked to be drawn.
+struct RenderRequest: Decodable {
+ var names: [String]
+ var size: Double
+ var weight: String
+ var scale: String
+ var rendering: String
+}
+
+struct IconPath: Encodable {
+ var d: String
+ var opacity: Double
+}
+
+/// A symbol fitted into the square of the size asked for, centred, as icons are.
+struct Icon: Encodable {
+ var paths: [IconPath]
+}
+
+private let weights: [String: Font.Weight] = [
+ "ultralight": .ultraLight, "thin": .thin, "light": .light, "regular": .regular,
+ "medium": .medium, "semibold": .semibold, "bold": .bold, "heavy": .heavy, "black": .black,
+]
+
+private let scales: [String: Image.Scale] = ["small": .small, "medium": .medium, "large": .large]
+
+private func number(_ value: CGFloat) -> String {
+ String(format: "%.3f", value).replacingOccurrences(
+ of: "\\.?0+$", with: "", options: .regularExpression)
+}
+
+/// SVG path data for `path` mapped through `transform`.
+private func pathData(_ path: CGPath, _ transform: CGAffineTransform) -> String {
+ var data = ""
+ func point(_ p: CGPoint) -> String {
+ let mapped = p.applying(transform)
+ return "\(number(mapped.x)) \(number(mapped.y))"
+ }
+ path.applyWithBlock { element in
+ let points = element.pointee.points
+ switch element.pointee.type {
+ case .moveToPoint: data += "M\(point(points[0]))"
+ case .addLineToPoint: data += "L\(point(points[0]))"
+ case .addQuadCurveToPoint: data += "Q\(point(points[0])) \(point(points[1]))"
+ case .addCurveToPoint: data += "C\(point(points[0])) \(point(points[1])) \(point(points[2]))"
+ case .closeSubpath: data += "Z"
+ @unknown default: break
+ }
+ }
+ return data
+}
+
+/// The symbol's drawing as a one-page PDF, and the box SwiftUI lays it out in.
+@MainActor
+private func pdf(_ name: String, _ request: RenderRequest) -> (Data, CGSize)? {
+ guard NSImage(systemSymbolName: name, accessibilityDescription: nil) != nil else { return nil }
+ let image = Image(systemName: name)
+ .font(.system(size: request.size, weight: weights[request.weight] ?? .regular))
+ .imageScale(scales[request.scale] ?? .medium)
+ .foregroundStyle(.black)
+ .symbolRenderingMode(request.rendering == "hierarchical" ? .hierarchical : .monochrome)
+ var result: (Data, CGSize)?
+ ImageRenderer(content: image).render { size, draw in
+ var box = CGRect(origin: .zero, size: size)
+ let data = NSMutableData()
+ guard let consumer = CGDataConsumer(data: data as CFMutableData),
+ let context = CGContext(consumer: consumer, mediaBox: &box, nil)
+ else { return }
+ context.beginPDFPage(nil)
+ draw(context)
+ context.endPDFPage()
+ context.closePDF()
+ result = (data as Data, size)
+ }
+ return result
+}
+
+/// A symbol as an icon, or nil when this Mac has no symbol by that name.
+@available(macOS 14, *)
+@MainActor
+func icon(_ name: String, _ request: RenderRequest) -> Icon? {
+ guard let (data, layout) = pdf(name, request) else { return nil }
+ let drawn = outlines(ofPDF: data)
+ // Badges reach past the box SwiftUI lays a symbol out in, so the icon holds both.
+ let bounds = drawn.reduce(CGRect(origin: .zero, size: layout)) {
+ $0.union($1.path.boundingBoxOfPath)
+ }
+ let scale = request.size / max(bounds.width, bounds.height)
+ // PDF pages run upward; icons run downward from their top left.
+ let transform = CGAffineTransform(translationX: -bounds.midX, y: -bounds.midY)
+ .concatenating(CGAffineTransform(scaleX: scale, y: -scale))
+ .concatenating(CGAffineTransform(translationX: request.size / 2, y: request.size / 2))
+ return Icon(
+ paths: drawn.map { IconPath(d: pathData($0.path, transform), opacity: $0.opacity) })
+}
diff --git a/packages/core/src/icons/index.ts b/packages/core/src/icons/index.ts
index 6cd7ca3ad..093555958 100644
--- a/packages/core/src/icons/index.ts
+++ b/packages/core/src/icons/index.ts
@@ -1,7 +1,7 @@
import { MATERIAL_SYMBOLS_PREFIXES } from './material-symbols/font'
import { createMaterialSymbolsProvider } from './material-symbols/provider'
import { createIconifyProvider, type IconProvider } from './provider'
-import { createIconSetsProvider } from './sets'
+import { createIconSetsProvider, type IconSetSource } from './sets'
export {
createIconifyProvider,
@@ -22,6 +22,11 @@ export type { IconCollection, IconData, IconOption, IconPath, IconSearchResult }
export { createMaterialSymbolsProvider } from './material-symbols/provider'
export { MATERIAL_SYMBOLS_PREFIXES } from './material-symbols/font'
export { createIconSetsProvider, type IconSetSource, type IconSetsOptions } from './sets'
+export {
+ createSFSymbolsProvider,
+ SF_SYMBOLS_PREFIX,
+ type SFSymbolsHost
+} from './sf-symbols/provider'
/** Iconify's icons, every set as Iconify serves it. */
export const iconify: IconProvider = createIconifyProvider()
@@ -31,14 +36,17 @@ const ICONIFY_MATERIAL_SYMBOLS = ['material-symbols', 'material-symbols-light']
/**
* Icons from Iconify, with Material Symbols drawn from Google's variable fonts at any of their
- * axes in place of Iconify's copies. `fetcher` reaches Google, as a host's web fonts do.
+ * axes in place of Iconify's copies. `fetcher` reaches Google, as a host's web fonts do; `sources`
+ * adds sets only some hosts draw, such as SF Symbols on a Mac.
*/
export function createIconProvider(
- fetcher: typeof globalThis.fetch = globalThis.fetch
+ fetcher: typeof globalThis.fetch = globalThis.fetch,
+ sources: readonly IconSetSource[] = []
): IconProvider {
return createIconSetsProvider({
sources: [
- { prefixes: MATERIAL_SYMBOLS_PREFIXES, provider: createMaterialSymbolsProvider(fetcher) }
+ { prefixes: MATERIAL_SYMBOLS_PREFIXES, provider: createMaterialSymbolsProvider(fetcher) },
+ ...sources
],
fallback: iconify,
replaced: ICONIFY_MATERIAL_SYMBOLS
diff --git a/packages/core/src/icons/render.ts b/packages/core/src/icons/render.ts
index 134adc1fa..b3192eb86 100644
--- a/packages/core/src/icons/render.ts
+++ b/packages/core/src/icons/render.ts
@@ -41,8 +41,8 @@ export interface PlaceIconOptions {
identity?: boolean
}
-function solid(color: Color) {
- return [{ type: 'SOLID' as const, color, opacity: 1, visible: true }]
+function solid(color: Color, opacity = 1) {
+ return [{ type: 'SOLID' as const, color, opacity, visible: true }]
}
/** One path of an icon as a vector filling the icon's box, marked where the icon's color paints. */
@@ -63,7 +63,7 @@ function addPath(graph: SceneGraph, frameId: string, path: IconPath, size: numbe
// Resizing the icon resizes its glyph, as the frame is the icon.
horizontalConstraint: 'SCALE',
verticalConstraint: 'SCALE',
- fills: path.fill ? solid(paint(path.fill, 'fill')) : []
+ fills: path.fill ? solid(paint(path.fill, 'fill'), path.fillOpacity) : []
})
if (path.stroke) {
const stroke = createPathStroke(
diff --git a/packages/core/src/icons/sf-symbols/provider.ts b/packages/core/src/icons/sf-symbols/provider.ts
new file mode 100644
index 000000000..45988ebbf
--- /dev/null
+++ b/packages/core/src/icons/sf-symbols/provider.ts
@@ -0,0 +1,223 @@
+import * as v from 'valibot'
+
+import type { IconOptions } from '@open-pencil/scene-graph/icons'
+import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
+
+import { parseIconName, type IconProvider } from '#core/icons/provider'
+import type {
+ IconCollection,
+ IconData,
+ IconOption,
+ IconPath,
+ IconSearchResult
+} from '#core/icons/types'
+
+export const SF_SYMBOLS_PREFIX = 'sf-symbols'
+
+/** How SF Symbols can be drawn, as SwiftUI draws them. */
+export const SF_SYMBOLS_OPTIONS = [
+ {
+ key: 'weight',
+ name: 'Weight',
+ values: [
+ 'ultralight',
+ 'thin',
+ 'light',
+ 'regular',
+ 'medium',
+ 'semibold',
+ 'bold',
+ 'heavy',
+ 'black'
+ ],
+ default: 'regular'
+ },
+ { key: 'scale', name: 'Scale', values: ['small', 'medium', 'large'], default: 'medium' },
+ {
+ key: 'rendering',
+ name: 'Rendering',
+ values: ['monochrome', 'hierarchical'],
+ default: 'monochrome'
+ }
+] as const satisfies readonly IconOption[]
+
+/** The size previews are drawn at, which their SVG scales. */
+const PREVIEW_SIZE = 24
+
+/**
+ * What draws SF Symbols: the Mac the app runs on, since Apple licenses them for its own platforms
+ * only. Both answer JSON, or null where the symbols cannot be drawn as outlines.
+ */
+export interface SFSymbolsHost {
+ catalogue(): Promise<string | null>
+ /** Draws `names` at a point size with the options set, in one request. */
+ render(request: string): Promise<string | null>
+}
+
+const catalogueSchema = v.pipe(
+ v.string(),
+ v.parseJson(),
+ v.object({
+ names: v.array(v.string()),
+ keywords: v.record(v.string(), v.array(v.string()))
+ })
+)
+
+const renderedSchema = v.pipe(
+ v.string(),
+ v.parseJson(),
+ v.record(
+ v.string(),
+ v.object({
+ paths: v.array(v.object({ d: v.string(), opacity: v.number() }))
+ })
+ )
+)
+
+type Catalogue = v.InferOutput<typeof catalogueSchema>
+/** The symbols drawn, by name; those the Mac lacks are left out. */
+type Rendered = Partial<v.InferOutput<typeof renderedSchema>>
+
+/** Every option set, each one a value the set offers, and defaulted where `options` leaves it out. */
+export function sfSymbolsOptions(options: IconOptions = {}): Record<string, string> {
+ return Object.fromEntries(
+ SF_SYMBOLS_OPTIONS.map(({ key, values, default: fallback }) => {
+ const value = options[key]
+ return [key, values.some((known) => known === value) ? String(value) : fallback]
+ })
+ )
+}
+
+function iconPath(d: string, opacity: number): IconPath {
+ return {
+ vectorNetwork: parseSVGPath(d, 'NONZERO'),
+ fill: 'currentColor',
+ fillOpacity: opacity,
+ stroke: null,
+ strokeWidth: 0,
+ strokeCap: 'butt',
+ strokeJoin: 'miter'
+ }
+}
+
+/** SF Symbols, drawn as outlines by `host` at the weight, scale, and rendering each icon sets. */
+export function createSFSymbolsProvider(host: SFSymbolsHost): IconProvider {
+ let catalogue: Promise<Catalogue | null> | null = null
+ const previewCache = new Map<string, string | null>()
+
+ function listed(): Promise<Catalogue | null> {
+ catalogue ??= host.catalogue().then((text) => {
+ if (text === null) return null
+ const parsed = v.safeParse(catalogueSchema, text)
+ return parsed.success ? parsed.output : null
+ })
+ // A failed catalogue is asked for again next time.
+ catalogue.catch(() => {
+ catalogue = null
+ })
+ return catalogue
+ }
+
+ async function render(
+ names: readonly string[],
+ size: number,
+ options: Record<string, string>
+ ): Promise<Rendered> {
+ const iconNames = names.flatMap((name) => {
+ const parsed = parseIconName(name)
+ return parsed?.prefix === SF_SYMBOLS_PREFIX ? [parsed.iconName] : []
+ })
+ if (iconNames.length === 0) return {}
+ const text = await host.render(JSON.stringify({ names: iconNames, size, ...options }))
+ if (text === null) return {}
+ const parsed = v.safeParse(renderedSchema, text)
+ return parsed.success ? parsed.output : {}
+ }
+
+ return {
+ async search(query, options = {}): Promise<IconSearchResult> {
+ const symbols = options.prefix && options.prefix !== SF_SYMBOLS_PREFIX ? null : await listed()
+ if (!symbols) return { icons: [], total: 0, collections: {} }
+ const term = query.trim().toLowerCase().replace(/\s+/g, '.')
+ const found = symbols.names.filter(
+ (name) =>
+ name.includes(term) || symbols.keywords[name]?.some((keyword) => keyword.includes(term))
+ )
+ const icons = found
+ .slice(0, options.limit ?? found.length)
+ .map((name) => `${SF_SYMBOLS_PREFIX}:${name}`)
+ return {
+ icons,
+ total: found.length,
+ collections: { [SF_SYMBOLS_PREFIX]: { name: 'SF Symbols', total: found.length } }
+ }
+ },
+
+ async collections(): Promise<IconCollection[]> {
+ const symbols = await listed()
+ if (!symbols) return []
+ return [
+ {
+ prefix: SF_SYMBOLS_PREFIX,
+ name: 'SF Symbols',
+ total: symbols.names.length,
+ category: 'Apple',
+ license: 'Apple',
+ multicolor: false,
+ options: SF_SYMBOLS_OPTIONS
+ }
+ ]
+ },
+
+ async browse(prefix) {
+ if (prefix !== SF_SYMBOLS_PREFIX) return []
+ return ((await listed())?.names ?? []).map((name) => `${SF_SYMBOLS_PREFIX}:${name}`)
+ },
+
+ async icons(names, size, options = {}) {
+ const set = sfSymbolsOptions(options)
+ const rendered = await render(names, size, set)
+ const found = new Map<string, IconData>()
+ for (const name of names) {
+ const parsed = parseIconName(name)
+ const icon = parsed?.prefix === SF_SYMBOLS_PREFIX ? rendered[parsed.iconName] : undefined
+ if (!parsed || !icon) continue
+ found.set(name, {
+ prefix: parsed.prefix,
+ name: parsed.iconName,
+ width: size,
+ height: size,
+ paths: icon.paths.map((path) => iconPath(path.d, path.opacity)),
+ options: set
+ })
+ }
+ return found
+ },
+
+ async previews(names) {
+ const missing = names.filter((name) => !previewCache.has(name))
+ const rendered = await render(missing, PREVIEW_SIZE, sfSymbolsOptions())
+ for (const name of missing) {
+ const parsed = parseIconName(name)
+ const icon = parsed?.prefix === SF_SYMBOLS_PREFIX ? rendered[parsed.iconName] : undefined
+ previewCache.set(
+ name,
+ icon
+ ? `<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 ${PREVIEW_SIZE} ${PREVIEW_SIZE}">${icon.paths
+ .map(
+ (path) =>
+ `<path fill="currentColor" fill-opacity="${path.opacity}" d="${path.d}"/>`
+ )
+ .join('')}</svg>`
+ : null
+ )
+ }
+ const found = new Map<string, string>()
+ for (const name of names) {
+ const preview = previewCache.get(name)
+ if (preview) found.set(name, preview)
+ }
+ return found
+ }
+ }
+}
diff --git a/packages/core/src/icons/types.ts b/packages/core/src/icons/types.ts
index 8d1da1a25..333771771 100644
--- a/packages/core/src/icons/types.ts
+++ b/packages/core/src/icons/types.ts
@@ -4,6 +4,8 @@ import type { IconOptions } from '@open-pencil/scene-graph/icons'
export interface IconPath {
vectorNetwork: VectorNetwork
fill: string | null
+ /** How opaque the fill is, as for a symbol's secondary layers; opaque when left out. */
+ fillOpacity?: number
stroke: string | null
strokeWidth: number
strokeCap: string
diff --git a/packages/core/tests/icons/sf-symbols/provider.test.ts b/packages/core/tests/icons/sf-symbols/provider.test.ts
new file mode 100644
index 000000000..7e39852dc
--- /dev/null
+++ b/packages/core/tests/icons/sf-symbols/provider.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, test } from 'bun:test'
+
+import * as v from 'valibot'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
+
+import { placeIcon, recolorIcon } from '#core/icons/render'
+import { createSFSymbolsProvider, type SFSymbolsHost } from '#core/icons/sf-symbols/provider'
+
+const CATALOGUE = JSON.stringify({
+ names: ['house', 'house.fill', 'cloud.sun.rain.fill'],
+ keywords: { 'house.fill': ['home', 'building'], 'cloud.sun.rain.fill': ['weather'] }
+})
+
+const requestSchema = v.pipe(
+ v.string(),
+ v.parseJson(),
+ v.looseObject({ names: v.array(v.string()) })
+)
+
+/** Two layers, as a hierarchical symbol draws them: one opaque, one half seen. */
+const DRAWN = {
+ paths: [
+ { d: 'M0 0L30 0L30 30Z', opacity: 1 },
+ { d: 'M0 0L0 30L30 30Z', opacity: 0.498 }
+ ]
+}
+
+/** A Mac that draws every symbol it lists, recording each request; or none, as elsewhere. */
+function setup(mac = true) {
+ const requests: Record<string, unknown>[] = []
+ const host: SFSymbolsHost = {
+ catalogue: async () => (mac ? CATALOGUE : null),
+ async render(request) {
+ if (!mac) return null
+ const parsed = v.parse(requestSchema, request)
+ requests.push(parsed)
+ return JSON.stringify(Object.fromEntries(parsed.names.map((name) => [name, DRAWN])))
+ }
+ }
+ return { provider: createSFSymbolsProvider(host), requests }
+}
+
+describe('SF Symbols', () => {
+ test('lists, browses, and searches the symbols the Mac draws, by name and keyword', async () => {
+ const { provider } = setup()
+ const [set] = await provider.collections()
+ expect(set).toMatchObject({ prefix: 'sf-symbols', name: 'SF Symbols', total: 3 })
+ expect(set?.options?.map((option) => option.key)).toEqual(['weight', 'scale', 'rendering'])
+ expect(await provider.browse('sf-symbols')).toHaveLength(3)
+ expect((await provider.search('home')).icons).toEqual(['sf-symbols:house.fill'])
+ expect((await provider.search('house fill')).icons).toEqual(['sf-symbols:house.fill'])
+ expect((await provider.search('house', { prefix: 'lucide' })).icons).toEqual([])
+ expect(await provider.search('house', { limit: 1 })).toMatchObject({
+ icons: ['sf-symbols:house'],
+ total: 2,
+ collections: { 'sf-symbols': { total: 2 } }
+ })
+ })
+
+ test('draws only its own set’s names, though another set has one alike', async () => {
+ const { provider } = setup()
+ const icons = await provider.icons(['sf-symbols:house', 'lucide:house'], 24)
+ expect([...icons.keys()]).toEqual(['sf-symbols:house'])
+ const previews = await provider.previews(['sf-symbols:house', 'lucide:house'])
+ expect(previews.get('lucide:house') ?? null).toBeNull()
+ expect(previews.get('sf-symbols:house')).toContain('<path')
+ })
+
+ test('offers nothing where the host cannot draw them', async () => {
+ const { provider } = setup(false)
+ expect(await provider.collections()).toEqual([])
+ expect((await provider.search('house')).icons).toEqual([])
+ expect((await provider.icons(['sf-symbols:house'], 24)).size).toBe(0)
+ })
+
+ test('draws icons in one request at the options set, defaults filling the rest', async () => {
+ const { provider, requests } = setup()
+ const icons = await provider.icons(['sf-symbols:house', 'sf-symbols:house.fill'], 24, {
+ weight: 'bold',
+ rendering: 'sideways'
+ })
+ expect(requests).toEqual([
+ {
+ names: ['house', 'house.fill'],
+ size: 24,
+ weight: 'bold',
+ scale: 'medium',
+ rendering: 'monochrome'
+ }
+ ])
+ const house = icons.get('sf-symbols:house')
+ expect(house?.options).toEqual({ weight: 'bold', scale: 'medium', rendering: 'monochrome' })
+ expect(house?.width).toBe(24)
+ expect(house?.paths.map((path) => path.fillOpacity)).toEqual([1, 0.498])
+ })
+
+ test('places each layer at its opacity, which recoloring keeps', async () => {
+ const { provider } = setup()
+ const icon = (await provider.icons(['sf-symbols:cloud.sun.rain.fill'], 24)).get(
+ 'sf-symbols:cloud.sun.rain.fill'
+ )
+ if (!icon) throw new Error('no icon')
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const frame = placeIcon(graph, page.id, icon, { size: 24, color: parseColor('#000000') })
+ recolorIcon(graph, frame.id, parseColor('#ff0000'))
+ expect(
+ graph.getChildren(frame.id).map((path) => [path.fills[0]?.opacity, path.fills[0]?.color.r])
+ ).toEqual([
+ [1, 1],
+ [0.498, 1]
+ ])
+ })
+
+ test('draws previews once', async () => {
+ const { provider, requests } = setup()
+ await provider.previews(['sf-symbols:house'])
+ const [preview] = (await provider.previews(['sf-symbols:house'])).values()
+ expect(requests).toHaveLength(1)
+ expect(preview).toContain('fill-opacity="0.498"')
+ })
+})
diff --git a/src/app/editor/icons/provider.ts b/src/app/editor/icons/provider.ts
index 3cbef67a9..5851da249 100644
--- a/src/app/editor/icons/provider.ts
+++ b/src/app/editor/icons/provider.ts
@@ -1,8 +1,28 @@
-import { createIconProvider } from '@open-pencil/core/icons'
+import {
+ createIconProvider,
+ createSFSymbolsProvider,
+ SF_SYMBOLS_PREFIX
+} from '@open-pencil/core/icons'
import { browserWebFontFetch } from '@/app/editor/fonts/browser-fetch'
import { tauriFetch } from '@/app/tauri/http'
import { IS_TAURI } from '@/constants'
-/** The app's icons: Iconify's, with Material Symbols drawn from Google's fonts, reached as the app's web fonts are. */
-export const appIcons = createIconProvider(IS_TAURI ? tauriFetch : browserWebFontFetch)
+async function invoke(command: string, args?: Record<string, unknown>): Promise<string | null> {
+ const { invoke } = await import('@tauri-apps/api/core')
+ return invoke<string | null>(command, args)
+}
+
+/** SF Symbols, drawn by the desktop app, which offers them only on a Mac that can draw them. */
+const sfSymbols = createSFSymbolsProvider({
+ catalogue: () => invoke('sf_symbols_catalogue'),
+ render: (request) => invoke('sf_symbols_render', { request })
+})
+
+/**
+ * The app's icons: Iconify's, with Material Symbols drawn from Google's fonts, reached as the app's
+ * web fonts are, and SF Symbols on the desktop.
+ */
+export const appIcons = IS_TAURI
+ ? createIconProvider(tauriFetch, [{ prefixes: [SF_SYMBOLS_PREFIX], provider: sfSymbols }])
+ : createIconProvider(browserWebFontFetch)