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