Skip to main content

tauri_plugin_widgets/
lib.rs

1//! # tauri-plugin-widgets
2//!
3//! A Tauri v2 plugin for building native widgets on Android, iOS, macOS,
4//! Windows, and Linux from a single JSON UI configuration.
5//!
6//! Empty placeholders for Adaptive Cards are avoided when the `rasterize`
7//! feature is enabled (chart/canvas/gauge/shape/zstack/gradients → PNG).
8//!
9//! ## Overview
10//!
11//! - **Widget Config API** — send a declarative [`WidgetConfig`](models::WidgetConfig)
12//!   describing layouts and elements. The native widget renders it using
13//!   SwiftUI (Apple), RemoteViews (Android), or HTML/CSS (desktop).
14//!
15//! - **Data API** — key-value storage shared with native widget extensions
16//!   via the App Group shared container (Apple), SharedPreferences (Android),
17//!   or JSON files (desktop).
18//!
19//! - **Desktop widget windows** — frameless, transparent Tauri webview windows
20//!   that render the same JSON config as HTML/CSS.
21//!
22//! ## Architecture
23//!
24//! The plugin acts as a **library**, not a builder. It does NOT compile or
25//! inject widget extensions at runtime. Instead, it provides:
26//!
27//! 1. **Rust side** — commands for data storage and WidgetKit reload
28//! 2. **Swift Package** (`swift/TauriWidgets`) — public SwiftUI views and
29//!    models that developers import into their own Widget Extension target
30//! 3. **Templates** (`templates/`) — ready-to-use scripts and Swift files
31//!
32//! This follows Apple's guidelines: the extension is built by Xcode, signed
33//! with the developer's certificate, and included in the app bundle at
34//! compile time.
35//!
36//! ## Quick Start (Rust)
37//!
38//! ```no_run
39//! tauri::Builder::default()
40//!     .plugin(tauri_plugin_widgets::init());
41//! ```
42//!
43//! ## iOS Setup
44//!
45//! 1. Open `gen/apple/*.xcodeproj` in Xcode
46//! 2. File → New → Target → Widget Extension
47//! 3. Add `swift/` as a Local Swift Package dependency
48//! 4. Add `TauriWidgets` library to the Widget Extension target
49//! 5. Enable **App Groups** in both targets (App + Widget Extension)
50//! 6. Use the template from `templates/ios-widget/MyWidget.swift`
51//!
52//! ## macOS Setup ("Satellite Project")
53//!
54//! Tauri for macOS does not generate an `.xcodeproj`, so the widget
55//! extension must be built as a separate Xcode project:
56//!
57//! 1. Create `src-tauri/widget-extension/` with an Xcode project
58//!    containing a Widget Extension target
59//! 2. Add `swift/` as a Local Swift Package dependency
60//! 3. Enable **App Groups** in both the main app entitlements and
61//!    the widget extension entitlements
62//! 4. `build-widget.sh` runs via `beforeBundleCommand` (builds + signs `.appex`)
63//! 5. `bundle.macOS.files` copies the `.appex` into `Contents/PlugIns/`
64//!    during a normal `tauri build` (Tauri nested-codesigns PlugIns)
65//! 6. Set `plugins.widgets.transport` (`appGroup` with Team ID, or
66//!    `widgetContainer` for ad-hoc) and `plugins.widgets.appGroup`
67//!
68//! ## Rust API
69//!
70//! Build a config with typed helpers (compile-checked, not executed here):
71//!
72//! ```
73//! use tauri_plugin_widgets::models::{text, vstack, WidgetConfig};
74//!
75//! let _cfg = WidgetConfig::small(vstack(vec![
76//!     text("72°").font_size(36.0).into(),
77//! ]));
78//! ```
79//!
80//! Then call [`WidgetExt::widget`] on an `AppHandle` to `set_widget_config` /
81//! `reload_all_timelines` (requires a running Tauri app).
82
83#![cfg_attr(docsrs, feature(doc_cfg))]
84#![warn(missing_docs)]
85
86#[cfg(mobile)]
87use tauri::RunEvent;
88use tauri::{
89    plugin::{Builder, TauriPlugin},
90    Manager, Runtime,
91};
92
93#[cfg(desktop)]
94use std::borrow::Cow;
95
96#[cfg(desktop)]
97#[allow(missing_docs)]
98#[cfg_attr(docsrs, doc(cfg(desktop)))]
99pub mod desktop;
100#[cfg(mobile)]
101#[allow(missing_docs)]
102#[cfg_attr(docsrs, doc(cfg(mobile)))]
103pub mod mobile;
104
105/// Adaptive Cards transpiler (Windows Widgets Board).
106#[allow(missing_docs)]
107pub mod adaptive_card;
108/// Outcomes for `set_widget_config` (written / reload / skip).
109pub mod apply;
110/// Element × platform capability matrix.
111#[allow(missing_docs)]
112pub mod capabilities;
113/// TypeScript IR emitter (`gen-ts`).
114#[allow(missing_docs)]
115pub mod codegen;
116mod commands;
117/// Plugin configuration (`plugins.widgets` in `tauri.conf.json`).
118pub mod config;
119/// Plugin error type.
120pub mod error;
121/// Host-side remote image prefetch for WidgetKit / desktop store writes.
122pub mod image_prefetch;
123/// SF Symbol → Material / emoji resolve for non-Apple hosts.
124pub mod icons;
125/// Widget IR models (`WidgetConfig`, `WidgetElement`, …).
126///
127/// Element structs and their fields carry rustdoc used by `schemars` / docs site.
128pub mod models;
129/// Host-side IR normalization (`textStyle` → points, semantic colors → adaptive hex).
130pub mod normalize;
131/// SVG / PNG helpers for Adaptive Cards fallbacks.
132#[allow(missing_docs)]
133pub mod rasterize;
134/// Render receipts written by native / desktop surfaces.
135pub mod receipt;
136/// Canonical layout dumps for snapshot tests.
137pub mod snapshot;
138/// Shared key-value store helpers and action envelopes.
139pub mod store;
140/// Host black-box journal (`WIDGET_DEBUG` / debug builds).
141pub mod trace;
142/// macOS / desktop config transport selection.
143pub mod transport;
144
145#[cfg(target_os = "windows")]
146#[allow(missing_docs)]
147#[cfg_attr(docsrs, doc(cfg(windows)))]
148pub mod windows;
149
150#[cfg(all(target_os = "linux", feature = "linux"))]
151#[allow(missing_docs)]
152#[cfg_attr(docsrs, doc(cfg(all(target_os = "linux", feature = "linux"))))]
153pub mod linux;
154
155#[cfg(target_os = "macos")]
156#[allow(missing_docs)]
157#[cfg_attr(docsrs, doc(cfg(macos)))]
158pub mod macos_transport;
159
160pub use adaptive_card::{to_adaptive_card, to_adaptive_card_for_size, TranspileResult};
161pub use apply::{ApplyOutcome, ReloadOutcome, SkipReason};
162pub use config::{TransportKind, WidgetsPluginConfig};
163pub use error::{Error, Result};
164pub use receipt::{SkippedElement, WidgetRenderReceipt};
165pub use store::WidgetActionEnvelope;
166pub use trace::{TraceEntry, TraceEvent, WidgetTrace};
167pub use transport::{Receipt, Transport};
168
169#[cfg(desktop)]
170pub use desktop::Widget;
171#[cfg(mobile)]
172pub use mobile::Widget;
173
174/// Extension trait for convenient access from any Tauri manager.
175pub trait WidgetExt<R: Runtime> {
176    /// Returns the managed [`Widget`] state.
177    fn widget(&self) -> &Widget<R>;
178}
179
180impl<R: Runtime, T: Manager<R>> WidgetExt<R> for T {
181    fn widget(&self) -> &Widget<R> {
182        self.state::<Widget<R>>().inner()
183    }
184}
185
186/// Initialize the widgets plugin. Register it with `tauri::Builder::plugin()`.
187pub fn init<R: Runtime>() -> TauriPlugin<R, Option<WidgetsPluginConfig>> {
188    let builder = Builder::<R, Option<WidgetsPluginConfig>>::new("widgets")
189        .invoke_handler(tauri::generate_handler![
190            commands::set_items,
191            commands::get_items,
192            commands::set_register_widget,
193            commands::reload_all_timelines,
194            commands::reload_timelines,
195            commands::request_widget,
196            commands::create_widget_window,
197            commands::close_widget_window,
198            commands::set_widget_config,
199            commands::get_widget_config,
200            commands::widget_action,
201            commands::poll_pending_actions,
202            commands::report_receipt,
203            commands::get_widget_diagnostics,
204            commands::get_widget_trace,
205            commands::flush_widget_trace,
206        ])
207        .setup(|app, api| {
208            #[cfg(mobile)]
209            let widget = mobile::init(app, api)?;
210            #[cfg(desktop)]
211            let widget = desktop::init(app, api)?;
212            app.manage(widget);
213            Ok(())
214        });
215
216    #[cfg(mobile)]
217    let builder = builder.on_event(|app, event| match event {
218        RunEvent::Ready | RunEvent::Resumed => {
219            if let Some(widget) = app.try_state::<Widget<R>>() {
220                widget.inner().drain_pending_actions_to_events();
221            }
222        }
223        _ => {}
224    });
225
226    #[cfg(desktop)]
227    let builder =
228        builder.register_uri_scheme_protocol(desktop::BUILTIN_PROTOCOL, |_app, _request| {
229            const HTML: &[u8] = include_bytes!("../widget.html");
230            tauri::http::Response::builder()
231                .header("content-type", "text/html; charset=utf-8")
232                .body(Cow::Borrowed(HTML))
233                .unwrap()
234        });
235
236    builder.build()
237}