feat: Add geolocation and haptics plugins (#1599)

* init geolocation plugin

* ios impl (w/o js api)

* generate ts api

* use newer tauri commit

* add temporary postinstall

* include src in files

* guest-js

* just ship dist-js for now

* fix watcher

* fix android compile error

* fix android build for real

* fix heading type

* initial getCurrentPosition android impl (wip)

* prevent panics if errors (strings) are sent over the channel

* Add android watchPosition implementation

* init haptics plugin (android)

* ios and new apis (ANDROID IS LIKELY BROKEN - MAY NOT EVEN COMPILE)

* use tauri-specta that accounts for raw fn arg idents

* add complete android support (it's not working great due to random soft-/hardware support)

* fix(haptics): Fix the NotificationFeedbackType::Success and Version (#1)

* Fix success feedback and version

* Apply suggestions from code review

* Update package.json

---------

Co-authored-by: Fabian-Lars <118197967+FabianLars-crabnebula@users.noreply.github.com>

* android: improve permission callback handling

* keep track of ongoing perms requests

* rebuild

* license headers

* rm sqlite feat

* fmt

* what diff u talkin bout?

* ignore dist-js again

* fix audits

* dedupe api.js

* clippy

* changefiles

* readmes

* clean up todos

* rm dsstore

* rm wrong feats

* mirror

* covector

* rebuild

* ios requires the wry feature

* lint

* update lock

---------

Co-authored-by: fabianlars <fabianlars@fabianlars.de>
Co-authored-by: Brendan Allan <brendonovich@outlook.com>
Co-authored-by: Naman Garg <155433377+naman-crabnebula@users.noreply.github.com>
Co-authored-by: Lucas Nogueira <lucas@crabnebula.dev>
pull/1619/head
Fabian-Lars 10 months ago committed by GitHub
parent 34df132fb1
commit 9606089b2a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -174,6 +174,14 @@
"path": "./plugins/dialog",
"manager": "javascript"
},
"geolocation": {
"path": "./plugins/geolocation",
"manager": "rust"
},
"geolocation-js": {
"path": "./plugins/geolocation",
"manager": "javascript"
},
"global-shortcut": {
"path": "./plugins/global-shortcut",
"manager": "rust"
@ -182,6 +190,14 @@
"path": "./plugins/global-shortcut",
"manager": "javascript"
},
"haptics": {
"path": "./plugins/haptics",
"manager": "rust"
},
"haptics-js": {
"path": "./plugins/haptics",
"manager": "javascript"
},
"http": {
"path": "./plugins/http",
"manager": "rust",

@ -0,0 +1,6 @@
---
"geolocation": major
"geolocation-js": major
---
Initial release.

@ -0,0 +1,6 @@
---
"haptics": major
"haptics-js": major
---
Initial release.

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

@ -49,10 +49,18 @@ jobs:
- .github/workflows/check-generated-files.yml
- plugins/fs/guest-js/**
- plugins/fs/src/api-iife.js
geolocation:
- .github/workflows/check-generated-files.yml
- plugins/geolocation/guest-js/**
- plugins/geolocation/src/api-iife.js
global-shortcut:
- .github/workflows/check-generated-files.yml
- plugins/global-shortcut/guest-js/**
- plugins/global-shortcut/src/api-iife.js
haptics:
- .github/workflows/check-generated-files.yml
- plugins/haptics/guest-js/**
- plugins/haptics/src/api-iife.js
http:
- .github/workflows/check-generated-files.yml
- plugins/http/guest-js/**

@ -63,9 +63,15 @@ jobs:
tauri-plugin-fs:
- .github/workflows/lint-rust.yml
- plugins/fs/**
tauri-plugin-geolocation:
- .github/workflows/lint-rust.yml
- plugins/geolocation/**
tauri-plugin-global-shortcut:
- .github/workflows/lint-rust.yml
- plugins/global-shortcut/**
tauri-plugin-haptics:
- .github/workflows/lint-rust.yml
- plugins/haptics/**
tauri-plugin-http:
- .github/workflows/lint-rust.yml
- plugins/http/**

@ -73,10 +73,18 @@ jobs:
- .github/workflows/test-rust.yml
- Cargo.toml
- plugins/fs/**
tauri-plugin-geolocation:
- .github/workflows/test-rust.yml
- Cargo.toml
- plugins/geolocation/**
tauri-plugin-global-shortcut:
- .github/workflows/test-rust.yml
- Cargo.toml
- plugins/global-shortcut/**
tauri-plugin-haptics:
- .github/workflows/test-rust.yml
- Cargo.toml
- plugins/haptics/**
tauri-plugin-http:
- .github/workflows/test-rust.yml
- Cargo.toml

@ -5,5 +5,6 @@ then
echo "working directory is clean"
else
echo "found diff"
git diff --name-status HEAD
exit 1
fi

119
Cargo.lock generated

@ -2,6 +2,12 @@
# It is not intended for manual editing.
version = 3
[[package]]
name = "Inflector"
version = "0.11.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3"
[[package]]
name = "addr2line"
version = "0.22.0"
@ -635,7 +641,7 @@ version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
dependencies = [
"digest 0.10.7",
"digest",
]
[[package]]
@ -1391,19 +1397,6 @@ dependencies = [
"cipher",
]
[[package]]
name = "curve25519-dalek"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b9fdf9972b2bd6af2d913799d9ebc165ea4d2e65878e329d9c6b372c4491b61"
dependencies = [
"byteorder",
"digest 0.9.0",
"rand_core 0.5.1",
"subtle",
"zeroize",
]
[[package]]
name = "curve25519-dalek"
version = "4.1.3"
@ -1413,7 +1406,7 @@ dependencies = [
"cfg-if",
"cpufeatures",
"curve25519-dalek-derive",
"digest 0.10.7",
"digest",
"fiat-crypto",
"rustc_version",
"subtle",
@ -1561,15 +1554,6 @@ dependencies = [
"nom",
]
[[package]]
name = "digest"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066"
dependencies = [
"generic-array",
]
[[package]]
name = "digest"
version = "0.10.7"
@ -1742,7 +1726,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
dependencies = [
"der",
"digest 0.10.7",
"digest",
"elliptic-curve",
"rfc6979",
"signature",
@ -1764,7 +1748,7 @@ version = "4.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d9ce6874da5d4415896cd45ffbc4d1cfc0c4f9c079427bd870742c30f2f65a9"
dependencies = [
"curve25519-dalek 4.1.3",
"curve25519-dalek",
"ed25519",
"hashbrown 0.14.5",
"hex",
@ -1790,7 +1774,7 @@ checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
dependencies = [
"base16ct",
"crypto-bigint",
"digest 0.10.7",
"digest",
"ff",
"generic-array",
"group",
@ -2706,7 +2690,7 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest 0.10.7",
"digest",
]
[[package]]
@ -3022,8 +3006,7 @@ dependencies = [
[[package]]
name = "iota-crypto"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5db0e2d85e258d6d0db66f4a6bf1e8bdf5b10c3353aa87d98b168778d13fdc1"
source = "git+https://github.com/iotaledger/crypto.rs?rev=489aa0e7936d0e491503f778a83cfc6ed1b28fe7#489aa0e7936d0e491503f778a83cfc6ed1b28fe7"
dependencies = [
"aead",
"aes",
@ -3033,8 +3016,8 @@ dependencies = [
"blake2",
"chacha20poly1305",
"cipher",
"curve25519-dalek 3.2.0",
"digest 0.10.7",
"curve25519-dalek",
"digest",
"ed25519-zebra",
"generic-array",
"getrandom 0.2.15",
@ -3521,7 +3504,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
"cfg-if",
"digest 0.10.7",
"digest",
]
[[package]]
@ -4201,7 +4184,7 @@ version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
dependencies = [
"digest 0.10.7",
"digest",
"hmac",
]
@ -5049,7 +5032,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d0e5124fcb30e76a7e79bfee683a2746db83784b86289f6251b54b7950a0dfc"
dependencies = [
"const-oid",
"digest 0.10.7",
"digest",
"num-bigint-dig",
"num-integer",
"num-traits",
@ -5574,7 +5557,7 @@ checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
dependencies = [
"cfg-if",
"cpufeatures",
"digest 0.10.7",
"digest",
]
[[package]]
@ -5585,7 +5568,7 @@ checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8"
dependencies = [
"cfg-if",
"cpufeatures",
"digest 0.10.7",
"digest",
]
[[package]]
@ -5622,7 +5605,7 @@ version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
dependencies = [
"digest 0.10.7",
"digest",
"rand_core 0.6.4",
]
@ -5733,6 +5716,29 @@ dependencies = [
"system-deps",
]
[[package]]
name = "specta"
version = "2.0.0-rc.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fd9fd8ec58ec895d2e947a7b431b5c8d2218956a1e378bbfdc3b7414109e2c5"
dependencies = [
"paste",
"specta-macros",
"thiserror",
]
[[package]]
name = "specta-macros"
version = "2.0.0-rc.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "649713524bd94bb77336b3d2924e3686a88de3cea780a57d45051923d5a5add4"
dependencies = [
"Inflector",
"proc-macro2",
"quote",
"syn 2.0.72",
]
[[package]]
name = "spin"
version = "0.9.8"
@ -5869,7 +5875,7 @@ dependencies = [
"byteorder",
"bytes",
"crc",
"digest 0.10.7",
"digest",
"dotenvy",
"either",
"futures-channel",
@ -6291,6 +6297,7 @@ dependencies = [
"serde_json",
"serde_repr",
"serialize-to-javascript",
"specta",
"state",
"swift-rs",
"tauri-build",
@ -6533,6 +6540,19 @@ dependencies = [
"uuid",
]
[[package]]
name = "tauri-plugin-geolocation"
version = "1.0.0"
dependencies = [
"log",
"serde",
"serde_json",
"specta",
"tauri",
"tauri-plugin",
"thiserror",
]
[[package]]
name = "tauri-plugin-global-shortcut"
version = "2.0.0-beta.9"
@ -6546,6 +6566,19 @@ dependencies = [
"thiserror",
]
[[package]]
name = "tauri-plugin-haptics"
version = "2.0.0-beta.0"
dependencies = [
"log",
"serde",
"serde_json",
"specta",
"tauri",
"tauri-plugin",
"thiserror",
]
[[package]]
name = "tauri-plugin-http"
version = "2.0.0-beta.13"
@ -8488,12 +8521,12 @@ checksum = "ec107c4503ea0b4a98ef47356329af139c0a4f7750e621cf2973cd3385ebcb3d"
[[package]]
name = "x25519-dalek"
version = "1.1.1"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a0c105152107e3b96f6a00a65e86ce82d9b125230e1c4302940eca58ff71f4f"
checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
dependencies = [
"curve25519-dalek 3.2.0",
"rand_core 0.5.1",
"curve25519-dalek",
"rand_core 0.6.4",
"zeroize",
]

@ -19,6 +19,8 @@ thiserror = "1"
url = "2"
schemars = "0.8"
dunce = "1"
specta = "=2.0.0-rc.16"
#tauri-specta = "=2.0.0-rc.11"
[workspace.package]
edition = "2021"
@ -34,3 +36,6 @@ codegen-units = 1
lto = true
incremental = false
opt-level = "s"
[patch.crates-io]
iota-crypto = { git = "https://github.com/iotaledger/crypto.rs", rev = "489aa0e7936d0e491503f778a83cfc6ed1b28fe7" }

@ -20,6 +20,7 @@ export default tseslint.config(
"**/init-iife.js",
"**/init.js",
"**/rollup.config.js",
"**/bindings.ts",
".scripts",
"eslint.config.js",
],

@ -31,12 +31,5 @@
},
"engines": {
"pnpm": "^9.0.0"
},
"pnpm": {
"auditConfig": {
"ignoreCves": [
"CVE-2023-46115"
]
}
}
}

@ -0,0 +1 @@
/.tauri

@ -0,0 +1,26 @@
[package]
name = "tauri-plugin-geolocation"
version = "1.0.0"
edition = { workspace = true }
authors = { workspace = true }
license = { workspace = true }
repository = { workspace = true }
links = "tauri-plugin-geolocation"
[package.metadata.docs.rs]
rustc-args = ["--cfg", "docsrs"]
rustdoc-args = ["--cfg", "docsrs"]
[build-dependencies]
tauri-plugin = { workspace = true, features = ["build"] }
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
tauri = { workspace = true, features = ["specta"] }
log = { workspace = true }
thiserror = { workspace = true }
specta = { 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,145 @@
![geolocation](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/geolocation/banner.png)
This plugin provides APIs for getting and tracking the device's current position, including information about altitude, heading, and speed (if available).
## Install
_This plugin requires a Rust version of at least **1.75**_
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-geolocation = "2.0.0-beta"
# alternatively with Git:
tauri-plugin-geolocation = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
```
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
> Note: Since most JavaScript package managers are unable to install packages from git monorepos we provide read-only mirrors of each plugin. This makes installation option 2 more ergonomic to use.
<!-- Add the branch for installations using git! -->
```sh
pnpm add @tauri-apps/plugin-geolocation
# or
npm add @tauri-apps/plugin-geolocation
# or
yarn add @tauri-apps/plugin-geolocation
# alternatively with Git:
pnpm add https://github.com/tauri-apps/tauri-plugin-geolocation#v2
# or
npm add https://github.com/tauri-apps/tauri-plugin-geolocation#v2
# or
yarn add https://github.com/tauri-apps/tauri-plugin-geolocation#v2
```
## Setting up
### iOS
Apple requires privacy descriptions to be specified in `Info.plist` for location information:
- `NSLocationWhenInUseDescription`
### Android
This plugin automatically adds the following permissions to your `AndroidManifest.xml` file:
```xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
```
If your app requires GPS functionality to function, **you** should add the following to your `AndroidManifest.xml` file:
```xml
<uses-feature android:name="android.hardware.gps" android:required="true" />
```
The Google Play Store uses this property to decide whether it should show the app to devices without GPS capabilities.
## Usage
First you need to register the core plugin with Tauri:
`src-tauri/src/main.rs`
```rust
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_geolocation::init())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
```
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
```javascript
import { getCurrentPosition, watchPosition } from "@tauri-apps/plugin-log";
const pos = await getCurrentPosition();
await watchPosition(
{ enableHighAccuracy: true, timeout: 10000, maximumAge: 0 },
(pos) => {
console.log(pos);
}
);
```
## Contributing
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
## Contributed By
<table>
<tbody>
<tr>
<td align="center" valign="middle">
<a href="https://crabnebula.dev" target="_blank">
<img src="contributors/crabnebula.svg" alt="CrabNebula" width="283">
</a>
</td>
<td align="center" valign="middle">
<a href="https://rescue.co" target="_blank">
<img src="contributors/rescue.png" alt="Rescue.co" width="283" height="90">
</a>
</td>
</tr>
</tbody>
</table>
## 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,46 @@
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "app.tauri.geolocation"
compileSdk = 34
defaultConfig {
minSdk = 24
targetSdk = 34
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles("consumer-rules.pro")
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "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.google.android.gms:play-services-location:21.3.0")
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,28 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
package app.tauri.geolocation
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("app.tauri.geolocation", appContext.packageName)
}
}

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- <uses-feature android:name="android.hardware.gps" android:required="true" /> -->
</manifest>

@ -0,0 +1,148 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
package app.tauri.geolocation
import android.annotation.SuppressLint
import android.content.Context
import android.location.Location
import android.location.LocationManager
import android.os.SystemClock
import androidx.core.location.LocationManagerCompat
import app.tauri.Logger
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.Priority
public class Geolocation(private val context: Context) {
private var fusedLocationClient: FusedLocationProviderClient? = null
private var locationCallback: LocationCallback? = null
fun isLocationServicesEnabled(): Boolean {
val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
return LocationManagerCompat.isLocationEnabled(lm)
}
@SuppressWarnings("MissingPermission")
fun sendLocation(enableHighAccuracy: Boolean, successCallback: (location: Location) -> Unit, errorCallback: (error: String) -> Unit) {
val resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context);
if (resultCode == ConnectionResult.SUCCESS) {
val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (this.isLocationServicesEnabled()) {
var networkEnabled = false
try {
networkEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
} catch (_: Exception) {
Logger.error("isProviderEnabled failed")
}
val lowPrio = if (networkEnabled) Priority.PRIORITY_BALANCED_POWER_ACCURACY else Priority.PRIORITY_LOW_POWER
val prio = if (enableHighAccuracy) Priority.PRIORITY_HIGH_ACCURACY else lowPrio
Logger.error(prio.toString())
LocationServices
.getFusedLocationProviderClient(context)
.getCurrentLocation(prio, null)
.addOnFailureListener { e -> e.message?.let { errorCallback(it) } }
.addOnSuccessListener { location ->
if (location == null) {
errorCallback("Location unavailable.")
} else {
successCallback(location)
}
}
} else {
errorCallback("Location disabled.")
}
} else {
errorCallback("Google Play Services unavailable.")
}
}
@SuppressLint("MissingPermission")
fun requestLocationUpdates(enableHighAccuracy: Boolean, timeout: Long, successCallback: (location: Location) -> Unit, errorCallback: (error: String) -> Unit) {
val resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context);
if (resultCode == ConnectionResult.SUCCESS) {
clearLocationUpdates()
fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (this.isLocationServicesEnabled()) {
var networkEnabled = false
try {
networkEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
} catch (_: Exception) {
Logger.error("isProviderEnabled failed")
}
val lowPrio = if (networkEnabled) Priority.PRIORITY_BALANCED_POWER_ACCURACY else Priority.PRIORITY_LOW_POWER
val prio = if (enableHighAccuracy) Priority.PRIORITY_HIGH_ACCURACY else lowPrio
Logger.error(prio.toString())
val locationRequest = LocationRequest.Builder(10000)
.setMaxUpdateDelayMillis(timeout)
.setMinUpdateIntervalMillis(5000)
.setPriority(prio)
.build()
locationCallback =
object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
val lastLocation = locationResult.lastLocation
if (lastLocation == null) {
errorCallback("Location unavailable.")
} else {
successCallback(lastLocation)
}
}
}
fusedLocationClient?.requestLocationUpdates(locationRequest, locationCallback!!, null)
} else {
errorCallback("Location disabled.")
}
} else {
errorCallback("Google Play Services not available.")
}
}
fun clearLocationUpdates() {
if (locationCallback != null) {
fusedLocationClient?.removeLocationUpdates(locationCallback!!)
locationCallback = null
}
}
@SuppressLint("MissingPermission")
fun getLastLocation(maximumAge: Long): Location? {
var lastLoc: Location? = null
val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
for (provider in lm.allProviders) {
val tmpLoc = lm.getLastKnownLocation(provider)
if (tmpLoc != null) {
val locationAge = SystemClock.elapsedRealtimeNanos() - tmpLoc.elapsedRealtimeNanos
val maxAgeNano = maximumAge * 1000000L
if (locationAge <= maxAgeNano && (lastLoc == null || lastLoc.elapsedRealtimeNanos > tmpLoc.elapsedRealtimeNanos)) {
lastLoc = tmpLoc
}
}
}
return lastLoc
}
}

@ -0,0 +1,248 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
package app.tauri.geolocation
import android.Manifest
import android.app.Activity
import android.location.Location
import android.os.Build
import android.webkit.WebView
import app.tauri.Logger
import app.tauri.PermissionState
import app.tauri.annotation.Command
import app.tauri.annotation.InvokeArg
import app.tauri.annotation.Permission
import app.tauri.annotation.PermissionCallback
import app.tauri.annotation.TauriPlugin
import app.tauri.plugin.Channel
import app.tauri.plugin.Invoke
import app.tauri.plugin.JSObject
import app.tauri.plugin.Plugin
@InvokeArg
class PositionOptions {
var enableHighAccuracy: Boolean = false
var maximumAge: Long = 0
var timeout: Long = 10000
}
@InvokeArg
class WatchArgs {
var options: PositionOptions = PositionOptions()
lateinit var channel: Channel
}
@InvokeArg
class ClearWatchArgs {
var channelId: Long = 0
}
// TODO: Plugin does not ask user to enable google location services (like gmaps does)
private const val ALIAS_LOCATION: String = "location"
private const val ALIAS_COARSE_LOCATION: String = "coarseLocation"
@TauriPlugin(
permissions = [
Permission(strings = [
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
],
alias = ALIAS_LOCATION
),
Permission(strings = [
Manifest.permission.ACCESS_COARSE_LOCATION
],
alias = ALIAS_COARSE_LOCATION
)
]
)
class GeolocationPlugin(private val activity: Activity): Plugin(activity) {
private lateinit var implementation: Geolocation// = Geolocation(activity.applicationContext)
private var watchers = hashMapOf<Long, Invoke>()
// If multiple permissions get requested in quick succession not all callbacks will be fired,
// So we'll store all requests ourselves instead of using the callback argument.
private var positionRequests = mutableListOf<Invoke>()
private var watchRequests = mutableListOf<Invoke>()
// If getCurrentPosition or watchPosition are called before a prior call is done requesting permission,
// the callback will be called with denied for the prior call(s) so we keep track of them to make sure
// to only run the logic on the last request.
// TODO: Find a better solution after switching to explicit requestPermissions call - likely needs changes in Tauri
private var ongoingPermissionRequests = 0;
override fun load(webView: WebView) {
super.load(webView)
implementation = Geolocation(activity.applicationContext)
}
override fun onPause() {
super.onPause()
// Clear all location updates on pause to avoid possible background location calls
implementation.clearLocationUpdates()
}
override fun onResume() {
super.onResume()
for (watcher in watchers.values) {
startWatch(watcher)
}
}
@Command
override fun checkPermissions(invoke: Invoke) {
if (implementation.isLocationServicesEnabled()) {
super.checkPermissions(invoke)
} else {
invoke.reject("Location services are disabled.")
}
}
@Command
override fun requestPermissions(invoke: Invoke) {
if (implementation.isLocationServicesEnabled()) {
super.requestPermissions(invoke)
} else {
invoke.reject("Location services are disabled.")
}
}
@Command
fun getCurrentPosition(invoke: Invoke) {
val args = invoke.parseArgs(PositionOptions::class.java)
val alias = getAlias(args.enableHighAccuracy)
if (getPermissionState(alias) != PermissionState.GRANTED) {
Logger.error("NOT GRANTED");
this.positionRequests.add(invoke)
this.ongoingPermissionRequests += 1
requestPermissionForAlias(alias, invoke, "positionPermissionCallback")
} else {
Logger.error("GRANTED");
getPosition(invoke, args)
}
}
@PermissionCallback
private fun positionPermissionCallback(invoke: Invoke) {
Logger.error("positionPermissionCallback - ongoingRequests: " + this.ongoingPermissionRequests.toString())
this.ongoingPermissionRequests -= 1
if (this.ongoingPermissionRequests > 0) {
return
}
val pRequests = this.positionRequests.toTypedArray()
val wRequests = this.watchRequests.toTypedArray()
this.positionRequests.clear()
this.watchRequests.clear()
// TODO: capacitor only checks for coarse here
val permissionGranted = getPermissionState(ALIAS_COARSE_LOCATION) == PermissionState.GRANTED;
Logger.error("positionPermissionCallback - permissionGranted: $permissionGranted");
for (inv in pRequests) {
if (permissionGranted) {
val args = inv.parseArgs(PositionOptions::class.java)
implementation.sendLocation(args.enableHighAccuracy,
{ location -> inv.resolve(convertLocation(location)) },
{ error -> inv.reject(error) })
} else {
inv.reject("Location permission was denied.")
}
}
for (inv in wRequests) {
if (permissionGranted) {
startWatch(invoke)
} else {
inv.reject("Location permission was denied.")
}
}
}
@Command
fun watchPosition(invoke: Invoke) {
val args = invoke.parseArgs(WatchArgs::class.java)
val alias = getAlias(args.options.enableHighAccuracy)
if (getPermissionState(alias) != PermissionState.GRANTED) {
this.watchRequests.add(invoke)
this.ongoingPermissionRequests += 1
requestPermissionForAlias(alias, invoke, "positionPermissionCallback")
} else {
startWatch(invoke)
}
}
private fun startWatch(invoke: Invoke) {
val args = invoke.parseArgs(WatchArgs::class.java)
implementation.requestLocationUpdates(
args.options.enableHighAccuracy,
args.options.timeout,
{ location -> args.channel.send(convertLocation(location)) },
{ error -> args.channel.sendObject(error) })
watchers[args.channel.id] = invoke
}
@Command
fun clearWatch(invoke: Invoke) {
val args = invoke.parseArgs(ClearWatchArgs::class.java)
watchers.remove(args.channelId)
if (watchers.isEmpty()) {
implementation.clearLocationUpdates()
}
invoke.resolve()
}
private fun getPosition(invoke: Invoke, options: PositionOptions) {
val location = implementation.getLastLocation(options.maximumAge)
if (location != null) {
Logger.error("getPosition location non-null")
invoke.resolve(convertLocation(location))
} else {
Logger.error("getPosition location null")
implementation.sendLocation(options.enableHighAccuracy,
{ loc -> invoke.resolve(convertLocation(loc)) },
{ error -> invoke.reject(error) })
}
}
private fun convertLocation(location: Location): JSObject {
val ret = JSObject()
val coords = JSObject()
coords.put("latitude", location.latitude)
coords.put("longitude", location.longitude)
coords.put("accuracy", location.accuracy)
coords.put("altitude", location.altitude)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
coords.put("altitudeAccuracy", location.verticalAccuracyMeters)
}
coords.put("speed", location.speed)
coords.put("heading", location.bearing)
ret.put("timestamp", location.time)
ret.put("coords", coords)
return ret
}
private fun getAlias(enableHighAccuracy: Boolean): String {
var alias = ALIAS_LOCATION;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (!enableHighAccuracy) {
alias = ALIAS_COARSE_LOCATION;
}
}
return alias
}
}

@ -0,0 +1,21 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
package app.tauri.geolocation
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}

@ -0,0 +1 @@
if("__TAURI__"in window){var __TAURI_PLUGIN_GEOLOCATION__=function(t){"use strict";function r(t,r,e,s){if("a"===e&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof r?t!==r||!s:!r.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===e?s:"a"===e?s.call(t):s?s.value:r.get(t)}function e(t,r,e,s,o){if("function"==typeof r?t!==r||!o:!r.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r.set(t,e),e}var s,o,i,a;"function"==typeof SuppressedError&&SuppressedError;class n{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,s.set(this,(()=>{})),o.set(this,0),i.set(this,{}),this.id=function(t,r=!1){return window.__TAURI_INTERNALS__.transformCallback(t,r)}((({message:t,id:a})=>{if(a===r(this,o,"f")){e(this,o,a+1),r(this,s,"f").call(this,t);const n=Object.keys(r(this,i,"f"));if(n.length>0){let t=a+1;for(const e of n.sort()){if(parseInt(e)!==t)break;{const o=r(this,i,"f")[e];delete r(this,i,"f")[e],r(this,s,"f").call(this,o),t+=1}}e(this,o,t)}}else r(this,i,"f")[a.toString()]=t}))}set onmessage(t){e(this,s,t)}get onmessage(){return r(this,s,"f")}toJSON(){return`__CHANNEL__:${this.id}`}}async function c(t,r={},e){return window.__TAURI_INTERNALS__.invoke(t,r,e)}s=new WeakMap,o=new WeakMap,i=new WeakMap,function(t){t.WINDOW_RESIZED="tauri://resize",t.WINDOW_MOVED="tauri://move",t.WINDOW_CLOSE_REQUESTED="tauri://close-requested",t.WINDOW_DESTROYED="tauri://destroyed",t.WINDOW_FOCUS="tauri://focus",t.WINDOW_BLUR="tauri://blur",t.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",t.WINDOW_THEME_CHANGED="tauri://theme-changed",t.WINDOW_CREATED="tauri://window-created",t.WEBVIEW_CREATED="tauri://webview-created",t.DRAG_ENTER="tauri://drag-enter",t.DRAG_OVER="tauri://drag-over",t.DRAG_DROP="tauri://drag-drop",t.DRAG_LEAVE="tauri://drag-leave"}(a||(a={}));const u={async getCurrentPosition(t){try{return{status:"ok",data:await c("plugin:geolocation|get_current_position",{options:t})}}catch(t){if(t instanceof Error)throw t;return{status:"error",error:t}}},async watchPosition(t,r){try{return{status:"ok",data:await c("plugin:geolocation|watch_position",{options:t,channel:r})}}catch(t){if(t instanceof Error)throw t;return{status:"error",error:t}}},async clearWatch(t){try{return{status:"ok",data:await c("plugin:geolocation|clear_watch",{channelId:t})}}catch(t){if(t instanceof Error)throw t;return{status:"error",error:t}}},async checkPermissions(){try{return{status:"ok",data:await c("plugin:geolocation|check_permissions")}}catch(t){if(t instanceof Error)throw t;return{status:"error",error:t}}},async requestPermissions(t){try{return{status:"ok",data:await c("plugin:geolocation|request_permissions",{permissions:t})}}catch(t){if(t instanceof Error)throw t;return{status:"error",error:t}}}};const{getCurrentPosition:_,clearWatch:h,checkPermissions:f,requestPermissions:w}=u;return t.checkPermissions=f,t.clearWatch=h,t.getCurrentPosition=_,t.requestPermissions=w,t.watchPosition=async function(t,r){const e=new n;return e.onmessage=r,await u.watchPosition(t,e),e.id},t}({});Object.defineProperty(window.__TAURI__,"geolocation",{value:__TAURI_PLUGIN_GEOLOCATION__})}

@ -0,0 +1,26 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
const COMMANDS: &[&str] = &[
"get_current_position",
"watch_position",
"clear_watch",
"check_permissions",
"clear_permissions",
];
fn main() {
if let Err(error) = tauri_plugin::Builder::new(COMMANDS)
.global_api_script_path("./api-iife.js")
.android_path("android")
.ios_path("ios")
.try_build()
{
println!("{error:#}");
// when building documentation for Android the plugin build result is irrelevant to the crate itself
if !(cfg!(docsrs) && std::env::var("TARGET").unwrap().contains("android")) {
std::process::exit(1);
}
}
}

@ -0,0 +1,248 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// @ts-nocheck
// This file was generated by [tauri-specta](https://github.com/oscartbeaumont/tauri-specta). Do not edit this file manually.
/** user-defined commands **/
export const commands = {
async getCurrentPosition(
options: PositionOptions | null,
): Promise<Result<Position, Error>> {
try {
return {
status: "ok",
data: await TAURI_INVOKE("plugin:geolocation|get_current_position", {
options,
}),
};
} catch (e) {
if (e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async watchPosition(
options: PositionOptions,
channel: any,
): Promise<Result<null, Error>> {
try {
return {
status: "ok",
data: await TAURI_INVOKE("plugin:geolocation|watch_position", {
options,
channel,
}),
};
} catch (e) {
if (e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async clearWatch(channelId: number): Promise<Result<null, Error>> {
try {
return {
status: "ok",
data: await TAURI_INVOKE("plugin:geolocation|clear_watch", {
channelId,
}),
};
} catch (e) {
if (e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async checkPermissions(): Promise<Result<PermissionStatus, Error>> {
try {
return {
status: "ok",
data: await TAURI_INVOKE("plugin:geolocation|check_permissions"),
};
} catch (e) {
if (e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async requestPermissions(
permissions: PermissionType[] | null,
): Promise<Result<PermissionStatus, Error>> {
try {
return {
status: "ok",
data: await TAURI_INVOKE("plugin:geolocation|request_permissions", {
permissions,
}),
};
} catch (e) {
if (e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
};
/** user-defined events **/
/* export const events = __makeEvents__<{
randomNumber: RandomNumber;
}>({
randomNumber: "plugin:geolocation:random-number",
}); */
/** user-defined statics **/
/** user-defined types **/
export type Coordinates = {
/**
* Latitude in decimal degrees.
*/
latitude: number;
/**
* Longitude in decimal degrees.
*/
longitude: number;
/**
* Accuracy level of the latitude and longitude coordinates in meters.
*/
accuracy: number;
/**
* Accuracy level of the altitude coordinate in meters, if available.
* Available on all iOS versions and on Android 8 and above.
*/
altitudeAccuracy: number | null;
/**
* The altitude the user is at, if available.
*/
altitude: number | null;
speed: number | null;
/**
* The heading the user is facing, if available.
*/
heading: number | null;
};
export type Error = never;
/**
* Permission state.
*/
export type PermissionState =
/**
* Permission access has been granted.
*/
| "granted"
/**
* Permission access has been denied.
*/
| "denied"
/**
* The end user should be prompted for permission.
*/
| "prompt";
export type PermissionStatus = {
/**
* Permission state for the location alias.
*
* On Android it requests/checks both ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION permissions.
*
* On iOS it requests/checks location permissions.
*/
location: PermissionState;
/**
* Permissions state for the coarseLoaction alias.
*
* On Android it requests/checks ACCESS_COARSE_LOCATION.
*
* On Android 12+, users can choose between Approximate location (ACCESS_COARSE_LOCATION) and Precise location (ACCESS_FINE_LOCATION).
*
* On iOS it will have the same value as the `location` alias.
*/
coarseLocation: PermissionState;
};
export type PermissionType = "location" | "coarseLocation";
export type Position = {
/**
* Creation time for these coordinates.
*/
timestamp: number;
/**
* The GPD coordinates along with the accuracy of the data.
*/
coords: Coordinates;
};
export type PositionOptions = {
/**
* High accuracy mode (such as GPS, if available)
* Will be ignored on Android 12+ if users didn't grant the ACCESS_FINE_LOCATION permission.
*/
enableHighAccuracy: boolean;
/**
* The maximum wait time in milliseconds for location updates.
* On Android the timeout gets ignored for getCurrentPosition.
* Ignored on iOS
*/
timeout: number;
/**
* The maximum age in milliseconds of a possible cached position that is acceptable to return.
* Default: 0
* Ignored on iOS
*/
maximumAge: number;
};
//export type RandomNumber = number;
/** tauri-specta globals **/
import { invoke as TAURI_INVOKE } from "@tauri-apps/api/core";
import * as TAURI_API_EVENT from "@tauri-apps/api/event";
import { type WebviewWindow as __WebviewWindow__ } from "@tauri-apps/api/webviewWindow";
type __EventObj__<T> = {
listen: (
cb: TAURI_API_EVENT.EventCallback<T>,
) => ReturnType<typeof TAURI_API_EVENT.listen<T>>;
once: (
cb: TAURI_API_EVENT.EventCallback<T>,
) => ReturnType<typeof TAURI_API_EVENT.once<T>>;
emit: T extends null
? (payload?: T) => ReturnType<typeof TAURI_API_EVENT.emit>
: (payload: T) => ReturnType<typeof TAURI_API_EVENT.emit>;
};
export type Result<T, E> =
| { status: "ok"; data: T }
| { status: "error"; error: E };
function __makeEvents__<T extends Record<string, any>>(
mappings: Record<keyof T, string>,
) {
return new Proxy(
{} as unknown as {
[K in keyof T]: __EventObj__<T[K]> & {
(handle: __WebviewWindow__): __EventObj__<T[K]>;
};
},
{
get: (_, event) => {
const name = mappings[event as keyof T];
return new Proxy((() => {}) as any, {
apply: (_, __, [window]: [__WebviewWindow__]) => ({
listen: (arg: any) => window.listen(name, arg),
once: (arg: any) => window.once(name, arg),
emit: (arg: any) => window.emit(name, arg),
}),
get: (_, command: keyof __EventObj__<any>) => {
switch (command) {
case "listen":
return (arg: any) => TAURI_API_EVENT.listen(name, arg);
case "once":
return (arg: any) => TAURI_API_EVENT.once(name, arg);
case "emit":
return (arg: any) => TAURI_API_EVENT.emit(name, arg);
}
},
});
},
},
);
}

@ -0,0 +1,37 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
/* eslint-disable @typescript-eslint/unbound-method */
import { Channel } from "@tauri-apps/api/core";
import { commands, type PositionOptions, type Position } from "./bindings";
export async function watchPosition(
options: PositionOptions,
// TODO: This can receive errors too
cb: (location: Position | string) => void,
): Promise<number> {
const channel = new Channel<Position>();
channel.onmessage = cb;
await commands.watchPosition(options, channel);
return channel.id;
}
export const {
getCurrentPosition,
clearWatch,
checkPermissions,
requestPermissions,
} = commands;
export type {
PermissionState,
PermissionStatus,
PermissionType,
Position,
PositionOptions,
Coordinates,
} from "./bindings";
// export { events };

@ -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,33 @@
// 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-geolocation",
platforms: [
.iOS(.v13),
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "tauri-plugin-geolocation",
type: .static,
targets: ["tauri-plugin-geolocation"]),
],
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-geolocation",
dependencies: [
.byName(name: "Tauri")
],
path: "Sources")
]
)

@ -0,0 +1,3 @@
# Tauri Plugin Geolocation
A description of this package.

@ -0,0 +1,246 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import SwiftRs
import Tauri
import UIKit
import WebKit
import CoreLocation
class GetPositionArgs: Decodable {
let enableHighAccuracy: Bool?
}
class WatchPositionArgs: Decodable {
let options: GetPositionArgs
let channel: Channel
}
class ClearWatchArgs: Decodable {
let channelId: UInt32
}
class GeolocationPlugin: Plugin, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
private var isUpdatingLocation: Bool = false
private var permissionRequests: [Invoke] = []
private var positionRequests: [Invoke] = []
private var watcherChannels: [Channel] = []
override init() {
super.init()
locationManager.delegate = self
}
//
// Tauri commands
//
@objc public func getCurrentPosition(_ invoke: Invoke) throws {
let args = try invoke.parseArgs(GetPositionArgs.self)
self.positionRequests.append(invoke)
DispatchQueue.main.async {
if args.enableHighAccuracy == true {
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
} else {
self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
}
// TODO: Use the authorizationStatus instance property with locationManagerDidChangeAuthorization(_:) instead.
if CLLocationManager.authorizationStatus() == .notDetermined {
self.locationManager.requestWhenInUseAuthorization()
} else {
self.locationManager.requestLocation()
}
}
}
@objc public func watchPosition(_ invoke: Invoke) throws {
let args = try invoke.parseArgs(WatchPositionArgs.self)
self.watcherChannels.append(args.channel)
DispatchQueue.main.async {
if args.options.enableHighAccuracy == true {
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
} else {
self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
}
// TODO: Use the authorizationStatus instance property with locationManagerDidChangeAuthorization(_:) instead.
if CLLocationManager.authorizationStatus() == .notDetermined {
self.locationManager.requestWhenInUseAuthorization()
} else {
self.locationManager.startUpdatingLocation()
self.isUpdatingLocation = true
}
}
invoke.resolve()
}
@objc public func clearWatch(_ invoke: Invoke) throws {
let args = try invoke.parseArgs(ClearWatchArgs.self)
self.watcherChannels = self.watcherChannels.filter { $0.id != args.channelId }
// TODO: capacitor plugin calls stopUpdating unconditionally
if self.watcherChannels.isEmpty {
self.stopUpdating()
}
invoke.resolve()
}
@objc override public func checkPermissions(_ invoke: Invoke) {
var status: String = ""
if CLLocationManager.locationServicesEnabled() {
// TODO: Use the authorizationStatus instance property with locationManagerDidChangeAuthorization(_:) instead.
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
status = "prompt"
case .restricted, .denied:
status = "denied"
case .authorizedAlways, .authorizedWhenInUse:
status = "granted"
@unknown default:
status = "prompt"
}
} else {
invoke.reject("Location services are not enabled.")
return
}
let result = ["location": status, "coarseLocation": status]
invoke.resolve(result)
}
@objc override public func requestPermissions(_ invoke: Invoke) {
if CLLocationManager.locationServicesEnabled() {
// TODO: Use the authorizationStatus instance property with locationManagerDidChangeAuthorization(_:) instead.
if CLLocationManager.authorizationStatus() == .notDetermined {
self.permissionRequests.append(invoke)
DispatchQueue.main.async {
self.locationManager.requestWhenInUseAuthorization()
}
} else {
checkPermissions(invoke)
}
} else {
invoke.reject("Location services are not enabled.")
}
}
//
// Delegate methods
//
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
Logger.error(error)
let requests = self.positionRequests + self.permissionRequests
self.positionRequests.removeAll()
self.permissionRequests.removeAll()
for request in requests {
request.reject(error.localizedDescription)
}
for channel in self.watcherChannels {
do {
try channel.send(error.localizedDescription)
} catch {
Logger.error(error)
}
}
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Respond to all getCurrentPosition() calls.
for request in self.positionRequests {
// The capacitor plugin uses locations.first but .last should be the most current one
// and i don't see a reason to use old locations
if let location = locations.last {
let result = convertLocation(location)
request.resolve(result)
} else {
request.reject("Location service returned an empty Location array.")
}
}
for channel in self.watcherChannels {
// The capacitor plugin uses locations.first but .last should be the most recent one
// and i don't see a reason to use old locations
if let location = locations.last {
let result = convertLocation(location)
do {
try channel.send(result)
} catch {
Logger.error(error)
}
} else {
do {
try channel.send("Location service returned an empty Location array.")
} catch {
Logger.error(error)
}
}
}
}
public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
let requests = self.permissionRequests
self.permissionRequests.removeAll()
for request in requests {
checkPermissions(request)
}
if !self.positionRequests.isEmpty {
self.locationManager.requestLocation()
}
if !self.watcherChannels.isEmpty && !self.isUpdatingLocation {
self.locationManager.startUpdatingLocation()
self.isUpdatingLocation = true
}
}
//
// Internal/Helper methods
//
// TODO: Why is this pub in capacitor
private func stopUpdating() {
self.locationManager.stopUpdatingLocation()
self.isUpdatingLocation = false
}
private func convertLocation(_ location: CLLocation) -> JsonObject {
var ret: JsonObject = [:]
var coords: JsonObject = [:]
coords["latitude"] = location.coordinate.latitude
coords["longitude"] = location.coordinate.longitude
coords["accuracy"] = location.horizontalAccuracy
coords["altitude"] = location.altitude
coords["altitudeAccuracy"] = location.verticalAccuracy
coords["speed"] = location.speed
coords["heading"] = location.course
ret["timestamp"] = Int((location.timestamp.timeIntervalSince1970 * 1000))
ret["coords"] = coords
return ret
}
}
@_cdecl("init_plugin_geolocation")
func initPlugin() -> Plugin {
return GeolocationPlugin()
}

@ -0,0 +1,12 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import XCTest
@testable import ExamplePlugin
final class ExamplePluginTests: XCTestCase {
func testExample() throws {
let plugin = ExamplePlugin()
}
}

@ -0,0 +1,28 @@
{
"name": "@tauri-apps/plugin-geolocation",
"version": "1.0.0",
"license": "MIT or APACHE-2.0",
"authors": [
"Tauri Programme within The Commons Conservancy"
],
"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.0.0-beta.16"
}
}

@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-check-permissions"
description = "Enables the check_permissions command without any pre-configured scope."
commands.allow = ["check_permissions"]
[[permission]]
identifier = "deny-check-permissions"
description = "Denies the check_permissions command without any pre-configured scope."
commands.deny = ["check_permissions"]

@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-clear-permissions"
description = "Enables the clear_permissions command without any pre-configured scope."
commands.allow = ["clear_permissions"]
[[permission]]
identifier = "deny-clear-permissions"
description = "Denies the clear_permissions command without any pre-configured scope."
commands.deny = ["clear_permissions"]

@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-clear-positions"
description = "Enables the clear_positions command without any pre-configured scope."
commands.allow = ["clear_positions"]
[[permission]]
identifier = "deny-clear-positions"
description = "Denies the clear_positions command without any pre-configured scope."
commands.deny = ["clear_positions"]

@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-clear-watch"
description = "Enables the clear_watch command without any pre-configured scope."
commands.allow = ["clear_watch"]
[[permission]]
identifier = "deny-clear-watch"
description = "Denies the clear_watch command without any pre-configured scope."
commands.deny = ["clear_watch"]

@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-execute"
description = "Enables the execute command without any pre-configured scope."
commands.allow = ["execute"]
[[permission]]
identifier = "deny-execute"
description = "Denies the execute command without any pre-configured scope."
commands.deny = ["execute"]

@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-get-current-position"
description = "Enables the get_current_position command without any pre-configured scope."
commands.allow = ["get_current_position"]
[[permission]]
identifier = "deny-get-current-position"
description = "Denies the get_current_position command without any pre-configured scope."
commands.deny = ["get_current_position"]

@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-watch-position"
description = "Enables the watch_position command without any pre-configured scope."
commands.allow = ["watch_position"]
[[permission]]
identifier = "deny-watch-position"
description = "Denies the watch_position command without any pre-configured scope."
commands.deny = ["watch_position"]

@ -0,0 +1,192 @@
### Permission Table
<table>
<tr>
<th>Identifier</th>
<th>Description</th>
</tr>
<tr>
<td>
`geolocation:allow-check-permissions`
</td>
<td>
Enables the check_permissions command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`geolocation:deny-check-permissions`
</td>
<td>
Denies the check_permissions command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`geolocation:allow-clear-permissions`
</td>
<td>
Enables the clear_permissions command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`geolocation:deny-clear-permissions`
</td>
<td>
Denies the clear_permissions command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`geolocation:allow-clear-positions`
</td>
<td>
Enables the clear_positions command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`geolocation:deny-clear-positions`
</td>
<td>
Denies the clear_positions command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`geolocation:allow-clear-watch`
</td>
<td>
Enables the clear_watch command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`geolocation:deny-clear-watch`
</td>
<td>
Denies the clear_watch command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`geolocation:allow-execute`
</td>
<td>
Enables the execute command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`geolocation:deny-execute`
</td>
<td>
Denies the execute command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`geolocation:allow-get-current-position`
</td>
<td>
Enables the get_current_position command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`geolocation:deny-get-current-position`
</td>
<td>
Denies the get_current_position command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`geolocation:allow-watch-position`
</td>
<td>
Enables the watch_position command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`geolocation:deny-watch-position`
</td>
<td>
Denies the watch_position command without any pre-configured scope.
</td>
</tr>
</table>

@ -0,0 +1,398 @@
{
"$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": "allow-check-permissions -> Enables the check_permissions command without any pre-configured scope.",
"type": "string",
"enum": [
"allow-check-permissions"
]
},
{
"description": "deny-check-permissions -> Denies the check_permissions command without any pre-configured scope.",
"type": "string",
"enum": [
"deny-check-permissions"
]
},
{
"description": "allow-clear-permissions -> Enables the clear_permissions command without any pre-configured scope.",
"type": "string",
"enum": [
"allow-clear-permissions"
]
},
{
"description": "deny-clear-permissions -> Denies the clear_permissions command without any pre-configured scope.",
"type": "string",
"enum": [
"deny-clear-permissions"
]
},
{
"description": "allow-clear-positions -> Enables the clear_positions command without any pre-configured scope.",
"type": "string",
"enum": [
"allow-clear-positions"
]
},
{
"description": "deny-clear-positions -> Denies the clear_positions command without any pre-configured scope.",
"type": "string",
"enum": [
"deny-clear-positions"
]
},
{
"description": "allow-clear-watch -> Enables the clear_watch command without any pre-configured scope.",
"type": "string",
"enum": [
"allow-clear-watch"
]
},
{
"description": "deny-clear-watch -> Denies the clear_watch command without any pre-configured scope.",
"type": "string",
"enum": [
"deny-clear-watch"
]
},
{
"description": "allow-execute -> Enables the execute command without any pre-configured scope.",
"type": "string",
"enum": [
"allow-execute"
]
},
{
"description": "deny-execute -> Denies the execute command without any pre-configured scope.",
"type": "string",
"enum": [
"deny-execute"
]
},
{
"description": "allow-get-current-position -> Enables the get_current_position command without any pre-configured scope.",
"type": "string",
"enum": [
"allow-get-current-position"
]
},
{
"description": "deny-get-current-position -> Denies the get_current_position command without any pre-configured scope.",
"type": "string",
"enum": [
"deny-get-current-position"
]
},
{
"description": "allow-watch-position -> Enables the watch_position command without any pre-configured scope.",
"type": "string",
"enum": [
"allow-watch-position"
]
},
{
"description": "deny-watch-position -> Denies the watch_position command without any pre-configured scope.",
"type": "string",
"enum": [
"deny-watch-position"
]
}
]
}
}
}

@ -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,47 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use tauri::{command, ipc::Channel, AppHandle, Runtime};
use crate::{GeolocationExt, PermissionStatus, PermissionType, Position, PositionOptions, Result};
#[command]
#[specta::specta]
pub(crate) async fn get_current_position<R: Runtime>(
app: AppHandle<R>,
options: Option<PositionOptions>,
) -> Result<Position> {
app.geolocation().get_current_position(options)
}
#[command]
#[specta::specta]
pub(crate) async fn watch_position<R: Runtime>(
app: AppHandle<R>,
options: PositionOptions,
channel: Channel,
) -> Result<()> {
app.geolocation().watch_position_inner(options, channel)
}
#[command]
#[specta::specta]
pub(crate) async fn clear_watch<R: Runtime>(app: AppHandle<R>, channel_id: u32) -> Result<()> {
app.geolocation().clear_watch(channel_id)
}
#[command]
#[specta::specta]
pub(crate) async fn check_permissions<R: Runtime>(app: AppHandle<R>) -> Result<PermissionStatus> {
app.geolocation().check_permissions()
}
#[command]
#[specta::specta]
pub(crate) async fn request_permissions<R: Runtime>(
app: AppHandle<R>,
permissions: Option<Vec<PermissionType>>,
) -> Result<PermissionStatus> {
app.geolocation().request_permissions(permissions)
}

@ -0,0 +1,95 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::{de::DeserializeOwned, Serialize};
use tauri::{
ipc::{Channel, InvokeBody},
plugin::PluginApi,
AppHandle, Runtime,
};
use crate::models::*;
pub fn init<R: Runtime, C: DeserializeOwned>(
app: &AppHandle<R>,
_api: PluginApi<R, C>,
) -> crate::Result<Geolocation<R>> {
Ok(Geolocation(app.clone()))
}
/// Access to the geolocation APIs.
pub struct Geolocation<R: Runtime>(AppHandle<R>);
impl<R: Runtime> Geolocation<R> {
pub fn get_current_position(
&self,
_options: Option<PositionOptions>,
) -> crate::Result<Position> {
Ok(Position::default())
}
pub fn watch_position<F: Fn(WatchEvent) + Send + Sync + 'static>(
&self,
options: PositionOptions,
callback: F,
) -> crate::Result<u32> {
let channel = Channel::new(move |event| {
let payload = match event {
InvokeBody::Json(payload) => serde_json::from_value::<WatchEvent>(payload)
.unwrap_or_else(|error| {
WatchEvent::Error(format!(
"Couldn't deserialize watch event payload: `{error}`"
))
}),
_ => WatchEvent::Error("Unexpected watch event payload.".to_string()),
};
callback(payload);
Ok(())
});
let id = channel.id();
self.watch_position_inner(options, channel)?;
Ok(id)
}
pub(crate) fn watch_position_inner(
&self,
_options: PositionOptions,
_callback_channel: Channel,
) -> crate::Result<()> {
Ok(())
}
pub fn clear_watch(&self, _channel_id: u32) -> crate::Result<()> {
Ok(())
}
pub fn check_permissions(&self) -> crate::Result<PermissionStatus> {
Ok(PermissionStatus::default())
}
pub fn request_permissions(
&self,
_permissions: Option<Vec<PermissionType>>,
) -> crate::Result<PermissionStatus> {
Ok(PermissionStatus::default())
}
}
#[derive(Serialize)]
#[allow(unused)] // TODO:
struct WatchPayload {
options: PositionOptions,
channel: Channel,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
#[allow(unused)] // TODO:
struct ClearWatchPayload {
channel_id: u32,
}

@ -0,0 +1,30 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::{ser::Serializer, Serialize};
use specta::Type;
pub type Result<T> = std::result::Result<T, Error>;
// TODO: Improve Error handling (different typed errors instead of one (stringified) PluginInvokeError for all mobile errors)
#[derive(Debug, thiserror::Error, Type)]
pub enum Error {
#[cfg(mobile)]
#[error(transparent)]
PluginInvoke(
#[serde(skip)]
#[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,100 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use tauri::{
plugin::{Builder, TauriPlugin},
Manager, Runtime,
};
//use tauri_specta::*;
pub use models::*;
#[cfg(desktop)]
mod desktop;
#[cfg(mobile)]
mod mobile;
mod commands;
mod error;
mod models;
pub use error::{Error, Result};
#[cfg(desktop)]
use desktop::Geolocation;
#[cfg(mobile)]
use mobile::Geolocation;
/* macro_rules! specta_builder {
() => {
ts::builder()
.commands(collect_commands![
commands::get_current_position,
commands::watch_position,
commands::clear_watch,
commands::check_permissions,
commands::request_permissions
])
.header("// @ts-nocheck")
.config(
specta::ts::ExportConfig::default()
.bigint(specta::ts::BigIntExportBehavior::Number),
)
};
} */
/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the geolocation APIs.
pub trait GeolocationExt<R: Runtime> {
fn geolocation(&self) -> &Geolocation<R>;
}
impl<R: Runtime, T: Manager<R>> crate::GeolocationExt<R> for T {
fn geolocation(&self) -> &Geolocation<R> {
self.state::<Geolocation<R>>().inner()
}
}
/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
/* let (invoke_handler, register_events) =
specta_builder!().build_plugin_utils("geolocation").unwrap(); */
Builder::new("geolocation")
.invoke_handler(tauri::generate_handler![
commands::get_current_position,
commands::watch_position,
commands::clear_watch,
commands::check_permissions,
commands::request_permissions
])
.setup(|app, api| {
#[cfg(mobile)]
let geolocation = mobile::init(app, api)?;
#[cfg(desktop)]
let geolocation = desktop::init(app, api)?;
app.manage(geolocation);
Ok(())
})
.build()
}
/* #[cfg(test)]
mod test {
use super::*;
#[test]
fn export_types() {
specta_builder!()
.path("./guest-js/bindings.ts")
.config(
specta::ts::ExportConfig::default()
.formatter(specta::ts::formatter::prettier)
.bigint(specta::ts::BigIntExportBehavior::Number),
)
.export_for_plugin("geolocation")
.expect("failed to export specta types");
}
}
*/

@ -0,0 +1,116 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::{de::DeserializeOwned, Serialize};
use tauri::{
ipc::{Channel, InvokeBody},
plugin::{PluginApi, PluginHandle},
AppHandle, Runtime,
};
use crate::models::*;
#[cfg(target_os = "android")]
const PLUGIN_IDENTIFIER: &str = "app.tauri.geolocation";
#[cfg(target_os = "ios")]
tauri::ios_plugin_binding!(init_plugin_geolocation);
// initializes the Kotlin or Swift plugin classes
pub fn init<R: Runtime, C: DeserializeOwned>(
_app: &AppHandle<R>,
api: PluginApi<R, C>,
) -> crate::Result<Geolocation<R>> {
#[cfg(target_os = "android")]
let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "GeolocationPlugin")?;
#[cfg(target_os = "ios")]
let handle = api.register_ios_plugin(init_plugin_geolocation)?;
Ok(Geolocation(handle))
}
/// Access to the geolocation APIs.
pub struct Geolocation<R: Runtime>(PluginHandle<R>);
impl<R: Runtime> Geolocation<R> {
pub fn get_current_position(
&self,
options: Option<PositionOptions>,
) -> crate::Result<Position> {
// TODO: We may have to send over None if that's better on Android
self.0
.run_mobile_plugin("getCurrentPosition", options.unwrap_or_default())
.map_err(Into::into)
}
/// Register a position watcher. This method returns an id to use in `clear_watch`.
pub fn watch_position<F: Fn(WatchEvent) + Send + Sync + 'static>(
&self,
options: PositionOptions,
callback: F,
) -> crate::Result<u32> {
let channel = Channel::new(move |event| {
let payload = match event {
InvokeBody::Json(payload) => serde_json::from_value::<WatchEvent>(dbg!(payload))
.unwrap_or_else(|error| {
WatchEvent::Error(format!(
"Couldn't deserialize watch event payload: `{error}`"
))
}),
_ => WatchEvent::Error("Unexpected watch event payload.".to_string()),
};
callback(payload);
Ok(())
});
let id = channel.id();
self.watch_position_inner(options, channel)?;
Ok(id)
}
pub(crate) fn watch_position_inner(
&self,
options: PositionOptions,
channel: Channel,
) -> crate::Result<()> {
self.0
.run_mobile_plugin("watchPosition", WatchPayload { options, channel })
.map_err(Into::into)
}
pub fn clear_watch(&self, channel_id: u32) -> crate::Result<()> {
self.0
.run_mobile_plugin("clearWatch", ClearWatchPayload { channel_id })
.map_err(Into::into)
}
pub fn check_permissions(&self) -> crate::Result<PermissionStatus> {
self.0
.run_mobile_plugin("checkPermissions", ())
.map_err(Into::into)
}
pub fn request_permissions(
&self,
permissions: Option<Vec<PermissionType>>,
) -> crate::Result<PermissionStatus> {
self.0
.run_mobile_plugin("requestPermissions", permissions)
.map_err(Into::into)
}
}
#[derive(Serialize)]
struct WatchPayload {
options: PositionOptions,
channel: Channel,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ClearWatchPayload {
channel_id: u32,
}

@ -0,0 +1,103 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::{Deserialize, Serialize};
use specta::Type;
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PermissionStatus {
/// Permission state for the location alias.
///
/// On Android it requests/checks both ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION permissions.
///
/// On iOS it requests/checks location permissions.
pub location: PermissionState,
/// Permissions state for the coarseLoaction alias.
///
/// On Android it requests/checks ACCESS_COARSE_LOCATION.
///
/// On Android 12+, users can choose between Approximate location (ACCESS_COARSE_LOCATION) and Precise location (ACCESS_FINE_LOCATION).
///
/// On iOS it will have the same value as the `location` alias.
pub coarse_location: PermissionState,
}
/// Permission state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum PermissionState {
/// Permission access has been granted.
Granted,
/// Permission access has been denied.
Denied,
/// The end user should be prompted for permission.
#[default]
Prompt,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PositionOptions {
/// High accuracy mode (such as GPS, if available)
/// Will be ignored on Android 12+ if users didn't grant the ACCESS_FINE_LOCATION permission.
pub enable_high_accuracy: bool,
/// The maximum wait time in milliseconds for location updates.
/// Default: 10000
/// On Android the timeout gets ignored for getCurrentPosition.
/// Ignored on iOS.
// TODO: Handle Infinity and default to it.
// TODO: Should be u64+ but specta doesn't like that?
pub timeout: u32,
/// The maximum age in milliseconds of a possible cached position that is acceptable to return.
/// Default: 0
/// Ignored on iOS.
// TODO: Handle Infinity.
// TODO: Should be u64+ but specta doesn't like that?
pub maximum_age: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum PermissionType {
Location,
CoarseLocation,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct Coordinates {
/// Latitude in decimal degrees.
pub latitude: f64,
/// Longitude in decimal degrees.
pub longitude: f64,
/// Accuracy level of the latitude and longitude coordinates in meters.
pub accuracy: f64,
/// Accuracy level of the altitude coordinate in meters, if available.
/// Available on all iOS versions and on Android 8 and above.
pub altitude_accuracy: Option<f64>,
/// The altitude the user is at, if available.
pub altitude: Option<f64>,
// The speed the user is traveling, if available.
pub speed: Option<f64>,
/// The heading the user is facing, if available.
pub heading: Option<f64>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct Position {
/// Creation time for these coordinates.
// TODO: Check if we're actually losing precision.
pub timestamp: u64,
/// The GPS coordinates along with the accuracy of the data.
pub coords: Coordinates,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(untagged)]
pub enum WatchEvent {
Position(Position),
Error(String),
}

@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.base.json",
"include": ["guest-js/*.ts"]
}

@ -0,0 +1 @@
/.tauri

@ -0,0 +1,26 @@
[package]
name = "tauri-plugin-haptics"
version = "2.0.0-beta.0"
edition = { workspace = true }
authors = { workspace = true }
license = { workspace = true }
repository = { workspace = true }
links = "tauri-plugin-haptics"
[package.metadata.docs.rs]
rustc-args = ["--cfg", "docsrs"]
rustdoc-args = ["--cfg", "docsrs"]
[build-dependencies]
tauri-plugin = { workspace = true, features = ["build"] }
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
tauri = { workspace = true, features = ["specta"] }
log = { workspace = true }
thiserror = { workspace = true }
specta = { 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,123 @@
![haptics](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/haptics/banner.png)
Haptic feedback and vibrations on Android and iOS.
There are no standards/requirements for vibration support on Android, so the `feedback` APIs may not work correctly on more affordable phones, including recently released ones.
## Install
_This plugin requires a Rust version of at least **1.75**_
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-haptics = "2.0.0-beta"
# alternatively with Git:
tauri-plugin-haptics = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
```
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
> Note: Since most JavaScript package managers are unable to install packages from git monorepos we provide read-only mirrors of each plugin. This makes installation option 2 more ergonomic to use.
<!-- Add the branch for installations using git! -->
```sh
pnpm add @tauri-apps/plugin-haptics
# or
npm add @tauri-apps/plugin-haptics
# or
yarn add @tauri-apps/plugin-haptics
# alternatively with Git:
pnpm add https://github.com/tauri-apps/tauri-plugin-haptics#v2
# or
npm add https://github.com/tauri-apps/tauri-plugin-haptics#v2
# or
yarn add https://github.com/tauri-apps/tauri-plugin-haptics#v2
```
## Usage
First you need to register the core plugin with Tauri:
`src-tauri/src/main.rs`
```rust
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_haptics::init())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
```
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
```javascript
import {
vibrate,
impactFeedback,
notificationFeedback,
selectionFeedback,
} from "@tauri-apps/plugin-haptics";
await vibrate(1);
await impactFeedback("medium");
await notificationFeedback("warning");
await selectionFeedback();
```
## Contributing
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
## Contributed By
<table>
<tbody>
<tr>
<td align="center" valign="middle">
<a href="https://crabnebula.dev" target="_blank">
<img src="contributors/crabnebula.svg" alt="CrabNebula" width="283">
</a>
</td>
<td align="center" valign="middle">
<a href="https://rescue.co" target="_blank">
<img src="contributors/rescue.png" alt="Rescue.co" width="283" height="90">
</a>
</td>
</tr>
</tbody>
</table>
## 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,46 @@
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "app.tauri.haptics"
compileSdk = 34
defaultConfig {
minSdk = 24
targetSdk = 34
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles("consumer-rules.pro")
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "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")
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,28 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
package app.tauri.haptics
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("app.tauri.haptics", appContext.packageName)
}
}

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.VIBRATE" />
</manifest>

@ -0,0 +1,143 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
package app.tauri.haptics
import android.app.Activity
import android.content.Context
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import app.tauri.Logger
import app.tauri.annotation.Command
import app.tauri.annotation.InvokeArg
import app.tauri.annotation.TauriPlugin
import app.tauri.haptics.patterns.ImpactPatternHeavy
import app.tauri.haptics.patterns.ImpactPatternLight
import app.tauri.haptics.patterns.ImpactPatternMedium
import app.tauri.haptics.patterns.ImpactPatternRigid
import app.tauri.haptics.patterns.ImpactPatternSoft
import app.tauri.haptics.patterns.NotificationPatternError
import app.tauri.haptics.patterns.NotificationPatternSuccess
import app.tauri.haptics.patterns.NotificationPatternWarning
import app.tauri.haptics.patterns.Pattern
import app.tauri.haptics.patterns.SelectionPattern
import app.tauri.plugin.Invoke
import app.tauri.plugin.Plugin
import com.fasterxml.jackson.annotation.JsonProperty
@InvokeArg
class HapticsOptions {
var duration: Long = 300
}
@InvokeArg
class NotificationFeedbackArgs {
val type: NotificationFeedbackType = NotificationFeedbackType.Success
}
@InvokeArg
enum class NotificationFeedbackType {
@JsonProperty("success")
Success,
@JsonProperty("warning")
Warning,
@JsonProperty("error")
Error;
fun into(): Pattern {
return when(this) {
Success -> NotificationPatternSuccess
Warning -> NotificationPatternWarning
Error -> NotificationPatternError
}
}
}
@InvokeArg
class ImpactFeedbackArgs {
val style: ImpactFeedbackStyle = ImpactFeedbackStyle.Medium
}
@InvokeArg
enum class ImpactFeedbackStyle {
@JsonProperty("light")
Light,
@JsonProperty("medium")
Medium,
@JsonProperty("heavy")
Heavy,
@JsonProperty("soft")
Soft,
@JsonProperty("rigid")
Rigid;
fun into(): Pattern {
return when(this) {
Light -> ImpactPatternLight
Medium -> ImpactPatternMedium
Heavy -> ImpactPatternHeavy
Soft -> ImpactPatternSoft
Rigid -> ImpactPatternRigid
}
}
}
@TauriPlugin
class HapticsPlugin(private val activity: Activity): Plugin(activity) {
private val vibrator: Vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val vibManager = activity.applicationContext.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
vibManager.defaultVibrator
} else {
@Suppress("DEPRECATION")
activity.applicationContext.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
}
//
// TAURI COMMANDS
//
@Command
fun vibrate(invoke: Invoke) {
val args = invoke.parseArgs(HapticsOptions::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(args.duration, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
vibrator.vibrate(args.duration)
}
invoke.resolve()
}
@Command
fun impactFeedback(invoke: Invoke) {
val args = invoke.parseArgs(ImpactFeedbackArgs::class.java)
vibratePattern(args.style.into())
invoke.resolve()
}
@Command
fun notificationFeedback(invoke: Invoke) {
val args = invoke.parseArgs(NotificationFeedbackArgs::class.java)
vibratePattern(args.type.into())
invoke.resolve()
}
// TODO: Consider breaking this up into Start,Change,End like capacitor
@Command
fun selectionFeedback(invoke: Invoke) {
vibratePattern(SelectionPattern)
invoke.resolve()
}
// INTERNAL FUNCTIONS
private fun vibratePattern(pattern: Pattern) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createWaveform(pattern.timings, pattern.amplitudes, -1))
} else {
vibrator.vibrate(pattern.oldSDKPattern, -1)
}
}
}

@ -0,0 +1,35 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
package app.tauri.haptics.patterns
val ImpactPatternLight = Pattern(
longArrayOf(0, 50),
intArrayOf(0, 30),
longArrayOf(0, 20)
)
val ImpactPatternMedium = Pattern(
longArrayOf(0, 43),
intArrayOf(0, 50),
longArrayOf(0, 43)
)
val ImpactPatternHeavy = Pattern(
longArrayOf(0, 60),
intArrayOf(0, 70),
longArrayOf(0, 61)
)
val ImpactPatternSoft = Pattern(
longArrayOf(0, 50),
intArrayOf(0, 30),
longArrayOf(0, 20)
)
val ImpactPatternRigid = Pattern(
longArrayOf(0, 43),
intArrayOf(0, 50),
longArrayOf(0, 43)
)

@ -0,0 +1,23 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
package app.tauri.haptics.patterns
val NotificationPatternSuccess = Pattern(
longArrayOf(0, 40, 100, 40),
intArrayOf(0, 50, 0, 60),
longArrayOf(0, 40, 100, 40)
)
val NotificationPatternWarning = Pattern(
longArrayOf(0, 40, 120, 60),
intArrayOf(0, 40, 0, 60),
longArrayOf(0, 40, 120, 60)
)
val NotificationPatternError = Pattern(
longArrayOf(0, 60, 100, 40, 80, 50),
intArrayOf(0, 50, 0, 40, 0, 50),
longArrayOf(0, 60, 100, 40, 80, 50)
)

@ -0,0 +1,11 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
package app.tauri.haptics.patterns
class Pattern (
val timings: LongArray,
val amplitudes: IntArray,
val oldSDKPattern: LongArray
) {}

@ -0,0 +1,11 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
package app.tauri.haptics.patterns
val SelectionPattern = Pattern (
timings = longArrayOf(0, 50),
amplitudes = intArrayOf(0, 30),
oldSDKPattern = longArrayOf(0, 70)
)

@ -0,0 +1,21 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
package app.tauri.haptics
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}

@ -0,0 +1 @@
if("__TAURI__"in window){var __TAURI_PLUGIN_HAPTICS__=function(r){"use strict";async function t(r,t={},e){return window.__TAURI_INTERNALS__.invoke(r,t,e)}var e;"function"==typeof SuppressedError&&SuppressedError,function(r){r.WINDOW_RESIZED="tauri://resize",r.WINDOW_MOVED="tauri://move",r.WINDOW_CLOSE_REQUESTED="tauri://close-requested",r.WINDOW_DESTROYED="tauri://destroyed",r.WINDOW_FOCUS="tauri://focus",r.WINDOW_BLUR="tauri://blur",r.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",r.WINDOW_THEME_CHANGED="tauri://theme-changed",r.WINDOW_CREATED="tauri://window-created",r.WEBVIEW_CREATED="tauri://webview-created",r.DRAG_ENTER="tauri://drag-enter",r.DRAG_OVER="tauri://drag-over",r.DRAG_DROP="tauri://drag-drop",r.DRAG_LEAVE="tauri://drag-leave"}(e||(e={}));const a={async vibrate(r){try{return{status:"ok",data:await t("plugin:haptics|vibrate",{duration:r})}}catch(r){if(r instanceof Error)throw r;return{status:"error",error:r}}},async impactFeedback(r){try{return{status:"ok",data:await t("plugin:haptics|impact_feedback",{style:r})}}catch(r){if(r instanceof Error)throw r;return{status:"error",error:r}}},async notificationFeedback(r){try{return{status:"ok",data:await t("plugin:haptics|notification_feedback",{type:r})}}catch(r){if(r instanceof Error)throw r;return{status:"error",error:r}}},async selectionFeedback(){try{return{status:"ok",data:await t("plugin:haptics|selection_feedback")}}catch(r){if(r instanceof Error)throw r;return{status:"error",error:r}}}},{vibrate:i,impactFeedback:c,notificationFeedback:n,selectionFeedback:o}=a;return r.impactFeedback=c,r.notificationFeedback=n,r.selectionFeedback=o,r.vibrate=i,r}({});Object.defineProperty(window.__TAURI__,"haptics",{value:__TAURI_PLUGIN_HAPTICS__})}

@ -0,0 +1,25 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
const COMMANDS: &[&str] = &[
"vibrate",
"impact_feedback",
"notification_feedback",
"selection_feedback",
];
fn main() {
if let Err(error) = tauri_plugin::Builder::new(COMMANDS)
.global_api_script_path("./api-iife.js")
.android_path("android")
.ios_path("ios")
.try_build()
{
println!("{error:#}");
// when building documentation for Android the plugin build result is irrelevant to the crate itself
if !(cfg!(docsrs) && std::env::var("TARGET").unwrap().contains("android")) {
std::process::exit(1);
}
}
}

@ -0,0 +1,140 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// @ts-nocheck
// This file was generated by [tauri-specta](https://github.com/oscartbeaumont/tauri-specta). Do not edit this file manually.
/** user-defined commands **/
export const commands = {
async vibrate(duration: number): Promise<Result<null, Error>> {
try {
return {
status: "ok",
data: await TAURI_INVOKE("plugin:haptics|vibrate", { duration }),
};
} catch (e) {
if (e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async impactFeedback(
style: ImpactFeedbackStyle,
): Promise<Result<null, Error>> {
try {
return {
status: "ok",
data: await TAURI_INVOKE("plugin:haptics|impact_feedback", { style }),
};
} catch (e) {
if (e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async notificationFeedback(
type: NotificationFeedbackType,
): Promise<Result<null, Error>> {
try {
return {
status: "ok",
data: await TAURI_INVOKE("plugin:haptics|notification_feedback", {
type,
}),
};
} catch (e) {
if (e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async selectionFeedback(): Promise<Result<null, Error>> {
try {
return {
status: "ok",
data: await TAURI_INVOKE("plugin:haptics|selection_feedback"),
};
} catch (e) {
if (e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
};
/** user-defined events **/
/* export const events = __makeEvents__<{
randomNumber: RandomNumber;
}>({
randomNumber: "plugin:haptics:random-number",
}); */
/** user-defined statics **/
/** user-defined types **/
export type Error = never;
export type ImpactFeedbackStyle =
| "light"
| "medium"
| "heavy"
| "soft"
| "rigid";
export type NotificationFeedbackType = "success" | "warning" | "error";
//export type RandomNumber = number;
/** tauri-specta globals **/
import { invoke as TAURI_INVOKE } from "@tauri-apps/api/core";
import * as TAURI_API_EVENT from "@tauri-apps/api/event";
import { type WebviewWindow as __WebviewWindow__ } from "@tauri-apps/api/webviewWindow";
type __EventObj__<T> = {
listen: (
cb: TAURI_API_EVENT.EventCallback<T>,
) => ReturnType<typeof TAURI_API_EVENT.listen<T>>;
once: (
cb: TAURI_API_EVENT.EventCallback<T>,
) => ReturnType<typeof TAURI_API_EVENT.once<T>>;
emit: T extends null
? (payload?: T) => ReturnType<typeof TAURI_API_EVENT.emit>
: (payload: T) => ReturnType<typeof TAURI_API_EVENT.emit>;
};
export type Result<T, E> =
| { status: "ok"; data: T }
| { status: "error"; error: E };
function __makeEvents__<T extends Record<string, any>>(
mappings: Record<keyof T, string>,
) {
return new Proxy(
{} as unknown as {
[K in keyof T]: __EventObj__<T[K]> & {
(handle: __WebviewWindow__): __EventObj__<T[K]>;
};
},
{
get: (_, event) => {
const name = mappings[event as keyof T];
return new Proxy((() => {}) as any, {
apply: (_, __, [window]: [__WebviewWindow__]) => ({
listen: (arg: any) => window.listen(name, arg),
once: (arg: any) => window.once(name, arg),
emit: (arg: any) => window.emit(name, arg),
}),
get: (_, command: keyof __EventObj__<any>) => {
switch (command) {
case "listen":
return (arg: any) => TAURI_API_EVENT.listen(name, arg);
case "once":
return (arg: any) => TAURI_API_EVENT.once(name, arg);
case "emit":
return (arg: any) => TAURI_API_EVENT.emit(name, arg);
}
},
});
},
},
);
}

@ -0,0 +1,18 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
/* eslint-disable @typescript-eslint/unbound-method */
import { commands } from "./bindings";
export const {
vibrate,
impactFeedback,
notificationFeedback,
selectionFeedback,
} = commands;
export { ImpactFeedbackStyle, NotificationFeedbackType } from "./bindings";
// export { events };

@ -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,33 @@
// 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-haptics",
platforms: [
.iOS(.v13),
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "tauri-plugin-haptics",
type: .static,
targets: ["tauri-plugin-haptics"]),
],
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-haptics",
dependencies: [
.byName(name: "Tauri")
],
path: "Sources")
]
)

@ -0,0 +1,3 @@
# Tauri Plugin Haptics
A description of this package.

@ -0,0 +1,133 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import SwiftRs
import Tauri
import UIKit
import WebKit
import CoreHaptics
import AudioToolbox
class ImpactFeedbackOptions: Decodable {
let style: ImpactFeedbackStyle
}
enum ImpactFeedbackStyle: String, Decodable {
case light, medium, heavy, soft, rigid
func into() -> UIImpactFeedbackGenerator.FeedbackStyle {
switch self {
case .light:
return .light
case .medium:
return .medium
case .heavy:
return .heavy
case .soft:
return .soft
case .rigid:
return .rigid
}
}
}
class NotificationFeedbackOptions: Decodable {
let type: NotificationFeedbackType
}
enum NotificationFeedbackType: String, Decodable {
case success, warning, error
func into() -> UINotificationFeedbackGenerator.FeedbackType {
switch self {
case .success:
return .success
case .warning:
return .warning
case .error:
return .error
}
}
}
class VibrateOptions: Decodable {
// TODO: Array
let duration: Double
}
class HapticsPlugin: Plugin {
//
// Tauri commands
//
@objc public func vibrate(_ invoke: Invoke) throws {
let args = try invoke.parseArgs(VibrateOptions.self)
if CHHapticEngine.capabilitiesForHardware().supportsHaptics {
do {
let engine = try CHHapticEngine()
try engine.start()
engine.resetHandler = { [] in
do {
try engine.start()
} catch {
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
}
}
// TODO: Make some of this (or all) configurable?
let intensity: CHHapticEventParameter = CHHapticEventParameter(parameterID: .hapticIntensity, value: 1.0)
let sharpness: CHHapticEventParameter = CHHapticEventParameter(parameterID: .hapticSharpness, value: 1.0)
let continuousEvent = CHHapticEvent(
eventType: .hapticContinuous,
parameters: [intensity, sharpness],
relativeTime: 0.0,
duration: args.duration/1000
)
let pattern = try CHHapticPattern(events: [continuousEvent], parameters: [])
let player = try engine.makePlayer(with: pattern)
try player.start(atTime: 0)
} catch {
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
}
} else {
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
}
Logger.error("VIBRATE END")
invoke.resolve()
}
@objc public func impactFeedback(_ invoke: Invoke) throws {
let args = try invoke.parseArgs(ImpactFeedbackOptions.self)
let generator = UIImpactFeedbackGenerator(style: args.style.into())
generator.prepare()
generator.impactOccurred()
invoke.resolve()
}
@objc public func notificationFeedback(_ invoke: Invoke) throws {
let args = try invoke.parseArgs(NotificationFeedbackOptions.self)
let generator = UINotificationFeedbackGenerator()
generator.prepare()
generator.notificationOccurred(args.type.into())
invoke.resolve()
}
// TODO: Consider breaking this up into Start,Change,End like capacitor
@objc public func selectionFeedback(_ invoke: Invoke) throws {
let generator = UISelectionFeedbackGenerator()
generator.prepare()
generator.selectionChanged()
invoke.resolve()
}
}
@_cdecl("init_plugin_haptics")
func initPlugin() -> Plugin {
return HapticsPlugin()
}

@ -0,0 +1,12 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import XCTest
@testable import ExamplePlugin
final class ExamplePluginTests: XCTestCase {
func testExample() throws {
let plugin = ExamplePlugin()
}
}

@ -0,0 +1,28 @@
{
"name": "@tauri-apps/plugin-haptics",
"version": "2.0.0-beta.0",
"license": "MIT or APACHE-2.0",
"authors": [
"Tauri Programme within The Commons Conservancy"
],
"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.0.0-beta.16"
}
}

@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-impact-feedback"
description = "Enables the impact_feedback command without any pre-configured scope."
commands.allow = ["impact_feedback"]
[[permission]]
identifier = "deny-impact-feedback"
description = "Denies the impact_feedback command without any pre-configured scope."
commands.deny = ["impact_feedback"]

@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-notification-feedback"
description = "Enables the notification_feedback command without any pre-configured scope."
commands.allow = ["notification_feedback"]
[[permission]]
identifier = "deny-notification-feedback"
description = "Denies the notification_feedback command without any pre-configured scope."
commands.deny = ["notification_feedback"]

@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-selection-feedback"
description = "Enables the selection_feedback command without any pre-configured scope."
commands.allow = ["selection_feedback"]
[[permission]]
identifier = "deny-selection-feedback"
description = "Denies the selection_feedback command without any pre-configured scope."
commands.deny = ["selection_feedback"]

@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
[[permission]]
identifier = "allow-vibrate"
description = "Enables the vibrate command without any pre-configured scope."
commands.allow = ["vibrate"]
[[permission]]
identifier = "deny-vibrate"
description = "Denies the vibrate command without any pre-configured scope."
commands.deny = ["vibrate"]

@ -0,0 +1,114 @@
### Permission Table
<table>
<tr>
<th>Identifier</th>
<th>Description</th>
</tr>
<tr>
<td>
`haptics:allow-impact-feedback`
</td>
<td>
Enables the impact_feedback command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`haptics:deny-impact-feedback`
</td>
<td>
Denies the impact_feedback command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`haptics:allow-notification-feedback`
</td>
<td>
Enables the notification_feedback command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`haptics:deny-notification-feedback`
</td>
<td>
Denies the notification_feedback command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`haptics:allow-selection-feedback`
</td>
<td>
Enables the selection_feedback command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`haptics:deny-selection-feedback`
</td>
<td>
Denies the selection_feedback command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`haptics:allow-vibrate`
</td>
<td>
Enables the vibrate command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`haptics:deny-vibrate`
</td>
<td>
Denies the vibrate command without any pre-configured scope.
</td>
</tr>
</table>

@ -0,0 +1,356 @@
{
"$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": "allow-impact-feedback -> Enables the impact_feedback command without any pre-configured scope.",
"type": "string",
"enum": [
"allow-impact-feedback"
]
},
{
"description": "deny-impact-feedback -> Denies the impact_feedback command without any pre-configured scope.",
"type": "string",
"enum": [
"deny-impact-feedback"
]
},
{
"description": "allow-notification-feedback -> Enables the notification_feedback command without any pre-configured scope.",
"type": "string",
"enum": [
"allow-notification-feedback"
]
},
{
"description": "deny-notification-feedback -> Denies the notification_feedback command without any pre-configured scope.",
"type": "string",
"enum": [
"deny-notification-feedback"
]
},
{
"description": "allow-selection-feedback -> Enables the selection_feedback command without any pre-configured scope.",
"type": "string",
"enum": [
"allow-selection-feedback"
]
},
{
"description": "deny-selection-feedback -> Denies the selection_feedback command without any pre-configured scope.",
"type": "string",
"enum": [
"deny-selection-feedback"
]
},
{
"description": "allow-vibrate -> Enables the vibrate command without any pre-configured scope.",
"type": "string",
"enum": [
"allow-vibrate"
]
},
{
"description": "deny-vibrate -> Denies the vibrate command without any pre-configured scope.",
"type": "string",
"enum": [
"deny-vibrate"
]
}
]
}
}
}

@ -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,37 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use tauri::{command, AppHandle, Runtime};
use crate::{HapticsExt, ImpactFeedbackStyle, NotificationFeedbackType, Result};
#[command]
#[specta::specta]
pub(crate) async fn vibrate<R: Runtime>(app: AppHandle<R>, duration: u32) -> Result<()> {
app.haptics().vibrate(duration)
}
#[command]
#[specta::specta]
pub(crate) async fn impact_feedback<R: Runtime>(
app: AppHandle<R>,
style: ImpactFeedbackStyle,
) -> Result<()> {
app.haptics().impact_feedback(style)
}
#[command]
#[specta::specta]
pub(crate) async fn notification_feedback<R: Runtime>(
app: AppHandle<R>,
r#type: NotificationFeedbackType,
) -> Result<()> {
app.haptics().notification_feedback(r#type)
}
#[command]
#[specta::specta]
pub(crate) async fn selection_feedback<R: Runtime>(app: AppHandle<R>) -> Result<()> {
app.haptics().selection_feedback()
}

@ -0,0 +1,36 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::de::DeserializeOwned;
use tauri::{plugin::PluginApi, AppHandle, Runtime};
use crate::models::*;
pub fn init<R: Runtime, C: DeserializeOwned>(
app: &AppHandle<R>,
_api: PluginApi<R, C>,
) -> crate::Result<Haptics<R>> {
Ok(Haptics(app.clone()))
}
/// Access to the haptics APIs.
pub struct Haptics<R: Runtime>(AppHandle<R>);
impl<R: Runtime> Haptics<R> {
pub fn vibrate(&self, _duration: u32) -> crate::Result<()> {
Ok(())
}
pub fn impact_feedback(&self, _style: ImpactFeedbackStyle) -> crate::Result<()> {
Ok(())
}
pub fn notification_feedback(&self, _type: NotificationFeedbackType) -> crate::Result<()> {
Ok(())
}
pub fn selection_feedback(&self) -> crate::Result<()> {
Ok(())
}
}

@ -0,0 +1,30 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::{ser::Serializer, Serialize};
use specta::Type;
pub type Result<T> = std::result::Result<T, Error>;
// TODO: Improve Error handling (different typed errors instead of one (stringified) PluginInvokeError for all mobile errors)
#[derive(Debug, thiserror::Error, Type)]
pub enum Error {
#[cfg(mobile)]
#[error(transparent)]
PluginInvoke(
#[serde(skip)]
#[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,98 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use tauri::{
plugin::{Builder, TauriPlugin},
Manager, Runtime,
};
//use tauri_specta::*;
pub use models::*;
#[cfg(desktop)]
mod desktop;
#[cfg(mobile)]
mod mobile;
mod commands;
mod error;
mod models;
pub use error::{Error, Result};
#[cfg(desktop)]
use desktop::Haptics;
#[cfg(mobile)]
use mobile::Haptics;
/* macro_rules! specta_builder {
() => {
ts::builder()
.commands(collect_commands![
commands::vibrate,
commands::impact_feedback,
commands::notification_feedback,
commands::selection_feedback
])
.header("// @ts-nocheck")
.config(
specta::ts::ExportConfig::default()
.bigint(specta::ts::BigIntExportBehavior::Number),
)
};
} */
/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the haptics APIs.
pub trait HapticsExt<R: Runtime> {
fn haptics(&self) -> &Haptics<R>;
}
impl<R: Runtime, T: Manager<R>> crate::HapticsExt<R> for T {
fn haptics(&self) -> &Haptics<R> {
self.state::<Haptics<R>>().inner()
}
}
/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
/* let (invoke_handler, register_events) =
specta_builder!().build_plugin_utils("haptics").unwrap(); */
Builder::new("haptics")
.invoke_handler(tauri::generate_handler![
commands::vibrate,
commands::impact_feedback,
commands::notification_feedback,
commands::selection_feedback
])
.setup(|app, api| {
#[cfg(mobile)]
let haptics = mobile::init(app, api)?;
#[cfg(desktop)]
let haptics = desktop::init(app, api)?;
app.manage(haptics);
Ok(())
})
.build()
}
/* #[cfg(test)]
mod test {
use super::*;
#[test]
fn export_types() {
specta_builder!()
.path("./guest-js/bindings.ts")
.config(
specta::ts::ExportConfig::default()
.formatter(specta::ts::formatter::prettier)
.bigint(specta::ts::BigIntExportBehavior::Number),
)
.export_for_plugin("haptics")
.expect("failed to export specta types");
}
}
*/

@ -0,0 +1,76 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::{de::DeserializeOwned, Serialize};
use tauri::{
plugin::{PluginApi, PluginHandle},
AppHandle, Runtime,
};
use crate::models::*;
#[cfg(target_os = "android")]
const PLUGIN_IDENTIFIER: &str = "app.tauri.haptics";
#[cfg(target_os = "ios")]
tauri::ios_plugin_binding!(init_plugin_haptics);
// initializes the Kotlin or Swift plugin classes
pub fn init<R: Runtime, C: DeserializeOwned>(
_app: &AppHandle<R>,
api: PluginApi<R, C>,
) -> crate::Result<Haptics<R>> {
#[cfg(target_os = "android")]
let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "HapticsPlugin")?;
#[cfg(target_os = "ios")]
let handle = api.register_ios_plugin(init_plugin_haptics)?;
Ok(Haptics(handle))
}
/// Access to the haptics APIs.
pub struct Haptics<R: Runtime>(PluginHandle<R>);
impl<R: Runtime> Haptics<R> {
pub fn vibrate(&self, duration: u32) -> crate::Result<()> {
self.0
.run_mobile_plugin("vibrate", VibratePayload { duration })
.map_err(Into::into)
}
pub fn impact_feedback(&self, style: ImpactFeedbackStyle) -> crate::Result<()> {
self.0
.run_mobile_plugin("impactFeedback", ImpactFeedbackPayload { style })
.map_err(Into::into)
}
pub fn notification_feedback(&self, r#type: NotificationFeedbackType) -> crate::Result<()> {
self.0
.run_mobile_plugin(
"notificationFeedback",
NotificationFeedbackPayload { r#type },
)
.map_err(Into::into)
}
pub fn selection_feedback(&self) -> crate::Result<()> {
self.0
.run_mobile_plugin("selectionFeedback", ())
.map_err(Into::into)
}
}
#[derive(Serialize)]
struct VibratePayload {
duration: u32,
}
#[derive(Serialize)]
struct ImpactFeedbackPayload {
style: ImpactFeedbackStyle,
}
#[derive(Serialize)]
struct NotificationFeedbackPayload {
r#type: NotificationFeedbackType,
}

@ -0,0 +1,34 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::{Deserialize, Serialize};
use specta::Type;
/*
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HapticsOptions {
// TODO: support array to match web api
pub duration: u32,
}
*/
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ImpactFeedbackStyle {
Light,
#[default]
Medium,
Heavy,
Soft,
Rigid,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum NotificationFeedbackType {
#[default]
Success,
Warning,
Error,
}

@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.base.json",
"include": ["guest-js/*.ts"]
}

@ -4,7 +4,9 @@ cli
clipboard-manager
dialog
fs
geolocation
global-shortcut
haptics
http
log
notification

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save