Skip to main content

tauri_plugin_barcode_scanner/
lib.rs

1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5//! Scan QR codes, EAN-13 and other kinds of barcodes with the device's camera.
6//!
7//! - Supported platforms: Android and iOS.
8
9#![cfg(mobile)]
10
11use tauri::{
12    Manager, Runtime,
13    plugin::{Builder, PluginHandle, TauriPlugin},
14};
15
16mod error;
17mod models;
18
19pub use error::{Error, Result};
20
21#[cfg(target_os = "android")]
22const PLUGIN_IDENTIFIER: &str = "app.tauri.barcodescanner";
23
24#[cfg(target_os = "ios")]
25tauri::ios_plugin_binding!(init_plugin_barcode_scanner);
26
27/// Access to the scanner APIs.
28pub struct BarcodeScanner<R: Runtime>(PluginHandle<R>);
29
30impl<R: Runtime> BarcodeScanner<R> {}
31
32/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the barcode scanner APIs.
33pub trait BarcodeScannerExt<R: Runtime> {
34    /// Returns the [`BarcodeScanner`] instance managed by the app.
35    fn barcode_scanner(&self) -> &BarcodeScanner<R>;
36}
37
38impl<R: Runtime, T: Manager<R>> crate::BarcodeScannerExt<R> for T {
39    fn barcode_scanner(&self) -> &BarcodeScanner<R> {
40        self.state::<BarcodeScanner<R>>().inner()
41    }
42}
43
44/// Initializes the plugin.
45pub fn init<R: Runtime>() -> TauriPlugin<R> {
46    Builder::new("barcode-scanner")
47        .setup(|app, api| {
48            #[cfg(target_os = "android")]
49            let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "BarcodeScannerPlugin")?;
50            #[cfg(target_os = "ios")]
51            let handle = api.register_ios_plugin(init_plugin_barcode_scanner)?;
52            app.manage(BarcodeScanner(handle));
53            Ok(())
54        })
55        .build()
56}