mirror of
https://github.com/tauri-apps/plugins-workspace.git
synced 2026-10-16 23:00:54 +02:00
feat: add torch plugin for iOS and Android (#3551)
* feat(barcode-scanner): add torch toggle * feat: torch plugin * fix --------- Co-authored-by: Lucas Nogueira <lucas@tauri.app>
This commit is contained in:
1 parent
c91a9e6af5
commit
d80b1be257
48 files changed
+1861
-4
No files matched your search
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"barcode-scanner": patch
|
||||
"barcode-scanner-js": patch
|
||||
---
|
||||
|
||||
On Android, expose the camera bound by an active scan so the torch plugin can turn the flash on and off during a scan.
|
||||
+12
-2
@@ -82,7 +82,8 @@
|
||||
"store",
|
||||
"updater",
|
||||
"geolocation",
|
||||
"haptics"
|
||||
"haptics",
|
||||
"torch"
|
||||
]
|
||||
},
|
||||
"api-example-js": {
|
||||
@@ -106,7 +107,8 @@
|
||||
"process-js",
|
||||
"shell-js",
|
||||
"store-js",
|
||||
"updater-js"
|
||||
"updater-js",
|
||||
"torch-js"
|
||||
],
|
||||
"postversion": "pnpm install --no-frozen-lockfile"
|
||||
},
|
||||
@@ -327,6 +329,14 @@
|
||||
"path": "./plugins/updater",
|
||||
"manager": "javascript"
|
||||
},
|
||||
"torch": {
|
||||
"path": "./plugins/torch",
|
||||
"manager": "rust"
|
||||
},
|
||||
"torch-js": {
|
||||
"path": "./plugins/torch",
|
||||
"manager": "javascript"
|
||||
},
|
||||
"upload": {
|
||||
"path": "./plugins/upload",
|
||||
"manager": "rust"
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"torch": minor:feat
|
||||
"torch-js": minor:feat
|
||||
---
|
||||
|
||||
Initial release of the torch plugin: turn the device flashlight on and off, toggle it, and query whether it is available and enabled on Android and iOS. On Android it also works while a barcode scanner scan holds the camera.
|
||||
Generated
+13
@@ -241,6 +241,7 @@ dependencies = [
|
||||
"tauri-plugin-shell",
|
||||
"tauri-plugin-sql",
|
||||
"tauri-plugin-store",
|
||||
"tauri-plugin-torch",
|
||||
"tauri-plugin-updater",
|
||||
"tauri-plugin-upload",
|
||||
"tauri-plugin-websocket",
|
||||
@@ -7119,6 +7120,18 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-torch"
|
||||
version = "2.0.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"tauri-plugin",
|
||||
"thiserror 2.0.12",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-updater"
|
||||
version = "2.13.3"
|
||||
|
||||
@@ -32,6 +32,7 @@ This repo and all plugins require a Rust version of at least **1.90**
|
||||
| [sql](plugins/sql) | Interface with SQL databases. | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [store](plugins/store) | Persistent key value storage. | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [stronghold](plugins/stronghold) | Encrypted, secure database. | ✅ | ✅ | ✅ | ? | ? |
|
||||
| [torch](plugins/torch) | Control the device flashlight (torch) on Android and iOS. | ? | ? | ? | ✅ | ✅ |
|
||||
| [updater](plugins/updater) | In-app updates for Tauri applications. | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| [upload](plugins/upload) | Tauri plugin for file uploads through HTTP. | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [websocket](plugins/websocket) | Open a WebSocket connection using a Rust client in JS. | ✅ | ✅ | ✅ | ? | ? |
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
"@tauri-apps/plugin-shell": "workspace:*",
|
||||
"@tauri-apps/plugin-sql": "workspace:*",
|
||||
"@tauri-apps/plugin-store": "workspace:*",
|
||||
"@tauri-apps/plugin-torch": "workspace:*",
|
||||
"@tauri-apps/plugin-updater": "workspace:*",
|
||||
"@tauri-apps/plugin-upload": "workspace:*",
|
||||
"@tauri-apps/plugin-websocket": "workspace:*",
|
||||
|
||||
@@ -79,6 +79,7 @@ tauri-plugin-barcode-scanner = { path = "../../../plugins/barcode-scanner/", ver
|
||||
tauri-plugin-nfc = { path = "../../../plugins/nfc", version = "2.4.2" }
|
||||
tauri-plugin-geolocation = { path = "../../../plugins/geolocation/", version = "2.4.2" }
|
||||
tauri-plugin-haptics = { path = "../../../plugins/haptics/", version = "2.4.2" }
|
||||
tauri-plugin-torch = { path = "../../../plugins/torch/", version = "2.0.0" }
|
||||
|
||||
[features]
|
||||
# Enables the WebDriver automation bridge; set by the e2e suite's build (packages/api-e2e).
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"haptics:allow-impact-feedback",
|
||||
"haptics:allow-notification-feedback",
|
||||
"haptics:allow-selection-feedback",
|
||||
"haptics:allow-vibrate"
|
||||
"haptics:allow-vibrate",
|
||||
"torch:default"
|
||||
]
|
||||
}
|
||||
@@ -95,6 +95,7 @@ pub fn run() {
|
||||
app.handle().plugin(tauri_plugin_nfc::init())?;
|
||||
app.handle().plugin(tauri_plugin_geolocation::init())?;
|
||||
app.handle().plugin(tauri_plugin_haptics::init())?;
|
||||
app.handle().plugin(tauri_plugin_torch::init())?;
|
||||
}
|
||||
|
||||
let mut webview_window_builder =
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
import Biometric from './views/Biometric.svelte'
|
||||
import Geolocation from './views/Geolocation.svelte'
|
||||
import Haptics from './views/Haptics.svelte'
|
||||
import Torch from './views/Torch.svelte'
|
||||
import Nfc from './views/Nfc.svelte'
|
||||
import Autostart from './views/Autostart.svelte'
|
||||
import DeepLink from './views/DeepLink.svelte'
|
||||
@@ -185,6 +186,11 @@
|
||||
label: 'Haptics',
|
||||
component: Haptics,
|
||||
icon: 'i-ph-vibrate'
|
||||
},
|
||||
isMobile && {
|
||||
label: 'Torch',
|
||||
component: Torch,
|
||||
icon: 'i-ph-flashlight'
|
||||
}
|
||||
].filter(Boolean) as {
|
||||
label: string
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
Format,
|
||||
cancel
|
||||
} from '@tauri-apps/plugin-barcode-scanner'
|
||||
import { toggle as toggleTorch } from '@tauri-apps/plugin-torch'
|
||||
|
||||
export let onMessage
|
||||
|
||||
@@ -35,6 +36,12 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleScanTorch() {
|
||||
toggleTorch()
|
||||
.then((on) => onMessage(`torch ${on ? 'on' : 'off'}`))
|
||||
.catch(onMessage)
|
||||
}
|
||||
|
||||
async function cancelScan() {
|
||||
await cancel()
|
||||
scanning = false
|
||||
@@ -67,6 +74,9 @@
|
||||
<p>Aim your camera at a QR code</p>
|
||||
<button class="btn" type="button" on:click={cancelScan}>Cancel</button
|
||||
>
|
||||
<button class="btn" type="button" on:click={toggleScanTorch}
|
||||
>Torch</button
|
||||
>
|
||||
</div>
|
||||
<div class="square surround-cover">
|
||||
<div class="barcode-scanner--area--outer surround-cover">
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<script>
|
||||
import { onMount } from 'svelte'
|
||||
import {
|
||||
enable,
|
||||
disable,
|
||||
toggle,
|
||||
isAvailable,
|
||||
isEnabled
|
||||
} from '@tauri-apps/plugin-torch'
|
||||
|
||||
export let onMessage
|
||||
|
||||
let available = null
|
||||
let enabled = null
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
available = await isAvailable()
|
||||
enabled = await isEnabled()
|
||||
} catch (e) {
|
||||
onMessage(e)
|
||||
}
|
||||
}
|
||||
|
||||
function run(action) {
|
||||
return () =>
|
||||
action()
|
||||
.then((res) => onMessage(res ?? 'ok'))
|
||||
.catch(onMessage)
|
||||
.finally(refresh)
|
||||
}
|
||||
|
||||
onMount(refresh)
|
||||
</script>
|
||||
|
||||
<div>
|
||||
<p>
|
||||
Available: <b>{available ?? '...'}</b> / Enabled:
|
||||
<b>{enabled ?? '...'}</b>
|
||||
</p>
|
||||
|
||||
<button class="btn" id="torch-enable" on:click={run(enable)}>enable</button>
|
||||
<button class="btn" id="torch-disable" on:click={run(disable)}
|
||||
>disable</button
|
||||
>
|
||||
<button class="btn" id="torch-toggle" on:click={run(toggle)}>toggle</button>
|
||||
<button class="btn" id="torch-refresh" on:click={refresh}>refresh state</button
|
||||
>
|
||||
</div>
|
||||
|
||||
<br />
|
||||
|
||||
<p>
|
||||
The torch can also be toggled while scanning from the Scanner page, which on
|
||||
Android goes through the barcode scanner's camera.
|
||||
</p>
|
||||
@@ -18,4 +18,8 @@
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
#-renamesourcefileattribute SourceFile
|
||||
# Looked up through reflection by the torch plugin.
|
||||
-keep class app.tauri.barcodescanner.BarcodeScannerPlugin {
|
||||
public static androidx.camera.core.Camera getActiveCamera();
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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"] }
|
||||
@@ -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: <text>Tauri is a rust project that enables developers to make secure
|
||||
and small desktop applications using a web frontend.
|
||||
</text>
|
||||
PackageComment: <text>The package includes the following libraries; see
|
||||
Relationship information.
|
||||
</text>
|
||||
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
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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:
|
||||
|
||||
<!-- Add the branch for installations using git! -->
|
||||
|
||||
```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
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://crabnebula.dev" target="_blank">
|
||||
<img src="https://github.com/tauri-apps/plugins-workspace/raw/v2/.github/sponsors/crabnebula.svg" alt="CrabNebula" width="283">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
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.
|
||||
@@ -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).
|
||||
@@ -0,0 +1,2 @@
|
||||
/build
|
||||
/.tauri
|
||||
@@ -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"))
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,2 @@
|
||||
include ':tauri-android'
|
||||
project(':tauri-android').projectDir = new File('./.tauri/tauri-api')
|
||||
@@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
</manifest>
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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__})}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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<void> {
|
||||
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<void> {
|
||||
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<boolean> {
|
||||
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<boolean> {
|
||||
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<boolean> {
|
||||
return await invoke<{ enabled: boolean }>('plugin:torch|is_enabled').then(
|
||||
(r) => r.enabled
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
.DS_Store
|
||||
/.build
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
xcuserdata/
|
||||
DerivedData/
|
||||
.swiftpm/config/registries.json
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
.netrc
|
||||
Package.resolved
|
||||
@@ -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")
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,3 @@
|
||||
# Tauri Plugin Torch
|
||||
|
||||
A description of this package.
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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"]
|
||||
@@ -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"]
|
||||
@@ -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"]
|
||||
@@ -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"]
|
||||
@@ -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"]
|
||||
@@ -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
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Identifier</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`torch:allow-disable`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the disable command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`torch:deny-disable`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the disable command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`torch:allow-enable`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the enable command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`torch:deny-enable`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the enable command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`torch:allow-is-available`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the is_available command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`torch:deny-is-available`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the is_available command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`torch:allow-is-enabled`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the is_enabled command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`torch:deny-is-enabled`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the is_enabled command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`torch:allow-toggle`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the toggle command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`torch:deny-toggle`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the toggle command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
@@ -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",
|
||||
]
|
||||
@@ -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 `<h4>` 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 `<h4>` 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`"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// 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<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(self.to_string().as_ref())
|
||||
}
|
||||
}
|
||||
@@ -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<R: Runtime>(PluginHandle<R>);
|
||||
|
||||
impl<R: Runtime> Torch<R> {
|
||||
/// 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<bool> {
|
||||
self.0
|
||||
.run_mobile_plugin::<EnabledResponse>("toggle", ())
|
||||
.map(|r| r.enabled)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Whether the device has a torch.
|
||||
pub fn is_available(&self) -> Result<bool> {
|
||||
self.0
|
||||
.run_mobile_plugin::<AvailableResponse>("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<bool> {
|
||||
self.0
|
||||
.run_mobile_plugin::<EnabledResponse>("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<R: Runtime> {
|
||||
/// Returns the [`Torch`] instance managed by the app.
|
||||
fn torch(&self) -> &Torch<R>;
|
||||
}
|
||||
|
||||
impl<R: Runtime, T: Manager<R>> crate::TorchExt<R> for T {
|
||||
fn torch(&self) -> &Torch<R> {
|
||||
self.state::<Torch<R>>().inner()
|
||||
}
|
||||
}
|
||||
|
||||
/// Initializes the plugin.
|
||||
pub fn init<R: Runtime>() -> TauriPlugin<R> {
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "guest-js"
|
||||
},
|
||||
"include": ["guest-js/*.ts"]
|
||||
}
|
||||
Generated
+9
@@ -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':
|
||||
|
||||
Reference in new issue
Block a user