[WIP] create tauri-plugin-opener

pull/2019/head
amrbashir 9 months ago
parent 3449dd5a8f
commit 38369c832d
No known key found for this signature in database
GPG Key ID: BBD7A47A2003FF33

@ -62,6 +62,7 @@
"dialog",
"fs",
"global-shortcut",
"opener",
"http",
"nfc",
"notification",
@ -87,6 +88,7 @@
"dialog-js",
"fs-js",
"global-shortcut-js",
"opener-js",
"http-js",
"nfc-js",
"notification-js",
@ -186,6 +188,14 @@
"path": "./plugins/global-shortcut",
"manager": "javascript"
},
"opener": {
"path": "./plugins/opener",
"manager": "rust"
},
"opener-js": {
"path": "./plugins/opener",
"manager": "javascript"
},
"haptics": {
"path": "./plugins/haptics",
"manager": "rust"

@ -0,0 +1,6 @@
---
"opener": "patch"
"opener-js": "patch"
---
Initial Release

@ -53,6 +53,10 @@ jobs:
- .github/workflows/check-generated-files.yml
- plugins/global-shortcut/guest-js/**
- plugins/global-shortcut/src/api-iife.js
opener:
- .github/workflows/check-generated-files.yml
- plugins/opener/guest-js/**
- plugins/opener/src/api-iife.js
haptics:
- .github/workflows/check-generated-files.yml
- plugins/haptics/guest-js/**

@ -66,6 +66,9 @@ jobs:
tauri-plugin-global-shortcut:
- .github/workflows/lint-rust.yml
- plugins/global-shortcut/**
tauri-plugin-opener:
- .github/workflows/lint-rust.yml
- plugins/opener/**
tauri-plugin-haptics:
- .github/workflows/lint-rust.yml
- plugins/haptics/**

@ -77,6 +77,10 @@ jobs:
- .github/workflows/test-rust.yml
- Cargo.toml
- plugins/global-shortcut/**
tauri-plugin-opener:
- .github/workflows/test-rust.yml
- Cargo.toml
- plugins/opener/**
tauri-plugin-haptics:
- .github/workflows/test-rust.yml
- Cargo.toml

14
Cargo.lock generated

@ -226,6 +226,7 @@ dependencies = [
"tauri-plugin-log",
"tauri-plugin-nfc",
"tauri-plugin-notification",
"tauri-plugin-opener",
"tauri-plugin-os",
"tauri-plugin-process",
"tauri-plugin-shell",
@ -6579,6 +6580,19 @@ dependencies = [
"windows-version",
]
[[package]]
name = "tauri-plugin-opener"
version = "2.0.0"
dependencies = [
"open",
"regex",
"serde",
"serde_json",
"tauri",
"tauri-plugin",
"thiserror",
]
[[package]]
name = "tauri-plugin-os"
version = "2.0.1"

@ -22,6 +22,7 @@ This repo and all plugins require a Rust version of at least **1.77.2**
| [log](plugins/log) | Configurable logging. | ✅ | ✅ | ✅ | ✅ | ✅ |
| [nfc](plugins/nfc) | Read and write NFC tags on Android and iOS. | ? | ? | ? | ✅ | ✅ |
| [notification](plugins/notification) | Send message notifications (brief auto-expiring OS window element) to your user. Can also be used with the Notification Web API. | ✅ | ✅ | ✅ | ✅ | ✅ |
| [opener](plugins/opener) | Open files and URLs using their default application. | ✅ | ✅ | ✅ | ? | ? |
| [os](plugins/os) | Read information about the operating system. | ✅ | ✅ | ✅ | ✅ | ✅ |
| [persisted-scope](plugins/persisted-scope) | Persist runtime scope changes on the filesystem. | ✅ | ✅ | ✅ | ? | ? |
| [positioner](plugins/positioner) | Move windows to common locations. | ✅ | ✅ | ✅ | ❌ | ❌ |

@ -18,6 +18,7 @@
"@tauri-apps/plugin-fs": "2.0.2",
"@tauri-apps/plugin-geolocation": "2.0.0",
"@tauri-apps/plugin-global-shortcut": "2.0.0",
"@tauri-apps/plugin-opener": "2.0.0",
"@tauri-apps/plugin-haptics": "2.0.0",
"@tauri-apps/plugin-http": "2.0.1",
"@tauri-apps/plugin-nfc": "2.0.0",

@ -33,6 +33,7 @@ tauri-plugin-notification = { path = "../../../plugins/notification", version =
] }
tauri-plugin-os = { path = "../../../plugins/os", version = "2.0.1" }
tauri-plugin-process = { path = "../../../plugins/process", version = "2.0.1" }
tauri-plugin-opener = { path = "../../../plugins/opener", version = "2.0.0" }
tauri-plugin-shell = { path = "../../../plugins/shell", version = "2.0.2" }
tauri-plugin-store = { path = "../../../plugins/store", version = "2.1.0" }

@ -16,6 +16,7 @@
},
"core:default",
"fs:default",
"opener:default",
"core:window:allow-minimize",
"core:window:allow-maximize",
"core:window:allow-unmaximize",

@ -36,6 +36,7 @@ pub fn run() {
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_os::init())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_store::Builder::default().build())
.setup(move |app| {

@ -1,6 +1,5 @@
<script>
import { writable } from 'svelte/store'
import { open } from '@tauri-apps/plugin-shell'
import { getCurrentWindow } from '@tauri-apps/api/window'
import { getCurrentWebview } from '@tauri-apps/api/webview'
import * as os from '@tauri-apps/plugin-os'
@ -14,6 +13,7 @@
import Notifications from './views/Notifications.svelte'
import Shortcuts from './views/Shortcuts.svelte'
import Shell from './views/Shell.svelte'
import Opener from './views/Opener.svelte'
import Store from './views/Store.svelte'
import Updater from './views/Updater.svelte'
import Clipboard from './views/Clipboard.svelte'
@ -91,6 +91,11 @@
component: Shell,
icon: 'i-codicon-terminal-bash'
},
{
label: 'Opener',
component: Opener,
icon: 'i-codicon-link-external'
},
{
label: 'Store',
component: Store,

@ -0,0 +1,47 @@
<script>
import { open } from '@tauri-apps/plugin-opener'
export let onMessage
const programs = [
'firefox',
'google chrome',
'chromium',
'safari',
'open',
'start',
'xdg-open',
'gio',
'gnome-open',
'kde-open',
'wslview'
]
let path = ''
let program = 'Default'
function openPath() {
open(path, program === 'Default' ? undefined : program).catch(onMessage)
}
</script>
<div class="flex flex-col">
<div class="flex flex-row gap-2 items-center">
<input
class="input grow"
placeholder="Type the path to watch..."
bind:value={path}
/>
<span> with </span>
<select class="input" bind:value={program}>
<option value="Default">Default</option>
{#each programs as p}
<option value={p}>{p}</option>
{/each}
</select>
<button class="btn" on:click={openPath}>Open</button>
</div>
</div>

@ -31,5 +31,6 @@
},
"engines": {
"pnpm": "^9.0.0"
}
},
"packageManager": "pnpm@9.11.0+sha512.0a203ffaed5a3f63242cd064c8fb5892366c103e328079318f78062f24ea8c9d50bc6a47aa3567cabefd824d170e78fa2745ed1f16b132e16436146b7688f19b"
}

@ -0,0 +1,36 @@
[package]
name = "tauri-plugin-opener"
version = "2.0.0"
edition = { workspace = true }
authors = { workspace = true }
license = { workspace = true }
repository = { workspace = true }
links = "tauri-plugin-opener"
[package.metadata.docs.rs]
rustc-args = ["--cfg", "docsrs"]
rustdoc-args = ["--cfg", "docsrs"]
# Platforms supported by the plugin
# Support levels are "full", "partial", "none", "unknown"
# Details of the support level are left to plugin maintainer
[package.metadata.platforms]
windows = { level = "full", notes = "" }
linux = { level = "full", notes = "" }
macos = { level = "full", notes = "" }
android = { level = "partial", notes = "Only allows to open URLs via `open`" }
ios = { level = "partial", notes = "Only allows to open URLs via `open`" }
[build-dependencies]
tauri-plugin = { workspace = true, features = ["build"] }
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
tauri = { workspace = true }
thiserror = { workspace = true }
regex = "1"
open = { version = "5", features = ["shellexecute-on-windows"] }

@ -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,100 @@
![opener](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/opener/banner.png)
<!-- description -->
| Platform | Supported |
| -------- | --------- |
| Linux | ✓ |
| Windows | ✓ |
| macOS | ✓ |
| 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-opener = "2.0.0"
# alternatively with Git:
tauri-plugin-opener = { 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-opener
# or
npm add @tauri-apps/plugin-opener
# or
yarn add @tauri-apps/plugin-opener
# alternatively with Git:
pnpm add https://github.com/tauri-apps/tauri-plugin-opener#v2
# or
npm add https://github.com/tauri-apps/tauri-plugin-opener#v2
# or
yarn add https://github.com/tauri-apps/tauri-plugin-opener#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_opener::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
```
## Contributing
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
## Partners
<table>
<tbody>
<tr>
<td align="center" valign="middle">
<a href="https://crabnebula.dev" target="_blank">
<img src="https://github.com/tauri-apps/plugins-workspace/raw/v2/.github/sponsors/crabnebula.svg" alt="CrabNebula" width="283">
</a>
</td>
</tr>
</tbody>
</table>
For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
## License
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
MIT or MIT/Apache 2.0 where applicable.

@ -0,0 +1,23 @@
# Security Policy
**Do not report security vulnerabilities through public GitHub issues.**
**Please use the [Private Vulnerability Disclosure](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability) feature of GitHub.**
Include as much of the following information:
- Type of issue (e.g. improper input parsing, privilege escalation, etc.)
- The location of the affected source code (tag/branch/commit or direct URL)
- Any special configuration required to reproduce the issue
- The distribution affected or used to help us with reproduction of the issue
- Step-by-step instructions to reproduce the issue
- Ideally a reproduction repository
- Impact of the issue, including how an attacker might exploit the issue
We prefer to receive reports in English.
## Contact
Please disclose a vulnerability or security relevant issue here: [https://github.com/tauri-apps/plugins-workspace/security/advisories/new](https://github.com/tauri-apps/plugins-workspace/security/advisories/new).
Alternatively, you can also contact us by email via [security@tauri.app](mailto:security@tauri.app).

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

@ -0,0 +1,39 @@
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "app.tauri.opener"
compileSdk = 34
defaultConfig {
minSdk = 24
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("com.fasterxml.jackson.core:jackson-databind:2.15.3")
implementation(project(":tauri-android"))
}

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

@ -0,0 +1,2 @@
include ':tauri-android'
project(':tauri-android').projectDir = new File('./.tauri/tauri-api')

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

@ -0,0 +1,30 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
package app.tauri.shell
import android.app.Activity
import android.content.Intent
import android.net.Uri
import app.tauri.annotation.Command
import app.tauri.annotation.TauriPlugin
import app.tauri.plugin.Invoke
import app.tauri.plugin.Plugin
import java.io.File
@TauriPlugin
class OpenerPlugin(private val activity: Activity) : Plugin(activity) {
@Command
fun open(invoke: Invoke) {
try {
val url = invoke.parseArgs(String::class.java)
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.applicationContext?.startActivity(intent)
invoke.resolve()
} catch (ex: Exception) {
invoke.reject(ex.message)
}
}
}

@ -0,0 +1 @@
if("__TAURI__"in window){var __TAURI_PLUGIN_OPENER__=function(n){"use strict";async function e(n,e={},_){return window.__TAURI_INTERNALS__.invoke(n,e,_)}return"function"==typeof SuppressedError&&SuppressedError,n.open=async function(n,_){await e("plugin:opener|open",{path:n,with:_})},n.revealInDir=async function(){return e("plugin:opener|reveal_in_dir")},n}({});Object.defineProperty(window.__TAURI__,"opener",{value:__TAURI_PLUGIN_OPENER__})}

@ -0,0 +1,27 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
const COMMANDS: &[&str] = &["open", "reveal_in_dir"];
fn main() {
tauri_plugin::Builder::new(COMMANDS)
.global_api_script_path("./api-iife.js")
.android_path("android")
.ios_path("ios")
.build();
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let mobile = target_os == "ios" || target_os == "android";
alias("desktop", !mobile);
alias("mobile", mobile);
}
// creates a cfg alias if `has_feature` is true.
// `alias` must be a snake case string.
fn alias(alias: &str, has_feature: bool) {
println!("cargo:rustc-check-cfg=cfg({alias})");
if has_feature {
println!("cargo:rustc-cfg={alias}");
}
}

@ -0,0 +1,57 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
/**
* Open files and URLs using their default application.
*
* ## Security
*
* This API has a scope configuration that forces you to restrict the files and urls to be opened.
*
* ### Restricting access to the {@link open | `open`} API
*
* On the configuration object, `open: true` means that the {@link open} API can be used with any URL,
* as the argument is validated with the `^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+` regex.
* You can change that regex by changing the boolean value to a string, e.g. `open: ^https://github.com/`.
*
* @module
*/
import { invoke } from '@tauri-apps/api/core'
/**
* Opens a path or URL with the system's default app,
* or the one specified with `openWith`.
*
* The `openWith` value must be one of `firefox`, `google chrome`, `chromium` `safari`,
* `open`, `start`, `xdg-open`, `gio`, `gnome-open`, `kde-open` or `wslview`.
*
* @example
* ```typescript
* import { open } from '@tauri-apps/plugin-opener';
* // opens the given URL on the default browser:
* await open('https://github.com/tauri-apps/tauri');
* // opens the given URL using `firefox`:
* await open('https://github.com/tauri-apps/tauri', 'firefox');
* // opens a file using the default program:
* await open('/path/to/file');
* ```
*
* @param path The path or URL to open.
* This value is matched against the string regex defined on `tauri.conf.json > plugins > opener > open`,
* which defaults to `^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+`.
* @param openWith The app to open the file or URL with.
* Defaults to the system default application for the specified path type.
*
* @since 2.0.0
*/
export async function open(path: string, openWith?: string): Promise<void> {
await invoke('plugin:opener|open', {
path,
with: openWith
})
}
export async function revealInDir() {
return invoke('plugin:opener|reveal_in_dir')
}

@ -0,0 +1,40 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import { invoke } from '@tauri-apps/api/core'
// open <a href="..."> links with the API
function openLinks(): void {
document.querySelector('body')?.addEventListener('click', function (e) {
let target: HTMLElement | null = e.target as HTMLElement
while (target) {
if (target.matches('a')) {
const t = target as HTMLAnchorElement
if (
t.href !== '' &&
['http://', 'https://', 'mailto:', 'tel:'].some((v) =>
t.href.startsWith(v)
) &&
t.target === '_blank'
) {
void invoke('plugin:opener|open', {
path: t.href
})
e.preventDefault()
}
break
}
target = target.parentElement
}
})
}
if (
document.readyState === 'complete' ||
document.readyState === 'interactive'
) {
openLinks()
} else {
window.addEventListener('DOMContentLoaded', openLinks, true)
}

@ -0,0 +1,16 @@
{
"object": {
"pins": [
{
"package": "SwiftRs",
"repositoryURL": "https://github.com/Brendonovich/swift-rs",
"state": {
"branch": null,
"revision": "b5ed223fcdab165bc21219c1925dc1e77e2bef5e",
"version": "1.0.6"
}
}
]
},
"version": 1
}

@ -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-opener",
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-opener",
type: .static,
targets: ["tauri-plugin-opener"])
],
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-opener",
dependencies: [
.byName(name: "Tauri")
],
path: "Sources")
]
)

@ -0,0 +1,34 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import Foundation
import SwiftRs
import Tauri
import UIKit
import WebKit
class OpenerPlugin: Plugin {
@objc public func open(_ invoke: Invoke) throws {
do {
let urlString = try invoke.parseArgs(String.self)
if let url = URL(string: urlString) {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:])
} else {
UIApplication.shared.openURL(url)
}
}
invoke.resolve()
} catch {
invoke.reject(error.localizedDescription)
}
}
}
@_cdecl("init_plugin_shell")
func initPlugin() -> Plugin {
return OpenerPlugin()
}

@ -0,0 +1,29 @@
{
"name": "@tauri-apps/plugin-opener",
"version": "2.0.0",
"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.0.0"
}
}

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

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

@ -0,0 +1,68 @@
## Default Permission
- `allow-open`
- `allow-reveal-in-dir`
## Permission Table
<table>
<tr>
<th>Identifier</th>
<th>Description</th>
</tr>
<tr>
<td>
`opener:allow-open`
</td>
<td>
Enables the open command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`opener:deny-open`
</td>
<td>
Denies the open command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`opener:allow-reveal-in-dir`
</td>
<td>
Enables the reveal_in_dir command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`opener:deny-reveal-in-dir`
</td>
<td>
Denies the reveal_in_dir command without any pre-configured scope.
</td>
</tr>
</table>

@ -0,0 +1,4 @@
"$schema" = "schemas/schema.json"
[default]
permissions = ["allow-open", "allow-reveal-in-dir"]

@ -0,0 +1,324 @@
{
"$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 open command without any pre-configured scope.",
"type": "string",
"const": "allow-open"
},
{
"description": "Denies the open command without any pre-configured scope.",
"type": "string",
"const": "deny-open"
},
{
"description": "Enables the reveal_in_dir command without any pre-configured scope.",
"type": "string",
"const": "allow-reveal-in-dir"
},
{
"description": "Denies the reveal_in_dir command without any pre-configured scope.",
"type": "string",
"const": "deny-reveal-in-dir"
},
{
"type": "string",
"const": "default"
}
]
}
}
}

@ -0,0 +1,22 @@
// 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'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import typescript from '@rollup/plugin-typescript'
import terser from '@rollup/plugin-terser'
export default createConfig({
additionalConfigs: {
input: 'guest-js/init.ts',
output: {
file: 'src/init-iife.js',
format: 'iife'
},
plugins: [typescript(), terser(), nodeResolve()],
onwarn: (warning) => {
throw Object.assign(new Error(), warning)
}
}
})

@ -0,0 +1,16 @@
use tauri::{AppHandle, Runtime, State};
use crate::{open::Program, Opener};
#[tauri::command]
pub async fn open<R: Runtime>(
_app: AppHandle<R>,
opener: State<'_, Opener<R>>,
path: String,
with: Option<Program>,
) -> crate::Result<()> {
opener.open(path, with)
}
#[tauri::command]
pub async fn reveal_in_dir() {}

@ -0,0 +1,62 @@
use regex::Regex;
use serde::Deserialize;
/// Scope for the open command
pub struct OpenScope {
/// The validation regex that `shell > open` paths must match against.
pub open: Option<Regex>,
}
/// Configuration for the shell plugin.
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Config {
/// Open URL with the user's default application.
#[serde(default)]
pub open: OpenConfig,
}
impl Config {
pub fn open_scope(&self) -> OpenScope {
let open = match &self.open {
OpenConfig::Flag(false) => None,
OpenConfig::Flag(true) => {
Some(Regex::new(r"^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+").unwrap())
}
OpenConfig::Validate(validator) => {
let regex = format!("^{validator}$");
let validator =
Regex::new(&regex).unwrap_or_else(|e| panic!("invalid regex {regex}: {e}"));
Some(validator)
}
};
OpenScope { open }
}
}
/// Defines the `opener > open` api scope.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
#[serde(untagged, deny_unknown_fields)]
#[non_exhaustive]
pub enum OpenConfig {
/// If the opener open API should be enabled.
///
/// If enabled, the default validation regex (`^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+`) is used.
Flag(bool),
/// Enable the opener open API, with a custom regex that the opened path must match against.
///
/// The regex string is automatically surrounded by `^...$` to match the full string.
/// For example the `https?://\w+` regex would be registered as `^https?://\w+$`.
///
/// If using a custom regex to support a non-http(s) schema, care should be used to prevent values
/// that allow flag-like strings to pass validation. e.g. `--enable-debugging`, `-i`, `/R`.
Validate(String),
}
impl Default for OpenConfig {
fn default() -> Self {
Self::Flag(false)
}
}

@ -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::{Serialize, Serializer};
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[cfg(mobile)]
#[error(transparent)]
PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError),
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("unknown program {0}")]
UnknownProgramName(String),
/// At least one argument did not pass input validation.
#[error("Scoped command argument at position {index} was found, but failed regex validation {validation}")]
Validation {
/// Index of the variable.
index: usize,
/// Regex that the variable value failed to match.
validation: String,
},
}
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 @@
!function(){"use strict";async function e(e,t={},n){return window.__TAURI_INTERNALS__.invoke(e,t,n)}function t(){document.querySelector("body")?.addEventListener("click",(function(t){let n=t.target;for(;n;){if(n.matches("a")){const r=n;""!==r.href&&["http://","https://","mailto:","tel:"].some((e=>r.href.startsWith(e)))&&"_blank"===r.target&&(e("plugin:opener|open",{path:r.href}),t.preventDefault());break}n=n.parentElement}}))}"function"==typeof SuppressedError&&SuppressedError,"complete"===document.readyState||"interactive"===document.readyState?t():window.addEventListener("DOMContentLoaded",t,!0)}();

@ -0,0 +1,91 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use config::OpenScope;
use tauri::{
plugin::{Builder, TauriPlugin},
AppHandle, Manager, Runtime,
};
#[cfg(mobile)]
use tauri::plugin::PluginHandle;
#[cfg(target_os = "android")]
const PLUGIN_IDENTIFIER: &str = "app.tauri.opener";
#[cfg(target_os = "ios")]
tauri::ios_plugin_binding!(init_plugin_opener);
mod commands;
mod config;
mod error;
mod open;
pub use error::Error;
type Result<T> = std::result::Result<T, Error>;
pub struct Opener<R: Runtime> {
#[allow(dead_code)]
app: AppHandle<R>,
#[cfg(mobile)]
mobile_plugin_handle: PluginHandle<R>,
open_scope: OpenScope,
}
impl<R: Runtime> Opener<R> {
/// Open a (url) path with a default or specific browser opening program.
///
/// See [`crate::open::open`] for how it handles security-related measures.
#[cfg(desktop)]
pub fn open(&self, path: impl Into<String>, with: Option<open::Program>) -> Result<()> {
open::open(&self.open_scope, path.into(), with).map_err(Into::into)
}
/// Open a (url) path with a default or specific browser opening program.
///
/// See [`crate::open::open`] for how it handles security-related measures.
#[cfg(mobile)]
pub fn open(&self, path: impl Into<String>, _with: Option<open::Program>) -> Result<()> {
self.mobile_plugin_handle
.run_mobile_plugin("open", path.into())
.map_err(Into::into)
}
}
/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the opener APIs.
pub trait OpenerExt<R: Runtime> {
fn opener(&self) -> &Opener<R>;
}
impl<R: Runtime, T: Manager<R>> crate::OpenerExt<R> for T {
fn opener(&self) -> &Opener<R> {
self.state::<Opener<R>>().inner()
}
}
/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R, Option<config::Config>> {
Builder::<R, Option<config::Config>>::new("opener")
.js_init_script(include_str!("init-iife.js").to_string())
.setup(|app, api| {
let default_config = config::Config::default();
let config = api.config().as_ref().unwrap_or(&default_config);
#[cfg(target_os = "android")]
let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "OpenerPlugin")?;
#[cfg(target_os = "ios")]
let handle = api.register_ios_plugin(init_plugin_opener)?;
app.manage(Opener {
app: app.clone(),
open_scope: config.open_scope(),
#[cfg(mobile)]
mobile_plugin_handle: handle,
});
Ok(())
})
.invoke_handler(tauri::generate_handler![
commands::open,
commands::reveal_in_dir
])
.build()
}

@ -0,0 +1,141 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Types and functions related to shell.
use serde::{Deserialize, Deserializer};
use std::str::FromStr;
use crate::{config::OpenScope, Error};
/// Program to use on the [`open()`] call.
pub enum Program {
/// Use the `open` program.
Open,
/// Use the `start` program.
Start,
/// Use the `xdg-open` program.
XdgOpen,
/// Use the `gio` program.
Gio,
/// Use the `gnome-open` program.
GnomeOpen,
/// Use the `kde-open` program.
KdeOpen,
/// Use the `wslview` program.
WslView,
/// Use the `Firefox` program.
Firefox,
/// Use the `Google Chrome` program.
Chrome,
/// Use the `Chromium` program.
Chromium,
/// Use the `Safari` program.
Safari,
}
impl FromStr for Program {
type Err = super::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let p = match s.to_lowercase().as_str() {
"open" => Self::Open,
"start" => Self::Start,
"xdg-open" => Self::XdgOpen,
"gio" => Self::Gio,
"gnome-open" => Self::GnomeOpen,
"kde-open" => Self::KdeOpen,
"wslview" => Self::WslView,
"firefox" => Self::Firefox,
"chrome" | "google chrome" => Self::Chrome,
"chromium" => Self::Chromium,
"safari" => Self::Safari,
_ => return Err(crate::Error::UnknownProgramName(s.to_string())),
};
Ok(p)
}
}
impl<'de> Deserialize<'de> for Program {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Program::from_str(&s).map_err(|e| serde::de::Error::custom(e.to_string()))
}
}
impl Program {
pub(crate) fn name(self) -> &'static str {
match self {
Self::Open => "open",
Self::Start => "start",
Self::XdgOpen => "xdg-open",
Self::Gio => "gio",
Self::GnomeOpen => "gnome-open",
Self::KdeOpen => "kde-open",
Self::WslView => "wslview",
#[cfg(target_os = "macos")]
Self::Firefox => "Firefox",
#[cfg(not(target_os = "macos"))]
Self::Firefox => "firefox",
#[cfg(target_os = "macos")]
Self::Chrome => "Google Chrome",
#[cfg(not(target_os = "macos"))]
Self::Chrome => "google-chrome",
#[cfg(target_os = "macos")]
Self::Chromium => "Chromium",
#[cfg(not(target_os = "macos"))]
Self::Chromium => "chromium",
#[cfg(target_os = "macos")]
Self::Safari => "Safari",
#[cfg(not(target_os = "macos"))]
Self::Safari => "safari",
}
}
}
/// Opens path or URL with the program specified in `with`, or system default if `None`.
///
/// The path will be matched against the shell open validation regex, defaulting to `^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+`.
/// A custom validation regex may be supplied in the config in `plugins > shell > scope > open`.
///
/// # Examples
///
/// ```rust,no_run
/// use tauri_plugin_shell::ShellExt;
/// tauri::Builder::default()
/// .setup(|app| {
/// // open the given URL on the system default browser
/// app.shell().open("https://github.com/tauri-apps/tauri", None)?;
/// Ok(())
/// });
/// ```
pub fn open<P: AsRef<str>>(scope: &OpenScope, path: P, with: Option<Program>) -> crate::Result<()> {
let path = path.as_ref();
// ensure we pass validation if the configuration has one
if let Some(regex) = &scope.open {
if !regex.is_match(path) {
return Err(Error::Validation {
index: 0,
validation: regex.as_str().into(),
});
}
}
// The prevention of argument escaping is handled by the usage of std::process::Command::arg by
// the `open` dependency. This behavior should be re-confirmed during upgrades of `open`.
match with.map(Program::name) {
Some(program) => ::open::with_detached(path, program),
None => ::open::that_detached(path),
}
.map_err(Into::into)
}

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

@ -182,6 +182,7 @@ fn main() {
// creates a cfg alias if `has_feature` is true.
// `alias` must be a snake case string.
fn alias(alias: &str, has_feature: bool) {
println!("cargo:rustc-check-cfg=cfg({alias})");
if has_feature {
println!("cargo:rustc-cfg={alias}");
}

@ -28,6 +28,7 @@ use tauri::{
mod commands;
mod config;
mod error;
#[deprecated(since = "2.1.0", note = "Use tauri-plugin-opener instead.")]
pub mod open;
pub mod process;
mod scope;
@ -72,6 +73,7 @@ impl<R: Runtime> Shell<R> {
///
/// See [`crate::open::open`] for how it handles security-related measures.
#[cfg(desktop)]
#[deprecated(since = "2.1.0", note = "Use tauri-plugin-opener instead.")]
pub fn open(&self, path: impl Into<String>, with: Option<open::Program>) -> Result<()> {
open::open(&self.open_scope, path.into(), with).map_err(Into::into)
}
@ -80,6 +82,7 @@ impl<R: Runtime> Shell<R> {
///
/// See [`crate::open::open`] for how it handles security-related measures.
#[cfg(mobile)]
#[deprecated(since = "2.1.0", note = "Use tauri-plugin-opener instead.")]
pub fn open(&self, path: impl Into<String>, _with: Option<open::Program>) -> Result<()> {
self.mobile_plugin_handle
.run_mobile_plugin("open", path.into())

@ -10,6 +10,7 @@ use crate::scope::OpenScope;
use std::str::FromStr;
/// Program to use on the [`open()`] call.
#[deprecated(since = "2.1.0", note = "Use tauri-plugin-opener instead.")]
pub enum Program {
/// Use the `open` program.
Open,
@ -117,6 +118,7 @@ impl Program {
/// Ok(())
/// });
/// ```
#[deprecated(since = "2.1.0", note = "Use tauri-plugin-opener instead.")]
pub fn open<P: AsRef<str>>(scope: &OpenScope, path: P, with: Option<Program>) -> crate::Result<()> {
scope.open(path.as_ref(), with).map_err(Into::into)
}

@ -18,6 +18,7 @@ fn main() {
// creates a cfg alias if `has_feature` is true.
// `alias` must be a snake case string.
fn alias(alias: &str, has_feature: bool) {
println!("cargo:rustc-check-cfg=cfg({alias})");
if has_feature {
println!("cargo:rustc-cfg={alias}");
}

@ -96,6 +96,9 @@ importers:
'@tauri-apps/plugin-notification':
specifier: 2.0.0
version: link:../../plugins/notification
'@tauri-apps/plugin-opener':
specifier: 2.0.0
version: link:../../plugins/opener
'@tauri-apps/plugin-os':
specifier: 2.0.0
version: link:../../plugins/os
@ -249,6 +252,12 @@ importers:
specifier: ^2.0.0
version: 2.0.3
plugins/opener:
dependencies:
'@tauri-apps/api':
specifier: ^2.0.0
version: 2.0.3
plugins/os:
dependencies:
'@tauri-apps/api':
@ -2415,14 +2424,13 @@ snapshots:
picocolors: 1.1.0
sisteransi: 1.0.5
'@covector/apply@0.10.0(mocha@10.7.3)':
'@covector/apply@0.10.0':
dependencies:
'@covector/files': 0.8.0
effection: 2.0.8(mocha@10.7.3)
semver: 7.6.3
transitivePeerDependencies:
- encoding
- mocha
'@covector/assemble@0.12.0(mocha@10.7.3)':
dependencies:
@ -2440,7 +2448,7 @@ snapshots:
- mocha
- supports-color
'@covector/changelog@0.12.0(mocha@10.7.3)':
'@covector/changelog@0.12.0':
dependencies:
'@covector/files': 0.8.0
effection: 2.0.8(mocha@10.7.3)
@ -2450,12 +2458,11 @@ snapshots:
unified: 9.2.2
transitivePeerDependencies:
- encoding
- mocha
- supports-color
'@covector/command@0.8.0(mocha@10.7.3)':
dependencies:
'@effection/process': 2.1.4(mocha@10.7.3)
'@effection/process': 2.1.4
effection: 2.0.8(mocha@10.7.3)
transitivePeerDependencies:
- encoding
@ -2506,8 +2513,10 @@ snapshots:
dependencies:
effection: 2.0.8(mocha@10.7.3)
mocha: 10.7.3
transitivePeerDependencies:
- encoding
'@effection/process@2.1.4(mocha@10.7.3)':
'@effection/process@2.1.4':
dependencies:
cross-spawn: 7.0.3
ctrlc-windows: 2.1.0
@ -2515,7 +2524,6 @@ snapshots:
shellwords: 0.1.1
transitivePeerDependencies:
- encoding
- mocha
'@effection/stream@2.0.6':
dependencies:
@ -3385,9 +3393,9 @@ snapshots:
covector@0.12.3(mocha@10.7.3):
dependencies:
'@clack/prompts': 0.7.0
'@covector/apply': 0.10.0(mocha@10.7.3)
'@covector/apply': 0.10.0
'@covector/assemble': 0.12.0(mocha@10.7.3)
'@covector/changelog': 0.12.0(mocha@10.7.3)
'@covector/changelog': 0.12.0
'@covector/command': 0.8.0(mocha@10.7.3)
'@covector/files': 0.8.0
effection: 2.0.8(mocha@10.7.3)

Loading…
Cancel
Save