Skip to content

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

refactor(desktop): use swift-rs strings for SF Symbols and refuse unreadable drawings (#1500)

Danila Poyarkovb4330bd35152
diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock
index bc183c7c2..03140ea1c 100644
--- a/desktop/Cargo.lock
+++ b/desktop/Cargo.lock
@@ -4660,9 +4660,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "swift-rs"
-version = "1.0.8"
+version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e45c444e496845d3f2a351146bff59aae4975b2280238df1dfaa0c7d1846f38e"
+checksum = "cefd87076fd385308ee4aff597256c902f1fbb4d031de1558efc12f8ffefadd9"
dependencies = [
"base64 0.21.7",
"serde",
diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml
index 374d10b4f..a1fb1e1cf 100644
--- a/desktop/Cargo.toml
+++ b/desktop/Cargo.toml
@@ -23,7 +23,7 @@ crate-type = ["staticlib", "cdylib", "rlib"]
tauri-build = { version = "2", features = [] }
[target.'cfg(target_os = "macos")'.build-dependencies]
-swift-rs = { version = "1.0.8", features = ["build"] }
+swift-rs = { version = "=1.0.9", features = ["build"] }
[dependencies]
tauri = { version = "2", features = ["devtools"] }
@@ -53,6 +53,7 @@ tauri-plugin-wdio-webdriver = { version = "1.3.0", optional = true }
[target.'cfg(target_os = "macos")'.dependencies]
security-framework = "3"
+swift-rs = "=1.0.9"
objc2-core-foundation = { version = "0.3.2", default-features = false, features = ["std", "CFArray", "CFBase", "CFDictionary", "CFSet", "CFString", "CFURL"] }
objc2-core-text = { version = "0.3.2", default-features = false, features = ["std", "CTFontDescriptor"] }
diff --git a/desktop/src/icons/sf_symbols.rs b/desktop/src/icons/sf_symbols.rs
index ca0d829bb..b2e402870 100644
--- a/desktop/src/icons/sf_symbols.rs
+++ b/desktop/src/icons/sf_symbols.rs
@@ -1,34 +1,19 @@
//! 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.
+//! SwiftUI. Requests and answers are JSON in `SRString`s.
-use std::ffi::{c_char, CStr, CString};
+use swift_rs::{swift, SRString};
-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)
-}
+swift!(fn op_sf_symbols_catalogue() -> Option<SRString>);
+swift!(fn op_sf_symbols_render(request: &SRString) -> Option<SRString>);
pub fn catalogue() -> Option<String> {
// SAFETY: the catalogue takes no arguments and may run on any thread.
- take(unsafe { op_sf_symbols_catalogue() })
+ unsafe { op_sf_symbols_catalogue() }.map(|answer| answer.to_string())
}
/// 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()) })
+ let request = SRString::from(request);
+ // SAFETY: the request is a Swift string that outlives the call.
+ unsafe { op_sf_symbols_render(&request) }.map(|answer| answer.to_string())
}
diff --git a/desktop/swift/sf-symbols/Package.resolved b/desktop/swift/sf-symbols/Package.resolved
new file mode 100644
index 000000000..70b816d79
--- /dev/null
+++ b/desktop/swift/sf-symbols/Package.resolved
@@ -0,0 +1,14 @@
+{
+ "pins" : [
+ {
+ "identity" : "swift-rs",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/Brendonovich/swift-rs",
+ "state" : {
+ "revision" : "207e4bfe5d36fdd0cc08f28d1849ff94ac7e24b8",
+ "version" : "1.0.9"
+ }
+ }
+ ],
+ "version" : 2
+}
diff --git a/desktop/swift/sf-symbols/Package.swift b/desktop/swift/sf-symbols/Package.swift
index 03dffd99a..c28aabcb8 100644
--- a/desktop/swift/sf-symbols/Package.swift
+++ b/desktop/swift/sf-symbols/Package.swift
@@ -5,5 +5,9 @@ let package = Package(
name: "SFSymbols",
platforms: [.macOS(.v13)],
products: [.library(name: "SFSymbols", type: .static, targets: ["SFSymbols"])],
- targets: [.target(name: "SFSymbols")]
+ // The Swift half of the `swift-rs` crate, at the version `desktop/Cargo.toml` pins.
+ dependencies: [.package(url: "https://github.com/Brendonovich/swift-rs", exact: "1.0.9")],
+ targets: [
+ .target(name: "SFSymbols", dependencies: [.product(name: "SwiftRs", package: "swift-rs")])
+ ]
)
diff --git a/desktop/swift/sf-symbols/Sources/SFSymbols/Bridge.swift b/desktop/swift/sf-symbols/Sources/SFSymbols/Bridge.swift
index 66ab94716..406bc4f1a 100644
--- a/desktop/swift/sf-symbols/Sources/SFSymbols/Bridge.swift
+++ b/desktop/swift/sf-symbols/Sources/SFSymbols/Bridge.swift
@@ -1,42 +1,31 @@
import Foundation
+import SwiftRs
-/// 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`.
+/// The functions the desktop app calls. Requests and answers are JSON in `SRString`s.
-private func json<T: Encodable>(_ value: T?) -> String? {
+private func json<T: Encodable>(_ value: T?) -> SRString? {
guard let value, let data = try? JSONEncoder().encode(value) else { return nil }
- return String(decoding: data, as: UTF8.self)
+ return SRString(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.
+/// The symbols this Mac draws, or nil when it cannot draw them as outlines.
@_cdecl("op_sf_symbols_catalogue")
-public func opSFSymbolsCatalogue() -> UnsafeMutablePointer<CChar>? {
+public func opSFSymbolsCatalogue() -> SRString? {
guard #available(macOS 14, *) else { return nil }
- return answer(json(catalogue()))
+ return 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>? {
+public func opSFSymbolsRender(_ request: SRString) -> SRString? {
guard #available(macOS 14, *),
- let request = try? JSONDecoder().decode(
- RenderRequest.self, from: Data(String(cString: request).utf8))
+ let request = try? JSONDecoder().decode(RenderRequest.self, from: Data(request.toString().utf8))
else { return nil }
- let icons = MainActor.assumeIsolated {
+ return 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/Outlines.swift b/desktop/swift/sf-symbols/Sources/SFSymbols/Outlines.swift
index 441041ec6..a8e0f8ae3 100644
--- a/desktop/swift/sf-symbols/Sources/SFSymbols/Outlines.swift
+++ b/desktop/swift/sf-symbols/Sources/SFSymbols/Outlines.swift
@@ -18,12 +18,19 @@ private struct GraphicsState {
var knockout: CGPath?
}
+/// A drawing that paints with operators outlines cannot read, such as strokes or images.
+struct UnreadableDrawing: Error {
+ var operators: Set<String>
+}
+
/// 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] = []
+ /// The painting operators met that this reader does not read.
+ var unsupported: Set<String> = []
var state: GraphicsState {
get { states[states.count - 1] }
@@ -79,10 +86,12 @@ private func matrix(_ form: CGPDFStreamRef) -> 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.
+/// The fills of a form, drawn with `transform`, read with a reader of their own; what that reader
+/// cannot read is `reader`'s too.
@available(macOS 14, *)
private func formOutlines(
- _ form: CGPDFStreamRef, parent: CGPDFContentStreamRef, transform: CGAffineTransform
+ _ form: CGPDFStreamRef, parent: CGPDFContentStreamRef, transform: CGAffineTransform,
+ for reader: Reader
) -> [Outline] {
let nested = Reader()
nested.state.transform = matrix(form).concatenating(transform)
@@ -92,9 +101,19 @@ private func formOutlines(
// 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)
+ reader.unsupported.formUnion(nested.unsupported)
return nested.outlines
}
+/// Whether an XObject is a form, a content stream of its own, rather than an image.
+private func isForm(_ stream: CGPDFStreamRef) -> Bool {
+ var subtype: UnsafePointer<CChar>?
+ guard let dictionary = CGPDFStreamGetDictionary(stream),
+ CGPDFDictionaryGetName(dictionary, "Subtype", &subtype), let subtype
+ else { return false }
+ return String(cString: subtype) == "Form"
+}
+
/// The stream a resource names, such as a form XObject.
private func resourceStream(
_ scanner: CGPDFScannerRef, _ category: String, _ key: String
@@ -201,7 +220,9 @@ private let operators: CGPDFOperatorTableRef = {
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)
+ let hidden = formOutlines(
+ group, parent: content, transform: reader.state.transform, for: reader
+ )
.filter { $0.gray < 0.5 }
.reduce(CGMutablePath()) { union, outline in
union.addPath(outline.path)
@@ -218,13 +239,32 @@ private let operators: CGPDFOperatorTableRef = {
guard let key = name(scanner), let form = resourceStream(scanner, "XObject", key) else {
return
}
+ guard isForm(form) else {
+ reader.unsupported.insert("Do (image)")
+ return
+ }
let content = CGPDFScannerGetContentStream(scanner)
- for var outline in formOutlines(form, parent: content, transform: reader.state.transform) {
+ let drawn = formOutlines(form, parent: content, transform: reader.state.transform, for: reader)
+ for var outline in drawn {
if let knockout = reader.state.knockout { outline.path = outline.path.subtracting(knockout) }
outline.opacity *= reader.state.opacity
reader.outlines.append(outline)
}
}
+ // Painting the reader does not read. Clips are left out: the `re W n` that bounds a form to its
+ // box is all SwiftUI writes, and `n` ends it.
+ on("S") { _, info in reader(info).unsupported.insert("S") }
+ on("s") { _, info in reader(info).unsupported.insert("s") }
+ on("B") { _, info in reader(info).unsupported.insert("B") }
+ on("B*") { _, info in reader(info).unsupported.insert("B*") }
+ on("b") { _, info in reader(info).unsupported.insert("b") }
+ on("b*") { _, info in reader(info).unsupported.insert("b*") }
+ on("sh") { _, info in reader(info).unsupported.insert("sh") }
+ on("BI") { _, info in reader(info).unsupported.insert("BI") }
+ on("Tj") { _, info in reader(info).unsupported.insert("Tj") }
+ on("TJ") { _, info in reader(info).unsupported.insert("TJ") }
+ on("'") { _, info in reader(info).unsupported.insert("'") }
+ on("\"") { _, info in reader(info).unsupported.insert("\"") }
return table
}()
@@ -235,13 +275,15 @@ private func scan(_ stream: CGPDFContentStreamRef, _ reader: Reader) {
CGPDFScannerRelease(scanner)
}
-/// The fills of a one-page PDF, in its page's coordinates.
+/// The fills of a one-page PDF, in its page's coordinates. Throws when the page paints with
+/// operators this reader does not read, rather than leaving that painting out.
@available(macOS 14, *)
-func outlines(ofPDF data: Data) -> [Outline] {
+func outlines(ofPDF data: Data) throws -> [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)
+ guard reader.unsupported.isEmpty else { throw UnreadableDrawing(operators: reader.unsupported) }
return reader.outlines
}
diff --git a/desktop/swift/sf-symbols/Sources/SFSymbols/Render.swift b/desktop/swift/sf-symbols/Sources/SFSymbols/Render.swift
index a37c07dbc..07dbf099b 100644
--- a/desktop/swift/sf-symbols/Sources/SFSymbols/Render.swift
+++ b/desktop/swift/sf-symbols/Sources/SFSymbols/Render.swift
@@ -78,12 +78,23 @@ private func pdf(_ name: String, _ request: RenderRequest) -> (Data, CGSize)? {
return result
}
-/// A symbol as an icon, or nil when this Mac has no symbol by that name.
+/// A symbol as an icon, or nil when this Mac has no symbol by that name or draws it in a way its
+/// outlines cannot be read from, which is reported rather than drawn incomplete.
@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)
+ let drawn: [Outline]
+ do {
+ drawn = try outlines(ofPDF: data)
+ } catch let unreadable as UnreadableDrawing {
+ let operators = unreadable.operators.sorted().joined(separator: ", ")
+ FileHandle.standardError.write(
+ Data("SF Symbols: \(name) paints with \(operators), which outlines cannot read\n".utf8))
+ return nil
+ } catch {
+ return nil
+ }
// 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)