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