mirror of
https://github.com/tauri-apps/plugins-workspace.git
synced 2026-06-04 13:48:01 +02:00
feat: Add geolocation and haptics plugins (#1599)
* init geolocation plugin * ios impl (w/o js api) * generate ts api * use newer tauri commit * add temporary postinstall * include src in files * guest-js * just ship dist-js for now * fix watcher * fix android compile error * fix android build for real * fix heading type * initial getCurrentPosition android impl (wip) * prevent panics if errors (strings) are sent over the channel * Add android watchPosition implementation * init haptics plugin (android) * ios and new apis (ANDROID IS LIKELY BROKEN - MAY NOT EVEN COMPILE) * use tauri-specta that accounts for raw fn arg idents * add complete android support (it's not working great due to random soft-/hardware support) * fix(haptics): Fix the NotificationFeedbackType::Success and Version (#1) * Fix success feedback and version * Apply suggestions from code review * Update package.json --------- Co-authored-by: Fabian-Lars <118197967+FabianLars-crabnebula@users.noreply.github.com> * android: improve permission callback handling * keep track of ongoing perms requests * rebuild * license headers * rm sqlite feat * fmt * what diff u talkin bout? * ignore dist-js again * fix audits * dedupe api.js * clippy * changefiles * readmes * clean up todos * rm dsstore * rm wrong feats * mirror * covector * rebuild * ios requires the wry feature * lint * update lock --------- Co-authored-by: fabianlars <fabianlars@fabianlars.de> Co-authored-by: Brendan Allan <brendonovich@outlook.com> Co-authored-by: Naman Garg <155433377+naman-crabnebula@users.noreply.github.com> Co-authored-by: Lucas Nogueira <lucas@crabnebula.dev>
This commit is contained in:
@@ -0,0 +1 @@
|
||||
/.tauri
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "tauri-plugin-haptics"
|
||||
version = "2.0.0-beta.0"
|
||||
edition = { workspace = true }
|
||||
authors = { workspace = true }
|
||||
license = { workspace = true }
|
||||
repository = { workspace = true }
|
||||
links = "tauri-plugin-haptics"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
rustc-args = ["--cfg", "docsrs"]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-plugin = { workspace = true, features = ["build"] }
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tauri = { workspace = true, features = ["specta"] }
|
||||
log = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
specta = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies]
|
||||
tauri = { workspace = true, features = ["wry"] }
|
||||
@@ -0,0 +1,20 @@
|
||||
SPDXVersion: SPDX-2.1
|
||||
DataLicense: CC0-1.0
|
||||
PackageName: tauri
|
||||
DataFormat: SPDXRef-1
|
||||
PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
|
||||
PackageHomePage: https://tauri.app
|
||||
PackageLicenseDeclared: Apache-2.0
|
||||
PackageLicenseDeclared: MIT
|
||||
PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
|
||||
PackageSummary: <text>Tauri is a rust project that enables developers to make secure
|
||||
and small desktop applications using a web frontend.
|
||||
</text>
|
||||
PackageComment: <text>The package includes the following libraries; see
|
||||
Relationship information.
|
||||
</text>
|
||||
Created: 2019-05-20T09:00:00Z
|
||||
PackageDownloadLocation: git://github.com/tauri-apps/tauri
|
||||
PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
|
||||
PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
|
||||
Creator: Person: Daniel Thompson-Yvetot
|
||||
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 - Present Tauri Apps Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,123 @@
|
||||

|
||||
|
||||
Haptic feedback and vibrations on Android and iOS.
|
||||
|
||||
There are no standards/requirements for vibration support on Android, so the `feedback` APIs may not work correctly on more affordable phones, including recently released ones.
|
||||
|
||||
## Install
|
||||
|
||||
_This plugin requires a Rust version of at least **1.75**_
|
||||
|
||||
There are three general methods of installation that we can recommend.
|
||||
|
||||
1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
|
||||
2. Pull sources directly from Github using git tags / revision hashes (most secure)
|
||||
3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
|
||||
|
||||
Install the Core plugin by adding the following to your `Cargo.toml` file:
|
||||
|
||||
`src-tauri/Cargo.toml`
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
tauri-plugin-haptics = "2.0.0-beta"
|
||||
# alternatively with Git:
|
||||
tauri-plugin-haptics = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
|
||||
```
|
||||
|
||||
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
|
||||
|
||||
> Note: Since most JavaScript package managers are unable to install packages from git monorepos we provide read-only mirrors of each plugin. This makes installation option 2 more ergonomic to use.
|
||||
|
||||
<!-- Add the branch for installations using git! -->
|
||||
|
||||
```sh
|
||||
pnpm add @tauri-apps/plugin-haptics
|
||||
# or
|
||||
npm add @tauri-apps/plugin-haptics
|
||||
# or
|
||||
yarn add @tauri-apps/plugin-haptics
|
||||
|
||||
# alternatively with Git:
|
||||
pnpm add https://github.com/tauri-apps/tauri-plugin-haptics#v2
|
||||
# or
|
||||
npm add https://github.com/tauri-apps/tauri-plugin-haptics#v2
|
||||
# or
|
||||
yarn add https://github.com/tauri-apps/tauri-plugin-haptics#v2
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
First you need to register the core plugin with Tauri:
|
||||
|
||||
`src-tauri/src/main.rs`
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_haptics::init())
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
```
|
||||
|
||||
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
|
||||
|
||||
```javascript
|
||||
import {
|
||||
vibrate,
|
||||
impactFeedback,
|
||||
notificationFeedback,
|
||||
selectionFeedback,
|
||||
} from "@tauri-apps/plugin-haptics";
|
||||
|
||||
await vibrate(1);
|
||||
await impactFeedback("medium");
|
||||
await notificationFeedback("warning");
|
||||
await selectionFeedback();
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
|
||||
|
||||
## Contributed By
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://crabnebula.dev" target="_blank">
|
||||
<img src="contributors/crabnebula.svg" alt="CrabNebula" width="283">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://rescue.co" target="_blank">
|
||||
<img src="contributors/rescue.png" alt="Rescue.co" width="283" height="90">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
## Partners
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://crabnebula.dev" target="_blank">
|
||||
<img src="https://github.com/tauri-apps/plugins-workspace/raw/v2/.github/sponsors/crabnebula.svg" alt="CrabNebula" width="283">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
|
||||
|
||||
## License
|
||||
|
||||
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
|
||||
|
||||
MIT or MIT/Apache 2.0 where applicable.
|
||||
@@ -0,0 +1,23 @@
|
||||
# Security Policy
|
||||
|
||||
**Do not report security vulnerabilities through public GitHub issues.**
|
||||
|
||||
**Please use the [Private Vulnerability Disclosure](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability) feature of GitHub.**
|
||||
|
||||
Include as much of the following information:
|
||||
|
||||
- Type of issue (e.g. improper input parsing, privilege escalation, etc.)
|
||||
- The location of the affected source code (tag/branch/commit or direct URL)
|
||||
- Any special configuration required to reproduce the issue
|
||||
- The distribution affected or used to help us with reproduction of the issue
|
||||
- Step-by-step instructions to reproduce the issue
|
||||
- Ideally a reproduction repository
|
||||
- Impact of the issue, including how an attacker might exploit the issue
|
||||
|
||||
We prefer to receive reports in English.
|
||||
|
||||
## Contact
|
||||
|
||||
Please disclose a vulnerability or security relevant issue here: [https://github.com/tauri-apps/plugins-workspace/security/advisories/new](https://github.com/tauri-apps/plugins-workspace/security/advisories/new).
|
||||
|
||||
Alternatively, you can also contact us by email via [security@tauri.app](mailto:security@tauri.app).
|
||||
@@ -0,0 +1,2 @@
|
||||
/build
|
||||
/.tauri
|
||||
@@ -0,0 +1,46 @@
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "app.tauri.haptics"
|
||||
compileSdk = 34
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 24
|
||||
targetSdk = 34
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
consumerProguardFiles("consumer-rules.pro")
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro"
|
||||
)
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
|
||||
implementation("androidx.core:core-ktx:1.9.0")
|
||||
implementation("androidx.appcompat:appcompat:1.6.0")
|
||||
implementation("com.google.android.material:material:1.7.0")
|
||||
implementation("com.fasterxml.jackson.core:jackson-databind:2.15.3")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.1.5")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
|
||||
implementation(project(":tauri-android"))
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
@@ -0,0 +1,2 @@
|
||||
include ':tauri-android'
|
||||
project(':tauri-android').projectDir = new File('./.tauri/tauri-api')
|
||||
@@ -0,0 +1,28 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.haptics
|
||||
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
import org.junit.Assert.*
|
||||
|
||||
/**
|
||||
* Instrumented test, which will execute on an Android device.
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class ExampleInstrumentedTest {
|
||||
@Test
|
||||
fun useAppContext() {
|
||||
// Context of the app under test.
|
||||
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
assertEquals("app.tauri.haptics", appContext.packageName)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
</manifest>
|
||||
@@ -0,0 +1,143 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.haptics
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.VibrationEffect
|
||||
import android.os.Vibrator
|
||||
import android.os.VibratorManager
|
||||
import app.tauri.Logger
|
||||
import app.tauri.annotation.Command
|
||||
import app.tauri.annotation.InvokeArg
|
||||
import app.tauri.annotation.TauriPlugin
|
||||
import app.tauri.haptics.patterns.ImpactPatternHeavy
|
||||
import app.tauri.haptics.patterns.ImpactPatternLight
|
||||
import app.tauri.haptics.patterns.ImpactPatternMedium
|
||||
import app.tauri.haptics.patterns.ImpactPatternRigid
|
||||
import app.tauri.haptics.patterns.ImpactPatternSoft
|
||||
import app.tauri.haptics.patterns.NotificationPatternError
|
||||
import app.tauri.haptics.patterns.NotificationPatternSuccess
|
||||
import app.tauri.haptics.patterns.NotificationPatternWarning
|
||||
import app.tauri.haptics.patterns.Pattern
|
||||
import app.tauri.haptics.patterns.SelectionPattern
|
||||
import app.tauri.plugin.Invoke
|
||||
import app.tauri.plugin.Plugin
|
||||
import com.fasterxml.jackson.annotation.JsonProperty
|
||||
|
||||
@InvokeArg
|
||||
class HapticsOptions {
|
||||
var duration: Long = 300
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
class NotificationFeedbackArgs {
|
||||
val type: NotificationFeedbackType = NotificationFeedbackType.Success
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
enum class NotificationFeedbackType {
|
||||
@JsonProperty("success")
|
||||
Success,
|
||||
@JsonProperty("warning")
|
||||
Warning,
|
||||
@JsonProperty("error")
|
||||
Error;
|
||||
|
||||
fun into(): Pattern {
|
||||
return when(this) {
|
||||
Success -> NotificationPatternSuccess
|
||||
Warning -> NotificationPatternWarning
|
||||
Error -> NotificationPatternError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
class ImpactFeedbackArgs {
|
||||
val style: ImpactFeedbackStyle = ImpactFeedbackStyle.Medium
|
||||
}
|
||||
|
||||
@InvokeArg
|
||||
enum class ImpactFeedbackStyle {
|
||||
@JsonProperty("light")
|
||||
Light,
|
||||
@JsonProperty("medium")
|
||||
Medium,
|
||||
@JsonProperty("heavy")
|
||||
Heavy,
|
||||
@JsonProperty("soft")
|
||||
Soft,
|
||||
@JsonProperty("rigid")
|
||||
Rigid;
|
||||
|
||||
fun into(): Pattern {
|
||||
return when(this) {
|
||||
Light -> ImpactPatternLight
|
||||
Medium -> ImpactPatternMedium
|
||||
Heavy -> ImpactPatternHeavy
|
||||
Soft -> ImpactPatternSoft
|
||||
Rigid -> ImpactPatternRigid
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@TauriPlugin
|
||||
class HapticsPlugin(private val activity: Activity): Plugin(activity) {
|
||||
private val vibrator: Vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
val vibManager = activity.applicationContext.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
|
||||
vibManager.defaultVibrator
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
activity.applicationContext.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
|
||||
}
|
||||
|
||||
//
|
||||
// TAURI COMMANDS
|
||||
//
|
||||
|
||||
@Command
|
||||
fun vibrate(invoke: Invoke) {
|
||||
val args = invoke.parseArgs(HapticsOptions::class.java)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
vibrator.vibrate(VibrationEffect.createOneShot(args.duration, VibrationEffect.DEFAULT_AMPLITUDE))
|
||||
} else {
|
||||
vibrator.vibrate(args.duration)
|
||||
}
|
||||
invoke.resolve()
|
||||
}
|
||||
|
||||
@Command
|
||||
fun impactFeedback(invoke: Invoke) {
|
||||
val args = invoke.parseArgs(ImpactFeedbackArgs::class.java)
|
||||
vibratePattern(args.style.into())
|
||||
invoke.resolve()
|
||||
}
|
||||
|
||||
@Command
|
||||
fun notificationFeedback(invoke: Invoke) {
|
||||
val args = invoke.parseArgs(NotificationFeedbackArgs::class.java)
|
||||
vibratePattern(args.type.into())
|
||||
invoke.resolve()
|
||||
}
|
||||
|
||||
// TODO: Consider breaking this up into Start,Change,End like capacitor
|
||||
@Command
|
||||
fun selectionFeedback(invoke: Invoke) {
|
||||
vibratePattern(SelectionPattern)
|
||||
invoke.resolve()
|
||||
}
|
||||
|
||||
// INTERNAL FUNCTIONS
|
||||
|
||||
private fun vibratePattern(pattern: Pattern) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
vibrator.vibrate(VibrationEffect.createWaveform(pattern.timings, pattern.amplitudes, -1))
|
||||
} else {
|
||||
vibrator.vibrate(pattern.oldSDKPattern, -1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.haptics.patterns
|
||||
|
||||
val ImpactPatternLight = Pattern(
|
||||
longArrayOf(0, 50),
|
||||
intArrayOf(0, 30),
|
||||
longArrayOf(0, 20)
|
||||
)
|
||||
|
||||
val ImpactPatternMedium = Pattern(
|
||||
longArrayOf(0, 43),
|
||||
intArrayOf(0, 50),
|
||||
longArrayOf(0, 43)
|
||||
)
|
||||
|
||||
val ImpactPatternHeavy = Pattern(
|
||||
longArrayOf(0, 60),
|
||||
intArrayOf(0, 70),
|
||||
longArrayOf(0, 61)
|
||||
)
|
||||
|
||||
val ImpactPatternSoft = Pattern(
|
||||
longArrayOf(0, 50),
|
||||
intArrayOf(0, 30),
|
||||
longArrayOf(0, 20)
|
||||
)
|
||||
|
||||
val ImpactPatternRigid = Pattern(
|
||||
longArrayOf(0, 43),
|
||||
intArrayOf(0, 50),
|
||||
longArrayOf(0, 43)
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.haptics.patterns
|
||||
|
||||
val NotificationPatternSuccess = Pattern(
|
||||
longArrayOf(0, 40, 100, 40),
|
||||
intArrayOf(0, 50, 0, 60),
|
||||
longArrayOf(0, 40, 100, 40)
|
||||
)
|
||||
|
||||
val NotificationPatternWarning = Pattern(
|
||||
longArrayOf(0, 40, 120, 60),
|
||||
intArrayOf(0, 40, 0, 60),
|
||||
longArrayOf(0, 40, 120, 60)
|
||||
)
|
||||
|
||||
val NotificationPatternError = Pattern(
|
||||
longArrayOf(0, 60, 100, 40, 80, 50),
|
||||
intArrayOf(0, 50, 0, 40, 0, 50),
|
||||
longArrayOf(0, 60, 100, 40, 80, 50)
|
||||
)
|
||||
@@ -0,0 +1,11 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.haptics.patterns
|
||||
|
||||
class Pattern (
|
||||
val timings: LongArray,
|
||||
val amplitudes: IntArray,
|
||||
val oldSDKPattern: LongArray
|
||||
) {}
|
||||
@@ -0,0 +1,11 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.haptics.patterns
|
||||
|
||||
val SelectionPattern = Pattern (
|
||||
timings = longArrayOf(0, 50),
|
||||
amplitudes = intArrayOf(0, 30),
|
||||
oldSDKPattern = longArrayOf(0, 70)
|
||||
)
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package app.tauri.haptics
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import org.junit.Assert.*
|
||||
|
||||
/**
|
||||
* Example local unit test, which will execute on the development machine (host).
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
class ExampleUnitTest {
|
||||
@Test
|
||||
fun addition_isCorrect() {
|
||||
assertEquals(4, 2 + 2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
if("__TAURI__"in window){var __TAURI_PLUGIN_HAPTICS__=function(r){"use strict";async function t(r,t={},e){return window.__TAURI_INTERNALS__.invoke(r,t,e)}var e;"function"==typeof SuppressedError&&SuppressedError,function(r){r.WINDOW_RESIZED="tauri://resize",r.WINDOW_MOVED="tauri://move",r.WINDOW_CLOSE_REQUESTED="tauri://close-requested",r.WINDOW_DESTROYED="tauri://destroyed",r.WINDOW_FOCUS="tauri://focus",r.WINDOW_BLUR="tauri://blur",r.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",r.WINDOW_THEME_CHANGED="tauri://theme-changed",r.WINDOW_CREATED="tauri://window-created",r.WEBVIEW_CREATED="tauri://webview-created",r.DRAG_ENTER="tauri://drag-enter",r.DRAG_OVER="tauri://drag-over",r.DRAG_DROP="tauri://drag-drop",r.DRAG_LEAVE="tauri://drag-leave"}(e||(e={}));const a={async vibrate(r){try{return{status:"ok",data:await t("plugin:haptics|vibrate",{duration:r})}}catch(r){if(r instanceof Error)throw r;return{status:"error",error:r}}},async impactFeedback(r){try{return{status:"ok",data:await t("plugin:haptics|impact_feedback",{style:r})}}catch(r){if(r instanceof Error)throw r;return{status:"error",error:r}}},async notificationFeedback(r){try{return{status:"ok",data:await t("plugin:haptics|notification_feedback",{type:r})}}catch(r){if(r instanceof Error)throw r;return{status:"error",error:r}}},async selectionFeedback(){try{return{status:"ok",data:await t("plugin:haptics|selection_feedback")}}catch(r){if(r instanceof Error)throw r;return{status:"error",error:r}}}},{vibrate:i,impactFeedback:c,notificationFeedback:n,selectionFeedback:o}=a;return r.impactFeedback=c,r.notificationFeedback=n,r.selectionFeedback=o,r.vibrate=i,r}({});Object.defineProperty(window.__TAURI__,"haptics",{value:__TAURI_PLUGIN_HAPTICS__})}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
const COMMANDS: &[&str] = &[
|
||||
"vibrate",
|
||||
"impact_feedback",
|
||||
"notification_feedback",
|
||||
"selection_feedback",
|
||||
];
|
||||
|
||||
fn main() {
|
||||
if let Err(error) = tauri_plugin::Builder::new(COMMANDS)
|
||||
.global_api_script_path("./api-iife.js")
|
||||
.android_path("android")
|
||||
.ios_path("ios")
|
||||
.try_build()
|
||||
{
|
||||
println!("{error:#}");
|
||||
// when building documentation for Android the plugin build result is irrelevant to the crate itself
|
||||
if !(cfg!(docsrs) && std::env::var("TARGET").unwrap().contains("android")) {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// @ts-nocheck
|
||||
// This file was generated by [tauri-specta](https://github.com/oscartbeaumont/tauri-specta). Do not edit this file manually.
|
||||
|
||||
/** user-defined commands **/
|
||||
|
||||
export const commands = {
|
||||
async vibrate(duration: number): Promise<Result<null, Error>> {
|
||||
try {
|
||||
return {
|
||||
status: "ok",
|
||||
data: await TAURI_INVOKE("plugin:haptics|vibrate", { duration }),
|
||||
};
|
||||
} catch (e) {
|
||||
if (e instanceof Error) throw e;
|
||||
else return { status: "error", error: e as any };
|
||||
}
|
||||
},
|
||||
async impactFeedback(
|
||||
style: ImpactFeedbackStyle,
|
||||
): Promise<Result<null, Error>> {
|
||||
try {
|
||||
return {
|
||||
status: "ok",
|
||||
data: await TAURI_INVOKE("plugin:haptics|impact_feedback", { style }),
|
||||
};
|
||||
} catch (e) {
|
||||
if (e instanceof Error) throw e;
|
||||
else return { status: "error", error: e as any };
|
||||
}
|
||||
},
|
||||
async notificationFeedback(
|
||||
type: NotificationFeedbackType,
|
||||
): Promise<Result<null, Error>> {
|
||||
try {
|
||||
return {
|
||||
status: "ok",
|
||||
data: await TAURI_INVOKE("plugin:haptics|notification_feedback", {
|
||||
type,
|
||||
}),
|
||||
};
|
||||
} catch (e) {
|
||||
if (e instanceof Error) throw e;
|
||||
else return { status: "error", error: e as any };
|
||||
}
|
||||
},
|
||||
async selectionFeedback(): Promise<Result<null, Error>> {
|
||||
try {
|
||||
return {
|
||||
status: "ok",
|
||||
data: await TAURI_INVOKE("plugin:haptics|selection_feedback"),
|
||||
};
|
||||
} catch (e) {
|
||||
if (e instanceof Error) throw e;
|
||||
else return { status: "error", error: e as any };
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/** user-defined events **/
|
||||
|
||||
/* export const events = __makeEvents__<{
|
||||
randomNumber: RandomNumber;
|
||||
}>({
|
||||
randomNumber: "plugin:haptics:random-number",
|
||||
}); */
|
||||
|
||||
/** user-defined statics **/
|
||||
|
||||
/** user-defined types **/
|
||||
|
||||
export type Error = never;
|
||||
export type ImpactFeedbackStyle =
|
||||
| "light"
|
||||
| "medium"
|
||||
| "heavy"
|
||||
| "soft"
|
||||
| "rigid";
|
||||
export type NotificationFeedbackType = "success" | "warning" | "error";
|
||||
//export type RandomNumber = number;
|
||||
|
||||
/** tauri-specta globals **/
|
||||
|
||||
import { invoke as TAURI_INVOKE } from "@tauri-apps/api/core";
|
||||
import * as TAURI_API_EVENT from "@tauri-apps/api/event";
|
||||
import { type WebviewWindow as __WebviewWindow__ } from "@tauri-apps/api/webviewWindow";
|
||||
|
||||
type __EventObj__<T> = {
|
||||
listen: (
|
||||
cb: TAURI_API_EVENT.EventCallback<T>,
|
||||
) => ReturnType<typeof TAURI_API_EVENT.listen<T>>;
|
||||
once: (
|
||||
cb: TAURI_API_EVENT.EventCallback<T>,
|
||||
) => ReturnType<typeof TAURI_API_EVENT.once<T>>;
|
||||
emit: T extends null
|
||||
? (payload?: T) => ReturnType<typeof TAURI_API_EVENT.emit>
|
||||
: (payload: T) => ReturnType<typeof TAURI_API_EVENT.emit>;
|
||||
};
|
||||
|
||||
export type Result<T, E> =
|
||||
| { status: "ok"; data: T }
|
||||
| { status: "error"; error: E };
|
||||
|
||||
function __makeEvents__<T extends Record<string, any>>(
|
||||
mappings: Record<keyof T, string>,
|
||||
) {
|
||||
return new Proxy(
|
||||
{} as unknown as {
|
||||
[K in keyof T]: __EventObj__<T[K]> & {
|
||||
(handle: __WebviewWindow__): __EventObj__<T[K]>;
|
||||
};
|
||||
},
|
||||
{
|
||||
get: (_, event) => {
|
||||
const name = mappings[event as keyof T];
|
||||
|
||||
return new Proxy((() => {}) as any, {
|
||||
apply: (_, __, [window]: [__WebviewWindow__]) => ({
|
||||
listen: (arg: any) => window.listen(name, arg),
|
||||
once: (arg: any) => window.once(name, arg),
|
||||
emit: (arg: any) => window.emit(name, arg),
|
||||
}),
|
||||
get: (_, command: keyof __EventObj__<any>) => {
|
||||
switch (command) {
|
||||
case "listen":
|
||||
return (arg: any) => TAURI_API_EVENT.listen(name, arg);
|
||||
case "once":
|
||||
return (arg: any) => TAURI_API_EVENT.once(name, arg);
|
||||
case "emit":
|
||||
return (arg: any) => TAURI_API_EVENT.emit(name, arg);
|
||||
}
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
|
||||
import { commands } from "./bindings";
|
||||
|
||||
export const {
|
||||
vibrate,
|
||||
impactFeedback,
|
||||
notificationFeedback,
|
||||
selectionFeedback,
|
||||
} = commands;
|
||||
|
||||
export { ImpactFeedbackStyle, NotificationFeedbackType } from "./bindings";
|
||||
|
||||
// export { events };
|
||||
@@ -0,0 +1,10 @@
|
||||
.DS_Store
|
||||
/.build
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
xcuserdata/
|
||||
DerivedData/
|
||||
.swiftpm/config/registries.json
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
.netrc
|
||||
Package.resolved
|
||||
@@ -0,0 +1,33 @@
|
||||
// swift-tools-version:5.3
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "tauri-plugin-haptics",
|
||||
platforms: [
|
||||
.iOS(.v13),
|
||||
],
|
||||
products: [
|
||||
// Products define the executables and libraries a package produces, and make them visible to other packages.
|
||||
.library(
|
||||
name: "tauri-plugin-haptics",
|
||||
type: .static,
|
||||
targets: ["tauri-plugin-haptics"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(name: "Tauri", path: "../.tauri/tauri-api")
|
||||
],
|
||||
targets: [
|
||||
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
|
||||
// Targets can depend on other targets in this package, and on products in packages this package depends on.
|
||||
.target(
|
||||
name: "tauri-plugin-haptics",
|
||||
dependencies: [
|
||||
.byName(name: "Tauri")
|
||||
],
|
||||
path: "Sources")
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,3 @@
|
||||
# Tauri Plugin Haptics
|
||||
|
||||
A description of this package.
|
||||
@@ -0,0 +1,133 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftRs
|
||||
import Tauri
|
||||
import UIKit
|
||||
import WebKit
|
||||
import CoreHaptics
|
||||
import AudioToolbox
|
||||
|
||||
class ImpactFeedbackOptions: Decodable {
|
||||
let style: ImpactFeedbackStyle
|
||||
}
|
||||
|
||||
enum ImpactFeedbackStyle: String, Decodable {
|
||||
case light, medium, heavy, soft, rigid
|
||||
|
||||
func into() -> UIImpactFeedbackGenerator.FeedbackStyle {
|
||||
switch self {
|
||||
case .light:
|
||||
return .light
|
||||
case .medium:
|
||||
return .medium
|
||||
case .heavy:
|
||||
return .heavy
|
||||
case .soft:
|
||||
return .soft
|
||||
case .rigid:
|
||||
return .rigid
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class NotificationFeedbackOptions: Decodable {
|
||||
let type: NotificationFeedbackType
|
||||
}
|
||||
|
||||
enum NotificationFeedbackType: String, Decodable {
|
||||
case success, warning, error
|
||||
|
||||
func into() -> UINotificationFeedbackGenerator.FeedbackType {
|
||||
switch self {
|
||||
case .success:
|
||||
return .success
|
||||
case .warning:
|
||||
return .warning
|
||||
case .error:
|
||||
return .error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class VibrateOptions: Decodable {
|
||||
// TODO: Array
|
||||
let duration: Double
|
||||
}
|
||||
|
||||
class HapticsPlugin: Plugin {
|
||||
//
|
||||
// Tauri commands
|
||||
//
|
||||
|
||||
@objc public func vibrate(_ invoke: Invoke) throws {
|
||||
let args = try invoke.parseArgs(VibrateOptions.self)
|
||||
if CHHapticEngine.capabilitiesForHardware().supportsHaptics {
|
||||
do {
|
||||
let engine = try CHHapticEngine()
|
||||
try engine.start()
|
||||
engine.resetHandler = { [] in
|
||||
do {
|
||||
try engine.start()
|
||||
} catch {
|
||||
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
|
||||
}
|
||||
}
|
||||
// TODO: Make some of this (or all) configurable?
|
||||
let intensity: CHHapticEventParameter = CHHapticEventParameter(parameterID: .hapticIntensity, value: 1.0)
|
||||
let sharpness: CHHapticEventParameter = CHHapticEventParameter(parameterID: .hapticSharpness, value: 1.0)
|
||||
let continuousEvent = CHHapticEvent(
|
||||
eventType: .hapticContinuous,
|
||||
parameters: [intensity, sharpness],
|
||||
relativeTime: 0.0,
|
||||
duration: args.duration/1000
|
||||
)
|
||||
let pattern = try CHHapticPattern(events: [continuousEvent], parameters: [])
|
||||
let player = try engine.makePlayer(with: pattern)
|
||||
|
||||
try player.start(atTime: 0)
|
||||
} catch {
|
||||
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
|
||||
}
|
||||
} else {
|
||||
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
|
||||
}
|
||||
|
||||
Logger.error("VIBRATE END")
|
||||
|
||||
invoke.resolve()
|
||||
}
|
||||
|
||||
@objc public func impactFeedback(_ invoke: Invoke) throws {
|
||||
let args = try invoke.parseArgs(ImpactFeedbackOptions.self)
|
||||
let generator = UIImpactFeedbackGenerator(style: args.style.into())
|
||||
generator.prepare()
|
||||
generator.impactOccurred()
|
||||
|
||||
invoke.resolve()
|
||||
}
|
||||
|
||||
@objc public func notificationFeedback(_ invoke: Invoke) throws {
|
||||
let args = try invoke.parseArgs(NotificationFeedbackOptions.self)
|
||||
let generator = UINotificationFeedbackGenerator()
|
||||
generator.prepare()
|
||||
generator.notificationOccurred(args.type.into())
|
||||
|
||||
invoke.resolve()
|
||||
}
|
||||
|
||||
// TODO: Consider breaking this up into Start,Change,End like capacitor
|
||||
@objc public func selectionFeedback(_ invoke: Invoke) throws {
|
||||
let generator = UISelectionFeedbackGenerator()
|
||||
generator.prepare()
|
||||
generator.selectionChanged()
|
||||
|
||||
invoke.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
@_cdecl("init_plugin_haptics")
|
||||
func initPlugin() -> Plugin {
|
||||
return HapticsPlugin()
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import XCTest
|
||||
@testable import ExamplePlugin
|
||||
|
||||
final class ExamplePluginTests: XCTestCase {
|
||||
func testExample() throws {
|
||||
let plugin = ExamplePlugin()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "@tauri-apps/plugin-haptics",
|
||||
"version": "2.0.0-beta.0",
|
||||
"license": "MIT or APACHE-2.0",
|
||||
"authors": [
|
||||
"Tauri Programme within The Commons Conservancy"
|
||||
],
|
||||
"type": "module",
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"main": "./dist-js/index.cjs",
|
||||
"module": "./dist-js/index.js",
|
||||
"exports": {
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"import": "./dist-js/index.js",
|
||||
"require": "./dist-js/index.cjs"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rollup -c"
|
||||
},
|
||||
"files": [
|
||||
"dist-js",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.0.0-beta.16"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-impact-feedback"
|
||||
description = "Enables the impact_feedback command without any pre-configured scope."
|
||||
commands.allow = ["impact_feedback"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-impact-feedback"
|
||||
description = "Denies the impact_feedback command without any pre-configured scope."
|
||||
commands.deny = ["impact_feedback"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-notification-feedback"
|
||||
description = "Enables the notification_feedback command without any pre-configured scope."
|
||||
commands.allow = ["notification_feedback"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-notification-feedback"
|
||||
description = "Denies the notification_feedback command without any pre-configured scope."
|
||||
commands.deny = ["notification_feedback"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-selection-feedback"
|
||||
description = "Enables the selection_feedback command without any pre-configured scope."
|
||||
commands.allow = ["selection_feedback"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-selection-feedback"
|
||||
description = "Denies the selection_feedback command without any pre-configured scope."
|
||||
commands.deny = ["selection_feedback"]
|
||||
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-vibrate"
|
||||
description = "Enables the vibrate command without any pre-configured scope."
|
||||
commands.allow = ["vibrate"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-vibrate"
|
||||
description = "Denies the vibrate command without any pre-configured scope."
|
||||
commands.deny = ["vibrate"]
|
||||
@@ -0,0 +1,114 @@
|
||||
|
||||
### Permission Table
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Identifier</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`haptics:allow-impact-feedback`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the impact_feedback command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`haptics:deny-impact-feedback`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the impact_feedback command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`haptics:allow-notification-feedback`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the notification_feedback command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`haptics:deny-notification-feedback`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the notification_feedback command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`haptics:allow-selection-feedback`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the selection_feedback command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`haptics:deny-selection-feedback`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the selection_feedback command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`haptics:allow-vibrate`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the vibrate command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`haptics:deny-vibrate`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the vibrate command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
@@ -0,0 +1,356 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "PermissionFile",
|
||||
"description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"default": {
|
||||
"description": "The default permission set for the plugin",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/DefaultPermission"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"set": {
|
||||
"description": "A list of permissions sets defined",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/PermissionSet"
|
||||
}
|
||||
},
|
||||
"permission": {
|
||||
"description": "A list of inlined permissions",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Permission"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"DefaultPermission": {
|
||||
"description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"permissions"
|
||||
],
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "The version of the permission.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint64",
|
||||
"minimum": 1.0
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does. Tauri convention is to use <h4> headings in markdown content for Tauri documentation generation purposes.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"permissions": {
|
||||
"description": "All permissions this set contains.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"PermissionSet": {
|
||||
"description": "A set of direct permissions grouped together under a new name.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"description",
|
||||
"identifier",
|
||||
"permissions"
|
||||
],
|
||||
"properties": {
|
||||
"identifier": {
|
||||
"description": "A unique identifier for the permission.",
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does.",
|
||||
"type": "string"
|
||||
},
|
||||
"permissions": {
|
||||
"description": "All permissions this set contains.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/PermissionKind"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Permission": {
|
||||
"description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"identifier"
|
||||
],
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "The version of the permission.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint64",
|
||||
"minimum": 1.0
|
||||
},
|
||||
"identifier": {
|
||||
"description": "A unique identifier for the permission.",
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does. Tauri internal convention is to use <h4> headings in markdown content for Tauri documentation generation purposes.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"commands": {
|
||||
"description": "Allowed or denied commands when using this permission.",
|
||||
"default": {
|
||||
"allow": [],
|
||||
"deny": []
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Commands"
|
||||
}
|
||||
]
|
||||
},
|
||||
"scope": {
|
||||
"description": "Allowed or denied scoped when using this permission.",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Scopes"
|
||||
}
|
||||
]
|
||||
},
|
||||
"platforms": {
|
||||
"description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Target"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Commands": {
|
||||
"description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"allow": {
|
||||
"description": "Allowed command.",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"deny": {
|
||||
"description": "Denied command, which takes priority.",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Scopes": {
|
||||
"description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"allow": {
|
||||
"description": "Data that defines what is allowed by the scope.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
},
|
||||
"deny": {
|
||||
"description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Value": {
|
||||
"description": "All supported ACL values.",
|
||||
"anyOf": [
|
||||
{
|
||||
"description": "Represents a null JSON value.",
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`bool`].",
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"description": "Represents a valid ACL [`Number`].",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Number"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`String`].",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"description": "Represents a list of other [`Value`]s.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "Represents a map of [`String`] keys to [`Value`]s.",
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"Number": {
|
||||
"description": "A valid ACL number.",
|
||||
"anyOf": [
|
||||
{
|
||||
"description": "Represents an [`i64`].",
|
||||
"type": "integer",
|
||||
"format": "int64"
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`f64`].",
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Target": {
|
||||
"description": "Platform target.",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "MacOS.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"macOS"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Windows.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"windows"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Linux.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"linux"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Android.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"android"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "iOS.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"iOS"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"PermissionKind": {
|
||||
"type": "string",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "allow-impact-feedback -> Enables the impact_feedback command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"allow-impact-feedback"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "deny-impact-feedback -> Denies the impact_feedback command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"deny-impact-feedback"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "allow-notification-feedback -> Enables the notification_feedback command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"allow-notification-feedback"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "deny-notification-feedback -> Denies the notification_feedback command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"deny-notification-feedback"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "allow-selection-feedback -> Enables the selection_feedback command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"allow-selection-feedback"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "deny-selection-feedback -> Denies the selection_feedback command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"deny-selection-feedback"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "allow-vibrate -> Enables the vibrate command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"allow-vibrate"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "deny-vibrate -> Denies the vibrate command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"deny-vibrate"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import { createConfig } from "../../shared/rollup.config.js";
|
||||
|
||||
export default createConfig();
|
||||
@@ -0,0 +1,37 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use tauri::{command, AppHandle, Runtime};
|
||||
|
||||
use crate::{HapticsExt, ImpactFeedbackStyle, NotificationFeedbackType, Result};
|
||||
|
||||
#[command]
|
||||
#[specta::specta]
|
||||
pub(crate) async fn vibrate<R: Runtime>(app: AppHandle<R>, duration: u32) -> Result<()> {
|
||||
app.haptics().vibrate(duration)
|
||||
}
|
||||
|
||||
#[command]
|
||||
#[specta::specta]
|
||||
pub(crate) async fn impact_feedback<R: Runtime>(
|
||||
app: AppHandle<R>,
|
||||
style: ImpactFeedbackStyle,
|
||||
) -> Result<()> {
|
||||
app.haptics().impact_feedback(style)
|
||||
}
|
||||
|
||||
#[command]
|
||||
#[specta::specta]
|
||||
pub(crate) async fn notification_feedback<R: Runtime>(
|
||||
app: AppHandle<R>,
|
||||
r#type: NotificationFeedbackType,
|
||||
) -> Result<()> {
|
||||
app.haptics().notification_feedback(r#type)
|
||||
}
|
||||
|
||||
#[command]
|
||||
#[specta::specta]
|
||||
pub(crate) async fn selection_feedback<R: Runtime>(app: AppHandle<R>) -> Result<()> {
|
||||
app.haptics().selection_feedback()
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use tauri::{plugin::PluginApi, AppHandle, Runtime};
|
||||
|
||||
use crate::models::*;
|
||||
|
||||
pub fn init<R: Runtime, C: DeserializeOwned>(
|
||||
app: &AppHandle<R>,
|
||||
_api: PluginApi<R, C>,
|
||||
) -> crate::Result<Haptics<R>> {
|
||||
Ok(Haptics(app.clone()))
|
||||
}
|
||||
|
||||
/// Access to the haptics APIs.
|
||||
pub struct Haptics<R: Runtime>(AppHandle<R>);
|
||||
|
||||
impl<R: Runtime> Haptics<R> {
|
||||
pub fn vibrate(&self, _duration: u32) -> crate::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn impact_feedback(&self, _style: ImpactFeedbackStyle) -> crate::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn notification_feedback(&self, _type: NotificationFeedbackType) -> crate::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn selection_feedback(&self) -> crate::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::{ser::Serializer, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
// TODO: Improve Error handling (different typed errors instead of one (stringified) PluginInvokeError for all mobile errors)
|
||||
|
||||
#[derive(Debug, thiserror::Error, Type)]
|
||||
pub enum Error {
|
||||
#[cfg(mobile)]
|
||||
#[error(transparent)]
|
||||
PluginInvoke(
|
||||
#[serde(skip)]
|
||||
#[from]
|
||||
tauri::plugin::mobile::PluginInvokeError,
|
||||
),
|
||||
}
|
||||
|
||||
impl Serialize for Error {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(self.to_string().as_ref())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use tauri::{
|
||||
plugin::{Builder, TauriPlugin},
|
||||
Manager, Runtime,
|
||||
};
|
||||
|
||||
//use tauri_specta::*;
|
||||
|
||||
pub use models::*;
|
||||
|
||||
#[cfg(desktop)]
|
||||
mod desktop;
|
||||
#[cfg(mobile)]
|
||||
mod mobile;
|
||||
|
||||
mod commands;
|
||||
mod error;
|
||||
mod models;
|
||||
|
||||
pub use error::{Error, Result};
|
||||
|
||||
#[cfg(desktop)]
|
||||
use desktop::Haptics;
|
||||
#[cfg(mobile)]
|
||||
use mobile::Haptics;
|
||||
|
||||
/* macro_rules! specta_builder {
|
||||
() => {
|
||||
ts::builder()
|
||||
.commands(collect_commands![
|
||||
commands::vibrate,
|
||||
commands::impact_feedback,
|
||||
commands::notification_feedback,
|
||||
commands::selection_feedback
|
||||
])
|
||||
.header("// @ts-nocheck")
|
||||
.config(
|
||||
specta::ts::ExportConfig::default()
|
||||
.bigint(specta::ts::BigIntExportBehavior::Number),
|
||||
)
|
||||
};
|
||||
} */
|
||||
|
||||
/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the haptics APIs.
|
||||
pub trait HapticsExt<R: Runtime> {
|
||||
fn haptics(&self) -> &Haptics<R>;
|
||||
}
|
||||
|
||||
impl<R: Runtime, T: Manager<R>> crate::HapticsExt<R> for T {
|
||||
fn haptics(&self) -> &Haptics<R> {
|
||||
self.state::<Haptics<R>>().inner()
|
||||
}
|
||||
}
|
||||
|
||||
/// Initializes the plugin.
|
||||
pub fn init<R: Runtime>() -> TauriPlugin<R> {
|
||||
/* let (invoke_handler, register_events) =
|
||||
specta_builder!().build_plugin_utils("haptics").unwrap(); */
|
||||
|
||||
Builder::new("haptics")
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
commands::vibrate,
|
||||
commands::impact_feedback,
|
||||
commands::notification_feedback,
|
||||
commands::selection_feedback
|
||||
])
|
||||
.setup(|app, api| {
|
||||
#[cfg(mobile)]
|
||||
let haptics = mobile::init(app, api)?;
|
||||
#[cfg(desktop)]
|
||||
let haptics = desktop::init(app, api)?;
|
||||
app.manage(haptics);
|
||||
Ok(())
|
||||
})
|
||||
.build()
|
||||
}
|
||||
|
||||
/* #[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn export_types() {
|
||||
specta_builder!()
|
||||
.path("./guest-js/bindings.ts")
|
||||
.config(
|
||||
specta::ts::ExportConfig::default()
|
||||
.formatter(specta::ts::formatter::prettier)
|
||||
.bigint(specta::ts::BigIntExportBehavior::Number),
|
||||
)
|
||||
.export_for_plugin("haptics")
|
||||
.expect("failed to export specta types");
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,76 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::{de::DeserializeOwned, Serialize};
|
||||
use tauri::{
|
||||
plugin::{PluginApi, PluginHandle},
|
||||
AppHandle, Runtime,
|
||||
};
|
||||
|
||||
use crate::models::*;
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
const PLUGIN_IDENTIFIER: &str = "app.tauri.haptics";
|
||||
|
||||
#[cfg(target_os = "ios")]
|
||||
tauri::ios_plugin_binding!(init_plugin_haptics);
|
||||
|
||||
// initializes the Kotlin or Swift plugin classes
|
||||
pub fn init<R: Runtime, C: DeserializeOwned>(
|
||||
_app: &AppHandle<R>,
|
||||
api: PluginApi<R, C>,
|
||||
) -> crate::Result<Haptics<R>> {
|
||||
#[cfg(target_os = "android")]
|
||||
let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "HapticsPlugin")?;
|
||||
#[cfg(target_os = "ios")]
|
||||
let handle = api.register_ios_plugin(init_plugin_haptics)?;
|
||||
Ok(Haptics(handle))
|
||||
}
|
||||
|
||||
/// Access to the haptics APIs.
|
||||
pub struct Haptics<R: Runtime>(PluginHandle<R>);
|
||||
|
||||
impl<R: Runtime> Haptics<R> {
|
||||
pub fn vibrate(&self, duration: u32) -> crate::Result<()> {
|
||||
self.0
|
||||
.run_mobile_plugin("vibrate", VibratePayload { duration })
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn impact_feedback(&self, style: ImpactFeedbackStyle) -> crate::Result<()> {
|
||||
self.0
|
||||
.run_mobile_plugin("impactFeedback", ImpactFeedbackPayload { style })
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn notification_feedback(&self, r#type: NotificationFeedbackType) -> crate::Result<()> {
|
||||
self.0
|
||||
.run_mobile_plugin(
|
||||
"notificationFeedback",
|
||||
NotificationFeedbackPayload { r#type },
|
||||
)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn selection_feedback(&self) -> crate::Result<()> {
|
||||
self.0
|
||||
.run_mobile_plugin("selectionFeedback", ())
|
||||
.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct VibratePayload {
|
||||
duration: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ImpactFeedbackPayload {
|
||||
style: ImpactFeedbackStyle,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct NotificationFeedbackPayload {
|
||||
r#type: NotificationFeedbackType,
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
/*
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HapticsOptions {
|
||||
// TODO: support array to match web api
|
||||
pub duration: u32,
|
||||
}
|
||||
*/
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ImpactFeedbackStyle {
|
||||
Light,
|
||||
#[default]
|
||||
Medium,
|
||||
Heavy,
|
||||
Soft,
|
||||
Rigid,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum NotificationFeedbackType {
|
||||
#[default]
|
||||
Success,
|
||||
Warning,
|
||||
Error,
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["guest-js/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user