+ The torch can also be toggled while scanning from the Scanner page, which on
+ Android goes through the barcode scanner's camera.
+
diff --git a/plugins/barcode-scanner/android/consumer-rules.pro b/plugins/barcode-scanner/android/consumer-rules.pro
index 481bb4348..8f41a13d3 100644
--- a/plugins/barcode-scanner/android/consumer-rules.pro
+++ b/plugins/barcode-scanner/android/consumer-rules.pro
@@ -18,4 +18,8 @@
# If you keep the line number information, uncomment this to
# hide the original source file name.
-#-renamesourcefileattribute SourceFile
\ No newline at end of file
+#-renamesourcefileattribute SourceFile
+# Looked up through reflection by the torch plugin.
+-keep class app.tauri.barcodescanner.BarcodeScannerPlugin {
+ public static androidx.camera.core.Camera getActiveCamera();
+}
diff --git a/plugins/barcode-scanner/android/src/main/java/BarcodeScannerPlugin.kt b/plugins/barcode-scanner/android/src/main/java/BarcodeScannerPlugin.kt
index 4ac921943..1eaf6e3ea 100644
--- a/plugins/barcode-scanner/android/src/main/java/BarcodeScannerPlugin.kt
+++ b/plugins/barcode-scanner/android/src/main/java/BarcodeScannerPlugin.kt
@@ -75,6 +75,10 @@ class BarcodeScannerPlugin(private val activity: Activity) : Plugin(activity),
private var cameraProvider: ProcessCameraProvider? = null
private var graphicOverlay: GraphicOverlay? = null
private var camera: Camera? = null
+ set(value) {
+ field = value
+ activeCamera = value
+ }
private var vibrator: Vibrator? = null
private var scannerOptions: BarcodeScannerOptions? = null
@@ -416,4 +420,19 @@ class BarcodeScannerPlugin(private val activity: Activity) : Plugin(activity),
private fun openSettingsResult(invoke: Invoke, result: ActivityResult) {
invoke.resolve()
}
+
+ companion object {
+ @Volatile
+ private var activeCamera: Camera? = null
+
+ /**
+ * The camera bound by an active scan, or `null` when no scan is running.
+ *
+ * Looked up through reflection by the torch plugin (`app.tauri.torch`): while a scan holds the
+ * camera, Android rejects `CameraManager.setTorchMode`, so the flash must be driven through
+ * this camera's `CameraControl` instead. Keep the name and signature stable.
+ */
+ @JvmStatic
+ fun getActiveCamera(): Camera? = activeCamera
+ }
}
diff --git a/plugins/torch/Cargo.toml b/plugins/torch/Cargo.toml
new file mode 100644
index 000000000..fb3c825ef
--- /dev/null
+++ b/plugins/torch/Cargo.toml
@@ -0,0 +1,34 @@
+[package]
+name = "tauri-plugin-torch"
+version = "2.0.0"
+description = "Control the device flashlight (torch) on Android and iOS"
+edition = { workspace = true }
+authors = { workspace = true }
+license = { workspace = true }
+rust-version = { workspace = true }
+repository = { workspace = true }
+links = "tauri-plugin-torch"
+exclude = ["/guest-js", "/package.json", "/rollup.config.js", "/tsconfig.json"]
+
+[package.metadata.docs.rs]
+targets = ["x86_64-linux-android"]
+
+[package.metadata.platforms.support]
+windows = { level = "none", notes = "" }
+linux = { level = "none", notes = "" }
+macos = { level = "none", notes = "" }
+android = { level = "full", notes = "" }
+ios = { level = "full", notes = "" }
+
+[build-dependencies]
+tauri-plugin = { workspace = true, features = ["build"] }
+
+[dependencies]
+serde = { workspace = true }
+serde_json = { workspace = true }
+tauri = { workspace = true }
+log = { workspace = true }
+thiserror = { workspace = true }
+
+[target.'cfg(target_os = "ios")'.dependencies]
+tauri = { workspace = true, features = ["wry"] }
diff --git a/plugins/torch/LICENSE.spdx b/plugins/torch/LICENSE.spdx
new file mode 100644
index 000000000..cdd0df5ad
--- /dev/null
+++ b/plugins/torch/LICENSE.spdx
@@ -0,0 +1,20 @@
+SPDXVersion: SPDX-2.1
+DataLicense: CC0-1.0
+PackageName: tauri
+DataFormat: SPDXRef-1
+PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
+PackageHomePage: https://tauri.app
+PackageLicenseDeclared: Apache-2.0
+PackageLicenseDeclared: MIT
+PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
+PackageSummary: Tauri is a rust project that enables developers to make secure
+and small desktop applications using a web frontend.
+
+PackageComment: The package includes the following libraries; see
+Relationship information.
+
+Created: 2019-05-20T09:00:00Z
+PackageDownloadLocation: git://github.com/tauri-apps/tauri
+PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
+PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
+Creator: Person: Daniel Thompson-Yvetot
\ No newline at end of file
diff --git a/plugins/torch/LICENSE_APACHE-2.0 b/plugins/torch/LICENSE_APACHE-2.0
new file mode 100644
index 000000000..4947287f7
--- /dev/null
+++ b/plugins/torch/LICENSE_APACHE-2.0
@@ -0,0 +1,177 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
\ No newline at end of file
diff --git a/plugins/torch/LICENSE_MIT b/plugins/torch/LICENSE_MIT
new file mode 100644
index 000000000..4d7547256
--- /dev/null
+++ b/plugins/torch/LICENSE_MIT
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 - Present Tauri Apps Contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/plugins/torch/README.md b/plugins/torch/README.md
new file mode 100644
index 000000000..a0349e637
--- /dev/null
+++ b/plugins/torch/README.md
@@ -0,0 +1,118 @@
+# Torch
+
+Control the device flashlight (torch) on Android and iOS.
+
+On Android, turning on the torch while another component holds the camera normally fails. This plugin also works while a [barcode scanner](../barcode-scanner) scan is running, so apps can offer a flashlight button in their scanning UI.
+
+| Platform | Supported |
+| -------- | --------- |
+| Linux | x |
+| Windows | x |
+| macOS | x |
+| Android | ✓ |
+| iOS | ✓ |
+
+## Install
+
+_This plugin requires a Rust version of at least **1.90**_
+
+There are three general methods of installation that we can recommend.
+
+1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
+2. Pull sources directly from Github using git tags / revision hashes (most secure)
+3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
+
+Install the Core plugin by adding the following to your `Cargo.toml` file:
+
+`src-tauri/Cargo.toml`
+
+```toml
+[dependencies]
+tauri-plugin-torch = "2.0.0"
+# alternatively with Git:
+tauri-plugin-torch = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
+```
+
+You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
+
+
+
+```sh
+pnpm add @tauri-apps/plugin-torch
+# or
+npm add @tauri-apps/plugin-torch
+# or
+yarn add @tauri-apps/plugin-torch
+```
+
+## Usage
+
+First you need to register the core plugin with Tauri:
+
+`src-tauri/src/lib.rs`
+
+```rust
+fn main() {
+ tauri::Builder::default()
+ .plugin(tauri_plugin_torch::init())
+ .run(tauri::generate_context!())
+ .expect("error while running tauri application");
+}
+```
+
+Second, add the required permissions in the project:
+
+`src-tauri/capabilities/default.json`
+
+```json
+ "permissions": ["torch:default"]
+```
+
+Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
+
+```javascript
+import {
+ enable,
+ disable,
+ toggle,
+ isAvailable,
+ isEnabled
+} from '@tauri-apps/plugin-torch'
+
+if (await isAvailable()) {
+ await enable()
+ console.log(await isEnabled()) // true
+ await toggle() // returns false, the torch is now off
+ await disable()
+}
+```
+
+`isEnabled` reads the hardware state, so it also reflects the torch being turned off by the system, another app, or a barcode scan ending.
+
+On iOS, apps can't see the torch state set by Control Center or another app: while the flashlight is on from there, `isEnabled` returns `false` and `toggle` tries to turn the torch on.
+
+## Contributing
+
+PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
+
+## Partners
+
+
+
+For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
+
+## License
+
+Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
+
+MIT or MIT/Apache 2.0 where applicable.
diff --git a/plugins/torch/SECURITY.md b/plugins/torch/SECURITY.md
new file mode 100644
index 000000000..4f09bbacd
--- /dev/null
+++ b/plugins/torch/SECURITY.md
@@ -0,0 +1,23 @@
+# Security Policy
+
+**Do not report security vulnerabilities through public GitHub issues.**
+
+**Please use the [Private Vulnerability Disclosure](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability) feature of GitHub.**
+
+Include as much of the following information:
+
+- Type of issue (e.g. improper input parsing, privilege escalation, etc.)
+- The location of the affected source code (tag/branch/commit or direct URL)
+- Any special configuration required to reproduce the issue
+- The distribution affected or used to help us with reproduction of the issue
+- Step-by-step instructions to reproduce the issue
+- Ideally a reproduction repository
+- Impact of the issue, including how an attacker might exploit the issue
+
+We prefer to receive reports in English.
+
+## Contact
+
+Please disclose a vulnerability or security relevant issue here: [https://github.com/tauri-apps/plugins-workspace/security/advisories/new](https://github.com/tauri-apps/plugins-workspace/security/advisories/new).
+
+Alternatively, you can also contact us by email via [security@tauri.app](mailto:security@tauri.app).
diff --git a/plugins/torch/android/.gitignore b/plugins/torch/android/.gitignore
new file mode 100644
index 000000000..c0f21ec2f
--- /dev/null
+++ b/plugins/torch/android/.gitignore
@@ -0,0 +1,2 @@
+/build
+/.tauri
diff --git a/plugins/torch/android/build.gradle.kts b/plugins/torch/android/build.gradle.kts
new file mode 100644
index 000000000..b53be2488
--- /dev/null
+++ b/plugins/torch/android/build.gradle.kts
@@ -0,0 +1,44 @@
+import org.jetbrains.kotlin.gradle.dsl.JvmTarget
+
+plugins {
+ id("com.android.library")
+ id("org.jetbrains.kotlin.android")
+}
+
+android {
+ namespace = "app.tauri.torch"
+ compileSdk = 36
+
+ defaultConfig {
+ minSdk = 24
+
+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
+ consumerProguardFiles("consumer-rules.pro")
+ }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_1_8
+ targetCompatibility = JavaVersion.VERSION_1_8
+ }
+}
+
+kotlin {
+ compilerOptions {
+ jvmTarget = JvmTarget.JVM_1_8
+ }
+}
+
+dependencies {
+
+ implementation("androidx.core:core-ktx:1.9.0")
+ implementation("androidx.appcompat:appcompat:1.6.0")
+ implementation("com.google.android.material:material:1.7.0")
+ implementation("com.fasterxml.jackson.core:jackson-databind:2.15.3")
+ // Only compiled against: CameraX is on the runtime classpath when the barcode scanner plugin is,
+ // and ScannerCamera, the only class using it, is only constructed while a scan is active.
+ compileOnly("androidx.camera:camera-core:1.5.1")
+ testImplementation("junit:junit:4.13.2")
+ androidTestImplementation("androidx.test.ext:junit:1.1.5")
+ androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
+ implementation(project(":tauri-android"))
+}
diff --git a/plugins/torch/android/consumer-rules.pro b/plugins/torch/android/consumer-rules.pro
new file mode 100644
index 000000000..481bb4348
--- /dev/null
+++ b/plugins/torch/android/consumer-rules.pro
@@ -0,0 +1,21 @@
+# Add project specific ProGuard rules here.
+# You can control the set of applied configuration files using the
+# proguardFiles setting in build.gradle.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+#-keepattributes SourceFile,LineNumberTable
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile
\ No newline at end of file
diff --git a/plugins/torch/android/settings.gradle b/plugins/torch/android/settings.gradle
new file mode 100644
index 000000000..14a752e43
--- /dev/null
+++ b/plugins/torch/android/settings.gradle
@@ -0,0 +1,2 @@
+include ':tauri-android'
+project(':tauri-android').projectDir = new File('./.tauri/tauri-api')
diff --git a/plugins/torch/android/src/main/AndroidManifest.xml b/plugins/torch/android/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..9a40236b9
--- /dev/null
+++ b/plugins/torch/android/src/main/AndroidManifest.xml
@@ -0,0 +1,3 @@
+
+
+
diff --git a/plugins/torch/android/src/main/java/ScannerCamera.kt b/plugins/torch/android/src/main/java/ScannerCamera.kt
new file mode 100644
index 000000000..c1e5d1df2
--- /dev/null
+++ b/plugins/torch/android/src/main/java/ScannerCamera.kt
@@ -0,0 +1,43 @@
+// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: MIT
+
+package app.tauri.torch
+
+import androidx.camera.core.Camera
+import androidx.camera.core.TorchState
+import java.util.concurrent.ExecutionException
+import java.util.concurrent.Executor
+
+/**
+ * The camera held by an active barcode scan.
+ *
+ * While CameraX holds the camera, `CameraManager.setTorchMode` fails with `CAMERA_IN_USE`, so the
+ * torch has to go through the camera's own `CameraControl`. This is the only class referencing
+ * CameraX, which is only on the classpath when the barcode scanner plugin is; only construct it
+ * from a camera returned by [TorchPlugin.findScannerCamera].
+ */
+internal class ScannerCamera(camera: Any) {
+ private val camera = camera as Camera
+
+ val hasFlashUnit: Boolean
+ get() = camera.cameraInfo.hasFlashUnit()
+
+ val torchEnabled: Boolean
+ get() = camera.cameraInfo.torchState.value == TorchState.ON
+
+ /** Calls [callback] with `null` once the torch changed, or with the error that prevented it. */
+ fun setTorch(enabled: Boolean, executor: Executor, callback: (Throwable?) -> Unit) {
+ val future = camera.cameraControl.enableTorch(enabled)
+ future.addListener({
+ try {
+ future.get()
+ callback(null)
+ } catch (e: ExecutionException) {
+ callback(e.cause ?: e)
+ } catch (e: Exception) {
+ callback(e)
+ }
+ }, executor)
+ }
+}
diff --git a/plugins/torch/android/src/main/java/TorchPlugin.kt b/plugins/torch/android/src/main/java/TorchPlugin.kt
new file mode 100644
index 000000000..f6aa21316
--- /dev/null
+++ b/plugins/torch/android/src/main/java/TorchPlugin.kt
@@ -0,0 +1,159 @@
+// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: MIT
+
+package app.tauri.torch
+
+import android.app.Activity
+import android.content.Context
+import android.hardware.camera2.CameraAccessException
+import android.hardware.camera2.CameraCharacteristics
+import android.hardware.camera2.CameraManager
+import android.os.Handler
+import android.os.Looper
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.content.ContextCompat
+import app.tauri.Logger
+import app.tauri.annotation.Command
+import app.tauri.annotation.TauriPlugin
+import app.tauri.plugin.Invoke
+import app.tauri.plugin.JSObject
+import app.tauri.plugin.Plugin
+
+private const val ERROR_NOT_AVAILABLE = "The torch is not available on this device"
+private const val SCANNER_PLUGIN_CLASS = "app.tauri.barcodescanner.BarcodeScannerPlugin"
+
+@TauriPlugin
+class TorchPlugin(private val activity: Activity) : Plugin(activity) {
+ private val cameraManager =
+ activity.getSystemService(Context.CAMERA_SERVICE) as CameraManager
+
+ // the camera whose flash unit is used as the torch, or null if the device has none
+ private val torchCameraId: String? = findTorchCameraId()
+
+ // the system-reported state of the torch, kept in sync by torchCallback so changes made by
+ // the system or other apps are reflected
+ @Volatile
+ private var torchEnabled = false
+
+ private val torchCallback = object : CameraManager.TorchCallback() {
+ override fun onTorchModeChanged(cameraId: String, enabled: Boolean) {
+ if (cameraId == torchCameraId) torchEnabled = enabled
+ }
+
+ override fun onTorchModeUnavailable(cameraId: String) {
+ if (cameraId == torchCameraId) torchEnabled = false
+ }
+ }
+
+ init {
+ if (torchCameraId != null) {
+ cameraManager.registerTorchCallback(torchCallback, Handler(Looper.getMainLooper()))
+ }
+ }
+
+ override fun onDestroy(activity: AppCompatActivity) {
+ cameraManager.unregisterTorchCallback(torchCallback)
+ }
+
+ private fun findTorchCameraId(): String? {
+ return try {
+ val withFlash = cameraManager.cameraIdList.filter {
+ cameraManager.getCameraCharacteristics(it)
+ .get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true
+ }
+ withFlash.firstOrNull {
+ cameraManager.getCameraCharacteristics(it)
+ .get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK
+ } ?: withFlash.firstOrNull()
+ } catch (e: Exception) {
+ Logger.error("Failed to look up the camera flash unit: ${e.message}")
+ null
+ }
+ }
+
+ // The camera of an active barcode scan, if the barcode scanner plugin is installed and scanning.
+ private fun findScannerCamera(): ScannerCamera? {
+ val camera = try {
+ Class.forName(SCANNER_PLUGIN_CLASS).getMethod("getActiveCamera").invoke(null)
+ } catch (e: Exception) {
+ null
+ } ?: return null
+ return ScannerCamera(camera)
+ }
+
+ private fun isTorchOn(): Boolean = findScannerCamera()?.torchEnabled ?: torchEnabled
+
+ private fun setTorch(invoke: Invoke, enabled: Boolean, onSuccess: () -> Unit) {
+ val action = if (enabled) "enable" else "disable"
+
+ val scannerCamera = findScannerCamera()
+ if (scannerCamera != null) {
+ if (!scannerCamera.hasFlashUnit) {
+ invoke.reject("The camera used by the barcode scanner has no flash unit")
+ return
+ }
+ scannerCamera.setTorch(enabled, ContextCompat.getMainExecutor(activity)) { error ->
+ if (error == null) {
+ onSuccess()
+ } else {
+ invoke.reject("Failed to $action the torch: ${error.message}")
+ }
+ }
+ return
+ }
+
+ val cameraId = torchCameraId
+ if (cameraId == null) {
+ invoke.reject(ERROR_NOT_AVAILABLE)
+ return
+ }
+ try {
+ cameraManager.setTorchMode(cameraId, enabled)
+ torchEnabled = enabled
+ onSuccess()
+ } catch (e: CameraAccessException) {
+ when (e.reason) {
+ CameraAccessException.CAMERA_IN_USE, CameraAccessException.MAX_CAMERAS_IN_USE ->
+ invoke.reject("Failed to $action the torch: the camera is in use by another app")
+ else -> invoke.reject("Failed to $action the torch: ${e.message}")
+ }
+ } catch (e: Exception) {
+ invoke.reject("Failed to $action the torch: ${e.message}")
+ }
+ }
+
+ @Command
+ fun enable(invoke: Invoke) {
+ setTorch(invoke, true) { invoke.resolve() }
+ }
+
+ @Command
+ fun disable(invoke: Invoke) {
+ setTorch(invoke, false) { invoke.resolve() }
+ }
+
+ @Command
+ fun toggle(invoke: Invoke) {
+ val enabled = !isTorchOn()
+ setTorch(invoke, enabled) {
+ val result = JSObject()
+ result.put("enabled", enabled)
+ invoke.resolve(result)
+ }
+ }
+
+ @Command
+ fun isAvailable(invoke: Invoke) {
+ val result = JSObject()
+ result.put("available", torchCameraId != null)
+ invoke.resolve(result)
+ }
+
+ @Command
+ fun isEnabled(invoke: Invoke) {
+ val result = JSObject()
+ result.put("enabled", isTorchOn())
+ invoke.resolve(result)
+ }
+}
diff --git a/plugins/torch/api-iife.js b/plugins/torch/api-iife.js
new file mode 100644
index 000000000..a0828e289
--- /dev/null
+++ b/plugins/torch/api-iife.js
@@ -0,0 +1 @@
+if("__TAURI__"in window){var __TAURI_PLUGIN_TORCH__=function(n,e){"use strict";return n.disable=async function(){await e.invoke("plugin:torch|disable")},n.enable=async function(){await e.invoke("plugin:torch|enable")},n.isAvailable=async function(){return await e.invoke("plugin:torch|is_available").then(n=>n.available)},n.isEnabled=async function(){return await e.invoke("plugin:torch|is_enabled").then(n=>n.enabled)},n.toggle=async function(){return await e.invoke("plugin:torch|toggle").then(n=>n.enabled)},n}({},window.__TAURI__.core);Object.defineProperty(window.__TAURI__,"torch",{value:__TAURI_PLUGIN_TORCH__})}
diff --git a/plugins/torch/build.rs b/plugins/torch/build.rs
new file mode 100644
index 000000000..dd2e81785
--- /dev/null
+++ b/plugins/torch/build.rs
@@ -0,0 +1,21 @@
+// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: MIT
+
+const COMMANDS: &[&str] = &["enable", "disable", "toggle", "is_available", "is_enabled"];
+
+fn main() {
+ let result = tauri_plugin::Builder::new(COMMANDS)
+ .global_api_script_path("./api-iife.js")
+ .android_path("android")
+ .ios_path("ios")
+ .try_build();
+
+ // when building documentation for Android the plugin build result is always Err() (docs.rs mounts the sources read-only) and is irrelevant to the crate documentation build
+ // `cfg(docsrs)` only reaches rustdoc, build scripts must check the `DOCS_RS` env var instead
+ if !(std::env::var_os("DOCS_RS").is_some()
+ && std::env::var("TARGET").unwrap().contains("android"))
+ {
+ result.unwrap();
+ }
+}
diff --git a/plugins/torch/guest-js/index.ts b/plugins/torch/guest-js/index.ts
new file mode 100644
index 000000000..bb6b814af
--- /dev/null
+++ b/plugins/torch/guest-js/index.ts
@@ -0,0 +1,101 @@
+// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: MIT
+
+/**
+ * Control the device flashlight (torch) on Android and iOS.
+ *
+ * On Android the torch keeps working while the barcode scanner plugin holds the camera.
+ *
+ * @module
+ */
+
+import { invoke } from '@tauri-apps/api/core'
+
+/**
+ * Turns the torch on.
+ *
+ * Rejects if the device has no torch, the torch is temporarily unavailable (e.g. the device is
+ * overheating) or the camera is held by another app.
+ *
+ * @example
+ * ```typescript
+ * import { enable } from '@tauri-apps/plugin-torch'
+ * await enable()
+ * ```
+ */
+export async function enable(): Promise {
+ await invoke('plugin:torch|enable')
+}
+
+/**
+ * Turns the torch off.
+ *
+ * Rejects in the same cases as {@link enable}.
+ *
+ * @example
+ * ```typescript
+ * import { disable } from '@tauri-apps/plugin-torch'
+ * await disable()
+ * ```
+ */
+export async function disable(): Promise {
+ await invoke('plugin:torch|disable')
+}
+
+/**
+ * Flips the torch.
+ *
+ * Rejects in the same cases as {@link enable}.
+ *
+ * @example
+ * ```typescript
+ * import { toggle } from '@tauri-apps/plugin-torch'
+ * const on = await toggle()
+ * ```
+ *
+ * @returns Whether the torch is now on.
+ */
+export async function toggle(): Promise {
+ return await invoke<{ enabled: boolean }>('plugin:torch|toggle').then(
+ (r) => r.enabled
+ )
+}
+
+/**
+ * Whether the device has a torch.
+ *
+ * @example
+ * ```typescript
+ * import { isAvailable } from '@tauri-apps/plugin-torch'
+ * if (await isAvailable()) {
+ * // show the torch button
+ * }
+ * ```
+ */
+export async function isAvailable(): Promise {
+ return await invoke<{ available: boolean }>('plugin:torch|is_available').then(
+ (r) => r.available
+ )
+}
+
+/**
+ * Whether the torch is currently on.
+ *
+ * This reads the hardware state, so it also reflects the torch being turned off by the system,
+ * another app, or a barcode scan ending.
+ *
+ * On iOS, the torch turned on from Control Center or by another app is not visible to the app,
+ * so this returns `false` for it.
+ *
+ * @example
+ * ```typescript
+ * import { isEnabled } from '@tauri-apps/plugin-torch'
+ * const on = await isEnabled()
+ * ```
+ */
+export async function isEnabled(): Promise {
+ return await invoke<{ enabled: boolean }>('plugin:torch|is_enabled').then(
+ (r) => r.enabled
+ )
+}
diff --git a/plugins/torch/ios/.gitignore b/plugins/torch/ios/.gitignore
new file mode 100644
index 000000000..5922fdaa5
--- /dev/null
+++ b/plugins/torch/ios/.gitignore
@@ -0,0 +1,10 @@
+.DS_Store
+/.build
+/Packages
+/*.xcodeproj
+xcuserdata/
+DerivedData/
+.swiftpm/config/registries.json
+.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
+.netrc
+Package.resolved
diff --git a/plugins/torch/ios/Package.swift b/plugins/torch/ios/Package.swift
new file mode 100644
index 000000000..c7e7a9e37
--- /dev/null
+++ b/plugins/torch/ios/Package.swift
@@ -0,0 +1,34 @@
+// swift-tools-version:5.3
+// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: MIT
+
+import PackageDescription
+
+let package = Package(
+ name: "tauri-plugin-torch",
+ platforms: [
+ .macOS(.v10_13),
+ .iOS(.v13),
+ ],
+ products: [
+ // Products define the executables and libraries a package produces, and make them visible to other packages.
+ .library(
+ name: "tauri-plugin-torch",
+ type: .static,
+ targets: ["tauri-plugin-torch"])
+ ],
+ dependencies: [
+ .package(name: "Tauri", path: "../.tauri/tauri-api")
+ ],
+ targets: [
+ // Targets are the basic building blocks of a package. A target can define a module or a test suite.
+ // Targets can depend on other targets in this package, and on products in packages this package depends on.
+ .target(
+ name: "tauri-plugin-torch",
+ dependencies: [
+ .byName(name: "Tauri")
+ ],
+ path: "Sources")
+ ]
+)
diff --git a/plugins/torch/ios/README.md b/plugins/torch/ios/README.md
new file mode 100644
index 000000000..91027847f
--- /dev/null
+++ b/plugins/torch/ios/README.md
@@ -0,0 +1,3 @@
+# Tauri Plugin Torch
+
+A description of this package.
diff --git a/plugins/torch/ios/Sources/TorchPlugin.swift b/plugins/torch/ios/Sources/TorchPlugin.swift
new file mode 100644
index 000000000..2ee748b59
--- /dev/null
+++ b/plugins/torch/ios/Sources/TorchPlugin.swift
@@ -0,0 +1,81 @@
+// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: MIT
+
+import AVFoundation
+import SwiftRs
+import Tauri
+import UIKit
+import WebKit
+
+private let errorNotAvailable = "The torch is not available on this device"
+
+class TorchPlugin: Plugin {
+ // The back camera, whose flash unit is the torch. Locking it for configuration also works while a
+ // capture session (e.g. the barcode scanner) is running on it.
+ private func torchDevice() -> AVCaptureDevice? {
+ let device =
+ AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)
+ ?? AVCaptureDevice.default(for: .video)
+ guard let device = device, device.hasTorch else { return nil }
+ return device
+ }
+
+ private func setTorch(_ invoke: Invoke, enabled: Bool) -> Bool {
+ let action = enabled ? "enable" : "disable"
+ guard let device = torchDevice() else {
+ invoke.reject(errorNotAvailable)
+ return false
+ }
+ // false while the device is overheating, among others
+ guard device.isTorchAvailable else {
+ invoke.reject("Failed to \(action) the torch: the torch is temporarily unavailable")
+ return false
+ }
+ do {
+ try device.lockForConfiguration()
+ defer { device.unlockForConfiguration() }
+ if enabled {
+ try device.setTorchModeOn(level: AVCaptureDevice.maxAvailableTorchLevel)
+ } else {
+ device.torchMode = .off
+ }
+ return true
+ } catch {
+ invoke.reject("Failed to \(action) the torch: \(error.localizedDescription)")
+ return false
+ }
+ }
+
+ @objc public func enable(_ invoke: Invoke) {
+ if setTorch(invoke, enabled: true) {
+ invoke.resolve()
+ }
+ }
+
+ @objc public func disable(_ invoke: Invoke) {
+ if setTorch(invoke, enabled: false) {
+ invoke.resolve()
+ }
+ }
+
+ @objc public func toggle(_ invoke: Invoke) {
+ let enabled = !(torchDevice()?.isTorchActive ?? false)
+ if setTorch(invoke, enabled: enabled) {
+ invoke.resolve(["enabled": enabled])
+ }
+ }
+
+ @objc public func isAvailable(_ invoke: Invoke) {
+ invoke.resolve(["available": torchDevice() != nil])
+ }
+
+ @objc public func isEnabled(_ invoke: Invoke) {
+ invoke.resolve(["enabled": torchDevice()?.isTorchActive ?? false])
+ }
+}
+
+@_cdecl("init_plugin_torch")
+public func initPlugin() -> Plugin {
+ return TorchPlugin()
+}
diff --git a/plugins/torch/package.json b/plugins/torch/package.json
new file mode 100644
index 000000000..08b9a70c3
--- /dev/null
+++ b/plugins/torch/package.json
@@ -0,0 +1,30 @@
+{
+ "name": "@tauri-apps/plugin-torch",
+ "version": "2.0.0",
+ "description": "Control the device flashlight (torch) on Android and iOS",
+ "license": "MIT OR Apache-2.0",
+ "authors": [
+ "Tauri Programme within The Commons Conservancy"
+ ],
+ "repository": "https://github.com/tauri-apps/plugins-workspace",
+ "type": "module",
+ "types": "./dist-js/index.d.ts",
+ "main": "./dist-js/index.cjs",
+ "module": "./dist-js/index.js",
+ "exports": {
+ "types": "./dist-js/index.d.ts",
+ "import": "./dist-js/index.js",
+ "require": "./dist-js/index.cjs"
+ },
+ "scripts": {
+ "build": "rollup -c"
+ },
+ "files": [
+ "dist-js",
+ "README.md",
+ "LICENSE"
+ ],
+ "dependencies": {
+ "@tauri-apps/api": "^2.12.0"
+ }
+}
diff --git a/plugins/torch/permissions/autogenerated/commands/disable.toml b/plugins/torch/permissions/autogenerated/commands/disable.toml
new file mode 100644
index 000000000..849c50a2d
--- /dev/null
+++ b/plugins/torch/permissions/autogenerated/commands/disable.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-disable"
+description = "Enables the disable command without any pre-configured scope."
+commands.allow = ["disable"]
+
+[[permission]]
+identifier = "deny-disable"
+description = "Denies the disable command without any pre-configured scope."
+commands.deny = ["disable"]
diff --git a/plugins/torch/permissions/autogenerated/commands/enable.toml b/plugins/torch/permissions/autogenerated/commands/enable.toml
new file mode 100644
index 000000000..f931a9e54
--- /dev/null
+++ b/plugins/torch/permissions/autogenerated/commands/enable.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-enable"
+description = "Enables the enable command without any pre-configured scope."
+commands.allow = ["enable"]
+
+[[permission]]
+identifier = "deny-enable"
+description = "Denies the enable command without any pre-configured scope."
+commands.deny = ["enable"]
diff --git a/plugins/torch/permissions/autogenerated/commands/is_available.toml b/plugins/torch/permissions/autogenerated/commands/is_available.toml
new file mode 100644
index 000000000..6f49c5ab4
--- /dev/null
+++ b/plugins/torch/permissions/autogenerated/commands/is_available.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-is-available"
+description = "Enables the is_available command without any pre-configured scope."
+commands.allow = ["is_available"]
+
+[[permission]]
+identifier = "deny-is-available"
+description = "Denies the is_available command without any pre-configured scope."
+commands.deny = ["is_available"]
diff --git a/plugins/torch/permissions/autogenerated/commands/is_enabled.toml b/plugins/torch/permissions/autogenerated/commands/is_enabled.toml
new file mode 100644
index 000000000..88a6a2823
--- /dev/null
+++ b/plugins/torch/permissions/autogenerated/commands/is_enabled.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-is-enabled"
+description = "Enables the is_enabled command without any pre-configured scope."
+commands.allow = ["is_enabled"]
+
+[[permission]]
+identifier = "deny-is-enabled"
+description = "Denies the is_enabled command without any pre-configured scope."
+commands.deny = ["is_enabled"]
diff --git a/plugins/torch/permissions/autogenerated/commands/toggle.toml b/plugins/torch/permissions/autogenerated/commands/toggle.toml
new file mode 100644
index 000000000..f214f0310
--- /dev/null
+++ b/plugins/torch/permissions/autogenerated/commands/toggle.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-toggle"
+description = "Enables the toggle command without any pre-configured scope."
+commands.allow = ["toggle"]
+
+[[permission]]
+identifier = "deny-toggle"
+description = "Denies the toggle command without any pre-configured scope."
+commands.deny = ["toggle"]
diff --git a/plugins/torch/permissions/autogenerated/reference.md b/plugins/torch/permissions/autogenerated/reference.md
new file mode 100644
index 000000000..87f6adbf5
--- /dev/null
+++ b/plugins/torch/permissions/autogenerated/reference.md
@@ -0,0 +1,156 @@
+## Default Permission
+
+This permission set configures which
+torch features are by default exposed.
+
+#### Granted Permissions
+
+It allows all torch related features.
+
+#### This default permission set includes the following:
+
+- `allow-disable`
+- `allow-enable`
+- `allow-is-available`
+- `allow-is-enabled`
+- `allow-toggle`
+
+## Permission Table
+
+
+
+
Identifier
+
Description
+
+
+
+
+
+
+`torch:allow-disable`
+
+
+
+
+Enables the disable command without any pre-configured scope.
+
+
+
+
+
+
+
+`torch:deny-disable`
+
+
+
+
+Denies the disable command without any pre-configured scope.
+
+
+
+
+
+
+
+`torch:allow-enable`
+
+
+
+
+Enables the enable command without any pre-configured scope.
+
+
+
+
+
+
+
+`torch:deny-enable`
+
+
+
+
+Denies the enable command without any pre-configured scope.
+
+
+
+
+
+
+
+`torch:allow-is-available`
+
+
+
+
+Enables the is_available command without any pre-configured scope.
+
+
+
+
+
+
+
+`torch:deny-is-available`
+
+
+
+
+Denies the is_available command without any pre-configured scope.
+
+
+
+
+
+
+
+`torch:allow-is-enabled`
+
+
+
+
+Enables the is_enabled command without any pre-configured scope.
+
+
+
+
+
+
+
+`torch:deny-is-enabled`
+
+
+
+
+Denies the is_enabled command without any pre-configured scope.
+
+
+
+
+
+
+
+`torch:allow-toggle`
+
+
+
+
+Enables the toggle command without any pre-configured scope.
+
+
+
+
+
+
+
+`torch:deny-toggle`
+
+
+
+
+Denies the toggle command without any pre-configured scope.
+
+
+
+
diff --git a/plugins/torch/permissions/default.toml b/plugins/torch/permissions/default.toml
new file mode 100644
index 000000000..471207261
--- /dev/null
+++ b/plugins/torch/permissions/default.toml
@@ -0,0 +1,19 @@
+"$schema" = "schemas/schema.json"
+[default]
+description = """
+This permission set configures which
+torch features are by default exposed.
+
+#### Granted Permissions
+
+It allows all torch related features.
+
+"""
+
+permissions = [
+ "allow-disable",
+ "allow-enable",
+ "allow-is-available",
+ "allow-is-enabled",
+ "allow-toggle",
+]
diff --git a/plugins/torch/permissions/schemas/schema.json b/plugins/torch/permissions/schemas/schema.json
new file mode 100644
index 000000000..0db4a6fc4
--- /dev/null
+++ b/plugins/torch/permissions/schemas/schema.json
@@ -0,0 +1,366 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "title": "PermissionFile",
+ "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
+ "type": "object",
+ "properties": {
+ "default": {
+ "description": "The default permission set for the plugin",
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DefaultPermission"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "set": {
+ "description": "A list of permissions sets defined",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionSet"
+ }
+ },
+ "permission": {
+ "description": "A list of inlined permissions",
+ "default": [],
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Permission"
+ }
+ }
+ },
+ "definitions": {
+ "DefaultPermission": {
+ "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
+ "type": "object",
+ "required": [
+ "permissions"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri convention is to use `
` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "PermissionSet": {
+ "description": "A set of direct permissions grouped together under a new name.",
+ "type": "object",
+ "required": [
+ "description",
+ "identifier",
+ "permissions"
+ ],
+ "properties": {
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does.",
+ "type": "string"
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionKind"
+ }
+ }
+ }
+ },
+ "Permission": {
+ "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
+ "type": "object",
+ "required": [
+ "identifier"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri internal convention is to use `
` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "commands": {
+ "description": "Allowed or denied commands when using this permission.",
+ "default": {
+ "allow": [],
+ "deny": []
+ },
+ "allOf": [
+ {
+ "$ref": "#/definitions/Commands"
+ }
+ ]
+ },
+ "scope": {
+ "description": "Allowed or denied scoped when using this permission.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Scopes"
+ }
+ ]
+ },
+ "platforms": {
+ "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Target"
+ }
+ }
+ }
+ },
+ "Commands": {
+ "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Allowed command.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "deny": {
+ "description": "Denied command, which takes priority.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "Scopes": {
+ "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Data that defines what is allowed by the scope.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ "deny": {
+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ }
+ },
+ "Value": {
+ "description": "All supported ACL values.",
+ "anyOf": [
+ {
+ "description": "Represents a null JSON value.",
+ "type": "null"
+ },
+ {
+ "description": "Represents a [`bool`].",
+ "type": "boolean"
+ },
+ {
+ "description": "Represents a valid ACL [`Number`].",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Number"
+ }
+ ]
+ },
+ {
+ "description": "Represents a [`String`].",
+ "type": "string"
+ },
+ {
+ "description": "Represents a list of other [`Value`]s.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ {
+ "description": "Represents a map of [`String`] keys to [`Value`]s.",
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ ]
+ },
+ "Number": {
+ "description": "A valid ACL number.",
+ "anyOf": [
+ {
+ "description": "Represents an [`i64`].",
+ "type": "integer",
+ "format": "int64"
+ },
+ {
+ "description": "Represents a [`f64`].",
+ "type": "number",
+ "format": "double"
+ }
+ ]
+ },
+ "Target": {
+ "description": "Platform target.",
+ "oneOf": [
+ {
+ "description": "MacOS.",
+ "type": "string",
+ "enum": [
+ "macOS"
+ ]
+ },
+ {
+ "description": "Windows.",
+ "type": "string",
+ "enum": [
+ "windows"
+ ]
+ },
+ {
+ "description": "Linux.",
+ "type": "string",
+ "enum": [
+ "linux"
+ ]
+ },
+ {
+ "description": "Android.",
+ "type": "string",
+ "enum": [
+ "android"
+ ]
+ },
+ {
+ "description": "iOS.",
+ "type": "string",
+ "enum": [
+ "iOS"
+ ]
+ }
+ ]
+ },
+ "PermissionKind": {
+ "type": "string",
+ "oneOf": [
+ {
+ "description": "Enables the disable command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-disable",
+ "markdownDescription": "Enables the disable command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the disable command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-disable",
+ "markdownDescription": "Denies the disable command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the enable command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-enable",
+ "markdownDescription": "Enables the enable command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the enable command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-enable",
+ "markdownDescription": "Denies the enable command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the is_available command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-is-available",
+ "markdownDescription": "Enables the is_available command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the is_available command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-is-available",
+ "markdownDescription": "Denies the is_available command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the is_enabled command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-is-enabled",
+ "markdownDescription": "Enables the is_enabled command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the is_enabled command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-is-enabled",
+ "markdownDescription": "Denies the is_enabled command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the toggle command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-toggle",
+ "markdownDescription": "Enables the toggle command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the toggle command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-toggle",
+ "markdownDescription": "Denies the toggle command without any pre-configured scope."
+ },
+ {
+ "description": "This permission set configures which\ntorch features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all torch related features.\n\n\n#### This default permission set includes:\n\n- `allow-disable`\n- `allow-enable`\n- `allow-is-available`\n- `allow-is-enabled`\n- `allow-toggle`",
+ "type": "string",
+ "const": "default",
+ "markdownDescription": "This permission set configures which\ntorch features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all torch related features.\n\n\n#### This default permission set includes:\n\n- `allow-disable`\n- `allow-enable`\n- `allow-is-available`\n- `allow-is-enabled`\n- `allow-toggle`"
+ }
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugins/torch/rollup.config.js b/plugins/torch/rollup.config.js
new file mode 100644
index 000000000..1f349ec8a
--- /dev/null
+++ b/plugins/torch/rollup.config.js
@@ -0,0 +1,7 @@
+// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: MIT
+
+import { createConfig } from '../../shared/rollup.config.js'
+
+export default createConfig()
diff --git a/plugins/torch/src/error.rs b/plugins/torch/src/error.rs
new file mode 100644
index 000000000..1c716360d
--- /dev/null
+++ b/plugins/torch/src/error.rs
@@ -0,0 +1,28 @@
+// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: MIT
+
+use serde::{Serialize, ser::Serializer};
+
+/// Alias for the result type returned by this crate's functions.
+pub type Result = std::result::Result;
+
+/// The error type returned by this crate's APIs. Serialized as its [`Display`](std::fmt::Display)
+/// string when it crosses the IPC boundary.
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ /// Failed to run a command on the mobile plugin implementation (Kotlin on Android, Swift on
+ /// iOS). This includes the native side rejecting the call, e.g. because the device has no
+ /// torch or the camera is held by another app.
+ #[error(transparent)]
+ PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError),
+}
+
+impl Serialize for Error {
+ fn serialize(&self, serializer: S) -> std::result::Result
+ where
+ S: Serializer,
+ {
+ serializer.serialize_str(self.to_string().as_ref())
+ }
+}
diff --git a/plugins/torch/src/lib.rs b/plugins/torch/src/lib.rs
new file mode 100644
index 000000000..0a897df79
--- /dev/null
+++ b/plugins/torch/src/lib.rs
@@ -0,0 +1,117 @@
+// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-License-Identifier: MIT
+
+//! Control the device flashlight (torch).
+//!
+//! - Supported platforms: Android and iOS.
+//!
+//! On Android the torch keeps working while the
+//! [barcode scanner](https://docs.rs/tauri-plugin-barcode-scanner) plugin holds the camera.
+
+#![cfg(mobile)]
+
+use serde::Deserialize;
+use tauri::{
+ Manager, Runtime,
+ plugin::{Builder, PluginHandle, TauriPlugin},
+};
+
+mod error;
+
+pub use error::{Error, Result};
+
+#[cfg(target_os = "android")]
+const PLUGIN_IDENTIFIER: &str = "app.tauri.torch";
+
+#[cfg(target_os = "ios")]
+tauri::ios_plugin_binding!(init_plugin_torch);
+
+#[derive(Deserialize)]
+struct AvailableResponse {
+ available: bool,
+}
+
+#[derive(Deserialize)]
+struct EnabledResponse {
+ enabled: bool,
+}
+
+/// Access to the torch APIs.
+pub struct Torch(PluginHandle);
+
+impl Torch {
+ /// Turns the torch on.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`Error::PluginInvoke`] if the device has no torch, the torch is temporarily
+ /// unavailable (e.g. the device is overheating) or the camera is held by another app.
+ pub fn enable(&self) -> Result<()> {
+ self.0.run_mobile_plugin("enable", ()).map_err(Into::into)
+ }
+
+ /// Turns the torch off.
+ ///
+ /// # Errors
+ ///
+ /// Same as [`Self::enable`].
+ pub fn disable(&self) -> Result<()> {
+ self.0.run_mobile_plugin("disable", ()).map_err(Into::into)
+ }
+
+ /// Flips the torch and returns its new state (`true` when it is now on).
+ ///
+ /// # Errors
+ ///
+ /// Same as [`Self::enable`].
+ pub fn toggle(&self) -> Result {
+ self.0
+ .run_mobile_plugin::("toggle", ())
+ .map(|r| r.enabled)
+ .map_err(Into::into)
+ }
+
+ /// Whether the device has a torch.
+ pub fn is_available(&self) -> Result {
+ self.0
+ .run_mobile_plugin::("isAvailable", ())
+ .map(|r| r.available)
+ .map_err(Into::into)
+ }
+
+ /// Whether the torch is currently on. Reads the hardware state, so it also reflects the torch
+ /// being turned off by the system or another app.
+ pub fn is_enabled(&self) -> Result {
+ self.0
+ .run_mobile_plugin::("isEnabled", ())
+ .map(|r| r.enabled)
+ .map_err(Into::into)
+ }
+}
+
+/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the torch APIs.
+pub trait TorchExt {
+ /// Returns the [`Torch`] instance managed by the app.
+ fn torch(&self) -> &Torch;
+}
+
+impl> crate::TorchExt for T {
+ fn torch(&self) -> &Torch {
+ self.state::>().inner()
+ }
+}
+
+/// Initializes the plugin.
+pub fn init() -> TauriPlugin {
+ Builder::new("torch")
+ .setup(|app, api| {
+ #[cfg(target_os = "android")]
+ let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "TorchPlugin")?;
+ #[cfg(target_os = "ios")]
+ let handle = api.register_ios_plugin(init_plugin_torch)?;
+ app.manage(Torch(handle));
+ Ok(())
+ })
+ .build()
+}
diff --git a/plugins/torch/tsconfig.json b/plugins/torch/tsconfig.json
new file mode 100644
index 000000000..437446880
--- /dev/null
+++ b/plugins/torch/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "rootDir": "guest-js"
+ },
+ "include": ["guest-js/*.ts"]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9c4ed83de..9af2c111b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -223,6 +223,9 @@ importers:
'@tauri-apps/plugin-store':
specifier: workspace:*
version: link:../../plugins/store
+ '@tauri-apps/plugin-torch':
+ specifier: workspace:*
+ version: link:../../plugins/torch
'@tauri-apps/plugin-updater':
specifier: workspace:*
version: link:../../plugins/updater
@@ -575,6 +578,12 @@ importers:
specifier: ^2.12.0
version: 2.12.1
+ plugins/torch:
+ dependencies:
+ '@tauri-apps/api':
+ specifier: ^2.12.0
+ version: 2.12.1
+
plugins/updater:
dependencies:
'@tauri-apps/api':