Skip to main content

g3_native_plugins/
lib.rs

1//! Dioxus wrappers around native platform capabilities: clipboard and share
2//! sheets, Apple and Google sign-in, opening external URLs, system back
3//! handling, background media playback, local and push notifications,
4//! over-the-air bundle updates, and receiving the URL a deep link opened the
5//! app with - plus helpers for the deep-link metadata files iOS and Android
6//! expect a server to host.
7//!
8//! Every plugin sits behind a feature flag, so an app compiles in only what
9//! it uses. Platform coverage is not uniform; see the support matrix in the
10//! README. Where a plugin has no implementation for the current target it
11//! compiles to an inert no-op rather than failing to build, which keeps the
12//! same call sites working on web, desktop, and mobile.
13#![allow(non_snake_case)]
14#![warn(missing_docs)]
15#[cfg(all(
16    target_os = "android",
17    any(
18        feature = "auth",
19        feature = "camera-microphone",
20        feature = "clipboard",
21        feature = "deep-links",
22        feature = "external-url",
23        feature = "geolocation",
24        feature = "in-app-purchases",
25        feature = "notifications",
26        feature = "storage",
27        feature = "updater"
28    )
29))]
30mod android_bridge;
31/// Both halves of deep linking: builders for the `apple-app-site-association`
32/// and `assetlinks.json` files that make universal links and App Links resolve
33/// to the app, and — behind the `deep-links` feature — the plugin that receives
34/// the URL once one does.
35#[cfg_attr(all(feature = "deep-links", target_os = "ios"), allow(missing_docs))]
36pub mod deep_links;
37/// The permission states plugins here report, in one place so an app can treat
38/// a refusal the same way whatever was refused.
39pub mod permissions;
40#[cfg(all(
41    feature = "deep-links",
42    any(
43        target_arch = "wasm32",
44        target_os = "android",
45        target_os = "ios",
46        target_os = "macos"
47    )
48))]
49#[allow(unused_imports)]
50pub use deep_links::DeepLinks;
51#[allow(unused_imports)]
52pub use permissions::PermissionState;
53cfg_if::cfg_if! {
54    if #[cfg(feature = "clipboard")] { mod clipboard;
55    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
56    #[allow(unused_imports)] pub use clipboard::Clipboard; }
57}
58cfg_if::cfg_if! {
59    if #[cfg(feature = "auth")] { mod auth;
60    #[cfg(any(target_os = "android", target_os = "ios", target_os = "macos"))]
61    #[allow(unused_imports)] pub use auth::Auth; }
62}
63cfg_if::cfg_if! {
64    if #[cfg(feature = "back-button")] { mod back_button;
65    #[allow(unused_imports)] pub use back_button::NATIVE_BACK_EVENT;
66    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
67    #[allow(unused_imports)] pub use back_button::BackButton; }
68}
69cfg_if::cfg_if! {
70    if #[cfg(feature = "camera-microphone")] { mod camera_microphone;
71    #[allow(unused_imports)] pub use camera_microphone::CapturePermissions;
72    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
73    #[allow(unused_imports)] pub use camera_microphone::CameraMicrophone; }
74}
75cfg_if::cfg_if! {
76    if #[cfg(feature = "external-url")] { mod external_url;
77    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
78    #[allow(unused_imports)] pub use external_url::ExternalUrl; }
79}
80cfg_if::cfg_if! {
81    if #[cfg(feature = "geolocation")] { mod geolocation;
82    #[allow(unused_imports)] pub use geolocation::{Coordinates, LocationState, PermissionStatus, Position, PositionOptions};
83    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
84    #[allow(unused_imports)] pub use geolocation::Geolocation; }
85}
86cfg_if::cfg_if! {
87    if #[cfg(feature = "in-app-purchases")] { mod in_app_purchases;
88    #[allow(unused_imports)] pub use in_app_purchases::{Entitlement, ExternalContentLinkToken, Product, ProductKind, PurchaseState, SubscriptionOffer, SubscriptionPeriod};
89    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
90    #[allow(unused_imports)] pub use in_app_purchases::InAppPurchases; }
91}
92cfg_if::cfg_if! {
93    if #[cfg(feature = "media")] { mod media;
94    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
95    #[allow(unused_imports)] pub use media::Media;
96    }
97}
98cfg_if::cfg_if! {
99    if #[cfg(feature = "notifications")] { mod notifications;
100    #[allow(unused_imports)] pub use notifications::{Action, ActionType, Channel, DeliveredNotification, Importance, Notification, NotificationEvent, PendingNotification, Schedule, ScheduleInterval, Visibility, TAP_ACTION};
101    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
102    #[allow(unused_imports)] pub use notifications::Notifications; }
103}
104cfg_if::cfg_if! {
105    if #[cfg(feature = "push-notifications")] { mod push_notifications;
106    #[allow(unused_imports)] pub use push_notifications::{FirebaseOptions, PushEvent, PushService, PushToken};
107    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
108    #[allow(unused_imports)] pub use push_notifications::PushNotifications; }
109}
110cfg_if::cfg_if! {
111    if #[cfg(feature = "storage")] { mod storage;
112    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
113    #[allow(unused_imports)] pub use storage::KeyValueStore; }
114}
115cfg_if::cfg_if! {
116    if #[cfg(feature = "updater")] { mod updater;
117    #[allow(unused_imports)] pub use updater::{bundle_content_type, DownloadProgress, Update, UpdaterConfig, UpdaterState};
118    #[cfg(any(target_arch = "wasm32", target_os = "android", target_os = "ios", target_os = "macos"))]
119    #[allow(unused_imports)] pub use updater::Updater; }
120}
121use dioxus::prelude::*;
122#[cfg(all(
123    any(
124        feature = "auth",
125        feature = "back-button",
126        feature = "camera-microphone",
127        feature = "clipboard",
128        feature = "deep-links",
129        feature = "external-url",
130        feature = "geolocation",
131        feature = "in-app-purchases",
132        feature = "media",
133        feature = "notifications",
134        feature = "storage",
135        feature = "updater"
136    ),
137    any(
138        target_arch = "wasm32",
139        target_os = "android",
140        target_os = "ios",
141        target_os = "macos"
142    )
143))]
144#[allow(unused_imports)]
145use dioxus_signals::Signal;
146#[cfg(any(
147    target_arch = "wasm32",
148    target_os = "android",
149    target_os = "ios",
150    target_os = "macos"
151))]
152#[derive(Clone, Copy)]
153/// Reactive handles for every enabled native plugin.
154///
155/// Construct this directly with [`NativePlugins::new`] or install it in the
156/// Dioxus context with [`NativePluginsProvider`].
157pub struct NativePlugins {
158    #[cfg(all(
159        feature = "auth",
160        any(target_os = "android", target_os = "ios", target_os = "macos")
161    ))]
162    /// Native Apple or Google authentication, depending on the target.
163    pub auth: Signal<Auth>,
164    /// Available on every target: the non-Android builds are inert, so callers
165    /// need no cfg of their own.
166    #[cfg(feature = "back-button")]
167    pub back_button: Signal<BackButton>,
168    /// Available on every target: the web and macOS builds are inert, so
169    /// callers need no cfg of their own.
170    #[cfg(feature = "camera-microphone")]
171    pub camera_microphone: Signal<CameraMicrophone>,
172    #[cfg(feature = "clipboard")]
173    /// Clipboard copying and the platform share sheet.
174    pub clipboard: Signal<Clipboard>,
175    /// Available on every target: the web and macOS builds are inert, so
176    /// callers need no cfg of their own.
177    #[cfg(feature = "deep-links")]
178    pub deep_links: Signal<DeepLinks>,
179    #[cfg(all(
180        feature = "external-url",
181        any(
182            target_arch = "wasm32",
183            target_os = "android",
184            target_os = "ios",
185            target_os = "macos"
186        )
187    ))]
188    /// Opens a URL outside the app on supported targets.
189    pub external_url: Signal<ExternalUrl>,
190    /// Available on every target: the web and macOS builds are inert, so
191    /// callers need no cfg of their own.
192    #[cfg(feature = "geolocation")]
193    pub geolocation: Signal<Geolocation>,
194    /// Available on every target: the web and macOS builds are inert, so
195    /// callers need no cfg of their own.
196    #[cfg(feature = "in-app-purchases")]
197    pub in_app_purchases: Signal<InAppPurchases>,
198    #[cfg(feature = "media")]
199    /// Background media playback, orientation, and picture-in-picture support.
200    pub media: Signal<Media>,
201    /// Local notifications. Available on every target: the web and macOS
202    /// builds are inert, so callers need no cfg of their own.
203    #[cfg(feature = "notifications")]
204    pub notifications: Signal<Notifications>,
205    /// Remote push through APNs and FCM. Available on every target: the web
206    /// and macOS builds are inert, so callers need no cfg of their own.
207    #[cfg(feature = "push-notifications")]
208    pub push_notifications: Signal<PushNotifications>,
209    /// Available on every target, but unlike the others the macOS build reports
210    /// an error rather than doing nothing: a store that silently discards is
211    /// worse than one that says it cannot help.
212    #[cfg(feature = "storage")]
213    pub storage: Signal<KeyValueStore>,
214    /// Over-the-air bundle updates. Available on every target: the web and
215    /// macOS builds are inert, so callers need no cfg of their own.
216    #[cfg(feature = "updater")]
217    pub updater: Signal<Updater>,
218}
219#[cfg(any(
220    target_arch = "wasm32",
221    target_os = "android",
222    target_os = "ios",
223    target_os = "macos"
224))]
225impl NativePlugins {
226    /// Creates reactive handles for every plugin enabled for this target.
227    pub fn new() -> Self {
228        Self {
229            #[cfg(all(
230                feature = "auth",
231                any(target_os = "android", target_os = "ios", target_os = "macos")
232            ))]
233            auth: Signal::new(Auth::new()),
234            #[cfg(feature = "back-button")]
235            back_button: Signal::new(BackButton::new()),
236            #[cfg(feature = "camera-microphone")]
237            camera_microphone: Signal::new(CameraMicrophone::new()),
238            #[cfg(feature = "clipboard")]
239            clipboard: Signal::new(Clipboard::new()),
240            #[cfg(feature = "deep-links")]
241            deep_links: Signal::new(DeepLinks::new()),
242            #[cfg(all(
243                feature = "external-url",
244                any(
245                    target_arch = "wasm32",
246                    target_os = "android",
247                    target_os = "ios",
248                    target_os = "macos"
249                )
250            ))]
251            external_url: Signal::new(ExternalUrl::new()),
252            #[cfg(feature = "geolocation")]
253            geolocation: Signal::new(Geolocation::new()),
254            #[cfg(feature = "in-app-purchases")]
255            in_app_purchases: Signal::new(InAppPurchases::new()),
256            #[cfg(feature = "media")]
257            media: Signal::new(Media::new()),
258            #[cfg(feature = "notifications")]
259            notifications: Signal::new(Notifications::new()),
260            #[cfg(feature = "push-notifications")]
261            push_notifications: Signal::new(PushNotifications::new()),
262            #[cfg(feature = "storage")]
263            storage: Signal::new(KeyValueStore::new()),
264            #[cfg(feature = "updater")]
265            updater: Signal::new(Updater::new()),
266        }
267    }
268}
269#[cfg(any(
270    target_arch = "wasm32",
271    target_os = "android",
272    target_os = "ios",
273    target_os = "macos"
274))]
275impl Default for NativePlugins {
276    fn default() -> Self {
277        Self::new()
278    }
279}
280#[component]
281pub fn NativePluginsProvider(children: Element) -> Element {
282    #[cfg(any(
283        target_arch = "wasm32",
284        target_os = "android",
285        target_os = "ios",
286        target_os = "macos"
287    ))]
288    use_context_provider(NativePlugins::default);
289    rsx! {
290        {children}
291    }
292}
293#[cfg(test)]
294mod tests {
295    fn production_source(source: &str) -> &str {
296        source
297            .split("#[cfg(test)]")
298            .next()
299            .expect("source should split before tests")
300    }
301    #[test]
302    fn back_button_interception_is_opt_in() {
303        let source = production_source(include_str!("back_button.rs"));
304        assert!(source.contains("intercepting: false"));
305        assert!(source.contains("pub fn set_intercepting"));
306        let kotlin = include_str!(
307            "android/back_button/src/main/kotlin/dev/dioxus/g3_native_plugins/back_button/BackButtonPlugin.kt",
308        );
309        assert!(kotlin.contains("g3nativeback"));
310        assert!(kotlin.contains("cancelable: true"));
311        assert!(kotlin.contains("evaluateJavascript(BACK_EVENT_SCRIPT"));
312        assert!(kotlin.contains("OnBackPressedCallback(false)"));
313        assert!(kotlin.contains("fun fallThroughFromRust()"));
314        assert!(kotlin.contains("current?.isEnabled = false"));
315        assert!(source.contains("pub fn fall_through"));
316        assert!(source.contains("pub const NATIVE_BACK_EVENT"));
317    }
318    #[test]
319    fn ios_back_button_raises_the_same_event_from_an_edge_swipe() {
320        let source = production_source(include_str!("back_button.rs"));
321        let swift = include_str!("ios/Sources/BackButtonPlugin.swift");
322        assert!(source.contains("#[manganis::ffi(\"src/ios\")]"));
323        assert!(source.contains(
324            "pub fn setInterceptingFromRust(this: &BackButtonPlugin, intercepting: bool);",
325        ),);
326        assert!(source.contains("pub fn fallThroughFromRust(this: &BackButtonPlugin);"));
327        assert!(swift.contains("UIScreenEdgePanGestureRecognizer"));
328        assert!(swift.contains("created.edges = .left"));
329        // The same event contract as Android, so one web listener serves both.
330        assert!(swift.contains("g3nativeback"));
331        assert!(swift.contains("cancelable: true"));
332        assert!(swift.contains("webView.allowsBackForwardNavigationGestures = false"));
333        assert!(swift.contains("panGestureRecognizer.require(toFail: created)"));
334        assert!(swift.contains("created.isEnabled = false"));
335    }
336    #[test]
337    fn deep_links_are_collected_from_both_launch_paths() {
338        let source = production_source(include_str!("deep_links.rs"));
339        let kotlin = include_str!(
340            "android/deep_links/src/main/kotlin/dev/dioxus/g3_native_plugins/deep_links/DeepLinksPlugin.kt",
341        );
342        let swift = include_str!("ios/Sources/DeepLinksPlugin.swift");
343        assert!(
344            source.contains("pub fn takeLinkFromRust(this: &DeepLinksPlugin) -> Option<String>;"),
345        );
346        assert!(source.contains("pub fn take_link(&mut self) -> Result<Option<String>, String>"),);
347        // Public so an app can prepare ahead of the provider, which is what
348        // makes an iOS cold-start link catchable at all.
349        assert!(source.contains("pub fn new() -> Self"));
350        // Android: cold start from the launch Intent, read once; warm links
351        // through the listener, since onNewIntent cannot be overridden here.
352        assert!(kotlin.contains("Intent.ACTION_VIEW"));
353        assert!(kotlin.contains("enqueue(activity.intent)"));
354        assert!(kotlin.contains("launchIntentConsumed = true"));
355        assert!(kotlin.contains("addOnNewIntentListener"));
356        // Static, so a link is not stranded on a discarded plugin instance.
357        assert!(kotlin.contains("companion object"));
358        // iOS: cold start from the launch options, warm links from delegate
359        // methods added to the host's delegate class at runtime.
360        assert!(swift.contains("didFinishLaunchingNotification"));
361        assert!(swift.contains("LaunchOptionsKey.userActivityDictionary"));
362        assert!(swift.contains("class_addMethod"));
363        assert!(swift.contains("application(_:continue:restorationHandler:)"));
364        assert!(swift.contains("application(_:open:options:)"));
365        // A cold-start link is reported through both paths; only one survives.
366        assert!(swift.contains("duplicateWindow"));
367    }
368    #[test]
369    fn android_plugins_resolve_classes_through_the_app_loader() {
370        // Learned the hard way on a device: JNI's FindClass resolves against
371        // the calling thread's loader, and a thread attached from native code
372        // gets the system loader, which has never heard of the app's classes.
373        // The macro's generated bindings use FindClass, so every Android call
374        // here goes through the bridge instead, which asks the Activity.
375        let bridge = include_str!("android_bridge.rs");
376        assert!(bridge.contains("getClassLoader"));
377        assert!(bridge.contains("loadClass"));
378        for source in [
379            include_str!("auth.rs"),
380            include_str!("camera_microphone.rs"),
381            include_str!("clipboard.rs"),
382            include_str!("deep_links.rs"),
383            include_str!("external_url.rs"),
384            include_str!("geolocation.rs"),
385            include_str!("in_app_purchases.rs"),
386            include_str!("notifications.rs"),
387            include_str!("push_notifications.rs"),
388            include_str!("storage.rs"),
389            include_str!("updater.rs"),
390        ] {
391            let production = production_source(source);
392            let android = production
393                .split("unsafe extern \"Kotlin\" {")
394                .nth(1)
395                .expect("each plugin declares a Kotlin block")
396                .split('}')
397                .next()
398                .expect("the Kotlin block should be closed");
399            // Only the type, so `dx` still builds the module. A function
400            // declared here would generate a FindClass binding and crash the
401            // moment a Dioxus effect called it.
402            assert!(
403                !android.contains("pub fn "),
404                "a Kotlin block still declares functions: {android}",
405            );
406            assert!(production.contains("crate::android_bridge::AndroidPlugin"));
407        }
408    }
409    #[test]
410    fn storage_encrypts_values_and_refuses_to_pretend_on_macos() {
411        let source = production_source(include_str!("storage.rs"));
412        let kotlin = include_str!(
413            "android/storage/src/main/kotlin/dev/dioxus/g3_native_plugins/storage/StoragePlugin.kt",
414        );
415        let swift = include_str!("ios/Sources/StoragePlugin.swift");
416        let gradle = include_str!("android/storage/build.gradle.kts");
417        assert!(source.contains("pub fn get(&mut self, key: &str)"));
418        assert!(source.contains("pub fn set(&mut self, key: &str, value: &str)"));
419        assert!(source.contains("pub fn keys(&mut self)"));
420        // Public so an app can read configuration before `dioxus::launch`.
421        assert!(source.contains("pub fn new() -> Self"));
422        // A store that silently discards is worse than one that says it cannot
423        // help, so this plugin alone does not compile to an inert no-op.
424        assert!(source.contains("Secure storage is not implemented on macOS"));
425        // Android: Keystore-held AES-GCM, and no Tink dependency behind an
426        // unmaintained library to get it.
427        assert!(kotlin.contains("AndroidKeyStore"));
428        assert!(kotlin.contains("AES/GCM/NoPadding"));
429        // No dependency at all, so nothing to argue about. The comment in that
430        // file names security-crypto to explain why, hence matching on the
431        // declaration form rather than the word.
432        assert!(!gradle.contains("implementation("));
433        // The cipher picks the nonce: a reused GCM nonce leaks the plaintext.
434        assert!(kotlin.contains("val nonce = cipher.iv"));
435        // kotlin.error() throws, so a helper of that name would be a live trap.
436        assert!(!kotlin.contains(" error("));
437        assert!(kotlin.contains("errorJson("));
438        // iOS: keychain, readable in the background after one unlock.
439        assert!(swift.contains("kSecClassGenericPassword"));
440        assert!(swift.contains("kSecAttrAccessibleAfterFirstUnlock"));
441        // The keychain has no upsert; update first, then add.
442        assert!(swift.contains("SecItemUpdate"));
443        assert!(swift.contains("SecItemAdd"));
444        assert!(swift.contains("errSecItemNotFound"));
445    }
446    #[test]
447    fn camera_microphone_leaves_the_webview_permission_bridge_to_wry() {
448        let source = production_source(include_str!("camera_microphone.rs"));
449        let kotlin = include_str!(
450            "android/camera_microphone/src/main/kotlin/dev/dioxus/g3_native_plugins/camera_microphone/CameraMicrophonePlugin.kt",
451        );
452        let swift = include_str!("ios/Sources/CameraMicrophonePlugin.swift");
453        assert!(source.contains("pub fn check_permissions"));
454        assert!(source.contains("pub fn open_settings"));
455        assert!(source.contains("pub struct CapturePermissions"));
456        // wry already answers the WebView's own permission callbacks. Taking
457        // either delegate over would break its file chooser and JS dialogs, so
458        // neither native side may install one. The prose above each plugin says
459        // as much, so these look for the code, not the words.
460        assert!(!kotlin.contains("setWebChromeClient"));
461        assert!(!kotlin.contains("override fun onPermissionRequest"));
462        assert!(!swift.contains("uiDelegate ="));
463        assert!(!swift.contains("func webView("));
464        // What is left is the part the page cannot reach.
465        assert!(kotlin.contains("ACTION_APPLICATION_DETAILS_SETTINGS"));
466        assert!(kotlin.contains("shouldShowRequestPermissionRationale"));
467        assert!(swift.contains("openSettingsURLString"));
468        assert!(swift.contains("AVCaptureDevice.authorizationStatus"));
469        assert!(swift.contains("AVCaptureDevice.requestAccess"));
470        // A .playback session has no input, so a shared session needs moving.
471        assert!(swift.contains("playAndRecord"));
472        assert!(swift.contains("defaultToSpeaker"));
473    }
474    #[test]
475    fn permission_state_is_shared_rather_than_duplicated_per_plugin() {
476        // Both plugins glob-export at the crate root, so a second definition
477        // would collide there rather than merely repeating itself.
478        let permissions = include_str!("permissions.rs");
479        let geolocation = production_source(include_str!("geolocation.rs"));
480        let capture = production_source(include_str!("camera_microphone.rs"));
481        assert!(permissions.contains("pub enum PermissionState"));
482        assert!(!geolocation.contains("pub enum PermissionState"));
483        assert!(!capture.contains("pub enum PermissionState"));
484        assert!(geolocation.contains("use crate::permissions::PermissionState;"));
485        assert!(capture.contains("use crate::permissions::PermissionState;"));
486    }
487    #[test]
488    fn geolocation_starts_and_polls_rather_than_blocking() {
489        let source = production_source(include_str!("geolocation.rs"));
490        let kotlin = include_str!(
491            "android/geolocation/src/main/kotlin/dev/dioxus/g3_native_plugins/geolocation/GeolocationPlugin.kt",
492        );
493        let swift = include_str!("ios/Sources/GeolocationPlugin.swift");
494        let gradle = include_str!("android/geolocation/build.gradle.kts");
495        assert!(source.contains("pub fn start_position_request"));
496        assert!(
497            source.contains("pub fn poll_position(&mut self) -> Result<Option<Position>, String>"),
498        );
499        assert!(source.contains("pub fn check_permissions"));
500        assert!(source.contains("pub struct Position"));
501        assert!(source.contains("pub struct Coordinates"));
502        // The reference example blocks the caller on both platforms; this one
503        // must not, because the call arrives on a Dioxus effect thread.
504        assert!(!kotlin.contains("CountDownLatch"));
505        assert!(!swift.contains("DispatchSemaphore"));
506        assert!(!swift.contains("RunLoop.current.run"));
507        // A library does not get to force Play Services on its consumers, so
508        // no dependency may name the coordinate the fused provider ships under.
509        assert!(!gradle.contains("com.google.android.gms"));
510        assert!(!kotlin.contains("com.google.android.gms"));
511        assert!(kotlin.contains("LocationManager"));
512        assert!(kotlin.contains("requestLocationUpdates"));
513        assert!(kotlin.contains("prompt-with-rationale"));
514        assert!(swift.contains("CLLocationManagerDelegate"));
515        assert!(swift.contains("manager.requestLocation()"));
516        assert!(swift.contains("locationManagerDidChangeAuthorization"));
517        // Negative CoreLocation accuracies mean invalid, not precise.
518        assert!(swift.contains("location.verticalAccuracy >= 0"));
519    }
520    #[test]
521    fn in_app_purchases_start_and_poll_on_both_stores() {
522        let source = production_source(include_str!("in_app_purchases.rs"));
523        let kotlin = include_str!(
524            "android/in_app_purchases/src/main/kotlin/dev/dioxus/g3_native_plugins/in_app_purchases/InAppPurchasesPlugin.kt",
525        );
526        let catalogue = include_str!(
527            "android/in_app_purchases/src/main/kotlin/dev/dioxus/g3_native_plugins/in_app_purchases/Catalogue.kt",
528        );
529        let swift = include_str!("ios/Sources/InAppPurchasesPlugin.swift");
530        let store = include_str!("ios/Sources/StoreCatalogue.swift");
531        let gradle = include_str!("android/in_app_purchases/build.gradle.kts");
532        assert!(source.contains("pub fn start_purchase"));
533        assert!(source.contains("pub fn poll_entitlements"));
534        assert!(source.contains("pub fn start_external_content_link_token"));
535        assert!(source.contains("pub fn launch_external_content_link"));
536        assert!(
537            production_source(include_str!("lib.rs"))
538                .contains("pub use in_app_purchases::{Entitlement, ExternalContentLinkToken")
539        );
540        assert!(source.contains("pub fn finish(&mut self, transaction_id: &str, consume: bool)"),);
541        assert!(source.contains("Subscription"));
542        assert!(source.contains("pub struct SubscriptionOffer"));
543        assert!(source.contains("pub will_auto_renew: bool"));
544        // Play billing has no substitute, so it is a real dependency rather
545        // than compileOnly like the androidx ones elsewhere.
546        assert!(gradle.contains("com.android.billingclient:billing:8.2.1"));
547        assert!(gradle.contains("implementation("));
548        assert!(kotlin.contains("BillingProgram.EXTERNAL_CONTENT_LINK"));
549        assert!(kotlin.contains("createBillingProgramReportingDetailsAsync"));
550        assert!(kotlin.contains("launchExternalLink"));
551        // A purchase left unacknowledged for three days is refunded by Play.
552        assert!(kotlin.contains("acknowledgePurchase"));
553        assert!(kotlin.contains("consumeAsync"));
554        assert!(kotlin.contains("needsFinishing"));
555        // Subscriptions cannot be bought without naming an offer token.
556        assert!(kotlin.contains("setOfferToken"));
557        assert!(kotlin.contains("queryPurchasesAsync"));
558        assert!(catalogue.contains("subscriptionOfferDetails"));
559        // StoreKit 2 is async Swift, which cannot cross the FFI boundary.
560        assert!(swift.contains("Transaction.updates"));
561        assert!(swift.contains("Transaction.currentEntitlements"));
562        assert!(swift.contains("Transaction.unfinished"));
563        assert!(swift.contains("AppStore.sync()"));
564        assert!(swift.contains("jwsRepresentation"));
565        assert!(swift.contains("renewal.willAutoRenew"));
566        assert!(store.contains("nonRenewable"));
567    }
568    #[test]
569    fn ios_media_plugin_owns_background_audio_and_lock_screen_controls() {
570        let source = production_source(include_str!("media.rs"));
571        let swift = include_str!("ios/Sources/MediaPlugin.swift");
572        assert!(source.contains("#[manganis::ffi(\"src/ios\")]"));
573        assert!(source.contains(
574            "pub fn setPlaybackActiveFromRust(this: &MediaPlugin, playbackJson: String);",
575        ),);
576        assert!(swift.contains("AVAudioSession.sharedInstance().setCategory(.playback"));
577        assert!(swift.contains("MPNowPlayingInfoCenter"));
578        assert!(swift.contains("MPRemoteCommandCenter.shared()"));
579        assert!(swift.contains("beginReceivingRemoteControlEvents"));
580        assert!(swift.contains("notifyOthersOnDeactivation"));
581        assert!(swift.contains("webkitSetPresentationMode"));
582        assert!(swift.contains("requestGeometryUpdate"));
583        // Same duplicate-event guard as Android, for the same audible reason.
584        assert!(swift.contains("if !wasActive || titleChanged"));
585        assert!(swift.contains("__tawnyPlaybackIntent"));
586    }
587    #[test]
588    fn native_plugins_provider_owns_plugin_construction() {
589        let source = production_source(include_str!("lib.rs"));
590        let provider_start = source
591            .find("pub fn NativePluginsProvider(children: Element) -> Element")
592            .expect("provider component should be exported");
593        let provider_prefix = &source[..provider_start];
594        assert!(source.contains("pub struct NativePlugins"));
595        assert!(source.contains("pub fn NativePluginsProvider(children: Element) -> Element"),);
596        assert!(
597            !provider_prefix
598                .trim_end()
599                .ends_with("target_os = \"macos\"\n))]\n#[component]"),
600        );
601        assert!(source.contains("use_context_provider(NativePlugins::default)"));
602        assert!(source.contains("{children}"));
603        assert!(source.contains("pub auth: Signal<Auth>"));
604        assert!(source.contains("pub camera_microphone: Signal<CameraMicrophone>"));
605        assert!(source.contains("pub clipboard: Signal<Clipboard>"));
606        assert!(source.contains("pub deep_links: Signal<DeepLinks>"));
607        assert!(source.contains("pub external_url: Signal<ExternalUrl>"));
608        assert!(source.contains("pub geolocation: Signal<Geolocation>"));
609        assert!(source.contains("pub in_app_purchases: Signal<InAppPurchases>"));
610        assert!(source.contains("pub media: Signal<Media>"));
611        assert!(source.contains("pub storage: Signal<KeyValueStore>"));
612        assert!(source.contains("auth: Signal::new(Auth::new())"));
613        assert!(source.contains("camera_microphone: Signal::new(CameraMicrophone::new())"));
614        assert!(source.contains("clipboard: Signal::new(Clipboard::new())"));
615        assert!(source.contains("deep_links: Signal::new(DeepLinks::new())"));
616        assert!(source.contains("external_url: Signal::new(ExternalUrl::new())"));
617        assert!(source.contains("geolocation: Signal::new(Geolocation::new())"));
618        assert!(source.contains("in_app_purchases: Signal::new(InAppPurchases::new())"));
619        assert!(source.contains("media: Signal::new(Media::new())"));
620        assert!(source.contains("storage: Signal::new(KeyValueStore::new())"));
621        assert!(source.contains("pub notifications: Signal<Notifications>"));
622        assert!(source.contains("pub push_notifications: Signal<PushNotifications>"));
623        assert!(source.contains("pub updater: Signal<Updater>"));
624        assert!(source.contains("notifications: Signal::new(Notifications::new())"));
625        assert!(source.contains("push_notifications: Signal::new(PushNotifications::new())"));
626        assert!(source.contains("updater: Signal::new(Updater::new())"));
627        assert!(source.contains("impl Default for NativePlugins"));
628        assert!(source.contains("Self::new()"));
629    }
630    #[test]
631    fn ios_clipboard_plugin_supports_copy_and_scene_safe_share() {
632        let swift = include_str!("ios/Sources/ClipboardPlugin.swift");
633        let rust = include_str!("clipboard.rs");
634        assert!(rust.contains("pub fn copy_to_clipboard(&mut self, text: String)"));
635        assert!(rust.contains(
636            "pub fn copyToClipboardFromRust(this: &ClipboardPlugin, text: String) -> String;",
637        ),);
638        assert!(swift.contains("public func copyToClipboardFromRust(_ text: String) -> String",),);
639        assert!(swift.contains("UIPasteboard.general.string = text"));
640        assert!(swift.contains("NSLog(\"[ClipboardPlugin]"));
641        assert!(swift.contains("connectedScenes"));
642        assert!(swift.contains("popover.sourceView = vc.view"));
643        assert!(!swift.contains("keyWindow"));
644    }
645    #[test]
646    fn ios_plugins_share_one_swift_package_for_current_dx() {
647        let manifest = include_str!("ios/Package.swift");
648        let auth = include_str!("auth.rs");
649        let swift_auth = include_str!("ios/Sources/AuthPlugin.swift");
650        let clipboard = include_str!("clipboard.rs");
651        let external_url = include_str!("external_url.rs");
652        assert!(manifest.contains("name: \"DioxusNativePlugins\""));
653        assert!(manifest.contains(".library(name: \"AuthPlugin\""));
654        assert!(manifest.contains(".library(name: \"BackButtonPlugin\""));
655        assert!(manifest.contains(".library(name: \"CameraMicrophonePlugin\""));
656        assert!(manifest.contains(".library(name: \"ClipboardPlugin\""));
657        assert!(manifest.contains(".library(name: \"DeepLinksPlugin\""));
658        assert!(manifest.contains(".library(name: \"ExternalUrlPlugin\""));
659        assert!(manifest.contains(".library(name: \"GeolocationPlugin\""));
660        assert!(manifest.contains(".library(name: \"InAppPurchasesPlugin\""));
661        assert!(manifest.contains(".linkedFramework(\"StoreKit\")"));
662        assert!(manifest.contains(".linkedFramework(\"CoreLocation\")"));
663        assert!(manifest.contains(".library(name: \"MediaPlugin\""));
664        assert!(manifest.contains(".library(name: \"StoragePlugin\""));
665        assert!(manifest.contains(".library(name: \"NotificationsPlugin\""));
666        assert!(manifest.contains(".library(name: \"PushNotificationsPlugin\""));
667        assert!(manifest.contains(".library(name: \"UpdaterPlugin\""));
668        assert!(manifest.contains(".linkedFramework(\"UserNotifications\")"));
669        assert!(manifest.contains(".linkedFramework(\"Security\")"));
670        assert!(manifest.contains(".linkedFramework(\"AuthenticationServices\")"));
671        assert!(manifest.contains(".linkedFramework(\"AVFoundation\")"));
672        assert!(manifest.contains(".linkedFramework(\"MediaPlayer\""));
673        assert!(manifest.contains(".linkedFramework(\"WebKit\")"));
674        assert!(auth.contains("#[manganis::ffi(\"src/ios\")]"));
675        assert!(
676            auth.contains("pub fn startAppleAuthFromRust(this: &AuthPlugin, requestJson: String) -> Option<String>;",),
677        );
678        assert!(auth.contains("pub fn getAuthState(this: &AuthPlugin) -> Option<String>;"),);
679        assert!(!auth.contains("signOutFromRust"));
680        assert!(swift_auth.contains("ASAuthorizationAppleIDProvider"));
681        assert!(swift_auth.contains("request.nonce = Self.sha256(authRequest.nonce)"));
682        assert!(swift_auth.contains("credential.authorizationCode"));
683        assert!(swift_auth.contains("\"authorization_code\""));
684        assert!(swift_auth.contains("public func getAuthState() -> String?"));
685        assert!(swift_auth.contains("identity_token"));
686        assert!(!swift_auth.contains("Email found:"));
687        assert!(!swift_auth.contains("Display name:"));
688        assert!(clipboard.contains("#[manganis::ffi(\"src/ios\")]"));
689        assert!(external_url.contains("#[manganis::ffi(\"src/ios\")]"));
690    }
691    #[test]
692    fn android_auth_plugin_exposes_google_sign_in() {
693        let auth = include_str!("auth.rs");
694        let kotlin_auth = include_str!(
695            "android/auth/src/main/kotlin/dev/dioxus/g3_native_plugins/auth/AuthPlugin.kt",
696        );
697        assert!(auth.contains("#[manganis::ffi(\"src/android/auth\")]"));
698        assert!(auth.contains("unsafe extern \"Kotlin\""));
699        let android = auth
700            .split("unsafe extern \"Kotlin\" {")
701            .nth(1)
702            .expect("auth declares its Kotlin module")
703            .split('}')
704            .next()
705            .expect("the Kotlin block should be closed");
706        assert!(!android.contains("pub fn "));
707        assert!(auth.contains("type AuthHandle = crate::android_bridge::AndroidPlugin"));
708        // The client id is the caller's, not the crate's. It names one Google
709        // Cloud project and is checked against an Android client registered
710        // there for the app's package and certificate, so a library carrying
711        // its own could only ever authenticate the app it shipped with.
712        assert!(auth.contains(
713            "pub fn start_google_auth(&mut self, server_client_id: &str) -> Result<(), String>",
714        ),);
715        assert!(
716            auth.contains("pub fn poll_auth_result(&mut self) -> Result<Option<String>, String>",)
717        );
718        assert!(auth.contains("pub fn is_auth_awaiting(&mut self) -> bool"));
719        assert!(kotlin_auth.contains("fun startGoogleAuthFromRust(serverClientId: String)"));
720        assert!(kotlin_auth.contains("fun getPendingResult(): String?"));
721        assert!(kotlin_auth.contains("fun getAuthState(): String"));
722        assert!(kotlin_auth.contains("setServerClientId(serverClientId)"));
723        assert!(!kotlin_auth.contains("apps.googleusercontent.com"));
724        assert!(!kotlin_auth.contains("CountDownLatch"));
725        assert!(!kotlin_auth.contains("TimeUnit"));
726        assert!(kotlin_auth.contains("GoogleIdTokenCredential.createFrom"));
727    }
728    #[test]
729    fn android_media_plugin_owns_mobile_playback_capabilities() {
730        let rust = include_str!("media.rs");
731        let kotlin = include_str!(
732            "android/media/src/main/kotlin/dev/dioxus/g3_native_plugins/media/MediaPlugin.kt",
733        );
734        let service = include_str!(
735            "android/media/src/main/kotlin/dev/dioxus/g3_native_plugins/media/PlaybackService.kt",
736        );
737        let manifest = include_str!("android/media/src/main/AndroidManifest.xml");
738        assert!(rust.contains("getClassLoader"));
739        assert!(rust.contains("enter_picture_in_picture"));
740        assert!(rust.contains("set_orientation"));
741        assert!(rust.contains("set_system_bars_hidden"));
742        assert!(rust.contains("set_playback_active"));
743        assert!(kotlin.contains("fun setSystemBarsHiddenFromRust(hidden: Boolean)"));
744        assert!(kotlin.contains("enterPictureInPictureMode"));
745        assert!(kotlin.contains("setActions(pipActions())"));
746        assert!(kotlin.contains("COMMAND_REWIND"));
747        assert!(kotlin.contains("COMMAND_FORWARD"));
748        assert!(kotlin.contains("dataset.androidPip"));
749        assert!(kotlin.contains("tawnynativepictureinpicturechange"));
750        assert!(kotlin.contains("tawnynativeplaybackresume"));
751        assert!(kotlin.contains("Application.ActivityLifecycleCallbacks"));
752        assert!(kotlin.contains("playing && !serviceForeground"));
753        assert!(rust.contains("clear_playback"));
754        assert!(kotlin.contains("fun clearPlaybackFromRust()"));
755        assert!(kotlin.contains("MediaSession(activity"));
756        assert!(kotlin.contains("setMediaSession(session.sessionToken)"));
757        assert!(kotlin.contains("OnWindowVisibilityChangeListener"));
758        assert!(service.contains("STOP_FOREGROUND_DETACH"));
759        assert!(manifest.contains("android:launchMode=\"singleTask\""));
760        assert!(!kotlin.contains("setSourceRectHint"));
761        assert!(kotlin.contains("SCREEN_ORIENTATION_SENSOR_LANDSCAPE"));
762        assert!(kotlin.contains("--android-status-bar-inset"));
763        assert!(service.contains("startForeground"));
764        assert!(manifest.contains("android:supportsPictureInPicture=\"true\""));
765        assert!(manifest.contains("foregroundServiceType=\"mediaPlayback\""));
766    }
767    #[test]
768    fn updater_trusts_nothing_before_the_signature_and_keeps_decisions_in_rust() {
769        let source = production_source(include_str!("updater.rs"));
770        let kotlin = include_str!(
771            "android/updater/src/main/kotlin/dev/dioxus/g3_native_plugins/updater/UpdaterPlugin.kt",
772        );
773        let swift = include_str!("ios/Sources/UpdaterPlugin.swift");
774        let gradle = include_str!("android/updater/build.gradle.kts");
775        // The manifest is verified before it is parsed, and its hashes carry
776        // that guarantee to every file.
777        let verified = source
778            .find("verify_signature(&config.pubkey")
779            .expect("the manifest signature is checked");
780        let parsed = source
781            .find("let manifest = parse_manifest(&bytes)?")
782            .unwrap();
783        assert!(verified < parsed);
784        assert!(source.contains("does not match the hash in the signed manifest"));
785        assert!(source.contains("minisign_verify::PublicKey"));
786        // Installed on trial, rolled back if never confirmed.
787        assert!(source.contains("pub fn notify_ready(&mut self)"));
788        assert!(source.contains("state.trial && state.trial_launches >= 1"));
789        // Downloads happen off the Dioxus thread.
790        assert!(source.contains("std::thread::Builder::new()"));
791        // The native sides only move bytes: no hashing or verification there.
792        assert!(!kotlin.contains("MessageDigest"));
793        assert!(!swift.contains("CryptoKit"));
794        assert!(kotlin.contains("noBackupFilesDir"));
795        assert!(swift.contains("isExcludedFromBackup = true"));
796        // A half-written file never sits where a finished one belongs.
797        assert!(kotlin.contains("partial.renameTo(destination)"));
798        assert!(!gradle.contains("implementation("));
799        assert!(!kotlin.contains(" error("));
800    }
801    #[test]
802    fn notifications_survive_reboots_without_claiming_exact_alarms() {
803        let source = production_source(include_str!("notifications.rs"));
804        let plugin = include_str!(
805            "android/notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/notifications/NotificationsPlugin.kt",
806        );
807        let store = include_str!(
808            "android/notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/notifications/Store.kt",
809        );
810        let poster = include_str!(
811            "android/notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/notifications/NotificationPoster.kt",
812        );
813        let receivers = include_str!(
814            "android/notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/notifications/Receivers.kt",
815        );
816        let manifest = include_str!("android/notifications/src/main/AndroidManifest.xml");
817        let gradle = include_str!("android/notifications/build.gradle.kts");
818        let swift = include_str!("ios/Sources/NotificationsPlugin.swift");
819        let relay = include_str!("ios/Sources/NotificationCenterRelay.swift");
820        assert!(
821            source.contains(
822                "pub fn take_event(&mut self) -> Result<Option<NotificationEvent>, String>"
823            )
824        );
825        assert!(source.contains("pub fn new() -> Self"));
826        // Android: alarms re-armed after a reboot, exact only when allowed,
827        // and the restricted permission left for the app to claim.
828        assert!(manifest.contains("android.permission.POST_NOTIFICATIONS"));
829        assert!(manifest.contains("android.intent.action.BOOT_COMPLETED"));
830        assert!(
831            !manifest.contains(
832                "uses-permission android:name=\"android.permission.SCHEDULE_EXACT_ALARM\""
833            )
834        );
835        assert!(manifest.contains("android:launchMode=\"singleTask\""));
836        assert!(store.contains("canScheduleExactAlarms()"));
837        assert!(receivers.contains("class BootReceiver"));
838        // Taps come back through both launch paths, like deep links.
839        assert!(plugin.contains("addOnNewIntentListener"));
840        assert!(plugin.contains("launchIntentConsumed = true"));
841        // PendingIntents differing only in extras collapse into one.
842        assert!(poster.contains("requestCode(notification.getInt(\"id\"), action)"));
843        // optString turns JSON null into the text "null".
844        assert!(poster.contains("stringOrNull(\"body\")"));
845        assert!(!gradle.contains("implementation("));
846        for kotlin in [plugin, store, poster, receivers] {
847            assert!(!kotlin.contains(" error("));
848        }
849        // iOS: one delegate for local and push, never displacing the host's.
850        assert!(relay.contains("UNPushNotificationTrigger"));
851        assert!(relay.contains("leaving it alone"));
852        assert!(swift.contains("UNTextInputNotificationAction"));
853        assert!(swift.contains("NotificationCenterRelay.install()"));
854    }
855    #[test]
856    fn push_keeps_firebase_out_of_local_only_apps() {
857        let source = production_source(include_str!("push_notifications.rs"));
858        let manifest = include_str!("../Cargo.toml");
859        let kotlin = include_str!(
860            "android/push_notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/push_notifications/PushNotificationsPlugin.kt",
861        );
862        let service = include_str!(
863            "android/push_notifications/src/main/kotlin/dev/dioxus/g3_native_plugins/push_notifications/PushMessagingService.kt",
864        );
865        let android_manifest =
866            include_str!("android/push_notifications/src/main/AndroidManifest.xml");
867        let gradle = include_str!("android/push_notifications/build.gradle.kts");
868        let swift = include_str!("ios/Sources/PushNotificationsPlugin.swift");
869        assert!(manifest.contains("push-notifications = [\"notifications\"]"));
870        assert!(gradle.contains("com.google.firebase:firebase-messaging"));
871        assert!(source.contains("pub fn register(&mut self, firebase: Option<&FirebaseOptions>)"));
872        // A generated Gradle project cannot run the google-services plugin,
873        // so Firebase is initialized from values passed at run time.
874        assert!(kotlin.contains("FirebaseApp.initializeApp(context, options)"));
875        assert!(android_manifest.contains("com.google.firebase.MESSAGING_EVENT"));
876        assert!(service.contains("override fun onNewToken"));
877        // iOS: APNs answers the app delegate, which Dioxus's does not
878        // implement, so the hooks are added at runtime.
879        assert!(swift.contains("class_addMethod"));
880        assert!(swift.contains("didRegisterForRemoteNotificationsWithDeviceToken"));
881        assert!(swift.contains("registerForRemoteNotifications()"));
882    }
883    #[test]
884    fn plugin_wrapper_constructors_stay_crate_private_and_lazy() {
885        for (source, plugin_type, handle_type) in [
886            (
887                production_source(include_str!("auth.rs")),
888                "AuthPlugin",
889                "AuthHandle",
890            ),
891            (
892                production_source(include_str!("clipboard.rs")),
893                "ClipboardPlugin",
894                "ClipboardHandle",
895            ),
896            (
897                production_source(include_str!("external_url.rs")),
898                "ExternalUrlPlugin",
899                "ExternalUrlHandle",
900            ),
901        ] {
902            assert!(source.contains("pub(crate) fn new() -> Self"));
903            assert!(!source.contains("pub fn new() -> Self"));
904            assert!(source.contains(&format!("plugin: Option<{handle_type}>")));
905            assert!(source.contains("Self { plugin: None }"));
906            assert!(source.contains("self.plugin = Some("));
907            assert!(source.contains(&format!("{plugin_type}::new()")));
908            assert!(!source.contains(&format!("plugin: Result<{plugin_type}, String>")));
909        }
910    }
911}