Expand description
§visionkit-rs
Safe Rust bindings for Apple’s VisionKit.framework on macOS.
Status: wraps the macOS
ImageAnalyzer,ImageAnalysis, andImageAnalysisOverlayViewsurface; four rows are partial (seeCOVERAGE.md). The iOS-only areas are availability metadata only.
§Requirements
Build a macOS binary that uses this crate with a deployment target of macOS 13.0 or later. The
Swift bridge uses Swift concurrency. Rust builds binaries for macOS 11.0 on Apple silicon and for
macOS 10.12 on x86_64 by default. With these targets, the binary loads the Swift runtime
through @rpath and stops at launch with an error such as
Library not loaded: @rpath/libswift_Concurrency.dylib. Set MACOSX_DEPLOYMENT_TARGET=13.0 in
the environment, or set it for the project in .cargo/config.toml:
[env]
MACOSX_DEPLOYMENT_TARGET = "13.0"Cargo does not link the binary again when only this variable changes, so run cargo clean
after you set it.
§Installation
[dependencies]
visionkit-rs = "0.4"The library is imported as visionkit. Optional features:
async: executor-agnostic futures invisionkit::async_api.apple-cf: analyze in-memoryapple_cf::cg::CGImageandapple_cf::cv::CVPixelBuffervalues.
visionkit-rs = { version = "0.4", features = ["async", "apple-cf"] }§Quick start
use visionkit::prelude::*;
fn main() -> Result<(), Box<dyn std::error::Error>> {
if !ImageAnalyzer::is_supported() {
println!("ImageAnalyzer is not supported on this Mac");
return Ok(());
}
let analyzer = ImageAnalyzer::new()?;
let configuration = ImageAnalyzerConfiguration::new(ImageAnalysisTypes::TEXT)
.with_locales(["en-US"]);
let analysis = analyzer.analyze_image_at_path(
"examples/assets/live_text.png",
ImageOrientation::Up,
&configuration,
)?;
let interaction = LiveTextInteraction::new()?;
interaction.track_image_at_path("examples/assets/live_text.png")?;
interaction.set_analysis(&analysis)?;
println!("transcript: {}", analysis.transcript()?);
println!("live text overlay text: {}", interaction.text()?);
Ok(())
}§Async API (async feature)
Enable with visionkit-rs = { version = "0.4", features = ["async"] }.
use visionkit::async_api::{block_on, AsyncImageAnalyzer};
use visionkit::{ImageAnalysisTypes, ImageAnalyzerConfiguration, ImageOrientation};
fn main() -> Result<(), Box<dyn std::error::Error>> {
if !AsyncImageAnalyzer::is_supported() {
return Ok(());
}
let result = block_on(async {
let cfg = ImageAnalyzerConfiguration::new(ImageAnalysisTypes::TEXT);
AsyncImageAnalyzer::new()?
.analyze_image_at_path("examples/assets/live_text.png", ImageOrientation::Up, &cfg)?
.await
});
println!("transcript: {}", result?.transcript()?);
Ok(())
}Note: VisionKit completes image analysis through the main queue. On the main thread block_on pumps the Obj-C main run loop until the future is woken; on other threads it parks, and the futures only complete while the main thread runs its run loop (an AppKit app, or a CLI whose main thread calls CFRunLoopRun). The futures also work with any other executor (Tokio, async-std, …) under the same condition.
§Highlights
ImageAnalyzer::is_supportedandsupported_text_recognition_languagesImageAnalyzerConfiguration,ImageAnalysisTypes, andImageOrientation- File-path based analysis through every public macOS analyzer overload: URL,
NSImage,CGImage,CIImage, andCVPixelBuffer - In-memory
CGImageandCVPixelBufferanalysis (ImageAnalyzer::analyze_cg_image,analyze_pixel_buffer, and their async counterparts) with theapple-cffeature ImageAnalysis::transcriptandhas_resultsLiveTextInteractioncoverage for macOSImageAnalysisOverlayView, including delegates, menu tags, selection metadata, tracking/content views, fonts, and subject analysis. Delegate calls are answered from a configuration you set and recorded as events you poll; they do not call back into Rust.VNDocumentCameraViewController,DataScannerViewController,RecognizedText,Barcode, andRecognizedItemavailability metadata on macOS. These iOS-only APIs are not wrapped: their constructors always fail on macOS.
§Threading
- VisionKit finishes
ImageAnalyzerwork on the main queue, although its Swift API is not bound to the main actor. A synchronous analysis on the main thread pumps the main run loop while it waits. On any other thread it needs the main thread to run its run loop (an AppKit app, or a CLI whose main thread callsCFRunLoopRun). If the main queue is not serviced within 10 seconds, the call returnsVisionKitError::MainRunLoopNotRunning. Any analysis times out after 60 seconds withVisionKitError::TimedOut. #[tokio::main]and other executors that block the main thread starve VisionKit. Run the executor on another thread and keep the main thread in its run loop, or call the synchronous API from the main thread.LiveTextInteractionand its companion types wrap main-actor AppKit views and must be created on the main thread: their constructors returnVisionKitError::NotOnMainThreadelsewhere. The types are notSend, so they stay on the main thread, and every call runs inline there. Subject queries pump the main run loop while they wait and time out after 10 seconds.
§Availability
ImageAnalyzer,ImageAnalysis, andLiveTextInteractionare available on macOS 13+.LiveTextInteraction::text,selected_text,selected_attributed_text,selected_ranges, andLiveTextMenuTagrequire macOS 14+ because Apple introduced those overlay accessors after macOS 13.VNDocumentCameraViewController,DataScannerViewController,RecognizedText,Barcode, andRecognizedItemare iOS-only Apple APIs. On macOS, this crate exposes them as structured availability metadata instead of pretending they exist.
§Examples
cargo run --example 01_vn_document_camera_view_controller
cargo run --example 02_framework_smoke
cargo run --example 03_data_scanner_view_controller
cargo run --example 04_image_analyzer
cargo run --example 05_live_text_interaction
cargo run --example 06_image_analysis
cargo run --example 07_recognized_text
cargo run --example 08_barcode
cargo run --example 09_recognized_item
cargo run --features async --example 10_async_analyzeSee COVERAGE.md for the audited VisionKit API matrix.
§License
Licensed under either of Apache-2.0 or MIT at your option.
Re-exports§
pub use barcode::Barcode;pub use data_scanner_view_controller::DataScannerViewController;pub use error::VisionKitError;pub use image_analysis::ImageAnalysis;pub use image_analyzer::ImageAnalysisTypes;pub use image_analyzer::ImageAnalyzer;pub use image_analyzer::ImageAnalyzerConfiguration;pub use image_analyzer::ImageOrientation;pub use live_text_interaction::EdgeInsets;pub use live_text_interaction::LiveTextAttributedText;pub use live_text_interaction::LiveTextAttributedTextAttribute;pub use live_text_interaction::LiveTextAttributedTextRun;pub use live_text_interaction::LiveTextContentView;pub use live_text_interaction::LiveTextDelegateEvent;pub use live_text_interaction::LiveTextEventInfo;pub use live_text_interaction::LiveTextFont;pub use live_text_interaction::LiveTextImageData;pub use live_text_interaction::LiveTextInteraction;pub use live_text_interaction::LiveTextInteractionDelegate;pub use live_text_interaction::LiveTextInteractionTypes;pub use live_text_interaction::LiveTextMenu;pub use live_text_interaction::LiveTextMenuItem;pub use live_text_interaction::LiveTextMenuTag;pub use live_text_interaction::LiveTextSubject;pub use live_text_interaction::LiveTextTextRange;pub use live_text_interaction::LiveTextTrackingImageView;pub use live_text_interaction::Point;pub use live_text_interaction::Rect;pub use live_text_interaction::Size;pub use recognized_item::RecognizedItem;pub use recognized_text::RecognizedText;pub use support::AreaSupportInfo;pub use vn_document_camera_view_controller::VNDocumentCameraViewController;
Modules§
- analyzer
- Re-exports the core VisionKit analyzer types.
- async_
api async - Exposes executor-agnostic async VisionKit wrappers.
Async API for
VisionKit - barcode
- Availability metadata for the iOS-only barcode area.
- data_
scanner_ view_ controller - Availability metadata for the iOS-only data scanner.
- error
- Exposes error types returned by the VisionKit wrappers.
- ffi
- Exposes the raw VisionKit bridge layer.
- image_
analysis - Exposes the VisionKit image analysis wrapper.
- image_
analyzer - Exposes the VisionKit image analyzer wrapper and configuration types.
- live_
text_ interaction - Exposes VisionKit live text and overlay wrappers.
- prelude
- Re-exports the core VisionKit wrappers for convenient imports.
- recognized_
item - Availability metadata for the iOS-only recognized-item area.
- recognized_
text - Availability metadata for the iOS-only recognized-text area.
- support
- Exposes VisionKit availability metadata types.
- vn_
document_ camera_ view_ controller - Availability metadata for the iOS-only document camera.