snapshot of https://github.com/tauri-apps/plugins-workspace.git (v2, 2026-09-23; blobs > 131072B omitted)
Some checks failed
integration tests / run-integration-tests (windows-latest) (push) Has been cancelled
Test Rust / test (push) Has been cancelled
test plugins e2e (mobile) / ios (push) Has been cancelled
test plugins e2e / test (map[name:Windows os:windows-latest]) (push) Has been cancelled
test plugins e2e / test (map[name:macOS os:macos-latest]) (push) Has been cancelled
integration tests / run-integration-tests (macos-latest) (push) Has been cancelled
version or publish / version-or-publish (push) Failing after 0s
integration tests / run-integration-tests (ubuntu-22.04) (push) Failing after 0s
Lint JavaScript / eslint (push) Failing after 0s
Sync / sync-to-mirrors (push) Failing after 0s
test plugins e2e (mobile) / android (push) Failing after 0s
test plugins e2e / test (map[name:Linux os:ubuntu-latest]) (push) Failing after 0s
Test Rust / changes (push) Failing after 0s
Lint Rust / changes (push) Failing after 0s
Lint Rust / clippy (push) Has been skipped
Audit Rust / audit-rust (push) Failing after 1s
Audit JavaScript / audit-js (push) Failing after 1s
Some checks failed
integration tests / run-integration-tests (windows-latest) (push) Has been cancelled
Test Rust / test (push) Has been cancelled
test plugins e2e (mobile) / ios (push) Has been cancelled
test plugins e2e / test (map[name:Windows os:windows-latest]) (push) Has been cancelled
test plugins e2e / test (map[name:macOS os:macos-latest]) (push) Has been cancelled
integration tests / run-integration-tests (macos-latest) (push) Has been cancelled
version or publish / version-or-publish (push) Failing after 0s
integration tests / run-integration-tests (ubuntu-22.04) (push) Failing after 0s
Lint JavaScript / eslint (push) Failing after 0s
Sync / sync-to-mirrors (push) Failing after 0s
test plugins e2e (mobile) / android (push) Failing after 0s
test plugins e2e / test (map[name:Linux os:ubuntu-latest]) (push) Failing after 0s
Test Rust / changes (push) Failing after 0s
Lint Rust / changes (push) Failing after 0s
Lint Rust / clippy (push) Has been skipped
Audit Rust / audit-rust (push) Failing after 1s
Audit JavaScript / audit-js (push) Failing after 1s
This commit is contained in:
79
plugins/geolocation/CHANGELOG.md
Normal file
79
plugins/geolocation/CHANGELOG.md
Normal file
@@ -0,0 +1,79 @@
|
||||
# Changelog
|
||||
|
||||
## [2.3.3]
|
||||
|
||||
- [`db9c5998`](https://github.com/tauri-apps/plugins-workspace/commit/db9c5998feff9384f9cbbefcbe0d45937c00a1fc) ([#3531](https://github.com/tauri-apps/plugins-workspace/pull/3531) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Fix missing `consumer-rules.pro` on Gradle v9.
|
||||
- [`f8053e65`](https://github.com/tauri-apps/plugins-workspace/commit/f8053e659e4ccd85c1f52833411ff8417cbc5e69) ([#3527](https://github.com/tauri-apps/plugins-workspace/pull/3527) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Documented Cargo feature flags in each plugin's crate-level documentation.
|
||||
|
||||
## \[2.3.2]
|
||||
|
||||
- [`93426f85`](https://github.com/tauri-apps/plugins-workspace/commit/93426f85120f49beb9f40222bff45185a32d54a9) Fixed an issue that caused docs.rs builds to fail. No user facing changes.
|
||||
|
||||
## \[2.3.1]
|
||||
|
||||
- [`6c9b61fb`](https://github.com/tauri-apps/plugins-workspace/commit/6c9b61fb658145d13893626112fc489f7458aa17) ([#3039](https://github.com/tauri-apps/plugins-workspace/pull/3039) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) On Android, updated compileSdk to 36.
|
||||
- [`e933acb0`](https://github.com/tauri-apps/plugins-workspace/commit/e933acb0044b4d49053eae6492b542351160e66a) ([#3010](https://github.com/tauri-apps/plugins-workspace/pull/3010) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) On Android, use the `timeout` value for `setMinUpdateIntervalMillis`, `setMaxUpdateDelayMillis` and `setIntervalMillis` instead of just `minUpdateInterval`.
|
||||
|
||||
## \[2.3.0]
|
||||
|
||||
- [`f209b2f2`](https://github.com/tauri-apps/plugins-workspace/commit/f209b2f23cb29133c97ad5961fb46ef794dbe063) ([#2804](https://github.com/tauri-apps/plugins-workspace/pull/2804) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Updated tauri to 2.6
|
||||
|
||||
## \[2.2.5]
|
||||
|
||||
- [`f634e524`](https://github.com/tauri-apps/plugins-workspace/commit/f634e5248ebe428f8305a59f74c13fc15147fb8e) This is an "empty" release to update the plugins' source files on crates.io and docs.rs. This should fix docs.rs build failures for projects using tauri plugins as dependencies.
|
||||
|
||||
## \[2.2.4]
|
||||
|
||||
- [`a1b3fa27`](https://github.com/tauri-apps/plugins-workspace/commit/a1b3fa27f11022c9b6622b4fab12d93239eb05de) ([#2515](https://github.com/tauri-apps/plugins-workspace/pull/2515) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Re-exported the `Geolocation`, `Haptics`, `Notification`, and `Os` structs so that they show up on docs.rs.
|
||||
|
||||
## \[2.2.3]
|
||||
|
||||
- [`406e6f48`](https://github.com/tauri-apps/plugins-workspace/commit/406e6f484cdc13d35c50fb949f7489ca9eeccc44) ([#2323](https://github.com/tauri-apps/plugins-workspace/pull/2323) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Fixed an issue that caused build failures when the `haptics` or `geolocation` plugin was used without their `specta` feature flag enabled.
|
||||
|
||||
## \[2.2.2]
|
||||
|
||||
- [`c9c13a0f`](https://github.com/tauri-apps/plugins-workspace/commit/c9c13a0fe7cdaac223843f5ba33176252f8e22f5) ([#2316](https://github.com/tauri-apps/plugins-workspace/pull/2316) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) **Breaking change:** `specta` integration is now behind a `specta` feature flag like in Tauri.
|
||||
- [`c9c13a0f`](https://github.com/tauri-apps/plugins-workspace/commit/c9c13a0fe7cdaac223843f5ba33176252f8e22f5) ([#2316](https://github.com/tauri-apps/plugins-workspace/pull/2316) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Unlock and widen `specta` version range to match Tauri. No API changes.
|
||||
|
||||
## \[2.2.1]
|
||||
|
||||
- [`fb67ab2b`](https://github.com/tauri-apps/plugins-workspace/commit/fb67ab2b926502bfc20d6b43fbdd156691ea8526) ([#2281](https://github.com/tauri-apps/plugins-workspace/pull/2281) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Added `specta-util` to fix a "dependency not found" compilation error.
|
||||
|
||||
## \[2.2.0]
|
||||
|
||||
- [`3a79266b`](https://github.com/tauri-apps/plugins-workspace/commit/3a79266b8cf96a55b1ae6339d725567d45a44b1d) ([#2173](https://github.com/tauri-apps/plugins-workspace/pull/2173) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Bumped all plugins to `v2.2.0`. From now, the versions for the Rust and JavaScript packages of each plugin will be in sync with each other.
|
||||
|
||||
## \[2.0.1]
|
||||
|
||||
- [`a1a82208`](https://github.com/tauri-apps/plugins-workspace/commit/a1a82208ed4ab87f83310be0dc95428aec9ab241) ([#1873](https://github.com/tauri-apps/plugins-workspace/pull/1873) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Downgrade MSRV to 1.77.2 to support Windows 7.
|
||||
|
||||
## \[2.0.0]
|
||||
|
||||
- [`e2c4dfb6`](https://github.com/tauri-apps/plugins-workspace/commit/e2c4dfb6af43e5dd8d9ceba232c315f5febd55c1) Update to tauri v2 stable release.
|
||||
|
||||
## \[2.0.0-rc.2]
|
||||
|
||||
- [`60765694`](https://github.com/tauri-apps/plugins-workspace/commit/60765694f54875e22b8eb70b1d2e32dbf0c585c7) ([#1773](https://github.com/tauri-apps/plugins-workspace/pull/1773) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update API to match other plugins.
|
||||
|
||||
## \[2.0.0-rc.1]
|
||||
|
||||
- [`e2e97db5`](https://github.com/tauri-apps/plugins-workspace/commit/e2e97db51983267f5be84d4f6f0278d58834d1f5) ([#1701](https://github.com/tauri-apps/plugins-workspace/pull/1701) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Use `PermissionState` from the `tauri` crate, which now also includes a "prompt with rationale" variant for Android (returned when your app must explain to the user why it needs the permission).
|
||||
- [`e2e97db5`](https://github.com/tauri-apps/plugins-workspace/commit/e2e97db51983267f5be84d4f6f0278d58834d1f5) ([#1701](https://github.com/tauri-apps/plugins-workspace/pull/1701) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri 2.0.0-rc.8
|
||||
|
||||
## \[2.0.0-rc.2]
|
||||
|
||||
- [`b9147758`](https://github.com/tauri-apps/plugins-workspace/commit/b914775898c2bee7ceb20bd17ee595005cd17a64) ([#1679](https://github.com/tauri-apps/plugins-workspace/pull/1679) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Explicitly set a minimum macOS version for the Swift package.
|
||||
|
||||
## \[2.0.0-rc.1]
|
||||
|
||||
- [`5d170a54`](https://github.com/tauri-apps/plugins-workspace/commit/5d170a5444982dcc14135f6f1fc3e5da359f0eb0) ([#1671](https://github.com/tauri-apps/plugins-workspace/pull/1671) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri 2.0.0-rc.3.
|
||||
|
||||
### changes
|
||||
|
||||
- [`6b079cfd`](https://github.com/tauri-apps/plugins-workspace/commit/6b079cfdd107c94abc2c7300f6af00bac3ff4040) ([#1649](https://github.com/tauri-apps/plugins-workspace/pull/1649) by [@ahqsoftwares](https://github.com/tauri-apps/plugins-workspace/../../ahqsoftwares)) Remove targetSdk from build.kts files as it is deprecated and will be removed from DSL v9.0
|
||||
|
||||
## \[2.0.0-rc.0]
|
||||
|
||||
- [`9606089b`](https://github.com/tauri-apps/plugins-workspace/commit/9606089b2add4a17f80ed5a09d59ce94824bd672) ([#1599](https://github.com/tauri-apps/plugins-workspace/pull/1599)) Initial release.
|
||||
- [`9887d1`](https://github.com/tauri-apps/plugins-workspace/commit/9887d14bd0e971c4c0f5c1188fc4005d3fc2e29e) Update to tauri RC.
|
||||
tauri-apps/plugins-workspace/commit/9887d14bd0e971c4c0f5c1188fc4005d3fc2e29e) Update to tauri RC.
|
||||
37
plugins/geolocation/Cargo.toml
Normal file
37
plugins/geolocation/Cargo.toml
Normal file
@@ -0,0 +1,37 @@
|
||||
[package]
|
||||
name = "tauri-plugin-geolocation"
|
||||
description = "Get and track the device's current position"
|
||||
version = "2.3.3"
|
||||
edition = { workspace = true }
|
||||
authors = { workspace = true }
|
||||
license = { workspace = true }
|
||||
repository = { workspace = true }
|
||||
links = "tauri-plugin-geolocation"
|
||||
exclude = ["/guest-js", "/package.json", "/rollup.config.js", "/tsconfig.json"]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-linux-android"]
|
||||
|
||||
[package.metadata.platforms.support]
|
||||
windows = { level = "none", notes = "" }
|
||||
linux = { level = "none", notes = "" }
|
||||
macos = { level = "none", notes = "" }
|
||||
android = { level = "full", notes = "" }
|
||||
ios = { level = "full", notes = "" }
|
||||
|
||||
[build-dependencies]
|
||||
tauri-plugin = { workspace = true, features = ["build"] }
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tauri = { workspace = true }
|
||||
log = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
specta = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies]
|
||||
tauri = { workspace = true, features = ["wry"] }
|
||||
|
||||
[features]
|
||||
specta = ["dep:specta", "tauri/specta"]
|
||||
20
plugins/geolocation/LICENSE.spdx
Normal file
20
plugins/geolocation/LICENSE.spdx
Normal file
@@ -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
|
||||
177
plugins/geolocation/LICENSE_APACHE-2.0
Normal file
177
plugins/geolocation/LICENSE_APACHE-2.0
Normal file
@@ -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
|
||||
21
plugins/geolocation/LICENSE_MIT
Normal file
21
plugins/geolocation/LICENSE_MIT
Normal file
@@ -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.
|
||||
173
plugins/geolocation/README.md
Normal file
173
plugins/geolocation/README.md
Normal file
@@ -0,0 +1,173 @@
|
||||

|
||||
|
||||
This plugin provides APIs for getting and tracking the device's current position, including information about altitude, heading, and speed (if available).
|
||||
|
||||
| Platform | Supported |
|
||||
| -------- | --------- |
|
||||
| Linux | x |
|
||||
| Windows | x |
|
||||
| macOS | x |
|
||||
| Android | ✓ |
|
||||
| iOS | ✓ |
|
||||
|
||||
## Install
|
||||
|
||||
_This plugin requires a Rust version of at least **1.77.2**_
|
||||
|
||||
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"
|
||||
# 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:
|
||||
|
||||
<!-- 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
|
||||
```
|
||||
|
||||
## 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.location.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/lib.rs`
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_geolocation::init())
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
```
|
||||
|
||||
Then, for instance, grant the plugin the permission to check or request permissions from the user and to read the device position
|
||||
|
||||
`src-tauri/capabilities/default.json`
|
||||
|
||||
```json
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"geolocation:allow-check-permissions",
|
||||
"geolocation:allow-request-permissions",
|
||||
"geolocation:allow-get-current-position",
|
||||
"geolocation:allow-watch-position",
|
||||
]
|
||||
```
|
||||
|
||||
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
|
||||
|
||||
```javascript
|
||||
import {
|
||||
checkPermissions,
|
||||
requestPermissions,
|
||||
getCurrentPosition,
|
||||
watchPosition
|
||||
} from '@tauri-apps/plugin-geolocation'
|
||||
|
||||
let permissions = await checkPermissions()
|
||||
if (
|
||||
permissions.location === 'prompt'
|
||||
|| permissions.location === 'prompt-with-rationale'
|
||||
) {
|
||||
permissions = await requestPermissions(['location'])
|
||||
}
|
||||
|
||||
if (permissions.location === 'granted') {
|
||||
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.
|
||||
23
plugins/geolocation/SECURITY.md
Normal file
23
plugins/geolocation/SECURITY.md
Normal file
@@ -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).
|
||||
2
plugins/geolocation/android/.gitignore
vendored
Normal file
2
plugins/geolocation/android/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/build
|
||||
/.tauri
|
||||
36
plugins/geolocation/android/build.gradle.kts
Normal file
36
plugins/geolocation/android/build.gradle.kts
Normal file
@@ -0,0 +1,36 @@
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "app.tauri.geolocation"
|
||||
compileSdk = 36
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 24
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
consumerProguardFiles("consumer-rules.pro")
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
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"))
|
||||
}
|
||||
21
plugins/geolocation/android/consumer-rules.pro
Normal file
21
plugins/geolocation/android/consumer-rules.pro
Normal file
@@ -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
|
||||
2
plugins/geolocation/android/settings.gradle
Normal file
2
plugins/geolocation/android/settings.gradle
Normal file
@@ -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)
|
||||
}
|
||||
}
|
||||
6
plugins/geolocation/android/src/main/AndroidManifest.xml
Normal file
6
plugins/geolocation/android/src/main/AndroidManifest.xml
Normal file
@@ -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>
|
||||
144
plugins/geolocation/android/src/main/java/Geolocation.kt
Normal file
144
plugins/geolocation/android/src/main/java/Geolocation.kt
Normal file
@@ -0,0 +1,144 @@
|
||||
// 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
|
||||
|
||||
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
|
||||
|
||||
val locationRequest = LocationRequest.Builder(timeout)
|
||||
.setMaxUpdateDelayMillis(timeout)
|
||||
.setMinUpdateIntervalMillis(timeout)
|
||||
.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
|
||||
}
|
||||
}
|
||||
172
plugins/geolocation/android/src/main/java/GeolocationPlugin.kt
Normal file
172
plugins/geolocation/android/src/main/java/GeolocationPlugin.kt
Normal file
@@ -0,0 +1,172 @@
|
||||
// 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
|
||||
private var watchers = hashMapOf<Long, Pair<Invoke, WatchArgs>>()
|
||||
|
||||
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()
|
||||
// resume watchers
|
||||
for ((watcher, args) in watchers.values) {
|
||||
startWatch(watcher, args)
|
||||
}
|
||||
}
|
||||
|
||||
@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 location = implementation.getLastLocation(args.maximumAge)
|
||||
if (location != null) {
|
||||
invoke.resolve(convertLocation(location))
|
||||
} else {
|
||||
implementation.sendLocation(args.enableHighAccuracy,
|
||||
{ loc -> invoke.resolve(convertLocation(loc)) },
|
||||
{ error -> invoke.reject(error) })
|
||||
}
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private fun positionPermissionCallback(invoke: Invoke) {
|
||||
val permissionsResultJSON = JSObject()
|
||||
permissionsResultJSON.put("location", getPermissionState(ALIAS_LOCATION))
|
||||
permissionsResultJSON.put("coarseLocation", getPermissionState(ALIAS_COARSE_LOCATION))
|
||||
invoke.resolve(permissionsResultJSON)
|
||||
}
|
||||
|
||||
@Command
|
||||
fun watchPosition(invoke: Invoke) {
|
||||
val args = invoke.parseArgs(WatchArgs::class.java)
|
||||
startWatch(invoke, args)
|
||||
}
|
||||
|
||||
private fun startWatch(invoke: Invoke, args: WatchArgs) {
|
||||
implementation.requestLocationUpdates(
|
||||
args.options.enableHighAccuracy,
|
||||
args.options.timeout,
|
||||
{ location -> args.channel.send(convertLocation(location)) },
|
||||
{ error -> args.channel.sendObject(error) })
|
||||
|
||||
watchers[args.channel.id] = Pair(invoke, args)
|
||||
}
|
||||
|
||||
@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 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
|
||||
}
|
||||
}
|
||||
21
plugins/geolocation/android/src/test/java/ExampleUnitTest.kt
Normal file
21
plugins/geolocation/android/src/test/java/ExampleUnitTest.kt
Normal file
@@ -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)
|
||||
}
|
||||
}
|
||||
1
plugins/geolocation/api-iife.js
Normal file
1
plugins/geolocation/api-iife.js
Normal file
@@ -0,0 +1 @@
|
||||
if("__TAURI__"in window){var __TAURI_PLUGIN_GEOLOCATION__=function(n,i){"use strict";return n.checkPermissions=async function(){return await i.checkPermissions("geolocation")},n.clearWatch=async function(n){await i.invoke("plugin:geolocation|clear_watch",{channelId:n})},n.getCurrentPosition=async function(n){return await i.invoke("plugin:geolocation|get_current_position",{options:n})},n.requestPermissions=async function(n){return await i.invoke("plugin:geolocation|request_permissions",{permissions:n})},n.watchPosition=async function(n,o){const e=new i.Channel;return e.onmessage=n=>{"string"==typeof n?o(null,n):o(n)},await i.invoke("plugin:geolocation|watch_position",{options:n,channel:e}),e.id},n}({},window.__TAURI__.core);Object.defineProperty(window.__TAURI__,"geolocation",{value:__TAURI_PLUGIN_GEOLOCATION__})}
|
||||
24
plugins/geolocation/build.rs
Normal file
24
plugins/geolocation/build.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
// 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",
|
||||
"request_permissions",
|
||||
];
|
||||
|
||||
fn main() {
|
||||
let result = tauri_plugin::Builder::new(COMMANDS)
|
||||
.global_api_script_path("./api-iife.js")
|
||||
.android_path("android")
|
||||
.ios_path("ios")
|
||||
.try_build();
|
||||
|
||||
// when building documentation for Android the plugin build result is always Err() and is irrelevant to the crate documentation build
|
||||
if !(cfg!(docsrs) && std::env::var("TARGET").unwrap().contains("android")) {
|
||||
result.unwrap();
|
||||
}
|
||||
}
|
||||
31
plugins/geolocation/contributors/crabnebula.svg
Normal file
31
plugins/geolocation/contributors/crabnebula.svg
Normal file
@@ -0,0 +1,31 @@
|
||||
<svg class="crabnebula-logo" width="100%" height="100%" viewBox="0 0 1204 210" version="1.1"
|
||||
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
xml:space="preserve" xmlns:serif="http://www.serif.com/"
|
||||
style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
|
||||
<style>
|
||||
.crabnebula-logo path,
|
||||
.crabnebula-logo rect {
|
||||
fill: #001e42;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.crabnebula-logo path, .crabnebula-logo rect {
|
||||
fill: #fff;
|
||||
}
|
||||
}
|
||||
html[data-color-mode="dark"] .crabnebula-logo path,
|
||||
html[data-color-mode="dark"] .crabnebula-logo rect {
|
||||
fill: #fff;
|
||||
}
|
||||
</style>
|
||||
<path d="M351.903,162.334C344.288,162.334 337.123,160.881 330.41,157.975C323.696,155.069 317.834,151.11 312.824,146.099C307.914,141.089 304.006,135.276 301.101,128.662C298.195,121.948 296.742,114.783 296.742,107.167C296.742,99.55 298.195,92.435 301.101,85.821C304.006,79.107 307.914,73.244 312.824,68.234C317.834,63.223 323.696,59.265 330.41,56.358C337.123,53.452 344.288,51.999 351.903,51.999C357.414,51.999 362.675,52.701 367.685,54.103C372.795,55.507 377.455,57.511 381.663,60.116C385.972,62.622 389.83,65.678 393.237,69.286C396.644,72.793 399.499,76.752 401.804,81.161L380.762,92.586C377.756,87.174 373.848,82.915 369.038,79.808C364.328,76.702 358.617,75.148 351.903,75.148C347.494,75.148 343.386,76 339.578,77.704C335.871,79.407 332.614,81.762 329.809,84.769C327.003,87.675 324.798,91.082 323.195,94.991C321.592,98.799 320.79,102.857 320.79,107.167C320.79,111.476 321.592,115.584 323.195,119.493C324.798,123.301 327.003,126.708 329.809,129.715C332.614,132.621 335.871,134.926 339.578,136.629C343.386,138.333 347.494,139.185 351.903,139.185C358.617,139.185 364.328,137.631 369.038,134.525C373.848,131.418 377.756,127.159 380.762,121.748L401.804,133.172C399.499,137.581 396.644,141.59 393.237,145.198C389.83,148.705 385.972,151.762 381.663,154.367C377.455,156.872 372.795,158.827 367.685,160.23C362.675,161.633 357.414,162.334 351.903,162.334Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
|
||||
<path d="M413.821,85.37L436.517,85.37L436.517,96.644C437.72,93.337 439.924,90.481 443.131,88.076C446.437,85.671 450.195,84.468 454.403,84.468C455.506,84.468 456.658,84.518 457.86,84.619C459.063,84.719 460.366,84.969 461.768,85.37L461.768,108.369C460.065,107.768 458.412,107.317 456.808,107.016C455.205,106.716 453.502,106.565 451.698,106.565C446.788,106.565 443.03,108.269 440.425,111.676C437.82,115.083 436.517,119.493 436.517,124.904L436.517,160.53L413.821,160.53L413.821,85.37Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
|
||||
<path d="M502.161,162.184C497.251,162.184 492.642,161.132 488.333,159.027C484.125,156.923 480.467,154.117 477.361,150.609C474.255,147.001 471.8,142.843 469.996,138.133C468.193,133.322 467.291,128.261 467.291,122.95C467.291,117.639 468.193,112.628 469.996,107.918C471.8,103.108 474.255,98.949 477.361,95.442C480.467,91.834 484.125,88.978 488.333,86.873C492.642,84.769 497.251,83.717 502.161,83.717C504.666,83.717 506.971,84.017 509.075,84.619C511.28,85.12 513.234,85.821 514.937,86.723C516.741,87.625 518.244,88.627 519.446,89.729C520.749,90.832 521.801,91.884 522.603,92.886L522.603,85.37L545.299,85.37L545.299,160.53L522.603,160.53L522.603,153.014C521.801,154.016 520.749,155.069 519.446,156.171C518.244,157.273 516.741,158.275 514.937,159.177C513.234,160.079 511.28,160.781 509.075,161.282C506.971,161.883 504.666,162.184 502.161,162.184ZM507.272,141.59C512.382,141.59 516.49,139.836 519.597,136.329C522.803,132.821 524.406,128.362 524.406,122.95C524.406,117.539 522.803,113.079 519.597,109.572C516.49,106.064 512.382,104.31 507.272,104.31C502.161,104.31 498.003,106.064 494.796,109.572C491.69,113.079 490.137,117.539 490.137,122.95C490.137,128.362 491.69,132.821 494.796,136.329C498.003,139.836 502.161,141.59 507.272,141.59Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
|
||||
<path d="M607.116,162.184C604.611,162.184 602.256,161.883 600.051,161.282C597.947,160.781 595.993,160.079 594.19,159.177C592.486,158.275 590.983,157.273 589.681,156.171C588.378,155.069 587.376,154.016 586.674,153.014L586.674,160.53L563.979,160.53L563.979,47.79L586.674,47.79L586.674,92.886C587.376,91.884 588.378,90.832 589.681,89.729C590.983,88.627 592.486,87.625 594.19,86.723C595.993,85.821 597.947,85.12 600.051,84.619C602.256,84.017 604.611,83.717 607.116,83.717C612.026,83.717 616.585,84.769 620.793,86.873C625.102,88.978 628.81,91.834 631.916,95.442C635.022,98.949 637.477,103.108 639.281,107.918C641.084,112.628 641.986,117.639 641.986,122.95C641.986,128.261 641.084,133.322 639.281,138.133C637.477,142.843 635.022,147.001 631.916,150.609C628.81,154.117 625.102,156.923 620.793,159.027C616.585,161.132 612.026,162.184 607.116,162.184ZM602.005,141.59C607.116,141.59 611.224,139.836 614.33,136.329C617.537,132.821 619.14,128.362 619.14,122.95C619.14,117.539 617.537,113.079 614.33,109.572C611.224,106.064 607.116,104.31 602.005,104.31C596.895,104.31 592.737,106.064 589.53,109.572C586.424,113.079 584.871,117.539 584.871,122.95C584.871,128.362 586.424,132.821 589.53,136.329C592.737,139.836 596.895,141.59 602.005,141.59Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
|
||||
<path d="M732.106,160.53L680.101,94.54L680.101,160.53L656.203,160.53L656.203,53.803L676.795,53.803L728.649,119.793L728.649,53.803L752.698,53.803L752.698,160.53L732.106,160.53Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
|
||||
<path d="M806.852,162.184C801.341,162.184 796.13,161.282 791.22,159.478C786.411,157.674 782.202,155.069 778.595,151.661C774.988,148.254 772.132,144.145 770.028,139.335C767.923,134.425 766.871,128.963 766.871,122.95C766.871,117.338 767.823,112.177 769.727,107.467C771.731,102.657 774.487,98.498 777.994,94.991C781.601,91.483 785.809,88.727 790.619,86.723C795.429,84.719 800.69,83.717 806.401,83.717C811.311,83.717 816.021,84.518 820.53,86.122C825.139,87.625 829.147,89.93 832.554,93.036C835.961,96.043 838.666,99.851 840.67,104.461C842.775,108.97 843.827,114.282 843.827,120.395C843.827,121.397 843.777,122.549 843.677,123.852C843.677,125.055 843.576,126.558 843.376,128.362L788.816,128.362C789.517,132.871 791.671,136.228 795.279,138.433C798.886,140.538 802.844,141.59 807.153,141.59C811.562,141.59 815.319,140.738 818.425,139.034C821.632,137.231 823.937,135.226 825.339,133.022L842.173,145.649C838.666,150.659 833.857,154.668 827.744,157.674C821.732,160.681 814.768,162.184 806.852,162.184ZM821.281,113.48C820.279,109.471 818.275,106.615 815.269,104.912C812.263,103.108 809.107,102.206 805.8,102.206C804.096,102.206 802.393,102.406 800.69,102.807C798.986,103.208 797.383,103.859 795.88,104.761C794.377,105.663 793.024,106.816 791.822,108.219C790.719,109.622 789.918,111.376 789.417,113.48L821.281,113.48Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
|
||||
<path d="M901.265,162.184C898.76,162.184 896.405,161.883 894.201,161.282C892.097,160.781 890.143,160.079 888.339,159.177C886.636,158.275 885.133,157.273 883.83,156.171C882.527,155.069 881.525,154.016 880.824,153.014L880.824,160.53L858.128,160.53L858.128,47.79L880.824,47.79L880.824,92.886C881.525,91.884 882.527,90.832 883.83,89.729C885.133,88.627 886.636,87.625 888.339,86.723C890.143,85.821 892.097,85.12 894.201,84.619C896.405,84.017 898.76,83.717 901.265,83.717C906.175,83.717 910.734,84.769 914.943,86.873C919.252,88.978 922.959,91.834 926.065,95.442C929.172,98.949 931.627,103.108 933.43,107.918C935.234,112.628 936.136,117.639 936.136,122.95C936.136,128.261 935.234,133.322 933.43,138.133C931.627,142.843 929.172,147.001 926.065,150.609C922.959,154.117 919.252,156.923 914.943,159.027C910.734,161.132 906.175,162.184 901.265,162.184ZM896.155,141.59C901.265,141.59 905.374,139.836 908.48,136.329C911.686,132.821 913.29,128.362 913.29,122.95C913.29,117.539 911.686,113.079 908.48,109.572C905.374,106.064 901.265,104.31 896.155,104.31C891.045,104.31 886.886,106.064 883.68,109.572C880.573,113.079 879.02,117.539 879.02,122.95C879.02,128.362 880.573,132.821 883.68,136.329C886.886,139.836 891.045,141.59 896.155,141.59Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
|
||||
<path d="M977.812,162.184C968.493,162.184 961.429,159.077 956.619,152.864C951.81,146.651 949.405,138.433 949.405,128.211L949.405,85.37L972.101,85.37L972.101,124.303C972.101,129.815 972.952,134.074 974.656,137.08C976.459,140.087 979.466,141.59 983.674,141.59C987.983,141.59 991.39,140.037 993.895,136.93C996.5,133.823 997.803,128.813 997.803,121.898L997.803,85.37L1020.5,85.37L1020.5,160.53L997.803,160.53L997.803,152.864C995.999,155.469 993.444,157.674 990.137,159.478C986.83,161.282 982.722,162.184 977.812,162.184Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
|
||||
<rect x="1039.11" y="47.79" width="22.701" height="112.74" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
|
||||
<path d="M1110.86,162.184C1105.95,162.184 1101.34,161.132 1097.03,159.027C1092.83,156.923 1089.17,154.117 1086.06,150.609C1082.96,147.001 1080.5,142.843 1078.7,138.133C1076.89,133.322 1075.99,128.261 1075.99,122.95C1075.99,117.639 1076.89,112.628 1078.7,107.918C1080.5,103.108 1082.96,98.949 1086.06,95.442C1089.17,91.834 1092.83,88.978 1097.03,86.873C1101.34,84.769 1105.95,83.717 1110.86,83.717C1113.37,83.717 1115.67,84.017 1117.78,84.619C1119.98,85.12 1121.94,85.821 1123.64,86.723C1125.44,87.625 1126.95,88.627 1128.15,89.729C1129.45,90.832 1130.5,91.884 1131.3,92.886L1131.3,85.37L1154,85.37L1154,160.53L1131.3,160.53L1131.3,153.014C1130.5,154.016 1129.45,155.069 1128.15,156.171C1126.95,157.273 1125.44,158.275 1123.64,159.177C1121.94,160.079 1119.98,160.781 1117.78,161.282C1115.67,161.883 1113.37,162.184 1110.86,162.184ZM1115.97,141.59C1121.08,141.59 1125.19,139.836 1128.3,136.329C1131.5,132.821 1133.11,128.362 1133.11,122.95C1133.11,117.539 1131.5,113.079 1128.3,109.572C1125.19,106.064 1121.08,104.31 1115.97,104.31C1110.86,104.31 1106.7,106.064 1103.5,109.572C1100.39,113.079 1098.84,117.539 1098.84,122.95C1098.84,128.362 1100.39,132.821 1103.5,136.329C1106.7,139.836 1110.86,141.59 1115.97,141.59Z" style="fill-rule:nonzero;stroke:black;stroke-width:0.55px;"/>
|
||||
<path d="M146.48,54.585C119.724,89.866 119.878,134.941 146.826,155.264C153.908,160.605 162.136,163.705 170.903,164.732C146.032,184.934 117.382,191.203 98.037,178.045C71.507,160 72.524,112.249 100.309,71.391C123.51,37.273 158.039,18.749 184.247,24.072C170.404,30.195 157.116,40.561 146.48,54.585ZM181.638,99.643C169.141,111.453 154.859,119.304 142.801,121.916C149.921,147.367 177.29,149.323 177.29,149.323C177.29,149.323 193.578,145.578 205.877,117.941C216.005,95.183 215.122,71.668 204.914,59.7C204.065,71.267 195.731,86.324 181.638,99.643Z" style="stroke:black;stroke-width:0.55px;"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 11 KiB |
BIN
plugins/geolocation/contributors/rescue.png
Normal file
BIN
plugins/geolocation/contributors/rescue.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 7.9 KiB |
239
plugins/geolocation/guest-js/index.ts
Normal file
239
plugins/geolocation/guest-js/index.ts
Normal file
@@ -0,0 +1,239 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/**
|
||||
* Get and track the device's current position, mirroring the W3C Geolocation API.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import {
|
||||
Channel,
|
||||
invoke,
|
||||
PermissionState,
|
||||
checkPermissions as checkPluginPermissions
|
||||
} from '@tauri-apps/api/core'
|
||||
|
||||
/**
|
||||
* The GPS coordinates of a {@link Position}, along with the accuracy of each reading.
|
||||
*/
|
||||
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
|
||||
/**
|
||||
* The speed the user is traveling, in meters per second, if available.
|
||||
*/
|
||||
speed: number | null
|
||||
/**
|
||||
* The heading the user is facing, if available.
|
||||
*/
|
||||
heading: number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* The current permission state for the geolocation APIs.
|
||||
*/
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* The individual permission aliases that can be requested with {@link requestPermissions}.
|
||||
*
|
||||
* `location` maps to both the coarse and fine location permissions on Android and to the standard
|
||||
* location permission on iOS. `coarseLocation` maps to the coarse location permission only on
|
||||
* Android, and behaves the same as `location` on iOS.
|
||||
*/
|
||||
export type PermissionType = 'location' | 'coarseLocation'
|
||||
|
||||
/**
|
||||
* A geolocation reading, as returned by {@link getCurrentPosition} and passed to the callback of {@link watchPosition}.
|
||||
*/
|
||||
export type Position = {
|
||||
/**
|
||||
* Creation time for these coordinates, in milliseconds since the Unix epoch.
|
||||
*/
|
||||
timestamp: number
|
||||
/**
|
||||
* The GPS coordinates along with the accuracy of the data.
|
||||
*/
|
||||
coords: Coordinates
|
||||
}
|
||||
|
||||
/**
|
||||
* Options used to configure a {@link getCurrentPosition} or {@link watchPosition} request.
|
||||
*/
|
||||
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 (`coarseLocation` 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
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a callback that is invoked with the device's position whenever it changes, similar to the W3C `navigator.geolocation.watchPosition` API. Pass the returned id to {@link clearWatch} to stop watching.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { watchPosition } from '@tauri-apps/plugin-geolocation';
|
||||
* const watchId = await watchPosition(
|
||||
* { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 },
|
||||
* (position, error) => {
|
||||
* if (error) {
|
||||
* console.error(error)
|
||||
* } else {
|
||||
* console.log(position)
|
||||
* }
|
||||
* }
|
||||
* );
|
||||
* ```
|
||||
*
|
||||
* @param options Configuration for the position watcher.
|
||||
* @param cb Callback invoked with the new {@link Position} on success, or `null` and an error message when a read fails.
|
||||
* @returns A promise resolving to the id of the registered watcher.
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export async function watchPosition(
|
||||
options: PositionOptions,
|
||||
cb: (location: Position | null, error?: string) => void
|
||||
): Promise<number> {
|
||||
const channel = new Channel<Position | string>()
|
||||
channel.onmessage = (message) => {
|
||||
if (typeof message === 'string') {
|
||||
cb(null, message)
|
||||
} else {
|
||||
cb(message)
|
||||
}
|
||||
}
|
||||
await invoke('plugin:geolocation|watch_position', {
|
||||
options,
|
||||
channel
|
||||
})
|
||||
return channel.id
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the device's current position, similar to the W3C `navigator.geolocation.getCurrentPosition` API.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { getCurrentPosition } from '@tauri-apps/plugin-geolocation';
|
||||
* const position = await getCurrentPosition();
|
||||
* ```
|
||||
*
|
||||
* @param options Configuration for the position request.
|
||||
* @returns A promise resolving to the current {@link Position}.
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export async function getCurrentPosition(
|
||||
options?: PositionOptions
|
||||
): Promise<Position> {
|
||||
return await invoke('plugin:geolocation|get_current_position', {
|
||||
options
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the position watcher registered with {@link watchPosition}.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { clearWatch } from '@tauri-apps/plugin-geolocation';
|
||||
* await clearWatch(watchId);
|
||||
* ```
|
||||
*
|
||||
* @param channelId The id returned by {@link watchPosition}.
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export async function clearWatch(channelId: number): Promise<void> {
|
||||
await invoke('plugin:geolocation|clear_watch', {
|
||||
channelId
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current state of the geolocation permissions. Rejects if location services are disabled on the device.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { checkPermissions } from '@tauri-apps/plugin-geolocation';
|
||||
* const permission = await checkPermissions();
|
||||
* ```
|
||||
*
|
||||
* @returns A promise resolving to the current {@link PermissionStatus}.
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export async function checkPermissions(): Promise<PermissionStatus> {
|
||||
return await checkPluginPermissions('geolocation')
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests the given geolocation permissions, prompting the user if needed. Rejects if location services are disabled on the device.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { requestPermissions } from '@tauri-apps/plugin-geolocation';
|
||||
* const permission = await requestPermissions(['location']);
|
||||
* ```
|
||||
*
|
||||
* @param permissions The permissions to request, or `null` to request all of them.
|
||||
* @returns A promise resolving to the resulting {@link PermissionStatus}.
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export async function requestPermissions(
|
||||
permissions: PermissionType[] | null
|
||||
): Promise<PermissionStatus> {
|
||||
return await invoke('plugin:geolocation|request_permissions', {
|
||||
permissions
|
||||
})
|
||||
}
|
||||
10
plugins/geolocation/ios/.gitignore
vendored
Normal file
10
plugins/geolocation/ios/.gitignore
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
.DS_Store
|
||||
/.build
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
xcuserdata/
|
||||
DerivedData/
|
||||
.swiftpm/config/registries.json
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
.netrc
|
||||
Package.resolved
|
||||
34
plugins/geolocation/ios/Package.swift
Normal file
34
plugins/geolocation/ios/Package.swift
Normal file
@@ -0,0 +1,34 @@
|
||||
// swift-tools-version:5.3
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "tauri-plugin-geolocation",
|
||||
platforms: [
|
||||
.macOS(.v10_13),
|
||||
.iOS(.v13),
|
||||
],
|
||||
products: [
|
||||
// Products define the executables and libraries a package produces, and make them visible to other packages.
|
||||
.library(
|
||||
name: "tauri-plugin-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")
|
||||
]
|
||||
)
|
||||
3
plugins/geolocation/ios/README.md
Normal file
3
plugins/geolocation/ios/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# Tauri Plugin Geolocation
|
||||
|
||||
A description of this package.
|
||||
250
plugins/geolocation/ios/Sources/GeolocationPlugin.swift
Normal file
250
plugins/geolocation/ios/Sources/GeolocationPlugin.swift
Normal file
@@ -0,0 +1,250 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import CoreLocation
|
||||
import SwiftRs
|
||||
import Tauri
|
||||
import UIKit
|
||||
import WebKit
|
||||
|
||||
class GetPositionArgs: Decodable {
|
||||
var 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()
|
||||
}
|
||||
12
plugins/geolocation/ios/Tests/PluginTests/PluginTests.swift
Normal file
12
plugins/geolocation/ios/Tests/PluginTests/PluginTests.swift
Normal file
@@ -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()
|
||||
}
|
||||
}
|
||||
29
plugins/geolocation/package.json
Normal file
29
plugins/geolocation/package.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@tauri-apps/plugin-geolocation",
|
||||
"version": "2.3.3",
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"authors": [
|
||||
"Tauri Programme within The Commons Conservancy"
|
||||
],
|
||||
"repository": "https://github.com/tauri-apps/plugins-workspace",
|
||||
"type": "module",
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"main": "./dist-js/index.cjs",
|
||||
"module": "./dist-js/index.js",
|
||||
"exports": {
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"import": "./dist-js/index.js",
|
||||
"require": "./dist-js/index.cjs"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rollup -c"
|
||||
},
|
||||
"files": [
|
||||
"dist-js",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.11.0"
|
||||
}
|
||||
}
|
||||
@@ -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-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-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-request-permissions"
|
||||
description = "Enables the request_permissions command without any pre-configured scope."
|
||||
commands.allow = ["request_permissions"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-request-permissions"
|
||||
description = "Denies the request_permissions command without any pre-configured scope."
|
||||
commands.deny = ["request_permissions"]
|
||||
@@ -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"]
|
||||
165
plugins/geolocation/permissions/autogenerated/reference.md
Normal file
165
plugins/geolocation/permissions/autogenerated/reference.md
Normal file
@@ -0,0 +1,165 @@
|
||||
## 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-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-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-request-permissions`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the request_permissions command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`geolocation:deny-request-permissions`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the request_permissions 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>
|
||||
372
plugins/geolocation/permissions/schemas/schema.json
Normal file
372
plugins/geolocation/permissions/schemas/schema.json
Normal file
@@ -0,0 +1,372 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "PermissionFile",
|
||||
"description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"default": {
|
||||
"description": "The default permission set for the plugin",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/DefaultPermission"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"set": {
|
||||
"description": "A list of permissions sets defined",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/PermissionSet"
|
||||
}
|
||||
},
|
||||
"permission": {
|
||||
"description": "A list of inlined permissions",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Permission"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"DefaultPermission": {
|
||||
"description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"permissions"
|
||||
],
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "The version of the permission.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint64",
|
||||
"minimum": 1.0
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"permissions": {
|
||||
"description": "All permissions this set contains.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"PermissionSet": {
|
||||
"description": "A set of direct permissions grouped together under a new name.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"description",
|
||||
"identifier",
|
||||
"permissions"
|
||||
],
|
||||
"properties": {
|
||||
"identifier": {
|
||||
"description": "A unique identifier for the permission.",
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does.",
|
||||
"type": "string"
|
||||
},
|
||||
"permissions": {
|
||||
"description": "All permissions this set contains.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/PermissionKind"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Permission": {
|
||||
"description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"identifier"
|
||||
],
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "The version of the permission.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint64",
|
||||
"minimum": 1.0
|
||||
},
|
||||
"identifier": {
|
||||
"description": "A unique identifier for the permission.",
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"commands": {
|
||||
"description": "Allowed or denied commands when using this permission.",
|
||||
"default": {
|
||||
"allow": [],
|
||||
"deny": []
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Commands"
|
||||
}
|
||||
]
|
||||
},
|
||||
"scope": {
|
||||
"description": "Allowed or denied scoped when using this permission.",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Scopes"
|
||||
}
|
||||
]
|
||||
},
|
||||
"platforms": {
|
||||
"description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Target"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Commands": {
|
||||
"description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"allow": {
|
||||
"description": "Allowed command.",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"deny": {
|
||||
"description": "Denied command, which takes priority.",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Scopes": {
|
||||
"description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"allow": {
|
||||
"description": "Data that defines what is allowed by the scope.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
},
|
||||
"deny": {
|
||||
"description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Value": {
|
||||
"description": "All supported ACL values.",
|
||||
"anyOf": [
|
||||
{
|
||||
"description": "Represents a null JSON value.",
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`bool`].",
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"description": "Represents a valid ACL [`Number`].",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Number"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`String`].",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"description": "Represents a list of other [`Value`]s.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "Represents a map of [`String`] keys to [`Value`]s.",
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"Number": {
|
||||
"description": "A valid ACL number.",
|
||||
"anyOf": [
|
||||
{
|
||||
"description": "Represents an [`i64`].",
|
||||
"type": "integer",
|
||||
"format": "int64"
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`f64`].",
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Target": {
|
||||
"description": "Platform target.",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "MacOS.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"macOS"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Windows.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"windows"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Linux.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"linux"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Android.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"android"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "iOS.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"iOS"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"PermissionKind": {
|
||||
"type": "string",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "Enables the check_permissions command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-check-permissions",
|
||||
"markdownDescription": "Enables the check_permissions command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the check_permissions command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-check-permissions",
|
||||
"markdownDescription": "Denies the check_permissions command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the clear_permissions command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-clear-permissions",
|
||||
"markdownDescription": "Enables the clear_permissions command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the clear_permissions command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-clear-permissions",
|
||||
"markdownDescription": "Denies the clear_permissions command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the clear_watch command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-clear-watch",
|
||||
"markdownDescription": "Enables the clear_watch command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the clear_watch command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-clear-watch",
|
||||
"markdownDescription": "Denies the clear_watch command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the get_current_position command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-get-current-position",
|
||||
"markdownDescription": "Enables the get_current_position command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the get_current_position command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-get-current-position",
|
||||
"markdownDescription": "Denies the get_current_position command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the request_permissions command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-request-permissions",
|
||||
"markdownDescription": "Enables the request_permissions command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the request_permissions command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-request-permissions",
|
||||
"markdownDescription": "Denies the request_permissions command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the watch_position command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-watch-position",
|
||||
"markdownDescription": "Enables the watch_position command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the watch_position command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-watch-position",
|
||||
"markdownDescription": "Denies the watch_position command without any pre-configured scope."
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
7
plugins/geolocation/rollup.config.js
Normal file
7
plugins/geolocation/rollup.config.js
Normal file
@@ -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()
|
||||
42
plugins/geolocation/src/commands.rs
Normal file
42
plugins/geolocation/src/commands.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
// 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]
|
||||
pub(crate) async fn get_current_position<R: Runtime>(
|
||||
app: AppHandle<R>,
|
||||
options: Option<PositionOptions>,
|
||||
) -> Result<Position> {
|
||||
app.geolocation().get_current_position(options)
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub(crate) async fn watch_position<R: Runtime>(
|
||||
app: AppHandle<R>,
|
||||
options: PositionOptions,
|
||||
channel: Channel,
|
||||
) -> Result<()> {
|
||||
app.geolocation().watch_position_inner(options, channel)
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub(crate) async fn clear_watch<R: Runtime>(app: AppHandle<R>, channel_id: u32) -> Result<()> {
|
||||
app.geolocation().clear_watch(channel_id)
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub(crate) async fn check_permissions<R: Runtime>(app: AppHandle<R>) -> Result<PermissionStatus> {
|
||||
app.geolocation().check_permissions()
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub(crate) async fn request_permissions<R: Runtime>(
|
||||
app: AppHandle<R>,
|
||||
permissions: Option<Vec<PermissionType>>,
|
||||
) -> Result<PermissionStatus> {
|
||||
app.geolocation().request_permissions(permissions)
|
||||
}
|
||||
100
plugins/geolocation/src/desktop.rs
Normal file
100
plugins/geolocation/src/desktop.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
// 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, InvokeResponseBody},
|
||||
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> {
|
||||
/// Not implemented on desktop platforms; always resolves to a default, zeroed [`Position`] without reading any real location.
|
||||
pub fn get_current_position(
|
||||
&self,
|
||||
_options: Option<PositionOptions>,
|
||||
) -> crate::Result<Position> {
|
||||
Ok(Position::default())
|
||||
}
|
||||
|
||||
/// Not implemented on desktop platforms. Registers a channel for `channel_id` bookkeeping, but `callback` is never invoked with a real [`WatchEvent`].
|
||||
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 {
|
||||
InvokeResponseBody::Json(payload) => serde_json::from_str::<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(())
|
||||
}
|
||||
|
||||
/// Not implemented on desktop platforms; always succeeds without doing anything.
|
||||
pub fn clear_watch(&self, _channel_id: u32) -> crate::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Not implemented on desktop platforms; always resolves to the default [`PermissionStatus`] (both permissions in the [`Prompt`](tauri::plugin::PermissionState::Prompt) state).
|
||||
pub fn check_permissions(&self) -> crate::Result<PermissionStatus> {
|
||||
Ok(PermissionStatus::default())
|
||||
}
|
||||
|
||||
/// Not implemented on desktop platforms; always resolves to the default [`PermissionStatus`] without prompting the user.
|
||||
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,
|
||||
}
|
||||
33
plugins/geolocation/src/error.rs
Normal file
33
plugins/geolocation/src/error.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::{ser::Serializer, Serialize};
|
||||
|
||||
/// Alias for the result type returned by the geolocation APIs.
|
||||
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)
|
||||
|
||||
/// Errors that can occur while interacting with the geolocation APIs.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[cfg_attr(feature = "specta", derive(specta::Type))]
|
||||
pub enum Error {
|
||||
/// Forwards an error returned by the underlying Android or iOS plugin invocation.
|
||||
#[cfg(mobile)]
|
||||
#[error(transparent)]
|
||||
PluginInvoke(
|
||||
#[cfg_attr(feature = "specta", specta(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())
|
||||
}
|
||||
}
|
||||
65
plugins/geolocation/src/lib.rs
Normal file
65
plugins/geolocation/src/lib.rs
Normal file
@@ -0,0 +1,65 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//! Access device geolocation APIs.
|
||||
//!
|
||||
//! ## Cargo features
|
||||
//!
|
||||
//! - **specta**: Add support for [`specta::specta`](https://docs.rs/specta/2.0.0-rc.25/specta/attr.specta.html) on structs like [`PermissionStatus`], [`PositionOptions`].
|
||||
|
||||
use tauri::{
|
||||
plugin::{Builder, TauriPlugin},
|
||||
Manager, Runtime,
|
||||
};
|
||||
|
||||
pub use models::*;
|
||||
|
||||
#[cfg(desktop)]
|
||||
mod desktop;
|
||||
#[cfg(mobile)]
|
||||
mod mobile;
|
||||
|
||||
mod commands;
|
||||
mod error;
|
||||
mod models;
|
||||
|
||||
pub use error::{Error, Result};
|
||||
|
||||
#[cfg(desktop)]
|
||||
pub use desktop::Geolocation;
|
||||
#[cfg(mobile)]
|
||||
pub use mobile::Geolocation;
|
||||
|
||||
/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the geolocation APIs.
|
||||
pub trait GeolocationExt<R: Runtime> {
|
||||
/// Returns the handle to the geolocation APIs.
|
||||
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> {
|
||||
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()
|
||||
}
|
||||
123
plugins/geolocation/src/mobile.rs
Normal file
123
plugins/geolocation/src/mobile.rs
Normal file
@@ -0,0 +1,123 @@
|
||||
// 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, InvokeResponseBody},
|
||||
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> {
|
||||
/// Returns the device's current [`Position`]. On Android this returns the last known location immediately if it is still within `maximum_age`, otherwise it requests a fresh reading. Errors if location services are disabled or the required permission was not granted.
|
||||
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 {
|
||||
InvokeResponseBody::Json(payload) => serde_json::from_str::<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,
|
||||
channel: Channel,
|
||||
) -> crate::Result<()> {
|
||||
self.0
|
||||
.run_mobile_plugin("watchPosition", WatchPayload { options, channel })
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Removes the position watcher registered with the given `channel_id`, as returned by [`Self::watch_position`]. Stops the platform location updates once no watcher remains.
|
||||
pub fn clear_watch(&self, channel_id: u32) -> crate::Result<()> {
|
||||
self.0
|
||||
.run_mobile_plugin("clearWatch", ClearWatchPayload { channel_id })
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Returns the current [`PermissionStatus`] for the geolocation APIs. Errors if location services are disabled on the device.
|
||||
pub fn check_permissions(&self) -> crate::Result<PermissionStatus> {
|
||||
self.0
|
||||
.run_mobile_plugin("checkPermissions", ())
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Requests the given `permissions` (or all of them when `None`) and returns the resulting [`PermissionStatus`]. Errors if location services are disabled on the device.
|
||||
pub fn request_permissions(
|
||||
&self,
|
||||
permissions: Option<Vec<PermissionType>>,
|
||||
) -> crate::Result<PermissionStatus> {
|
||||
self.0
|
||||
.run_mobile_plugin(
|
||||
"requestPermissions",
|
||||
serde_json::json!({ "permissions": permissions }),
|
||||
)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct WatchPayload {
|
||||
options: PositionOptions,
|
||||
channel: Channel,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ClearWatchPayload {
|
||||
channel_id: u32,
|
||||
}
|
||||
106
plugins/geolocation/src/models.rs
Normal file
106
plugins/geolocation/src/models.rs
Normal file
@@ -0,0 +1,106 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::plugin::PermissionState;
|
||||
|
||||
/// The current permission state for the geolocation APIs.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "specta", derive(specta::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,
|
||||
}
|
||||
|
||||
/// Options used to configure a [`get_current_position`](crate::Geolocation::get_current_position) or [`watch_position`](crate::Geolocation::watch_position) request.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "specta", derive(specta::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,
|
||||
}
|
||||
|
||||
/// The individual permission aliases that can be requested with [`request_permissions`](crate::Geolocation::request_permissions).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "specta", derive(specta::Type))]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PermissionType {
|
||||
/// The `location` alias. On Android this maps to both `ACCESS_COARSE_LOCATION` and `ACCESS_FINE_LOCATION`. On iOS it maps to the standard location permission.
|
||||
Location,
|
||||
/// The `coarseLocation` alias. On Android this maps to `ACCESS_COARSE_LOCATION` only. On iOS it behaves the same as [`Location`](Self::Location).
|
||||
CoarseLocation,
|
||||
}
|
||||
|
||||
/// The GPS coordinates of a [`Position`], along with the accuracy of each reading.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "specta", derive(specta::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, in meters per second, if available.
|
||||
pub speed: Option<f64>,
|
||||
/// The heading the user is facing, if available.
|
||||
pub heading: Option<f64>,
|
||||
}
|
||||
|
||||
/// A geolocation reading, as returned by [`get_current_position`](crate::Geolocation::get_current_position) and reported through [`WatchEvent::Position`].
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "specta", derive(specta::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,
|
||||
}
|
||||
|
||||
/// A single update sent through the channel callback registered with [`watch_position`](crate::Geolocation::watch_position).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "specta", derive(specta::Type))]
|
||||
#[serde(untagged)]
|
||||
pub enum WatchEvent {
|
||||
/// A new position was read successfully.
|
||||
Position(Position),
|
||||
/// The platform failed to read a position; the string is the platform-provided error message.
|
||||
Error(String),
|
||||
}
|
||||
7
plugins/geolocation/tsconfig.json
Normal file
7
plugins/geolocation/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "guest-js"
|
||||
},
|
||||
"include": ["guest-js/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user