Merge branch 'v2' into fix/deb_update

pull/1991/head
jLynx 8 months ago committed by GitHub
commit 9c5eaef1cf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -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 @@
---
fs: minor
persisted-scope: minor
---
**Breaking Change:** Replaced the custom `tauri_plugin_fs::Scope` struct with `tauri::fs::Scope`.

@ -0,0 +1,6 @@
---
"fs": "patch"
"fs-js": "patch"
---
Improve performance of `readTextFile` and `readTextFileLines` APIs

@ -0,0 +1,7 @@
---
"fs": "patch"
"fs-js": "patch"
---
Add support for using `ReadableStream<Unit8Array>` with `writeFile` API.

@ -0,0 +1,5 @@
---
"http": "patch"
---
Add tracing logs for requestes and responses behind `tracing` feature flag.

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

@ -0,0 +1,6 @@
---
"positioner-js": minor
---
Add `moveWindowConstrained` function that is similar to `moveWindow` but constrains the window to the screen dimensions in case of tray icon positions.

@ -0,0 +1,6 @@
---
"positioner": minor
---
Add `WindowExt::move_window_constrained` method that is similar to `WindowExt::move_window` but constrains the window to the screen dimensions in case of tray icon positions.

@ -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

943
Cargo.lock generated

File diff suppressed because it is too large Load Diff

@ -10,6 +10,7 @@ resolver = "2"
[workspace.dependencies]
serde = { version = "1", features = ["derive"] }
tracing = "0.1"
log = "0.4"
tauri = { version = "2", default-features = false }
tauri-build = "2"
@ -21,6 +22,8 @@ url = "2"
schemars = "0.8"
dunce = "1"
specta = "=2.0.0-rc.20"
glob = "0.3"
zbus = "4"
#tauri-specta = "=2.0.0-rc.11"
[workspace.package]

@ -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. | ✅ | ✅ | ✅ | ❌ | ❌ |

@ -19,6 +19,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": "1.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 = "1.0.0" }
tauri-plugin-shell = { path = "../../../plugins/shell", version = "2.0.2" }
tauri-plugin-store = { path = "../../../plugins/store", version = "2.1.0" }

@ -80,6 +80,11 @@
],
"deny": ["$APPDATA/db/*.stronghold"]
},
"store:default"
"store:default",
"opener:default",
{
"identifier": "opener:allow-open-path",
"allow": [{ "path": "$APPDATA" }, { "path": "$APPDATA/**" }]
}
]
}

@ -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'
@ -92,6 +92,11 @@
component: Shell,
icon: 'i-codicon-terminal-bash'
},
{
label: 'Opener',
component: Opener,
icon: 'i-codicon-link-external'
},
{
label: 'Store',
component: Store,

@ -0,0 +1,66 @@
<script>
import * as opener from '@tauri-apps/plugin-opener'
export let onMessage
let url = ''
let urlProgram = ''
function openUrl() {
opener.openUrl(url, urlProgram ? urlProgram : undefined).catch(onMessage)
}
let path = ''
let pathProgram = ''
function openPath() {
opener
.openPath(path, pathProgram ? pathProgram : undefined)
.catch(onMessage)
}
let revealPath = ''
function revealItemInDir() {
opener.revealItemInDir(revealPath).catch(onMessage)
}
</script>
<div class="flex flex-col gap-2">
<form
class="flex flex-row gap-2 items-center"
on:submit|preventDefault={openUrl}
>
<button class="btn" type="submit">Open URL</button>
<input
class="input grow"
placeholder="Type the URL to open..."
bind:value={url}
/>
<span> with </span>
<input class="input" bind:value={urlProgram} />
</form>
<form
class="flex flex-row gap-2 items-center"
on:submit|preventDefault={openPath}
>
<button class="btn" type="submit">Open Path</button>
<input
class="input grow"
placeholder="Type the path to open..."
bind:value={path}
/>
<span> with </span>
<input class="input" bind:value={pathProgram} />
</form>
<form
class="flex flex-row gap-2 items-center"
on:submit|preventDefault={revealItemInDir}
>
<button class="btn" type="submit">Reveal</button>
<input
class="input grow"
placeholder="Type the path to reveal..."
bind:value={revealPath}
/>
</form>
</div>

@ -11,20 +11,20 @@
"example:api:dev": "pnpm run --filter \"api\" tauri dev"
},
"devDependencies": {
"@eslint/js": "9.14.0",
"@eslint/js": "9.15.0",
"@rollup/plugin-node-resolve": "15.3.0",
"@rollup/plugin-terser": "0.4.4",
"@rollup/plugin-typescript": "11.1.6",
"@types/eslint__js": "8.42.3",
"covector": "^0.12.3",
"eslint": "9.14.0",
"eslint": "9.15.0",
"eslint-config-prettier": "9.1.0",
"eslint-plugin-security": "3.0.1",
"prettier": "3.3.3",
"rollup": "4.26.0",
"rollup": "4.27.3",
"tslib": "2.8.1",
"typescript": "5.6.3",
"typescript-eslint": "8.14.0"
"typescript-eslint": "8.15.0"
},
"resolutions": {
"semver": ">=7.5.2",

@ -27,6 +27,5 @@ tauri-plugin = { workspace = true, features = ["build"] }
serde = { workspace = true }
serde_json = { workspace = true }
tauri = { workspace = true }
log = { workspace = true }
thiserror = { workspace = true }
auto-launch = "0.5"

@ -11,8 +11,6 @@
#![cfg(not(any(target_os = "android", target_os = "ios")))]
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
#[cfg(target_os = "macos")]
use log::info;
use serde::{ser::Serializer, Serialize};
use tauri::{
command,
@ -133,7 +131,6 @@ pub fn init<R: Runtime>(
} else {
exe_path
};
info!("auto_start path {}", &app_path);
builder.set_app_path(&app_path);
}
#[cfg(target_os = "linux")]

@ -90,7 +90,7 @@ async function writeImage(
* import { readImage } from '@tauri-apps/plugin-clipboard-manager';
*
* const clipboardImage = await readImage();
* const blob = new Blob([clipboardImage.bytes], { type: 'image' })
* const blob = new Blob([await clipboardImage.rbga()], { type: 'image' })
* const url = URL.createObjectURL(blob)
* ```
* @since 2.0.0

@ -32,7 +32,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
tauri = { workspace = true }
tauri-utils = { workspace = true }
log = { workspace = true }
tracing = { workspace = true }
thiserror = { workspace = true }
url = { workspace = true }

@ -215,7 +215,7 @@ mod imp {
current.replace(vec![url.clone()]);
let _ = self.app.emit("deep-link://new-url", vec![url]);
} else if cfg!(debug_assertions) {
log::warn!("argument {url} does not match any configured deep link scheme; skipping it");
tracing::warn!("argument {url} does not match any configured deep link scheme; skipping it");
}
}
}

@ -143,7 +143,7 @@ pub(crate) async fn open<R: Runtime>(
for folder in folders {
if let Ok(path) = folder.clone().into_path() {
if let Some(s) = window.try_fs_scope() {
s.allow_directory(&path, options.recursive);
s.allow_directory(&path, options.recursive)?;
}
tauri_scope.allow_directory(&path, options.directory)?;
}
@ -157,7 +157,7 @@ pub(crate) async fn open<R: Runtime>(
if let Some(folder) = &folder {
if let Ok(path) = folder.clone().into_path() {
if let Some(s) = window.try_fs_scope() {
s.allow_directory(&path, options.recursive);
s.allow_directory(&path, options.recursive)?;
}
tauri_scope.allow_directory(&path, options.directory)?;
}
@ -175,7 +175,7 @@ pub(crate) async fn open<R: Runtime>(
for file in files {
if let Ok(path) = file.clone().into_path() {
if let Some(s) = window.try_fs_scope() {
s.allow_file(&path);
s.allow_file(&path)?;
}
tauri_scope.allow_file(&path)?;
@ -190,7 +190,7 @@ pub(crate) async fn open<R: Runtime>(
if let Some(file) = &file {
if let Ok(path) = file.clone().into_path() {
if let Some(s) = window.try_fs_scope() {
s.allow_file(&path);
s.allow_file(&path)?;
}
tauri_scope.allow_file(&path)?;
}
@ -232,7 +232,7 @@ pub(crate) async fn save<R: Runtime>(
if let Some(p) = &path {
if let Ok(path) = p.clone().into_path() {
if let Some(s) = window.try_fs_scope() {
s.allow_file(&path);
s.allow_file(&path)?;
}
tauri_scope.allow_file(&path)?;
}

@ -14,7 +14,7 @@ rustc-args = ["--cfg", "docsrs"]
rustdoc-args = ["--cfg", "docsrs"]
[package.metadata.platforms.support]
windows = { level = "full", notes = "" }
windows = { level = "full", notes = "Apps installed via MSI or NSIS in `perMachine` and `both` mode require admin permissions for write acces in `$RESOURCES` folder" }
linux = { level = "full", notes = "No write access to `$RESOURCES` folder" }
macos = { level = "full", notes = "No write access to `$RESOURCES` folder" }
android = { level = "partial", notes = "Access is restricted to Application folder by default" }
@ -24,6 +24,8 @@ ios = { level = "partial", notes = "Access is restricted to Application folder b
tauri-plugin = { workspace = true, features = ["build"] }
schemars = { workspace = true }
serde = { workspace = true }
toml = "0.8"
tauri-utils = { workspace = true, features = ["build"] }
[dependencies]
serde = { workspace = true }
@ -34,7 +36,7 @@ thiserror = { workspace = true }
url = { workspace = true }
anyhow = "1"
uuid = { version = "1", features = ["v4"] }
glob = "0.3"
glob = { workspace = true }
# TODO: Remove `serialization-compat-6` in v3
notify = { version = "7", optional = true, features = [
"serde",

File diff suppressed because one or more lines are too long

@ -7,6 +7,8 @@ use std::{
path::{Path, PathBuf},
};
use tauri_utils::acl::manifest::PermissionFile;
#[path = "src/scope.rs"]
#[allow(dead_code)]
mod scope;
@ -16,10 +18,23 @@ mod scope;
#[serde(untagged)]
#[allow(unused)]
enum FsScopeEntry {
/// FS scope path.
/// A path that can be accessed by the webview when using the fs APIs.
/// FS scope path pattern.
///
/// The pattern can start with a variable that resolves to a system base directory.
/// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
/// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
/// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`,
/// `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.
Value(PathBuf),
Object {
/// FS scope path.
/// A path that can be accessed by the webview when using the fs APIs.
///
/// The pattern can start with a variable that resolves to a system base directory.
/// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
/// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
/// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`,
/// `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.
path: PathBuf,
},
}
@ -62,31 +77,31 @@ const BASE_DIR_VARS: &[&str] = &[
"APPCACHE",
"APPLOG",
];
const COMMANDS: &[&str] = &[
"mkdir",
"create",
"copy_file",
"remove",
"rename",
"truncate",
"ftruncate",
"write",
"write_file",
"write_text_file",
"read_dir",
"read_file",
"read",
"open",
"read_text_file",
"read_text_file_lines",
"read_text_file_lines_next",
"seek",
"stat",
"lstat",
"fstat",
"exists",
"watch",
"unwatch",
const COMMANDS: &[(&str, &[&str])] = &[
("mkdir", &[]),
("create", &[]),
("copy_file", &[]),
("remove", &[]),
("rename", &[]),
("truncate", &[]),
("ftruncate", &[]),
("write", &[]),
("write_file", &["open", "write"]),
("write_text_file", &[]),
("read_dir", &[]),
("read_file", &[]),
("read", &[]),
("open", &[]),
("read_text_file", &[]),
("read_text_file_lines", &["read_text_file_lines_next"]),
("read_text_file_lines_next", &[]),
("seek", &[]),
("stat", &[]),
("lstat", &[]),
("fstat", &[]),
("exists", &[]),
("watch", &[]),
("unwatch", &[]),
];
fn main() {
@ -192,9 +207,47 @@ permissions = [
}
}
tauri_plugin::Builder::new(COMMANDS)
tauri_plugin::Builder::new(&COMMANDS.iter().map(|c| c.0).collect::<Vec<_>>())
.global_api_script_path("./api-iife.js")
.global_scope_schema(schemars::schema_for!(FsScopeEntry))
.android_path("android")
.build();
// workaround to include nested permissions as `tauri_plugin` doesn't support it
let permissions_dir = autogenerated.join("commands");
for (command, nested_commands) in COMMANDS {
if nested_commands.is_empty() {
continue;
}
let permission_path = permissions_dir.join(format!("{command}.toml"));
let content = std::fs::read_to_string(&permission_path)
.unwrap_or_else(|_| panic!("failed to read {command}.toml"));
let mut permission_file = toml::from_str::<PermissionFile>(&content)
.unwrap_or_else(|_| panic!("failed to deserialize {command}.toml"));
for p in permission_file
.permission
.iter_mut()
.filter(|p| p.identifier.starts_with("allow"))
{
p.commands
.allow
.extend(nested_commands.iter().map(|s| s.to_string()));
}
let out = toml::to_string_pretty(&permission_file)
.unwrap_or_else(|_| panic!("failed to serialize {command}.toml"));
let out = format!(
r#"# Automatically generated - DO NOT EDIT!
"$schema" = "../../schemas/schema.json"
{out}"#
);
std::fs::write(permission_path, out)
.unwrap_or_else(|_| panic!("failed to write {command}.toml"));
}
}

@ -266,6 +266,7 @@ function fromBytes(buffer: FixedSizeArray<number, 8>): number {
const size = bytes.byteLength
let x = 0
for (let i = 0; i < size; i++) {
// eslint-disable-next-line security/detect-object-injection
const byte = bytes[i]
x *= 0x100
x += byte
@ -427,11 +428,11 @@ class FileHandle extends Resource {
}
/**
* Writes `p.byteLength` bytes from `p` to the underlying data stream. It
* resolves to the number of bytes written from `p` (`0` <= `n` <=
* `p.byteLength`) or reject with the error encountered that caused the
* Writes `data.byteLength` bytes from `data` to the underlying data stream. It
* resolves to the number of bytes written from `data` (`0` <= `n` <=
* `data.byteLength`) or reject with the error encountered that caused the
* write to stop early. `write()` must reject with a non-null error if
* would resolve to `n` < `p.byteLength`. `write()` must not modify the
* would resolve to `n` < `data.byteLength`. `write()` must not modify the
* slice data, even temporarily.
*
* @example
@ -769,10 +770,14 @@ async function readTextFile(
throw new TypeError('Must be a file URL.')
}
return await invoke<string>('plugin:fs|read_text_file', {
const arr = await invoke<ArrayBuffer | number[]>('plugin:fs|read_text_file', {
path: path instanceof URL ? path.toString() : path,
options
})
const bytes = arr instanceof ArrayBuffer ? arr : Uint8Array.from(arr)
return new TextDecoder().decode(bytes)
}
/**
@ -803,6 +808,7 @@ async function readTextFileLines(
return await Promise.resolve({
path: pathStr,
rid: null as number | null,
async next(): Promise<IteratorResult<string>> {
if (this.rid === null) {
this.rid = await invoke<number>('plugin:fs|read_text_file_lines', {
@ -811,19 +817,35 @@ async function readTextFileLines(
})
}
const [line, done] = await invoke<[string | null, boolean]>(
const arr = await invoke<ArrayBuffer | number[]>(
'plugin:fs|read_text_file_lines_next',
{ rid: this.rid }
)
// an iteration is over, reset rid for next iteration
if (done) this.rid = null
const bytes =
arr instanceof ArrayBuffer ? new Uint8Array(arr) : Uint8Array.from(arr)
// Rust side will never return an empty array for this command and
// ensure there is at least one elements there.
//
// This is an optimization to include whether we finished iteration or not (1 or 0)
// at the end of returned array to avoid serialization overhead of separate values.
const done = bytes[bytes.byteLength - 1] === 1
if (done) {
// a full iteration is over, reset rid for next iteration
this.rid = null
return { value: null, done }
}
const line = new TextDecoder().decode(bytes.slice(0, bytes.byteLength))
return {
value: done ? '' : line!,
value: line,
done
}
},
[Symbol.asyncIterator](): AsyncIterableIterator<string> {
return this
}
@ -1044,19 +1066,27 @@ interface WriteFileOptions {
*/
async function writeFile(
path: string | URL,
data: Uint8Array,
data: Uint8Array | ReadableStream<Uint8Array>,
options?: WriteFileOptions
): Promise<void> {
if (path instanceof URL && path.protocol !== 'file:') {
throw new TypeError('Must be a file URL.')
}
await invoke('plugin:fs|write_file', data, {
headers: {
path: encodeURIComponent(path instanceof URL ? path.toString() : path),
options: JSON.stringify(options)
if (data instanceof ReadableStream) {
const file = await open(path, options)
for await (const chunk of data) {
await file.write(chunk)
}
})
await file.close()
} else {
await invoke('plugin:fs|write_file', data, {
headers: {
path: encodeURIComponent(path instanceof URL ? path.toString() : path),
options: JSON.stringify(options)
}
})
}
}
/**

@ -5,9 +5,18 @@
[[permission]]
identifier = "allow-read-text-file-lines"
description = "Enables the read_text_file_lines command without any pre-configured scope."
commands.allow = ["read_text_file_lines"]
[permission.commands]
allow = [
"read_text_file_lines",
"read_text_file_lines_next",
]
deny = []
[[permission]]
identifier = "deny-read-text-file-lines"
description = "Denies the read_text_file_lines command without any pre-configured scope."
commands.deny = ["read_text_file_lines"]
[permission.commands]
allow = []
deny = ["read_text_file_lines"]

@ -5,9 +5,19 @@
[[permission]]
identifier = "allow-write-file"
description = "Enables the write_file command without any pre-configured scope."
commands.allow = ["write_file"]
[permission.commands]
allow = [
"write_file",
"open",
"write",
]
deny = []
[[permission]]
identifier = "deny-write-file"
description = "Denies the write_file command without any pre-configured scope."
commands.deny = ["write_file"]
[permission.commands]
allow = []
deny = ["write_file"]

@ -15,14 +15,14 @@ use tauri::{
use std::{
borrow::Cow,
fs::File,
io::{BufReader, Lines, Read, Write},
path::PathBuf,
io::{BufRead, BufReader, Read, Write},
path::{Path, PathBuf},
str::FromStr,
sync::Mutex,
time::{SystemTime, UNIX_EPOCH},
};
use crate::{scope::Entry, Error, FsExt, SafeFilePath};
use crate::{scope::Entry, Error, SafeFilePath};
#[derive(Debug, thiserror::Error)]
pub enum CommandError {
@ -372,6 +372,7 @@ pub async fn read_file<R: Runtime>(
Ok(tauri::ipc::Response::new(contents))
}
// TODO, remove in v3, rely on `read_file` command instead
#[tauri::command]
pub async fn read_text_file<R: Runtime>(
webview: Webview<R>,
@ -379,33 +380,8 @@ pub async fn read_text_file<R: Runtime>(
command_scope: CommandScope<Entry>,
path: SafeFilePath,
options: Option<BaseOptions>,
) -> CommandResult<String> {
let (mut file, path) = resolve_file(
&webview,
&global_scope,
&command_scope,
path,
OpenOptions {
base: BaseOptions {
base_dir: options.as_ref().and_then(|o| o.base_dir),
},
options: crate::OpenOptions {
read: true,
..Default::default()
},
},
)?;
let mut contents = String::new();
file.read_to_string(&mut contents).map_err(|e| {
format!(
"failed to read file as text at path: {} with error: {e}",
path.display()
)
})?;
Ok(contents)
) -> CommandResult<tauri::ipc::Response> {
read_file(webview, global_scope, command_scope, path, options).await
}
#[tauri::command]
@ -416,8 +392,6 @@ pub fn read_text_file_lines<R: Runtime>(
path: SafeFilePath,
options: Option<BaseOptions>,
) -> CommandResult<ResourceId> {
use std::io::BufRead;
let resolved_path = resolve_path(
&webview,
&global_scope,
@ -433,7 +407,7 @@ pub fn read_text_file_lines<R: Runtime>(
)
})?;
let lines = BufReader::new(file).lines();
let lines = BufReader::new(file);
let rid = webview.resources_table().add(StdLinesResource::new(lines));
Ok(rid)
@ -443,18 +417,28 @@ pub fn read_text_file_lines<R: Runtime>(
pub async fn read_text_file_lines_next<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
) -> CommandResult<(Option<String>, bool)> {
) -> CommandResult<tauri::ipc::Response> {
let mut resource_table = webview.resources_table();
let lines = resource_table.get::<StdLinesResource>(rid)?;
let ret = StdLinesResource::with_lock(&lines, |lines| {
lines.next().map(|a| (a.ok(), false)).unwrap_or_else(|| {
let _ = resource_table.close(rid);
(None, true)
})
let ret = StdLinesResource::with_lock(&lines, |lines| -> CommandResult<Vec<u8>> {
// This is an optimization to include wether we finished iteration or not (1 or 0)
// at the end of returned vector so we can use `tauri::ipc::Response`
// and avoid serialization overhead of separate values.
match lines.next() {
Some(Ok(mut bytes)) => {
bytes.push(false as u8);
Ok(bytes)
}
Some(Err(_)) => Ok(vec![false as u8]),
None => {
resource_table.close(rid)?;
Ok(vec![true as u8])
}
}
});
Ok(ret)
ret.map(tauri::ipc::Response::new)
}
#[derive(Debug, Clone, Deserialize)]
@ -805,10 +789,11 @@ fn default_create_value() -> bool {
true
}
fn write_file_inner<R: Runtime>(
#[tauri::command]
pub async fn write_file<R: Runtime>(
webview: Webview<R>,
global_scope: &GlobalScope<Entry>,
command_scope: &CommandScope<Entry>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
request: tauri::ipc::Request<'_>,
) -> CommandResult<()> {
let data = match request.body() {
@ -839,8 +824,8 @@ fn write_file_inner<R: Runtime>(
let (mut file, path) = resolve_file(
&webview,
global_scope,
command_scope,
&global_scope,
&command_scope,
path,
if let Some(opts) = options {
OpenOptions {
@ -883,17 +868,7 @@ fn write_file_inner<R: Runtime>(
.map_err(Into::into)
}
#[tauri::command]
pub async fn write_file<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
request: tauri::ipc::Request<'_>,
) -> CommandResult<()> {
write_file_inner(webview, &global_scope, &command_scope, request)
}
// TODO, in v3, remove this command and rely on `write_file` command only
// TODO, remove in v3, rely on `write_file` command instead
#[tauri::command]
pub async fn write_text_file<R: Runtime>(
webview: Webview<R>,
@ -901,7 +876,7 @@ pub async fn write_text_file<R: Runtime>(
command_scope: CommandScope<Entry>,
request: tauri::ipc::Request<'_>,
) -> CommandResult<()> {
write_file_inner(webview, &global_scope, &command_scope, request)
write_file(webview, global_scope, command_scope, request).await
}
#[tauri::command]
@ -967,6 +942,8 @@ pub fn resolve_file<R: Runtime>(
path: SafeFilePath,
open_options: OpenOptions,
) -> CommandResult<(File, PathBuf)> {
use crate::FsExt;
match path {
SafeFilePath::Url(url) => {
let path = url.as_str().into();
@ -999,40 +976,81 @@ pub fn resolve_path<R: Runtime>(
path
};
let fs_scope = webview.state::<crate::Scope>();
let scope = tauri::scope::fs::Scope::new(
webview,
&FsScope::Scope {
allow: webview
.fs_scope()
.allowed
.lock()
.unwrap()
.clone()
.into_iter()
.chain(global_scope.allows().iter().filter_map(|e| e.path.clone()))
allow: global_scope
.allows()
.iter()
.filter_map(|e| e.path.clone())
.chain(command_scope.allows().iter().filter_map(|e| e.path.clone()))
.collect(),
deny: webview
.fs_scope()
.denied
.lock()
.unwrap()
.clone()
.into_iter()
.chain(global_scope.denies().iter().filter_map(|e| e.path.clone()))
deny: global_scope
.denies()
.iter()
.filter_map(|e| e.path.clone())
.chain(command_scope.denies().iter().filter_map(|e| e.path.clone()))
.collect(),
require_literal_leading_dot: webview.fs_scope().require_literal_leading_dot,
require_literal_leading_dot: fs_scope.require_literal_leading_dot,
},
)?;
if scope.is_allowed(&path) {
let require_literal_leading_dot = fs_scope.require_literal_leading_dot.unwrap_or(cfg!(unix));
if is_forbidden(&fs_scope.scope, &path, require_literal_leading_dot)
|| is_forbidden(&scope, &path, require_literal_leading_dot)
{
return Err(CommandError::Plugin(Error::PathForbidden(path)));
}
if fs_scope.scope.is_allowed(&path) || scope.is_allowed(&path) {
Ok(path)
} else {
Err(CommandError::Plugin(Error::PathForbidden(path)))
}
}
fn is_forbidden<P: AsRef<Path>>(
scope: &tauri::fs::Scope,
path: P,
require_literal_leading_dot: bool,
) -> bool {
let path = path.as_ref();
let path = if path.is_symlink() {
match std::fs::read_link(path) {
Ok(p) => p,
Err(_) => return false,
}
} else {
path.to_path_buf()
};
let path = if !path.exists() {
crate::Result::Ok(path)
} else {
std::fs::canonicalize(path).map_err(Into::into)
};
if let Ok(path) = path {
let path: PathBuf = path.components().collect();
scope.forbidden_patterns().iter().any(|p| {
p.matches_path_with(
&path,
glob::MatchOptions {
// this is needed so `/dir/*` doesn't match files within subdirectories such as `/dir/subdir/file.txt`
// see: <https://github.com/tauri-apps/tauri/security/advisories/GHSA-6mv3-wm7j-h4w5>
require_literal_separator: true,
require_literal_leading_dot,
..Default::default()
},
)
})
} else {
false
}
}
struct StdFileResource(Mutex<File>);
impl StdFileResource {
@ -1048,14 +1066,38 @@ impl StdFileResource {
impl Resource for StdFileResource {}
struct StdLinesResource(Mutex<Lines<BufReader<File>>>);
/// Same as [std::io::Lines] but with bytes
struct LinesBytes<T: BufRead>(T);
impl<B: BufRead> Iterator for LinesBytes<B> {
type Item = std::io::Result<Vec<u8>>;
fn next(&mut self) -> Option<std::io::Result<Vec<u8>>> {
let mut buf = Vec::new();
match self.0.read_until(b'\n', &mut buf) {
Ok(0) => None,
Ok(_n) => {
if buf.last() == Some(&b'\n') {
buf.pop();
if buf.last() == Some(&b'\r') {
buf.pop();
}
}
Some(Ok(buf))
}
Err(e) => Some(Err(e)),
}
}
}
struct StdLinesResource(Mutex<LinesBytes<BufReader<File>>>);
impl StdLinesResource {
fn new(lines: Lines<BufReader<File>>) -> Self {
Self(Mutex::new(lines))
fn new(lines: BufReader<File>) -> Self {
Self(Mutex::new(LinesBytes(lines)))
}
fn with_lock<R, F: FnMut(&mut Lines<BufReader<File>>) -> R>(&self, mut f: F) -> R {
fn with_lock<R, F: FnMut(&mut LinesBytes<BufReader<File>>) -> R>(&self, mut f: F) -> R {
let mut lines = self.0.lock().unwrap();
f(&mut lines)
}
@ -1154,7 +1196,12 @@ fn get_stat(metadata: std::fs::Metadata) -> FileInfo {
}
}
#[cfg(test)]
mod test {
use std::io::{BufRead, BufReader};
use super::LinesBytes;
#[test]
fn safe_file_path_parse() {
use super::SafeFilePath;
@ -1168,4 +1215,24 @@ mod test {
Ok(SafeFilePath::Url(_))
));
}
#[test]
fn test_lines_bytes() {
let base = String::from("line 1\nline2\nline 3\nline 4");
let bytes = base.as_bytes();
let string1 = base.lines().collect::<String>();
let string2 = BufReader::new(bytes)
.lines()
.map_while(Result::ok)
.collect::<String>();
let string3 = LinesBytes(BufReader::new(bytes))
.flatten()
.flat_map(String::from_utf8)
.collect::<String>();
assert_eq!(string1, string2);
assert_eq!(string1, string3);
assert_eq!(string2, string3);
}
}

@ -15,7 +15,7 @@ use serde::Deserialize;
use tauri::{
ipc::ScopeObject,
plugin::{Builder as PluginBuilder, TauriPlugin},
utils::acl::Value,
utils::{acl::Value, config::FsScope},
AppHandle, DragDropEvent, Manager, RunEvent, Runtime, WindowEvent,
};
@ -39,7 +39,6 @@ pub use desktop::Fs;
pub use mobile::Fs;
pub use error::Error;
pub use scope::{Event as ScopeEvent, Scope};
pub use file_path::FilePath;
pub use file_path::SafeFilePath;
@ -365,21 +364,26 @@ impl ScopeObject for scope::Entry {
}
}
pub(crate) struct Scope {
pub(crate) scope: tauri::fs::Scope,
pub(crate) require_literal_leading_dot: Option<bool>,
}
pub trait FsExt<R: Runtime> {
fn fs_scope(&self) -> &Scope;
fn try_fs_scope(&self) -> Option<&Scope>;
fn fs_scope(&self) -> tauri::fs::Scope;
fn try_fs_scope(&self) -> Option<tauri::fs::Scope>;
/// Cross platform file system APIs that also support manipulating Android files.
fn fs(&self) -> &Fs<R>;
}
impl<R: Runtime, T: Manager<R>> FsExt<R> for T {
fn fs_scope(&self) -> &Scope {
self.state::<Scope>().inner()
fn fs_scope(&self) -> tauri::fs::Scope {
self.state::<Scope>().scope.clone()
}
fn try_fs_scope(&self) -> Option<&Scope> {
self.try_state::<Scope>().map(|s| s.inner())
fn try_fs_scope(&self) -> Option<tauri::fs::Scope> {
self.try_state::<Scope>().map(|s| s.scope.clone())
}
fn fs(&self) -> &Fs<R> {
@ -419,11 +423,13 @@ pub fn init<R: Runtime>() -> TauriPlugin<R, Option<config::Config>> {
watcher::unwatch
])
.setup(|app, api| {
let mut scope = Scope::default();
scope.require_literal_leading_dot = api
.config()
.as_ref()
.and_then(|c| c.require_literal_leading_dot);
let scope = Scope {
require_literal_leading_dot: api
.config()
.as_ref()
.and_then(|c| c.require_literal_leading_dot),
scope: tauri::fs::Scope::new(app, &FsScope::default())?,
};
#[cfg(target_os = "android")]
{
@ -446,9 +452,9 @@ pub fn init<R: Runtime>() -> TauriPlugin<R, Option<config::Config>> {
let scope = app.fs_scope();
for path in paths {
if path.is_file() {
scope.allow_file(path);
let _ = scope.allow_file(path);
} else {
scope.allow_directory(path, true);
let _ = scope.allow_directory(path, true);
}
}
}

@ -2,130 +2,18 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{
atomic::{AtomicU32, Ordering},
Mutex,
},
};
use std::path::PathBuf;
use serde::Deserialize;
#[derive(Deserialize)]
#[serde(untagged)]
pub(crate) enum EntryRaw {
Value(PathBuf),
Object { path: PathBuf },
}
#[derive(Debug)]
pub struct Entry {
pub path: Option<PathBuf>,
}
pub type EventId = u32;
type EventListener = Box<dyn Fn(&Event) + Send>;
/// Scope change event.
#[derive(Debug, Clone)]
pub enum Event {
/// A path has been allowed.
PathAllowed(PathBuf),
/// A path has been forbidden.
PathForbidden(PathBuf),
}
#[derive(Default)]
pub struct Scope {
pub(crate) allowed: Mutex<Vec<PathBuf>>,
pub(crate) denied: Mutex<Vec<PathBuf>>,
event_listeners: Mutex<HashMap<EventId, EventListener>>,
next_event_id: AtomicU32,
pub(crate) require_literal_leading_dot: Option<bool>,
}
impl Scope {
/// Extend the allowed patterns with the given directory.
///
/// After this function has been called, the frontend will be able to use the Tauri API to read
/// the directory and all of its files. If `recursive` is `true`, subdirectories will be accessible too.
pub fn allow_directory<P: AsRef<Path>>(&self, path: P, recursive: bool) {
let path = path.as_ref();
{
let mut allowed = self.allowed.lock().unwrap();
allowed.push(path.to_path_buf());
allowed.push(path.join(if recursive { "**" } else { "*" }));
}
self.emit(Event::PathAllowed(path.to_path_buf()));
}
/// Extend the allowed patterns with the given file path.
///
/// After this function has been called, the frontend will be able to use the Tauri API to read the contents of this file.
pub fn allow_file<P: AsRef<Path>>(&self, path: P) {
let path = path.as_ref();
self.allowed.lock().unwrap().push(path.to_path_buf());
self.emit(Event::PathAllowed(path.to_path_buf()));
}
/// Set the given directory path to be forbidden by this scope.
///
/// **Note:** this takes precedence over allowed paths, so its access gets denied **always**.
pub fn forbid_directory<P: AsRef<Path>>(&self, path: P, recursive: bool) {
let path = path.as_ref();
{
let mut denied = self.denied.lock().unwrap();
denied.push(path.to_path_buf());
denied.push(path.join(if recursive { "**" } else { "*" }));
}
self.emit(Event::PathForbidden(path.to_path_buf()));
}
/// Set the given file path to be forbidden by this scope.
///
/// **Note:** this takes precedence over allowed paths, so its access gets denied **always**.
pub fn forbid_file<P: AsRef<Path>>(&self, path: P) {
let path = path.as_ref();
self.denied.lock().unwrap().push(path.to_path_buf());
self.emit(Event::PathForbidden(path.to_path_buf()));
}
/// List of allowed paths.
pub fn allowed(&self) -> Vec<PathBuf> {
self.allowed.lock().unwrap().clone()
}
/// List of forbidden paths.
pub fn forbidden(&self) -> Vec<PathBuf> {
self.denied.lock().unwrap().clone()
}
fn next_event_id(&self) -> u32 {
self.next_event_id.fetch_add(1, Ordering::Relaxed)
}
fn emit(&self, event: Event) {
let listeners = self.event_listeners.lock().unwrap();
let handlers = listeners.values();
for listener in handlers {
listener(&event);
}
}
/// Listen to an event on this scope.
pub fn listen<F: Fn(&Event) + Send + 'static>(&self, f: F) -> EventId {
let id = self.next_event_id();
self.event_listeners.lock().unwrap().insert(id, Box::new(f));
id
}
#[derive(Deserialize)]
#[serde(untagged)]
pub(crate) enum EntryRaw {
Value(PathBuf),
Object { path: PathBuf },
}

@ -92,6 +92,20 @@ fn main() {
}
```
Then, for instance, grant the plugin the permission to check or request permissions from the user and to read the device position
`src-tauri/capabilities/default.json`
```json
"permissions": [
"core:default",
"geolocation:allow-check-permissions",
"geolocation:allow-request-permissions",
"geolocation:allow-get-current-position",
"geolocation:allow-watch-position",
]
```
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
```javascript

@ -41,6 +41,7 @@ http = "1"
reqwest = { version = "0.12", default-features = false }
url = { workspace = true }
data-url = "0.3"
tracing = { workspace = true, optional = true }
[features]
default = [
@ -71,3 +72,4 @@ http2 = ["reqwest/http2"]
charset = ["reqwest/charset"]
macos-system-configuration = ["reqwest/macos-system-configuration"]
unsafe-headers = []
tracing = ["dep:tracing"]

@ -283,6 +283,9 @@ pub async fn fetch<R: Runtime>(
request = request.headers(headers);
#[cfg(feature = "tracing")]
tracing::trace!("{:?}", request);
let fut = async move { request.send().await.map_err(Into::into) };
let mut resources_table = webview.resources_table();
let rid = resources_table.add_request(Box::pin(fut));
@ -304,6 +307,9 @@ pub async fn fetch<R: Runtime>(
.header(header::CONTENT_TYPE, data_url.mime_type().to_string())
.body(reqwest::Body::from(body))?;
#[cfg(feature = "tracing")]
tracing::trace!("{:?}", response);
let fut = async move { Ok(reqwest::Response::from(response)) };
let mut resources_table = webview.resources_table();
let rid = resources_table.add_request(Box::pin(fut));
@ -351,6 +357,9 @@ pub async fn fetch_send<R: Runtime>(
}
};
#[cfg(feature = "tracing")]
tracing::trace!("{:?}", res);
let status = res.status();
let url = res.url().to_string();
let mut headers = Vec::new();

@ -15,7 +15,7 @@ rustdoc-args = ["--cfg", "docsrs"]
targets = ["x86_64-unknown-linux-gnu", "x86_64-linux-android"]
[package.metadata.platforms.support]
windows = { level = "full", notes = "" }
windows = { level = "full", notes = "Only works for installed apps. Shows powershell name & icon in development." }
linux = { level = "full", notes = "" }
macos = { level = "full", notes = "" }
android = { level = "full", notes = "" }

@ -0,0 +1,65 @@
[package]
name = "tauri-plugin-opener"
version = "1.0.0"
description = "Open files and URLs using their default application."
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"] }
schemars = { workspace = true }
serde = { workspace = true }
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
tauri = { workspace = true }
thiserror = { workspace = true }
open = { version = "5", features = ["shellexecute-on-windows"] }
glob = { workspace = true }
[target."cfg(windows)".dependencies]
dunce = { workspace = true }
[target."cfg(windows)".dependencies.windows]
version = "0.58"
features = [
"Win32_Foundation",
"Win32_UI_Shell_Common",
"Win32_UI_WindowsAndMessaging",
"Win32_System_Com",
"Win32_System_Registry",
]
[target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"netbsd\", target_os = \"openbsd\"))".dependencies]
zbus = { workspace = true }
url = { workspace = true }
[target."cfg(target_os = \"macos\")".dependencies.objc2-app-kit]
version = "0.2"
features = ["NSWorkspace"]
[target."cfg(target_os = \"macos\")".dependencies.objc2-foundation]
version = "0.2"
features = ["NSURL", "NSArray", "NSString"]
[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,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.openPath=async function(n,_){await e("plugin:opener|open_path",{path:n,with:_})},n.openUrl=async function(n,_){await e("plugin:opener|open_url",{url:n,with:_})},n.revealItemInDir=async function(n){return e("plugin:opener|reveal_item_in_dir",{path:n})},n}({});Object.defineProperty(window.__TAURI__,"opener",{value:__TAURI_PLUGIN_OPENER__})}

@ -0,0 +1,136 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::PathBuf;
#[path = "src/scope_entry.rs"]
#[allow(dead_code)]
mod scope;
/// Opener scope application.
#[derive(schemars::JsonSchema)]
#[serde(untagged)]
#[allow(unused)]
enum Application {
/// Open in default application.
Default,
/// If true, allow open with any application.
Enable(bool),
/// Allow specific application to open with.
App(String),
}
impl Default for Application {
fn default() -> Self {
Self::Default
}
}
/// Opener scope entry.
#[derive(schemars::JsonSchema)]
#[serde(untagged)]
#[allow(unused)]
enum OpenerScopeEntry {
Url {
/// A URL that can be opened by the webview when using the Opener APIs.
///
/// Wildcards can be used following the UNIX glob pattern.
///
/// Examples:
///
/// - "https://*" : allows all HTTPS origin
///
/// - "https://*.github.com/tauri-apps/tauri": allows any subdomain of "github.com" with the "tauri-apps/api" path
///
/// - "https://myapi.service.com/users/*": allows access to any URLs that begins with "https://myapi.service.com/users/"
url: String,
/// An application to open this url with, for example: firefox.
#[serde(default)]
app: Application,
},
Path {
/// A path that can be opened by the webview when using the Opener APIs.
///
/// The pattern can start with a variable that resolves to a system base directory.
/// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
/// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
/// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`,
/// `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.
path: PathBuf,
/// An application to open this path with, for example: xdg-open.
#[serde(default)]
app: Application,
},
}
// Ensure `OpenerScopeEntry` and `scope::EntryRaw` is kept in sync
fn _f() {
match (scope::EntryRaw::Url {
url: String::new(),
app: scope::Application::Enable(true),
}) {
scope::EntryRaw::Url { url, app } => OpenerScopeEntry::Url {
url,
app: match app {
scope::Application::Enable(p) => Application::Enable(p),
scope::Application::App(p) => Application::App(p),
scope::Application::Default => Application::Default,
},
},
scope::EntryRaw::Path { path, app } => OpenerScopeEntry::Path {
path,
app: match app {
scope::Application::Enable(p) => Application::Enable(p),
scope::Application::App(p) => Application::App(p),
scope::Application::Default => Application::Default,
},
},
};
match (OpenerScopeEntry::Url {
url: String::new(),
app: Application::Enable(true),
}) {
OpenerScopeEntry::Url { url, app } => scope::EntryRaw::Url {
url,
app: match app {
Application::Enable(p) => scope::Application::Enable(p),
Application::App(p) => scope::Application::App(p),
Application::Default => scope::Application::Default,
},
},
OpenerScopeEntry::Path { path, app } => scope::EntryRaw::Path {
path,
app: match app {
Application::Enable(p) => scope::Application::Enable(p),
Application::App(p) => scope::Application::App(p),
Application::Default => scope::Application::Default,
},
},
};
}
const COMMANDS: &[&str] = &["open_url", "open_path", "reveal_item_in_dir"];
fn main() {
tauri_plugin::Builder::new(COMMANDS)
.global_api_script_path("./api-iife.js")
.android_path("android")
.ios_path("ios")
.global_scope_schema(schemars::schema_for!(OpenerScopeEntry))
.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,92 @@
// 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 url with the system's default app, or the one specified with {@linkcode openWith}.
*
* @example
* ```typescript
* import { openUrl } from '@tauri-apps/plugin-opener';
*
* // opens the given URL on the default browser:
* await openUrl('https://github.com/tauri-apps/tauri');
* // opens the given URL using `firefox`:
* await openUrl('https://github.com/tauri-apps/tauri', 'firefox');
* ```
*
* @param url The URL to open.
* @param openWith The app to open the URL with. If not specified, defaults to the system default application for the specified url type.
*
* @since 2.0.0
*/
export async function openUrl(url: string, openWith?: string): Promise<void> {
await invoke('plugin:opener|open_url', {
url,
with: openWith
})
}
/**
* Opens a path with the system's default app, or the one specified with {@linkcode openWith}.
*
* @example
* ```typescript
* import { openPath } from '@tauri-apps/plugin-opener';
*
* // opens a file using the default program:
* await openPath('/path/to/file');
* // opens a file using `vlc` command on Windows.
* await openPath('C:/path/to/file', 'vlc');
* ```
*
* @param path The path to open.
* @param openWith The app to open the path with. If not specified, defaults to the system default application for the specified path type.
*
* @since 2.0.0
*/
export async function openPath(path: string, openWith?: string): Promise<void> {
await invoke('plugin:opener|open_path', {
path,
with: openWith
})
}
/**
* Reveal a path the system's default explorer.
*
* #### Platform-specific:
*
* - **Android / iOS:** Unsupported.
*
* @example
* ```typescript
* import { revealItemInDir } from '@tauri-apps/plugin-opener';
* await revealItemInDir('/path/to/file');
* ```
*
* @param path The path to reveal.
*
* @since 2.0.0
*/
export async function revealItemInDir(path: string) {
return invoke('plugin:opener|reveal_item_in_dir', { path })
}

@ -0,0 +1,61 @@
// 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
window.addEventListener('click', function (evt) {
// return early if
if (
// event was prevented
evt.defaultPrevented ||
// or not a left click
evt.button !== 0 ||
// or meta key pressed
evt.metaKey ||
// or al key pressed
evt.altKey
)
return
const a = evt
.composedPath()
.find((el) => el instanceof Node && el.nodeName.toUpperCase() === 'A') as
| HTMLAnchorElement
| undefined
// return early if
if (
// not tirggered from <a> element
!a ||
// or doesn't have a href
!a.href ||
// or not supposed to be open in a new tab
!(
a.target === '_blank' ||
// or ctrl key pressed
evt.ctrlKey ||
// or shift key pressed
evt.shiftKey
)
)
return
const url = new URL(a.href)
// return early if
if (
// same origin (internal navigation)
url.origin === window.location.origin ||
// not default protocols
['http:', 'https:', 'mailto:', 'tel:'].every((p) => url.protocol !== p)
)
return
evt.preventDefault()
void invoke('plugin:opener|open_url', {
url
})
})

@ -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,30 @@
{
"name": "@tauri-apps/plugin-opener",
"version": "1.0.0",
"description": "Open files and URLs using their default application.",
"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,17 @@
"$schema" = "schemas/schema.json"
[[permission]]
identifier = "allow-default-urls"
description = "This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application."
[[permission.scope.allow]]
url = "mailto:*"
[[permission.scope.allow]]
url = "tel:*"
[[permission.scope.allow]]
url = "http://*"
[[permission.scope.allow]]
url = "https://*"

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

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

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

@ -0,0 +1,109 @@
## Default Permission
This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application
as well as reveal file in directories using default file explorer
- `allow-open-url`
- `allow-reveal-item-in-dir`
- `allow-default-urls`
## Permission Table
<table>
<tr>
<th>Identifier</th>
<th>Description</th>
</tr>
<tr>
<td>
`opener:allow-default-urls`
</td>
<td>
This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application.
</td>
</tr>
<tr>
<td>
`opener:allow-open-path`
</td>
<td>
Enables the open_path command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`opener:deny-open-path`
</td>
<td>
Denies the open_path command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`opener:allow-open-url`
</td>
<td>
Enables the open_url command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`opener:deny-open-url`
</td>
<td>
Denies the open_url command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`opener:allow-reveal-item-in-dir`
</td>
<td>
Enables the reveal_item_in_dir command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`opener:deny-reveal-item-in-dir`
</td>
<td>
Denies the reveal_item_in_dir command without any pre-configured scope.
</td>
</tr>
</table>

@ -0,0 +1,10 @@
"$schema" = "schemas/schema.json"
[default]
description = """This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application
as well as reveal file in directories using default file explorer"""
permissions = [
"allow-open-url",
"allow-reveal-item-in-dir",
"allow-default-urls",
]

@ -0,0 +1,340 @@
{
"$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": "This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application.",
"type": "string",
"const": "allow-default-urls"
},
{
"description": "Enables the open_path command without any pre-configured scope.",
"type": "string",
"const": "allow-open-path"
},
{
"description": "Denies the open_path command without any pre-configured scope.",
"type": "string",
"const": "deny-open-path"
},
{
"description": "Enables the open_url command without any pre-configured scope.",
"type": "string",
"const": "allow-open-url"
},
{
"description": "Denies the open_url command without any pre-configured scope.",
"type": "string",
"const": "deny-open-url"
},
{
"description": "Enables the reveal_item_in_dir command without any pre-configured scope.",
"type": "string",
"const": "allow-reveal-item-in-dir"
},
{
"description": "Denies the reveal_item_in_dir command without any pre-configured scope.",
"type": "string",
"const": "deny-reveal-item-in-dir"
},
{
"description": "This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application\nas well as reveal file in directories using default file explorer",
"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,75 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::{Path, PathBuf};
use tauri::{
ipc::{CommandScope, GlobalScope},
AppHandle, Runtime,
};
use crate::{scope::Scope, Error};
#[tauri::command]
pub async fn open_url<R: Runtime>(
app: AppHandle<R>,
command_scope: CommandScope<crate::scope::Entry>,
global_scope: GlobalScope<crate::scope::Entry>,
url: String,
with: Option<String>,
) -> crate::Result<()> {
let scope = Scope::new(
&app,
command_scope
.allows()
.iter()
.chain(global_scope.allows())
.collect(),
command_scope
.denies()
.iter()
.chain(global_scope.denies())
.collect(),
);
if scope.is_url_allowed(&url, with.as_deref()) {
crate::open_url(url, with)
} else {
Err(Error::ForbiddenUrl { url, with })
}
}
#[tauri::command]
pub async fn open_path<R: Runtime>(
app: AppHandle<R>,
command_scope: CommandScope<crate::scope::Entry>,
global_scope: GlobalScope<crate::scope::Entry>,
path: String,
with: Option<String>,
) -> crate::Result<()> {
let scope = Scope::new(
&app,
command_scope
.allows()
.iter()
.chain(global_scope.allows())
.collect(),
command_scope
.denies()
.iter()
.chain(global_scope.denies())
.collect(),
);
if scope.is_path_allowed(Path::new(&path), with.as_deref())? {
crate::open_path(path, with)
} else {
Err(Error::ForbiddenPath { path, with })
}
}
#[tauri::command]
pub async fn reveal_item_in_dir(path: PathBuf) -> crate::Result<()> {
crate::reveal_item_in_dir(path)
}

@ -0,0 +1,54 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::PathBuf;
use serde::{Serialize, Serializer};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[cfg(mobile)]
#[error(transparent)]
PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError),
#[error(transparent)]
Tauri(#[from] tauri::Error),
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
Json(#[from] serde_json::Error),
#[error("unknown program {0}")]
UnknownProgramName(String),
#[error("Not allowed to open path {}{}", .path, .with.as_ref().map(|w| format!(" with {w}")).unwrap_or_default())]
ForbiddenPath { path: String, with: Option<String> },
#[error("Not allowed to open url {}{}", .url, .with.as_ref().map(|w| format!(" with {w}")).unwrap_or_default())]
ForbiddenUrl { url: String, with: Option<String> },
#[error("API not supported on the current platform")]
UnsupportedPlatform,
#[error(transparent)]
#[cfg(windows)]
Win32Error(#[from] windows::core::Error),
#[error("Path doesn't have a parent: {0}")]
NoParent(PathBuf),
#[error("Failed to convert path to file:// url")]
FailedToConvertPathToFileUrl,
#[error(transparent)]
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
Zbus(#[from] zbus::Error),
}
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";"function"==typeof SuppressedError&&SuppressedError,window.addEventListener("click",(function(e){if(e.defaultPrevented||0!==e.button||e.metaKey||e.altKey)return;const t=e.composedPath().find((e=>e instanceof Node&&"A"===e.nodeName.toUpperCase()));if(!t||!t.href||"_blank"!==t.target&&!e.ctrlKey&&!e.shiftKey)return;const n=new URL(t.href);n.origin===window.location.origin||["http:","https:","mailto:","tel:"].every((e=>n.protocol!==e))||(e.preventDefault(),async function(e,t={},n){window.__TAURI_INTERNALS__.invoke(e,t,n)}("plugin:opener|open_url",{url:n}))}))}();

@ -0,0 +1,169 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::Path;
use tauri::{plugin::TauriPlugin, 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 error;
mod open;
mod reveal_item_in_dir;
mod scope;
mod scope_entry;
pub use error::Error;
type Result<T> = std::result::Result<T, Error>;
pub use open::{open_path, open_url};
pub use reveal_item_in_dir::reveal_item_in_dir;
pub struct Opener<R: Runtime> {
// we use `fn() -> R` to slicence the unused generic error
// while keeping this struct `Send + Sync` without requiring `R` to be
#[cfg(not(mobile))]
_marker: std::marker::PhantomData<fn() -> R>,
#[cfg(mobile)]
mobile_plugin_handle: PluginHandle<R>,
}
impl<R: Runtime> Opener<R> {
/// Open a url with a default or specific program.
///
/// ## Platform-specific:
///
/// - **Android / iOS**: Always opens using default program.
#[cfg(desktop)]
pub fn open_url(&self, url: impl Into<String>, with: Option<impl Into<String>>) -> Result<()> {
crate::open::open(url.into(), with.map(Into::into)).map_err(Into::into)
}
/// Open a url with a default or specific program.
///
/// ## Platform-specific:
///
/// - **Android / iOS**: Always opens using default program.
#[cfg(mobile)]
pub fn open_url(&self, url: impl Into<String>, _with: Option<impl Into<String>>) -> Result<()> {
self.mobile_plugin_handle
.run_mobile_plugin("open", url.into())
.map_err(Into::into)
}
/// Open a path with a default or specific program.
///
/// ## Platform-specific:
///
/// - **Android / iOS**: Always opens using default program.
#[cfg(desktop)]
pub fn open_path(
&self,
path: impl Into<String>,
with: Option<impl Into<String>>,
) -> Result<()> {
crate::open::open(path.into(), with.map(Into::into)).map_err(Into::into)
}
/// Open a path with a default or specific program.
///
/// ## Platform-specific:
///
/// - **Android / iOS**: Always opens using default program.
#[cfg(mobile)]
pub fn open_path(
&self,
path: impl Into<String>,
_with: Option<impl Into<String>>,
) -> Result<()> {
self.mobile_plugin_handle
.run_mobile_plugin("open", path.into())
.map_err(Into::into)
}
pub fn reveal_item_in_dir<P: AsRef<Path>>(&self, p: P) -> Result<()> {
crate::reveal_item_in_dir::reveal_item_in_dir(p)
}
}
/// 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()
}
}
/// The opener plugin Builder.
pub struct Builder {
open_js_links_on_click: bool,
}
impl Default for Builder {
fn default() -> Self {
Self {
open_js_links_on_click: true,
}
}
}
impl Builder {
/// Create a new opener plugin Builder.
pub fn new() -> Self {
Self::default()
}
/// Whether the plugin should inject a JS script to open URLs in default browser
/// when clicking on `<a>` elements that has `_blank` target, or when pressing `Ctrl` or `Shift` while clicking it.
///
/// Enabled by default for `http:`, `https:`, `mailto:`, `tel:` links.
pub fn open_js_links_on_click(mut self, open: bool) -> Self {
self.open_js_links_on_click = open;
self
}
/// Build and Initializes the plugin.
pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
let mut builder = tauri::plugin::Builder::new("opener")
.setup(|app, _api| {
#[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 {
#[cfg(not(mobile))]
_marker: std::marker::PhantomData::<fn() -> R>,
#[cfg(mobile)]
mobile_plugin_handle: handle,
});
Ok(())
})
.invoke_handler(tauri::generate_handler![
commands::open_url,
commands::open_path,
commands::reveal_item_in_dir
]);
if self.open_js_links_on_click {
builder = builder.js_init_script(include_str!("init-iife.js").to_string());
}
builder.build()
}
}
/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::default().build()
}

@ -0,0 +1,57 @@
// 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 std::{ffi::OsStr, path::Path};
pub(crate) fn open<P: AsRef<OsStr>, S: AsRef<str>>(path: P, with: Option<S>) -> crate::Result<()> {
match with {
Some(program) => ::open::with_detached(path, program.as_ref()),
None => ::open::that_detached(path),
}
.map_err(Into::into)
}
/// Opens URL with the program specified in `with`, or system default if `None`.
///
/// ## Platform-specific:
///
/// - **Android / iOS**: Always opens using default program.
///
/// # Examples
///
/// ```rust,no_run
/// tauri::Builder::default()
/// .setup(|app| {
/// // open the given URL on the system default browser
/// tauri_plugin_opener::open_url("https://github.com/tauri-apps/tauri", None)?;
/// Ok(())
/// });
/// ```
pub fn open_url<P: AsRef<str>, S: AsRef<str>>(url: P, with: Option<S>) -> crate::Result<()> {
let url = url.as_ref();
open(url, with)
}
/// Opens path with the program specified in `with`, or system default if `None`.
///
/// ## Platform-specific:
///
/// - **Android / iOS**: Always opens using default program.
///
/// # Examples
///
/// ```rust,no_run
/// tauri::Builder::default()
/// .setup(|app| {
/// // open the given URL on the system default browser
/// tauri_plugin_opener::open_path("/path/to/file", None)?;
/// Ok(())
/// });
/// ```
pub fn open_path<P: AsRef<Path>, S: AsRef<str>>(path: P, with: Option<S>) -> crate::Result<()> {
let path = path.as_ref();
open(path, with)
}

@ -0,0 +1,196 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::Path;
/// Reveal a path the system's default explorer.
///
/// ## Platform-specific:
///
/// - **Android / iOS:** Unsupported.
pub fn reveal_item_in_dir<P: AsRef<Path>>(path: P) -> crate::Result<()> {
let path = path.as_ref().canonicalize()?;
#[cfg(any(
windows,
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
return imp::reveal_item_in_dir(&path);
#[cfg(not(any(
windows,
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)))]
Err(crate::Error::UnsupportedPlatform)
}
#[cfg(windows)]
mod imp {
use super::*;
use windows::{
core::{w, HSTRING, PCWSTR},
Win32::{
Foundation::ERROR_FILE_NOT_FOUND,
System::Com::CoInitialize,
UI::{
Shell::{
ILCreateFromPathW, ILFree, SHOpenFolderAndSelectItems, ShellExecuteExW,
SHELLEXECUTEINFOW,
},
WindowsAndMessaging::SW_SHOWNORMAL,
},
},
};
pub fn reveal_item_in_dir(path: &Path) -> crate::Result<()> {
let file = dunce::simplified(path);
let _ = unsafe { CoInitialize(None) };
let dir = file
.parent()
.ok_or_else(|| crate::Error::NoParent(file.to_path_buf()))?;
let dir = HSTRING::from(dir);
let dir_item = unsafe { ILCreateFromPathW(&dir) };
let file_h = HSTRING::from(file);
let file_item = unsafe { ILCreateFromPathW(&file_h) };
unsafe {
if let Err(e) = SHOpenFolderAndSelectItems(dir_item, Some(&[file_item]), 0) {
// from https://github.com/electron/electron/blob/10d967028af2e72382d16b7e2025d243b9e204ae/shell/common/platform_util_win.cc#L302
// On some systems, the above call mysteriously fails with "file not
// found" even though the file is there. In these cases, ShellExecute()
// seems to work as a fallback (although it won't select the file).
if e.code().0 == ERROR_FILE_NOT_FOUND.0 as i32 {
let is_dir = file.is_dir();
let mut info = SHELLEXECUTEINFOW {
cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as _,
nShow: SW_SHOWNORMAL.0,
lpFile: PCWSTR(dir.as_ptr()),
lpClass: if is_dir { w!("folder") } else { PCWSTR::null() },
lpVerb: if is_dir {
w!("explore")
} else {
PCWSTR::null()
},
..std::mem::zeroed()
};
ShellExecuteExW(&mut info).inspect_err(|_| {
ILFree(Some(dir_item));
ILFree(Some(file_item));
})?;
}
}
}
unsafe {
ILFree(Some(dir_item));
ILFree(Some(file_item));
}
Ok(())
}
}
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
mod imp {
use std::collections::HashMap;
use super::*;
pub fn reveal_item_in_dir(path: &Path) -> crate::Result<()> {
let connection = zbus::blocking::Connection::session()?;
reveal_with_filemanager1(path, &connection)
.or_else(|_| reveal_with_open_uri_portal(path, &connection))
}
fn reveal_with_filemanager1(
path: &Path,
connection: &zbus::blocking::Connection,
) -> crate::Result<()> {
let uri = url::Url::from_file_path(path)
.map_err(|_| crate::Error::FailedToConvertPathToFileUrl)?;
#[zbus::proxy(
interface = "org.freedesktop.FileManager1",
default_service = "org.freedesktop.FileManager1",
default_path = "/org/freedesktop/FileManager1"
)]
trait FileManager1 {
async fn ShowItems(&self, name: Vec<&str>, arg2: &str) -> crate::Result<()>;
}
let proxy = FileManager1ProxyBlocking::new(connection)?;
proxy.ShowItems(vec![uri.as_str()], "")
}
fn reveal_with_open_uri_portal(
path: &Path,
connection: &zbus::blocking::Connection,
) -> crate::Result<()> {
let uri = url::Url::from_file_path(path)
.map_err(|_| crate::Error::FailedToConvertPathToFileUrl)?;
#[zbus::proxy(
interface = "org.freedesktop.portal.Desktop",
default_service = "org.freedesktop.portal.OpenURI",
default_path = "/org/freedesktop/portal/desktop"
)]
trait PortalDesktop {
async fn OpenDirectory(
&self,
arg1: &str,
name: &str,
arg3: HashMap<&str, &str>,
) -> crate::Result<()>;
}
let proxy = PortalDesktopProxyBlocking::new(connection)?;
proxy.OpenDirectory("", uri.as_str(), HashMap::new())
}
}
#[cfg(target_os = "macos")]
mod imp {
use super::*;
use objc2_app_kit::NSWorkspace;
use objc2_foundation::{NSArray, NSString, NSURL};
pub fn reveal_item_in_dir(path: &Path) -> crate::Result<()> {
unsafe {
let path = path.to_string_lossy();
let path = NSString::from_str(&path);
let urls = vec![NSURL::fileURLWithPath(&path)];
let urls = NSArray::from_vec(urls);
let workspace = NSWorkspace::new();
workspace.activateFileViewerSelectingURLs(&urls);
}
Ok(())
}
}

@ -0,0 +1,138 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
marker::PhantomData,
path::{Path, PathBuf},
sync::Arc,
};
use tauri::{ipc::ScopeObject, utils::acl::Value, AppHandle, Manager, Runtime};
use crate::{scope_entry::EntryRaw, Error};
pub use crate::scope_entry::Application;
#[derive(Debug)]
pub enum Entry {
Url {
url: glob::Pattern,
app: Application,
},
Path {
path: Option<PathBuf>,
app: Application,
},
}
impl ScopeObject for Entry {
type Error = Error;
fn deserialize<R: Runtime>(
app_handle: &AppHandle<R>,
raw: Value,
) -> std::result::Result<Self, Self::Error> {
serde_json::from_value(raw.into())
.and_then(|raw| {
let entry = match raw {
EntryRaw::Url { url, app } => Entry::Url {
url: glob::Pattern::new(&url)
.map_err(|e| serde::de::Error::custom(e.to_string()))?,
app,
},
EntryRaw::Path { path, app } => {
let path = match app_handle.path().parse(path) {
Ok(path) => Some(path),
#[cfg(not(target_os = "android"))]
Err(tauri::Error::UnknownPath) => None,
Err(err) => return Err(serde::de::Error::custom(err.to_string())),
};
Entry::Path { path, app }
}
};
Ok(entry)
})
.map_err(Into::into)
}
}
impl Application {
fn matches(&self, a: Option<&str>) -> bool {
match self {
Self::Default => a.is_none(),
Self::Enable(enable) => *enable,
Self::App(program) => Some(program.as_str()) == a,
}
}
}
impl Entry {
fn path(&self) -> Option<PathBuf> {
match self {
Self::Url { .. } => None,
Self::Path { path, .. } => path.clone(),
}
}
fn matches_url(&self, u: &str, a: Option<&str>) -> bool {
match self {
Self::Url { url, app } => url.matches(u) && app.matches(a),
Self::Path { .. } => false,
}
}
fn matches_path_program(&self, a: Option<&str>) -> bool {
match self {
Self::Url { .. } => false,
Self::Path { app, .. } => app.matches(a),
}
}
}
#[derive(Debug)]
pub struct Scope<'a, R: Runtime, M: Manager<R>> {
allowed: Vec<&'a Arc<Entry>>,
denied: Vec<&'a Arc<Entry>>,
manager: &'a M,
_marker: PhantomData<R>,
}
impl<'a, R: Runtime, M: Manager<R>> Scope<'a, R, M> {
pub(crate) fn new(
manager: &'a M,
allowed: Vec<&'a Arc<Entry>>,
denied: Vec<&'a Arc<Entry>>,
) -> Self {
Self {
manager,
allowed,
denied,
_marker: PhantomData,
}
}
pub fn is_url_allowed(&self, url: &str, with: Option<&str>) -> bool {
let denied = self.denied.iter().any(|e| e.matches_url(url, with));
if denied {
false
} else {
self.allowed.iter().any(|e| e.matches_url(url, with))
}
}
pub fn is_path_allowed(&self, path: &Path, with: Option<&str>) -> crate::Result<bool> {
let fs_scope = tauri::fs::Scope::new(
self.manager,
&tauri::utils::config::FsScope::Scope {
allow: self.allowed.iter().filter_map(|e| e.path()).collect(),
deny: self.denied.iter().filter_map(|e| e.path()).collect(),
require_literal_leading_dot: None,
},
)?;
Ok(fs_scope.is_allowed(path) && self.allowed.iter().any(|e| e.matches_path_program(with)))
}
}

@ -0,0 +1,36 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::PathBuf;
use serde::Deserialize;
#[derive(Deserialize, Debug)]
#[serde(untagged)]
pub enum Application {
Default,
Enable(bool),
App(String),
}
impl Default for Application {
fn default() -> Self {
Self::Default
}
}
#[derive(Deserialize)]
#[serde(untagged, rename_all = "camelCase")]
pub(crate) enum EntryRaw {
Url {
url: String,
#[serde(default)]
app: Application,
},
Path {
path: PathBuf,
#[serde(default)]
app: Application,
},
}

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

@ -14,13 +14,11 @@ use serde::{Deserialize, Serialize};
use tauri::{
plugin::{Builder, TauriPlugin},
scope::fs::Pattern as GlobPattern,
Manager, Runtime,
};
use tauri_plugin_fs::FsExt;
use std::{
collections::HashSet,
fs::{create_dir_all, File},
io::Write,
path::Path,
@ -44,81 +42,6 @@ const PATTERNS: &[&str] = &[
];
const REPLACE_WITH: &[&str] = &[r"[", r"]", r"?", r"*", r"\?", r"\\?\", r"\\?\"];
trait ScopeExt {
type Pattern: ToString;
fn allow_file(&self, path: &Path);
fn allow_directory(&self, path: &Path, recursive: bool);
fn forbid_file(&self, path: &Path);
fn forbid_directory(&self, path: &Path, recursive: bool);
fn allowed_patterns(&self) -> HashSet<Self::Pattern>;
fn forbidden_patterns(&self) -> HashSet<Self::Pattern>;
}
impl ScopeExt for tauri::scope::fs::Scope {
type Pattern = GlobPattern;
fn allow_file(&self, path: &Path) {
let _ = tauri::scope::fs::Scope::allow_file(self, path);
}
fn allow_directory(&self, path: &Path, recursive: bool) {
let _ = tauri::scope::fs::Scope::allow_directory(self, path, recursive);
}
fn forbid_file(&self, path: &Path) {
let _ = tauri::scope::fs::Scope::forbid_file(self, path);
}
fn forbid_directory(&self, path: &Path, recursive: bool) {
let _ = tauri::scope::fs::Scope::forbid_directory(self, path, recursive);
}
fn allowed_patterns(&self) -> HashSet<Self::Pattern> {
tauri::scope::fs::Scope::allowed_patterns(self)
}
fn forbidden_patterns(&self) -> HashSet<Self::Pattern> {
tauri::scope::fs::Scope::forbidden_patterns(self)
}
}
impl ScopeExt for tauri_plugin_fs::Scope {
type Pattern = String;
fn allow_file(&self, path: &Path) {
tauri_plugin_fs::Scope::allow_file(self, path);
}
fn allow_directory(&self, path: &Path, recursive: bool) {
tauri_plugin_fs::Scope::allow_directory(self, path, recursive);
}
fn forbid_file(&self, path: &Path) {
tauri_plugin_fs::Scope::forbid_file(self, path);
}
fn forbid_directory(&self, path: &Path, recursive: bool) {
tauri_plugin_fs::Scope::forbid_directory(self, path, recursive);
}
fn allowed_patterns(&self) -> HashSet<Self::Pattern> {
self.allowed()
.into_iter()
.map(|p| p.to_string_lossy().to_string())
.collect()
}
fn forbidden_patterns(&self) -> HashSet<Self::Pattern> {
self.forbidden()
.into_iter()
.map(|p| p.to_string_lossy().to_string())
.collect()
}
}
#[derive(Debug, thiserror::Error)]
enum Error {
#[error(transparent)]
@ -179,41 +102,41 @@ fn fix_directory(path_str: &str) -> &Path {
path
}
fn allow_path(scope: &impl ScopeExt, path: &str) {
fn allow_path(scope: &tauri::fs::Scope, path: &str) {
let target_type = detect_scope_type(path);
match target_type {
TargetType::File => {
scope.allow_file(Path::new(path));
let _ = scope.allow_file(Path::new(path));
}
TargetType::Directory => {
// We remove the '*' at the end of it, else it will be escaped by the pattern.
scope.allow_directory(fix_directory(path), false);
let _ = scope.allow_directory(fix_directory(path), false);
}
TargetType::RecursiveDirectory => {
// We remove the '**' at the end of it, else it will be escaped by the pattern.
scope.allow_directory(fix_directory(path), true);
let _ = scope.allow_directory(fix_directory(path), true);
}
}
}
fn forbid_path(scope: &impl ScopeExt, path: &str) {
fn forbid_path(scope: &tauri::fs::Scope, path: &str) {
let target_type = detect_scope_type(path);
match target_type {
TargetType::File => {
scope.forbid_file(Path::new(path));
let _ = scope.forbid_file(Path::new(path));
}
TargetType::Directory => {
scope.forbid_directory(fix_directory(path), false);
let _ = scope.forbid_directory(fix_directory(path), false);
}
TargetType::RecursiveDirectory => {
scope.forbid_directory(fix_directory(path), true);
let _ = scope.forbid_directory(fix_directory(path), true);
}
}
}
fn save_scopes(scope: &impl ScopeExt, app_dir: &Path, scope_state_path: &Path) {
fn save_scopes(scope: &tauri::fs::Scope, app_dir: &Path, scope_state_path: &Path) {
let scope = Scope {
allowed_paths: scope
.allowed_patterns()
@ -250,8 +173,11 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
#[cfg(feature = "protocol-asset")]
let asset_scope_state_path = app_dir.join(ASSET_SCOPE_STATE_FILENAME);
if let Some(fs_scope) = fs_scope {
fs_scope.forbid_file(&fs_scope_state_path);
if let Some(fs_scope) = &fs_scope {
let _ = fs_scope.forbid_file(&fs_scope_state_path);
} else {
#[cfg(debug_assertions)]
eprintln!("Please make sure to register the `fs` plugin before the `persisted-scope` plugin!");
}
#[cfg(feature = "protocol-asset")]
let _ = asset_protocol_scope.forbid_file(&asset_scope_state_path);
@ -260,7 +186,7 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
// We will still save some semi-broken values because the scope events are quite spammy and we don't want to reduce runtime performance any further.
let ac = AhoCorasick::new(PATTERNS).unwrap(/* This should be impossible to fail since we're using a small static input */);
if let Some(fs_scope) = fs_scope {
if let Some(fs_scope) = &fs_scope {
if fs_scope_state_path.exists() {
let scope: Scope = std::fs::read(&fs_scope_state_path)
.map_err(Error::from)
@ -305,11 +231,11 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
#[cfg(feature = "protocol-asset")]
let app_dir_ = app_dir.clone();
if let Some(fs_scope) = fs_scope {
if let Some(fs_scope) = &fs_scope {
let app_ = app.clone();
fs_scope.listen(move |event| {
if let tauri_plugin_fs::ScopeEvent::PathAllowed(_) = event {
save_scopes(app_.fs_scope(), &app_dir, &fs_scope_state_path);
if let tauri::fs::Event::PathAllowed(_) = event {
save_scopes(&app_.fs_scope(), &app_dir, &fs_scope_state_path);
}
});
}

@ -1 +1 @@
if("__TAURI__"in window){var __TAURI_PLUGIN_POSITIONER__=function(t){"use strict";async function o(t,o={},e){return window.__TAURI_INTERNALS__.invoke(t,o,e)}var e;return"function"==typeof SuppressedError&&SuppressedError,t.Position=void 0,(e=t.Position||(t.Position={}))[e.TopLeft=0]="TopLeft",e[e.TopRight=1]="TopRight",e[e.BottomLeft=2]="BottomLeft",e[e.BottomRight=3]="BottomRight",e[e.TopCenter=4]="TopCenter",e[e.BottomCenter=5]="BottomCenter",e[e.LeftCenter=6]="LeftCenter",e[e.RightCenter=7]="RightCenter",e[e.Center=8]="Center",e[e.TrayLeft=9]="TrayLeft",e[e.TrayBottomLeft=10]="TrayBottomLeft",e[e.TrayRight=11]="TrayRight",e[e.TrayBottomRight=12]="TrayBottomRight",e[e.TrayCenter=13]="TrayCenter",e[e.TrayBottomCenter=14]="TrayBottomCenter",t.handleIconState=async function(t){await o("plugin:positioner|set_tray_icon_state",{position:t.rect.position,size:t.rect.size})},t.moveWindow=async function(t){await o("plugin:positioner|move_window",{position:t})},t}({});Object.defineProperty(window.__TAURI__,"positioner",{value:__TAURI_PLUGIN_POSITIONER__})}
if("__TAURI__"in window){var __TAURI_PLUGIN_POSITIONER__=function(t){"use strict";async function o(t,o={},e){return window.__TAURI_INTERNALS__.invoke(t,o,e)}var e;return"function"==typeof SuppressedError&&SuppressedError,t.Position=void 0,(e=t.Position||(t.Position={}))[e.TopLeft=0]="TopLeft",e[e.TopRight=1]="TopRight",e[e.BottomLeft=2]="BottomLeft",e[e.BottomRight=3]="BottomRight",e[e.TopCenter=4]="TopCenter",e[e.BottomCenter=5]="BottomCenter",e[e.LeftCenter=6]="LeftCenter",e[e.RightCenter=7]="RightCenter",e[e.Center=8]="Center",e[e.TrayLeft=9]="TrayLeft",e[e.TrayBottomLeft=10]="TrayBottomLeft",e[e.TrayRight=11]="TrayRight",e[e.TrayBottomRight=12]="TrayBottomRight",e[e.TrayCenter=13]="TrayCenter",e[e.TrayBottomCenter=14]="TrayBottomCenter",t.handleIconState=async function(t){await o("plugin:positioner|set_tray_icon_state",{position:t.rect.position,size:t.rect.size})},t.moveWindow=async function(t){await o("plugin:positioner|move_window",{position:t})},t.moveWindowConstrained=async function(t){await o("plugin:positioner|move_window_constrained",{position:t})},t}({});Object.defineProperty(window.__TAURI__,"positioner",{value:__TAURI_PLUGIN_POSITIONER__})}

@ -2,7 +2,11 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
const COMMANDS: &[&str] = &["move_window", "set_tray_icon_state"];
const COMMANDS: &[&str] = &[
"move_window",
"move_window_constrained",
"set_tray_icon_state",
];
fn main() {
tauri_plugin::Builder::new(COMMANDS)

@ -39,6 +39,19 @@ export async function moveWindow(to: Position): Promise<void> {
})
}
/**
* Moves the `Window` to the given {@link Position} using `WindowExt.move_window_constrained()`
*
* This move operation constrains the window to the screen dimensions in case of
* tray-icon positions.
* @param to The (tray) {@link Position} to move to.
*/
export async function moveWindowConstrained(to: Position): Promise<void> {
await invoke('plugin:positioner|move_window_constrained', {
position: to
})
}
export async function handleIconState(event: TrayIconEvent): Promise<void> {
await invoke('plugin:positioner|set_tray_icon_state', {
position: event.rect.position,

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

@ -3,7 +3,8 @@
Allows the moveWindow and handleIconState APIs
- `allow-move-window`
- `set-tray-icon-state`
- `allow-move-window-constrained`
- `allow-set-tray-icon-state`
## Permission Table
@ -43,6 +44,32 @@ Denies the move_window command without any pre-configured scope.
<tr>
<td>
`positioner:allow-move-window-constrained`
</td>
<td>
Enables the move_window_constrained command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`positioner:deny-move-window-constrained`
</td>
<td>
Denies the move_window_constrained command without any pre-configured scope.
</td>
</tr>
<tr>
<td>
`positioner:allow-set-tray-icon-state`
</td>

@ -1,4 +1,8 @@
"$schema" = "schemas/schema.json"
[default]
description = "Allows the moveWindow and handleIconState APIs"
permissions = ["allow-move-window", "set-tray-icon-state"]
permissions = [
"allow-move-window",
"allow-move-window-constrained",
"allow-set-tray-icon-state",
]

@ -304,6 +304,16 @@
"type": "string",
"const": "deny-move-window"
},
{
"description": "Enables the move_window_constrained command without any pre-configured scope.",
"type": "string",
"const": "allow-move-window-constrained"
},
{
"description": "Denies the move_window_constrained command without any pre-configured scope.",
"type": "string",
"const": "deny-move-window-constrained"
},
{
"description": "Enables the set_tray_icon_state command without any pre-configured scope.",
"type": "string",

@ -8,6 +8,8 @@ use crate::Tray;
use serde_repr::Deserialize_repr;
#[cfg(feature = "tray-icon")]
use tauri::Manager;
#[cfg(feature = "tray-icon")]
use tauri::Monitor;
use tauri::{PhysicalPosition, PhysicalSize, Result, Runtime, WebviewWindow, Window};
/// Well known window positions.
@ -41,172 +43,265 @@ pub enum Position {
pub trait WindowExt {
/// Moves the [`Window`] to the given [`Position`]
///
/// All positions are relative to the **current** screen.
/// All (non-tray) positions are relative to the **current** screen.
fn move_window(&self, position: Position) -> Result<()>;
#[cfg(feature = "tray-icon")]
/// Moves the [`Window`] to the given [`Position`] while constraining Tray Positions to the dimensions of the screen.
///
/// All non-tray positions will not be constrained by this method.
///
/// This method allows you to position your Tray Windows without having them
/// cut off on the screen borders.
fn move_window_constrained(&self, position: Position) -> Result<()>;
}
impl<R: Runtime> WindowExt for WebviewWindow<R> {
fn move_window(&self, pos: Position) -> Result<()> {
self.as_ref().window().move_window(pos)
}
#[cfg(feature = "tray-icon")]
fn move_window_constrained(&self, position: Position) -> Result<()> {
self.as_ref().window().move_window_constrained(position)
}
}
impl<R: Runtime> WindowExt for Window<R> {
#[cfg(feature = "tray-icon")]
fn move_window_constrained(&self, position: Position) -> Result<()> {
// Diverge to basic move_window, if the position is not a tray position
if !matches!(
position,
Position::TrayLeft
| Position::TrayBottomLeft
| Position::TrayRight
| Position::TrayBottomRight
| Position::TrayCenter
| Position::TrayBottomCenter
) {
return self.move_window(position);
}
let window_position = calculate_position(self, position)?;
let monitor = get_monitor_for_tray_icon(self)?;
if let Some(monitor) = monitor {
let monitor_size = monitor.size();
let monitor_position = monitor.position();
let window_size = self.outer_size()?;
let right_border_monitor = monitor_position.x as f64 + monitor_size.width as f64;
let left_border_monitor = monitor_position.x as f64;
let right_border_window = window_position.x as f64 + window_size.width as f64;
let left_border_window = window_position.x as f64;
let constrained_x = if left_border_window < left_border_monitor {
left_border_monitor
} else if right_border_window > right_border_monitor {
right_border_monitor - window_size.width as f64
} else {
window_position.x as f64
};
let bottom_border_monitor = monitor_position.y as f64 + monitor_size.height as f64;
let top_border_monitor = monitor_position.y as f64;
let bottom_border_window = window_position.y as f64 + window_size.height as f64;
let top_border_window = window_position.y as f64;
let constrained_y = if top_border_window < top_border_monitor {
top_border_monitor
} else if bottom_border_window > bottom_border_monitor {
bottom_border_monitor - window_size.height as f64
} else {
window_position.y as f64
};
self.set_position(PhysicalPosition::new(constrained_x, constrained_y))?;
} else {
// Fallback on non constrained positioning
self.set_position(window_position)?;
}
Ok(())
}
fn move_window(&self, pos: Position) -> Result<()> {
use Position::*;
let screen = self.current_monitor()?.unwrap();
let screen_position = screen.position();
let screen_size = PhysicalSize::<i32> {
width: screen.size().width as i32,
height: screen.size().height as i32,
};
let window_size = PhysicalSize::<i32> {
width: self.outer_size()?.width as i32,
height: self.outer_size()?.height as i32,
};
let position = calculate_position(self, pos)?;
self.set_position(position)
}
}
#[cfg(feature = "tray-icon")]
/// Retrieve the monitor, where the tray icon is located on.
fn get_monitor_for_tray_icon<R: Runtime>(window: &Window<R>) -> Result<Option<Monitor>> {
let tray_position = window
.state::<Tray>()
.0
.lock()
.unwrap()
.map(|(pos, _)| pos)
.unwrap_or_default();
window.monitor_from_point(tray_position.x, tray_position.y)
}
/// Calculate the top-left position of the window based on the given
/// [`Position`].
fn calculate_position<R: Runtime>(
window: &Window<R>,
pos: Position,
) -> Result<PhysicalPosition<i32>> {
use Position::*;
let screen = window.current_monitor()?.unwrap();
// Only use the screen_position for the Tray independent positioning,
// because a tray event may not be called on the currently active monitor.
let screen_position = screen.position();
let screen_size = PhysicalSize::<i32> {
width: screen.size().width as i32,
height: screen.size().height as i32,
};
let window_size = PhysicalSize::<i32> {
width: window.outer_size()?.width as i32,
height: window.outer_size()?.height as i32,
};
#[cfg(feature = "tray-icon")]
let (tray_position, tray_size) = window
.state::<Tray>()
.0
.lock()
.unwrap()
.map(|(pos, size)| {
(
Some((pos.x as i32, pos.y as i32)),
Some((size.width as i32, size.height as i32)),
)
})
.unwrap_or_default();
let physical_pos = match pos {
TopLeft => *screen_position,
TopRight => PhysicalPosition {
x: screen_position.x + (screen_size.width - window_size.width),
y: screen_position.y,
},
BottomLeft => PhysicalPosition {
x: screen_position.x,
y: screen_size.height - (window_size.height - screen_position.y),
},
BottomRight => PhysicalPosition {
x: screen_position.x + (screen_size.width - window_size.width),
y: screen_size.height - (window_size.height - screen_position.y),
},
TopCenter => PhysicalPosition {
x: screen_position.x + ((screen_size.width / 2) - (window_size.width / 2)),
y: screen_position.y,
},
BottomCenter => PhysicalPosition {
x: screen_position.x + ((screen_size.width / 2) - (window_size.width / 2)),
y: screen_size.height - (window_size.height - screen_position.y),
},
LeftCenter => PhysicalPosition {
x: screen_position.x,
y: screen_position.y + (screen_size.height / 2) - (window_size.height / 2),
},
RightCenter => PhysicalPosition {
x: screen_position.x + (screen_size.width - window_size.width),
y: screen_position.y + (screen_size.height / 2) - (window_size.height / 2),
},
Center => PhysicalPosition {
x: screen_position.x + ((screen_size.width / 2) - (window_size.width / 2)),
y: screen_position.y + (screen_size.height / 2) - (window_size.height / 2),
},
#[cfg(feature = "tray-icon")]
let (tray_position, tray_size) = self
.state::<Tray>()
.0
.lock()
.unwrap()
.map(|(pos, size)| {
(
Some((pos.x as i32, pos.y as i32)),
Some((size.width as i32, size.height as i32)),
)
})
.unwrap_or_default();
let physical_pos = match pos {
TopLeft => *screen_position,
TopRight => PhysicalPosition {
x: screen_position.x + (screen_size.width - window_size.width),
y: screen_position.y,
},
BottomLeft => PhysicalPosition {
x: screen_position.x,
y: screen_size.height - (window_size.height - screen_position.y),
},
BottomRight => PhysicalPosition {
x: screen_position.x + (screen_size.width - window_size.width),
y: screen_size.height - (window_size.height - screen_position.y),
},
TopCenter => PhysicalPosition {
x: screen_position.x + ((screen_size.width / 2) - (window_size.width / 2)),
y: screen_position.y,
},
BottomCenter => PhysicalPosition {
x: screen_position.x + ((screen_size.width / 2) - (window_size.width / 2)),
y: screen_size.height - (window_size.height - screen_position.y),
},
LeftCenter => PhysicalPosition {
x: screen_position.x,
y: screen_position.y + (screen_size.height / 2) - (window_size.height / 2),
},
RightCenter => PhysicalPosition {
x: screen_position.x + (screen_size.width - window_size.width),
y: screen_position.y + (screen_size.height / 2) - (window_size.height / 2),
},
Center => PhysicalPosition {
x: screen_position.x + ((screen_size.width / 2) - (window_size.width / 2)),
y: screen_position.y + (screen_size.height / 2) - (window_size.height / 2),
},
#[cfg(feature = "tray-icon")]
TrayLeft => {
if let (Some((tray_x, tray_y)), Some((_, _tray_height))) =
(tray_position, tray_size)
{
let y = tray_y - window_size.height;
// Choose y value based on the target OS
#[cfg(target_os = "windows")]
let y = if y < 0 { tray_y + _tray_height } else { y };
#[cfg(target_os = "macos")]
let y = if y < 0 { tray_y } else { y };
PhysicalPosition { x: tray_x, y }
} else {
panic!("Tray position not set");
}
TrayLeft => {
if let (Some((tray_x, tray_y)), Some((_, _tray_height))) = (tray_position, tray_size) {
let y = tray_y - window_size.height;
// Choose y value based on the target OS
#[cfg(target_os = "windows")]
let y = if y < 0 { tray_y + _tray_height } else { y };
#[cfg(target_os = "macos")]
let y = if y < 0 { tray_y } else { y };
PhysicalPosition { x: tray_x, y }
} else {
panic!("Tray position not set");
}
#[cfg(feature = "tray-icon")]
TrayBottomLeft => {
if let Some((tray_x, tray_y)) = tray_position {
PhysicalPosition {
x: tray_x,
y: tray_y,
}
} else {
panic!("Tray position not set");
}
#[cfg(feature = "tray-icon")]
TrayBottomLeft => {
if let Some((tray_x, tray_y)) = tray_position {
PhysicalPosition {
x: tray_x,
y: tray_y,
}
} else {
panic!("Tray position not set");
}
#[cfg(feature = "tray-icon")]
TrayRight => {
if let (Some((tray_x, tray_y)), Some((tray_width, _tray_height))) =
(tray_position, tray_size)
{
let y = tray_y - window_size.height;
// Choose y value based on the target OS
#[cfg(target_os = "windows")]
let y = if y < 0 { tray_y + _tray_height } else { y };
#[cfg(target_os = "macos")]
let y = if y < 0 { tray_y } else { y };
PhysicalPosition {
x: tray_x + tray_width,
y,
}
} else {
panic!("Tray position not set");
}
#[cfg(feature = "tray-icon")]
TrayRight => {
if let (Some((tray_x, tray_y)), Some((tray_width, _tray_height))) =
(tray_position, tray_size)
{
let y = tray_y - window_size.height;
// Choose y value based on the target OS
#[cfg(target_os = "windows")]
let y = if y < 0 { tray_y + _tray_height } else { y };
#[cfg(target_os = "macos")]
let y = if y < 0 { tray_y } else { y };
PhysicalPosition {
x: tray_x + tray_width,
y,
}
} else {
panic!("Tray position not set");
}
#[cfg(feature = "tray-icon")]
TrayBottomRight => {
if let (Some((tray_x, tray_y)), Some((tray_width, _))) = (tray_position, tray_size)
{
PhysicalPosition {
x: tray_x + tray_width,
y: tray_y,
}
} else {
panic!("Tray position not set");
}
#[cfg(feature = "tray-icon")]
TrayBottomRight => {
if let (Some((tray_x, tray_y)), Some((tray_width, _))) = (tray_position, tray_size) {
PhysicalPosition {
x: tray_x + tray_width,
y: tray_y,
}
} else {
panic!("Tray position not set");
}
#[cfg(feature = "tray-icon")]
TrayCenter => {
if let (Some((tray_x, tray_y)), Some((tray_width, _tray_height))) =
(tray_position, tray_size)
{
let x = tray_x + tray_width / 2 - window_size.width / 2;
let y = tray_y - window_size.height;
// Choose y value based on the target OS
#[cfg(target_os = "windows")]
let y = if y < 0 { tray_y + _tray_height } else { y };
#[cfg(target_os = "macos")]
let y = if y < 0 { tray_y } else { y };
PhysicalPosition { x, y }
} else {
panic!("Tray position not set");
}
}
#[cfg(feature = "tray-icon")]
TrayCenter => {
if let (Some((tray_x, tray_y)), Some((tray_width, _tray_height))) =
(tray_position, tray_size)
{
let x = tray_x + tray_width / 2 - window_size.width / 2;
let y = tray_y - window_size.height;
// Choose y value based on the target OS
#[cfg(target_os = "windows")]
let y = if y < 0 { tray_y + _tray_height } else { y };
#[cfg(target_os = "macos")]
let y = if y < 0 { tray_y } else { y };
PhysicalPosition { x, y }
} else {
panic!("Tray position not set");
}
#[cfg(feature = "tray-icon")]
TrayBottomCenter => {
if let (Some((tray_x, tray_y)), Some((tray_width, _))) = (tray_position, tray_size)
{
PhysicalPosition {
x: tray_x + (tray_width / 2) - (window_size.width / 2),
y: tray_y,
}
} else {
panic!("Tray position not set");
}
#[cfg(feature = "tray-icon")]
TrayBottomCenter => {
if let (Some((tray_x, tray_y)), Some((tray_width, _))) = (tray_position, tray_size) {
PhysicalPosition {
x: tray_x + (tray_width / 2) - (window_size.width / 2),
y: tray_y,
}
} else {
panic!("Tray position not set");
}
};
}
};
self.set_position(tauri::Position::Physical(physical_pos))
}
Ok(physical_pos)
}

@ -61,6 +61,15 @@ async fn move_window<R: Runtime>(window: tauri::Window<R>, position: Position) -
window.move_window(position)
}
#[cfg(feature = "tray-icon")]
#[tauri::command]
async fn move_window_constrained<R: Runtime>(
window: tauri::Window<R>,
position: Position,
) -> Result<()> {
window.move_window_constrained(position)
}
#[cfg(feature = "tray-icon")]
#[tauri::command]
fn set_tray_icon_state<R: Runtime>(
@ -80,6 +89,8 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
let plugin = plugin::Builder::new("positioner").invoke_handler(tauri::generate_handler![
move_window,
#[cfg(feature = "tray-icon")]
move_window_constrained,
#[cfg(feature = "tray-icon")]
set_tray_icon_state
]);

@ -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}");
}

@ -11,8 +11,9 @@ use tauri::{
Manager, Runtime, State, Window,
};
#[allow(deprecated)]
use crate::open::Program;
use crate::{
open::Program,
process::{CommandEvent, TerminatedPayload},
scope::ExecuteArgs,
Shell,
@ -302,6 +303,7 @@ pub fn kill<R: Runtime>(
Ok(())
}
#[allow(deprecated)]
#[tauri::command]
pub async fn open<R: Runtime>(
_window: Window<R>,

@ -26,6 +26,8 @@ use tauri::{
mod commands;
mod config;
mod error;
#[deprecated(since = "2.1.0", note = "Use tauri-plugin-opener instead.")]
#[allow(deprecated)]
pub mod open;
pub mod process;
mod scope;
@ -70,6 +72,8 @@ 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.")]
#[allow(deprecated)]
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)
}
@ -78,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)
}

@ -4,6 +4,7 @@
use std::sync::Arc;
#[allow(deprecated)]
use crate::open::Program;
use crate::process::Command;
@ -201,6 +202,7 @@ impl OpenScope {
///
/// The path is validated against the `plugins > shell > open` validation regex, which
/// defaults to `^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+`.
#[allow(deprecated)]
pub fn open(&self, path: &str, with: Option<Program>) -> Result<(), Error> {
// ensure we pass validation if the configuration has one
if let Some(regex) = &self.open {

@ -24,7 +24,7 @@ ios = { level = "none", notes = "" }
serde = { workspace = true }
serde_json = { workspace = true }
tauri = { workspace = true }
log = { workspace = true }
tracing = { workspace = true }
thiserror = { workspace = true }
tauri-plugin-deep-link = { path = "../deep-link", version = "2.0.1", optional = true }
semver = { version = "1", optional = true }
@ -42,7 +42,7 @@ features = [
]
[target."cfg(target_os = \"linux\")".dependencies]
zbus = "4"
zbus = { workspace = true }
[features]
semver = ["dep:semver"]

@ -34,7 +34,7 @@ pub fn init<R: Runtime>(cb: Box<SingleInstanceCallback<R>>) -> TauriPlugin<R> {
listen_for_other_instances(&socket, app.clone(), cb);
}
_ => {
log::debug!(
tracing::debug!(
"single_instance failed to notify - launching normally: {}",
e
);
@ -108,11 +108,13 @@ fn listen_for_other_instances<A: Runtime>(
s.split('\0').map(String::from).collect();
cb(app.app_handle(), args, cwd.clone());
}
Err(e) => log::debug!("single_instance failed to be notified: {e}"),
Err(e) => {
tracing::debug!("single_instance failed to be notified: {e}")
}
}
}
Err(err) => {
log::debug!("single_instance failed to be notified: {}", err);
tracing::debug!("single_instance failed to be notified: {}", err);
continue;
}
}
@ -120,7 +122,7 @@ fn listen_for_other_instances<A: Runtime>(
});
}
Err(err) => {
log::error!(
tracing::error!(
"single_instance failed to listen to other processes - launching normally: {}",
err
);

@ -104,6 +104,11 @@ impl DbPool {
}
Ok(Self::Postgres(Pool::connect(conn_url).await?))
}
#[cfg(not(any(feature = "sqlite", feature = "postgres", feature = "mysql")))]
_ => Err(crate::Error::InvalidDbUrl(format!(
"{conn_url} - No database driver enabled!"
))),
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
_ => Err(crate::Error::InvalidDbUrl(conn_url.to_string())),
}
}

@ -27,7 +27,7 @@ tauri-plugin = { workspace = true, features = ["build"] }
serde = { workspace = true }
serde_json = { workspace = true }
tauri = { workspace = true }
log = { workspace = true }
tracing = { workspace = true }
thiserror = { workspace = true }
dunce = { workspace = true }
tokio = { version = "1", features = ["sync", "time", "macros"] }

@ -432,7 +432,7 @@ impl Builder {
for (path, rid) in stores.iter() {
if let Ok(store) = app_handle.resources_table().get::<Store<R>>(*rid) {
if let Err(err) = store.save() {
log::error!("failed to save store {path:?} with error {err:?}");
tracing::error!("failed to save store {path:?} with error {err:?}");
}
}
}

@ -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}");
}

@ -44,5 +44,5 @@ native-tls-vendored = ["reqwest/native-tls-vendored"]
rustls-tls = ["reqwest/rustls-tls"]
[dev-dependencies]
mockito = "1.5.0"
mockito = "1.6.1"
tokio = { version = "1", features = ["macros"] }

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save