Merge branch 'v2' into feat/fs/performance

pull/1962/head
amrbashir 8 months ago
commit 6ff5eb05c6
No known key found for this signature in database
GPG Key ID: BBD7A47A2003FF33

@ -0,0 +1,6 @@
---
"upload": "minor"
"upload-js": "minor"
---
Added a new field `progressTotal` to track the total amount of data transferred during the upload/download process.

@ -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 @@
---
deep-link: patch
deep-link-js: patch
---
`onOpenUrl()` will now not call `getCurrent()` anymore, matching the documented behavior.

@ -0,0 +1,6 @@
---
'log-plugin': 'patch'
'log-js': 'patch'
---
Make webview log target more consistent that it always starts with `webview`

@ -0,0 +1,7 @@
---
"fs": "patch"
"fs-js": "patch"
---
Fix `readDir` function failing to read directories that contain broken symlinks.

@ -0,0 +1,5 @@
---
'localhost': 'minor'
---
Add custom host binding to allow external access

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

@ -0,0 +1,5 @@
---
"sql": "patch"
---
Allow blocking on async code without creating a nested runtime.

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

1718
Cargo.lock generated

File diff suppressed because it is too large Load Diff

@ -11,16 +11,18 @@ resolver = "2"
[workspace.dependencies]
serde = { version = "1", features = ["derive"] }
log = "0.4"
tauri = { version = "2.0.4", default-features = false }
tauri-build = "2.0.1"
tauri-plugin = "2.0.1"
tauri-utils = "2.0.1"
tauri = { version = "2", default-features = false }
tauri-build = "2"
tauri-plugin = "2"
tauri-utils = "2"
serde_json = "1"
thiserror = "1"
thiserror = "2"
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]

@ -1,36 +1,45 @@
# Official Tauri Plugins
This repo and all plugins require a Rust version of at least **1.77.2**
## Plugins Found Here
| | | Win | Mac | Lin | iOS | And |
| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | --- | --- | --- | --- |
| [autostart](plugins/autostart) | Automatically launch your app at system startup. | ✅ | ✅ | ✅ | ? | ? |
| [autostart](plugins/autostart) | Automatically launch your app at system startup. | ✅ | ✅ | ✅ | ❌ | ❌ |
| [barcode-scanner](plugins/barcode-scanner) | Allows your mobile application to use the camera to scan QR codes, EAN-13 and other kinds of barcodes. | ? | ? | ? | ✅ | ✅ |
| [biometric](plugins/biometric) | Prompt the user for biometric authentication on Android and iOS. | ? | ? | ? | ✅ | ✅ |
| [cli](plugins/cli) | Parse arguments from your Command Line Interface | ✅ | ✅ | ✅ | ? | ? |
| [cli](plugins/cli) | Parse arguments from your Command Line Interface | ✅ | ✅ | ✅ | ❌ | ❌ |
| [clipboard-manager](plugins/clipboard-manager) | Read and write to the system clipboard. | ✅ | ✅ | ✅ | ✅ | ✅ |
| [deep-link](plugins/deep-link) | Set your Tauri application as the default handler for an URL. | ✅ | ✅ | ✅ | ✅ | ✅ |
| [dialog](plugins/dialog) | Native system dialogs for opening and saving files along with message dialogs. | ✅ | ✅ | ✅ | ✅ | ✅ |
| [fs](plugins/fs) | Access the file system. | ✅ | ✅ | ✅ | ? | ? |
| [geolocation](plugins/geolocation) | Get and track current device position. | ? | ? | ? | ✅ | ✅ |
| [global-shortcut](plugins/global-shortcut) | Register global shortcuts. | ✅ | ✅ | ✅ | ? | ? |
| [haptics](plugins/haptics) | Haptic feedback and vibrations. | ? | ? | ? | ✅ | ✅ |
| [http](plugins/http) | Access the HTTP client written in Rust. | ✅ | ✅ | ✅ | ✅ | ✅ |
| [localhost](plugins/localhost) | Use a localhost server in production apps. | ✅ | ✅ | ✅ | ? | ? |
| [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. | ✅ | ✅ | ✅ | ? | ? |
| [positioner](plugins/positioner) | Move windows to common locations. | ✅ | ✅ | ✅ | ❌ | ❌ |
| [process](plugins/process) | This plugin provides APIs to access the current process. To spawn child processes, see the [`shell`](https://github.com/tauri-apps/tauri-plugin-shell) plugin. | ✅ | ✅ | ✅ | ? | ? |
| [shell](plugins/shell) | Access the system shell. Allows you to spawn child processes and manage files and URLs using their default application. | ✅ | ✅ | ✅ | ? | ? |
| [single-instance](plugins/single-instance) | Ensure a single instance of your tauri app is running. | ✅ | ? | ✅ | ? | ? |
| [sql](plugins/sql) | Interface with SQL databases. | ✅ | ✅ | ✅ | ? | ? |
| [single-instance](plugins/single-instance) | Ensure a single instance of your tauri app is running. | ✅ | ✅ | ✅ | ❌ | ❌ |
| [sql](plugins/sql) | Interface with SQL databases. | ✅ | ✅ | ✅ | ? | |
| [store](plugins/store) | Persistent key value storage. | ✅ | ✅ | ✅ | ✅ | ✅ |
| [stronghold](plugins/stronghold) | Encrypted, secure database. | ✅ | ✅ | ✅ | ? | ? |
| [updater](plugins/updater) | In-app updates for Tauri applications. | ✅ | ✅ | ✅ | ? | ? |
| [updater](plugins/updater) | In-app updates for Tauri applications. | ✅ | ✅ | ✅ | ❌ | ❌ |
| [upload](plugins/upload) | Tauri plugin for file uploads through HTTP. | ✅ | ✅ | ✅ | ? | ? |
| [websocket](plugins/websocket) | Open a WebSocket connection using a Rust client in JS. | ✅ | ✅ | ✅ | ? | ? |
| [window-state](plugins/window-state) | Persist window sizes and positions. | ✅ | ✅ | ✅ | ? | ? |
| [window-state](plugins/window-state) | Persist window sizes and positions. | ✅ | ✅ | ✅ | ❌ | ❌ |
_This repo and all plugins require a Rust version of at least **1.77.2**_
- ✅: (Partially) Supported
- ❌: Not supported
- `?` : Unknown/Untested or Planned
## Contributing

@ -1,5 +1,11 @@
# Changelog
## \[2.0.2]
### Dependencies
- Upgraded to `fs-js@2.0.2`
## \[2.0.1]
### Dependencies

@ -1,23 +1,25 @@
{
"name": "svelte-app",
"name": "api",
"private": true,
"version": "2.0.1",
"version": "2.0.2",
"type": "module",
"scripts": {
"dev": "vite --clearScreen false",
"build": "vite build",
"serve": "vite preview"
"serve": "vite preview",
"tauri": "tauri"
},
"dependencies": {
"@tauri-apps/api": "2.0.2",
"@tauri-apps/api": "2.1.1",
"@tauri-apps/plugin-barcode-scanner": "2.0.0",
"@tauri-apps/plugin-biometric": "2.0.0",
"@tauri-apps/plugin-cli": "2.0.0",
"@tauri-apps/plugin-clipboard-manager": "2.0.0",
"@tauri-apps/plugin-dialog": "2.0.1",
"@tauri-apps/plugin-fs": "2.0.1",
"@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",
@ -32,11 +34,11 @@
"devDependencies": {
"@iconify-json/codicon": "^1.1.37",
"@iconify-json/ph": "^1.1.8",
"@sveltejs/vite-plugin-svelte": "^3.0.1",
"@tauri-apps/cli": "2.0.3",
"@unocss/extractor-svelte": "^0.63.0",
"svelte": "^4.2.19",
"unocss": "^0.63.0",
"@sveltejs/vite-plugin-svelte": "^4.0.0",
"@tauri-apps/cli": "2.1.0",
"@unocss/extractor-svelte": "^0.64.0",
"svelte": "^5.0.0",
"unocss": "^0.64.0",
"vite": "^5.4.7"
}
}

@ -1,5 +1,12 @@
# Changelog
## \[2.0.5]
### Dependencies
- Upgraded to `clipboard-manager@2.0.2`
- Upgraded to `log-plugin@2.0.2`
## \[2.0.4]
### Dependencies

@ -1,7 +1,7 @@
[package]
name = "api"
publish = false
version = "2.0.4"
version = "2.0.5"
description = "An example Tauri Application showcasing the api"
edition = "2021"
rust-version = { workspace = true }
@ -19,11 +19,11 @@ serde_json = { workspace = true }
serde = { workspace = true }
tiny_http = "0.12"
log = { workspace = true }
tauri-plugin-log = { path = "../../../plugins/log", version = "2.0.1" }
tauri-plugin-log = { path = "../../../plugins/log", version = "2.0.2" }
tauri-plugin-fs = { path = "../../../plugins/fs", version = "2.0.3", features = [
"watch",
] }
tauri-plugin-clipboard-manager = { path = "../../../plugins/clipboard-manager", version = "2.0.1" }
tauri-plugin-clipboard-manager = { path = "../../../plugins/clipboard-manager", version = "2.0.2" }
tauri-plugin-dialog = { path = "../../../plugins/dialog", version = "2.0.3" }
tauri-plugin-http = { path = "../../../plugins/http", features = [
"multipart",
@ -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" }

@ -53,6 +53,7 @@
}
]
},
"shell:allow-open",
"shell:allow-kill",
"shell:allow-stdin-write",
"process:allow-exit",
@ -79,6 +80,11 @@
],
"deny": ["$APPDATA/db/*.stronghold"]
},
"store:default"
"store:default",
"opener:default",
{
"identifier": "opener:allow-open-path",
"allow": [{ "path": "$APPDATA" }, { "path": "$APPDATA/**" }]
}
]
}

@ -9,6 +9,8 @@
"updater:default",
"global-shortcut:allow-unregister",
"global-shortcut:allow-register",
"global-shortcut:allow-unregister-all"
"global-shortcut:allow-unregister-all",
{ "identifier": "fs:allow-watch", "allow": ["*", "**/*"] },
"fs:allow-unwatch"
]
}

@ -15,6 +15,10 @@
"geolocation:allow-check-permissions",
"geolocation:allow-request-permissions",
"geolocation:allow-watch-position",
"geolocation:allow-get-current-position"
"geolocation:allow-get-current-position",
"haptics:allow-impact-feedback",
"haptics:allow-notification-feedback",
"haptics:allow-selection-feedback",
"haptics:allow-vibrate"
]
}

@ -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'
@ -21,6 +21,7 @@
import Scanner from './views/Scanner.svelte'
import Biometric from './views/Biometric.svelte'
import Geolocation from './views/Geolocation.svelte'
import Haptics from './views/Haptics.svelte'
import { onMount, tick } from 'svelte'
import { ask } from '@tauri-apps/plugin-dialog'
@ -91,6 +92,11 @@
component: Shell,
icon: 'i-codicon-terminal-bash'
},
{
label: 'Opener',
component: Opener,
icon: 'i-codicon-link-external'
},
{
label: 'Store',
component: Store,
@ -130,6 +136,11 @@
label: 'Geolocation',
component: Geolocation,
icon: 'i-ph-map-pin'
},
isMobile && {
label: 'Haptics',
component: Haptics,
icon: 'i-ph-vibrate'
}
]
@ -205,7 +216,7 @@
if (consoleTextEl) consoleTextEl.scrollTop = consoleTextEl.scrollHeight
}
// this function is renders HTML without sanitizing it so it's insecure
// this function renders HTML without sanitizing it so it's insecure
// we only use it with our own input data
async function insecureRenderHtml(html) {
messages.update((r) => [
@ -334,42 +345,46 @@
children:h-100% children:w-12 children:inline-flex
children:items-center children:justify-center"
>
<span
<button
aria-label="Toggle dark mode"
title={isDark ? 'Switch to Light mode' : 'Switch to Dark mode'}
class="hover:bg-hoverOverlay active:bg-hoverOverlayDarker dark:hover:bg-darkHoverOverlay dark:active:bg-darkHoverOverlayDarker"
class="bg-inherit border-none hover:bg-hoverOverlay active:bg-hoverOverlayDarker dark:hover:bg-darkHoverOverlay dark:active:bg-darkHoverOverlayDarker"
on:click={toggleDark}
>
{#if isDark}
<div class="i-ph-sun" />
<div class="i-ph-sun"></div>
{:else}
<div class="i-ph-moon" />
<div class="i-ph-moon"></div>
{/if}
</span>
<span
</button>
<button
aria-label="Minimize window"
title="Minimize"
class="hover:bg-hoverOverlay active:bg-hoverOverlayDarker dark:hover:bg-darkHoverOverlay dark:active:bg-darkHoverOverlayDarker"
class="bg-inherit border-none hover:bg-hoverOverlay active:bg-hoverOverlayDarker dark:hover:bg-darkHoverOverlay dark:active:bg-darkHoverOverlayDarker"
on:click={minimize}
>
<div class="i-codicon-chrome-minimize" />
</span>
<span
<div class="i-codicon-chrome-minimize"></div>
</button>
<button
aria-label="Maximize window"
title={isWindowMaximized ? 'Restore' : 'Maximize'}
class="hover:bg-hoverOverlay active:bg-hoverOverlayDarker dark:hover:bg-darkHoverOverlay dark:active:bg-darkHoverOverlayDarker"
class="bg-inherit border-none hover:bg-hoverOverlay active:bg-hoverOverlayDarker dark:hover:bg-darkHoverOverlay dark:active:bg-darkHoverOverlayDarker"
on:click={toggleMaximize}
>
{#if isWindowMaximized}
<div class="i-codicon-chrome-restore" />
<div class="i-codicon-chrome-restore"></div>
{:else}
<div class="i-codicon-chrome-maximize" />
<div class="i-codicon-chrome-maximize"></div>
{/if}
</span>
<span
</button>
<button
aria-label="Close window"
title="Close"
class="hover:bg-red-700 dark:hover:bg-red-700 hover:text-darkPrimaryText active:bg-red-700/90 dark:active:bg-red-700/90 active:text-darkPrimaryText"
class="bg-inherit border-none hover:bg-red-700 dark:hover:bg-red-700 hover:text-darkPrimaryText active:bg-red-700/90 dark:active:bg-red-700/90 active:text-darkPrimaryText"
on:click={close}
>
<div class="i-codicon-chrome-close" />
</span>
<div class="i-codicon-chrome-close"></div>
</button>
</span>
</div>
{/if}
@ -377,13 +392,13 @@
<!-- Sidebar toggle, only visible on small screens -->
<div
id="sidebarToggle"
class="z-2000 sidebar-toggle display-none lt-sm:flex justify-center absolute items-center w-8 h-8 rd-8
class="z-2000 sidebar-toggle hidden lt-sm:flex justify-center absolute items-center w-8 h-8 rd-8
bg-accent dark:bg-darkAccent active:bg-accentDark dark:active:bg-darkAccentDark"
>
{#if isSideBarOpen}
<span class="i-codicon-close animate-duration-300ms animate-fade-in" />
<span class="i-codicon-close animate-duration-300ms animate-fade-in"></span>
{:else}
<span class="i-codicon-menu animate-duration-300ms animate-fade-in" />
<span class="i-codicon-menu animate-duration-300ms animate-fade-in"></span>
{/if}
</div>
@ -395,24 +410,21 @@
class="lt-sm:h-screen lt-sm:shadow-lg lt-sm:shadow lt-sm:transition-transform lt-sm:absolute lt-sm:z-1999
bg-darkPrimaryLighter transition-colors-250 overflow-hidden grid select-none px-2"
>
<img
on:click={() => open('https://tauri.app/')}
class="self-center p-7 cursor-pointer"
src="tauri_logo.png"
alt="Tauri logo"
/>
<a href="https://tauri.app" target="_blank">
<img class="p-7" src="tauri_logo.png" alt="Tauri logo" />
</a>
{#if !isWindows}
<a href="##" class="nv justify-between h-8" on:click={toggleDark}>
{#if isDark}
Switch to Light mode
<div class="i-ph-sun" />
<div class="i-ph-sun"></div>
{:else}
Switch to Dark mode
<div class="i-ph-moon" />
<div class="i-ph-moon"></div>
{/if}
</a>
<br />
<div class="bg-white/5 h-2px" />
<div class="bg-white/5 h-2px"></div>
<br />
{/if}
@ -422,7 +434,7 @@
href="https://tauri.app/v1/guides/"
>
Documentation
<span class="i-codicon-link-external" />
<span class="i-codicon-link-external"></span>
</a>
<a
class="nv justify-between h-8"
@ -430,7 +442,7 @@
href="https://github.com/tauri-apps/tauri"
>
GitHub
<span class="i-codicon-link-external" />
<span class="i-codicon-link-external"></span>
</a>
<a
class="nv justify-between h-8"
@ -438,10 +450,10 @@
href="https://github.com/tauri-apps/tauri/tree/dev/examples/api"
>
Source
<span class="i-codicon-link-external" />
<span class="i-codicon-link-external"></span>
</a>
<br />
<div class="bg-white/5 h-2px" />
<div class="bg-white/5 h-2px"></div>
<br />
<div
class="flex flex-col overflow-y-auto children-h-10 children-flex-none gap-1"
@ -456,7 +468,7 @@
isSideBarOpen = false
}}
>
<div class="{view.icon} mr-2" />
<div class="{view.icon} mr-2"></div>
<p>{view.label}</p></a
>
{/if}
@ -485,21 +497,23 @@
id="console"
class="select-none h-15rem grid grid-rows-[2px_2rem_1fr] gap-1 overflow-hidden"
>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
on:mousedown={startResizingConsole}
class="bg-black/20 h-2px cursor-ns-resize"
/>
></div>
<div class="flex justify-between items-center px-2">
<p class="font-semibold">Console</p>
<div
class="cursor-pointer h-85% rd-1 p-1 flex justify-center items-center
<button
aria-label="Clear Console"
class="cursor-pointer h-85% rd-1 p-1 flex justify-center items-center border-none bg-inherit
hover:bg-hoverOverlay dark:hover:bg-darkHoverOverlay
active:bg-hoverOverlay/25 dark:active:bg-darkHoverOverlay/25
"
on:click={clear}
>
<div class="i-codicon-clear-all" />
</div>
<div class="i-codicon-clear-all"></div>
</button>
</div>
<div
bind:this={consoleTextEl}

@ -5,8 +5,9 @@
import 'uno.css'
import './app.css'
import App from './App.svelte'
import { mount } from 'svelte'
const app = new App({
const app = mount(App, {
target: document.querySelector('#app')
})

@ -1,14 +1,14 @@
<script>
import { getMatches } from "@tauri-apps/plugin-cli";
import { getMatches } from '@tauri-apps/plugin-cli'
export let onMessage;
export let onMessage
function cliMatches() {
getMatches().then(onMessage).catch(onMessage);
getMatches().then(onMessage).catch(onMessage)
}
</script>
<p>
<div>
This binary can be run from the terminal and takes the following arguments:
<code class="code-block flex flex-wrap my-2">
<pre>
@ -17,7 +17,7 @@
--verbose</pre>
</code>
Additionally, it has a <code>update --background</code> subcommand.
</p>
</div>
<br />
<div class="note">
Note that the arguments are only parsed, not implemented.

@ -0,0 +1,46 @@
<script>
import {
vibrate,
impactFeedback,
notificationFeedback,
selectionFeedback
} from '@tauri-apps/plugin-haptics'
export let onMessage
</script>
<div>
<button
class="btn"
on:click={() => vibrate(300).then(onMessage).catch(onMessage)}
>vibrate short</button
>
<button
class="btn"
on:click={() => vibrate(1500).then(onMessage).catch(onMessage)}
>vibrate long</button
>
<button
class="btn"
on:click={() => impactFeedback('medium').then(onMessage).catch(onMessage)}
>impact medium</button
>
<button
class="btn"
on:click={() =>
notificationFeedback('warning').then(onMessage).catch(onMessage)}
>notification warning</button
>
<button
class="btn"
on:click={() => selectionFeedback().then(onMessage).catch(onMessage)}
>selection</button
>
</div>
<br />
<p>
Depending on your device settings for haptic feedback some of the buttons may
not work.
</p>

@ -1,69 +1,69 @@
<script>
import { fetch as tauriFetch } from "@tauri-apps/plugin-http";
import { JsonView } from "@zerodevx/svelte-json-view";
import { fetch as tauriFetch } from '@tauri-apps/plugin-http'
import { JsonView } from '@zerodevx/svelte-json-view'
let httpMethod = "GET";
let httpBody = "";
let httpMethod = 'GET'
let httpBody = ''
export let onMessage;
export let onMessage
async function makeHttpRequest() {
let method = httpMethod || "GET";
let method = httpMethod || 'GET'
const options = {
method: method || "GET",
headers: {},
};
method: method || 'GET',
headers: {}
}
let bodyType;
let bodyType
if (method !== "GET") {
options.body = httpBody;
if (method !== 'GET') {
options.body = httpBody
if (
(httpBody.startsWith("{") && httpBody.endsWith("}")) ||
(httpBody.startsWith("[") && httpBody.endsWith("]"))
(httpBody.startsWith('{') && httpBody.endsWith('}')) ||
(httpBody.startsWith('[') && httpBody.endsWith(']'))
) {
options.headers["Content-Type"] = "application/json";
bodyType = "json";
} else if (httpBody !== "") {
bodyType = "text";
options.headers['Content-Type'] = 'application/json'
bodyType = 'json'
} else if (httpBody !== '') {
bodyType = 'text'
}
}
const response = await tauriFetch("http://localhost:3003", options);
const response = await tauriFetch('http://localhost:3003', options)
const body =
bodyType === "json" ? await response.json() : await response.text();
bodyType === 'json' ? await response.json() : await response.text()
onMessage({
url: response.url,
status: response.status,
ok: response.ok,
headers: Object.fromEntries(response.headers.entries()),
body,
});
body
})
}
/// http form
let foo = "baz";
let bar = "qux";
let result = null;
let foo = 'baz'
let bar = 'qux'
let result = null
async function doPost() {
const form = new FormData();
form.append("foo", foo);
form.append("bar", bar);
const response = await tauriFetch("http://localhost:3003/tauri", {
method: "POST",
body: form,
});
const form = new FormData()
form.append('foo', foo)
form.append('bar', bar)
const response = await tauriFetch('http://localhost:3003/tauri', {
method: 'POST',
body: form
})
result = {
url: response.url,
status: response.status,
ok: response.ok,
headers: Object.fromEntries(response.headers.entries()),
body: await response.text(),
};
body: await response.text()
}
}
</script>
@ -82,7 +82,7 @@
placeholder="Request body"
rows="5"
bind:value={httpBody}
/>
></textarea>
<br />
<button class="btn" id="make-request"> Make request </button>
</form>

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

@ -1,38 +1,44 @@
<script>
import { scan, checkPermissions, requestPermissions, Format, cancel } from "@tauri-apps/plugin-barcode-scanner";
import {
scan,
checkPermissions,
requestPermissions,
Format,
cancel
} from '@tauri-apps/plugin-barcode-scanner'
export let onMessage;
export let onMessage
let scanning = false;
let windowed = true;
let formats = [Format.QRCode];
const supportedFormats = [Format.QRCode, Format.EAN13];
let scanning = false
let windowed = true
let formats = [Format.QRCode]
const supportedFormats = [Format.QRCode, Format.EAN13]
async function startScan() {
let permission = await checkPermissions();
let permission = await checkPermissions()
if (permission === 'prompt') {
permission = await requestPermissions();
permission = await requestPermissions()
}
if (permission === 'granted') {
scanning = true;
scanning = true
scan({ windowed, formats })
.then((res) => {
scanning = false;
onMessage(res);
scanning = false
onMessage(res)
})
.catch((error) => {
scanning = false;
onMessage(error);
});
scanning = false
onMessage(error)
})
} else {
onMessage('Permission denied')
}
}
async function cancelScan() {
await cancel();
scanning = false;
onMessage("cancelled");
await cancel()
scanning = false
onMessage('cancelled')
}
</script>
@ -59,11 +65,12 @@
<div class="barcode-scanner--area--container">
<div class="relative">
<p>Aim your camera at a QR code</p>
<button class="btn" type="button" on:click={cancelScan}>Cancel</button>
<button class="btn" type="button" on:click={cancelScan}>Cancel</button
>
</div>
<div class="square surround-cover">
<div class="barcode-scanner--area--outer surround-cover">
<div class="barcode-scanner--area--inner" />
<div class="barcode-scanner--area--inner"></div>
</div>
</div>
</div>
@ -111,7 +118,7 @@
transition: 0.3s;
}
.square:after {
content: "";
content: '';
top: 0;
display: block;
padding-bottom: 100%;
@ -141,7 +148,8 @@
width: 100%;
margin: 1rem;
border: 2px solid #fff;
box-shadow: 0px 0px 2px 1px rgb(0 0 0 / 0.5),
box-shadow:
0px 0px 2px 1px rgb(0 0 0 / 0.5),
inset 0px 0px 2px 1px rgb(0 0 0 / 0.5);
border-radius: 1rem;
}

@ -1,56 +1,56 @@
<script>
import { check } from "@tauri-apps/plugin-updater";
import { relaunch } from "@tauri-apps/plugin-process";
import { check } from '@tauri-apps/plugin-updater'
import { relaunch } from '@tauri-apps/plugin-process'
export let onMessage;
export let onMessage
let isChecking, isInstalling, newUpdate;
let isChecking, isInstalling, newUpdate
let totalSize = 0,
downloadedSize = 0;
downloadedSize = 0
async function checkUpdate() {
isChecking = true;
isChecking = true
try {
const update = await check();
onMessage(`Should update: ${update.available}`);
onMessage(update);
const update = await check()
onMessage(`Should update: ${update.available}`)
onMessage(update)
newUpdate = update;
newUpdate = update
} catch (e) {
onMessage(e);
onMessage(e)
} finally {
isChecking = false;
isChecking = false
}
}
async function install() {
isInstalling = true;
downloadedSize = 0;
isInstalling = true
downloadedSize = 0
try {
await newUpdate.downloadAndInstall((downloadProgress) => {
switch (downloadProgress.event) {
case "Started":
totalSize = downloadProgress.data.contentLength;
break;
case "Progress":
downloadedSize += downloadProgress.data.chunkLength;
break;
case "Finished":
break;
case 'Started':
totalSize = downloadProgress.data.contentLength
break
case 'Progress':
downloadedSize += downloadProgress.data.chunkLength
break
case 'Finished':
break
}
});
onMessage("Installation complete, restarting...");
await new Promise((resolve) => setTimeout(resolve, 2000));
await relaunch();
})
onMessage('Installation complete, restarting...')
await new Promise((resolve) => setTimeout(resolve, 2000))
await relaunch()
} catch (e) {
console.error(e);
onMessage(e);
console.error(e)
onMessage(e)
} finally {
isInstalling = false;
isInstalling = false
}
}
$: progress = totalSize ? Math.round((downloadedSize / totalSize) * 100) : 0;
$: progress = totalSize ? Math.round((downloadedSize / totalSize) * 100) : 0
</script>
<div class="flex children:grow children:h10">
@ -61,7 +61,7 @@
{:else}
<div class="progress">
<span>{progress}%</span>
<div class="progress-bar" style="width: {progress}%" />
<div class="progress-bar" style="width: {progress}%"></div>
</div>
{/if}
</div>

@ -7,23 +7,24 @@
"build": "pnpm run -r --parallel --filter !plugins-workspace --filter !\"./plugins/*/examples/**\" --filter !\"./examples/*\" build",
"lint": "eslint .",
"format": "prettier --write .",
"format:check": "prettier --check ."
"format:check": "prettier --check .",
"example:api:dev": "pnpm run --filter \"api\" tauri dev"
},
"devDependencies": {
"@eslint/js": "9.13.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.13.0",
"eslint": "9.15.0",
"eslint-config-prettier": "9.1.0",
"eslint-plugin-security": "3.0.1",
"prettier": "3.3.3",
"rollup": "4.22.4",
"tslib": "2.7.0",
"rollup": "4.27.3",
"tslib": "2.8.1",
"typescript": "5.6.3",
"typescript-eslint": "8.10.0"
"typescript-eslint": "8.15.0"
},
"resolutions": {
"semver": ">=7.5.2",

@ -2,8 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! [![](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/autostart/banner.png)](https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/autostart)
//!
//! Automatically launch your application at startup. Supports Windows, Mac (via AppleScript or Launch Agent), and Linux.
#![doc(

@ -2,8 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! [![](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/cli/banner.png)](https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/cli)
//!
//! Parse arguments from your Command Line Interface.
//!
//! - Supported platforms: Windows, Linux and macOS.

@ -1,5 +1,9 @@
# Changelog
## \[2.0.2]
- [`d57df4de`](https://github.com/tauri-apps/plugins-workspace/commit/d57df4debe7c75cfbd6d6558fff1beb07dbee54c) ([#1986](https://github.com/tauri-apps/plugins-workspace/pull/1986) by [@RikaKagurasaka](https://github.com/tauri-apps/plugins-workspace/../../RikaKagurasaka)) Fix that `read_image` wrongly set the image rgba data with binary PNG data.
## \[2.0.1]
- [`a1a82208`](https://github.com/tauri-apps/plugins-workspace/commit/a1a82208ed4ab87f83310be0dc95428aec9ab241) ([#1873](https://github.com/tauri-apps/plugins-workspace/pull/1873) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Downgrade MSRV to 1.77.2 to support Windows 7.

@ -1,6 +1,6 @@
[package]
name = "tauri-plugin-clipboard-manager"
version = "2.0.1"
version = "2.0.2"
description = "Read and write to the system clipboard."
edition = { workspace = true }
authors = { workspace = true }
@ -37,4 +37,3 @@ tauri = { workspace = true, features = ["wry"] }
[target."cfg(any(target_os = \"macos\", windows, target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies]
arboard = "3"
image = "0.25"

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

@ -3,7 +3,6 @@
// SPDX-License-Identifier: MIT
use arboard::ImageData;
use image::ImageEncoder;
use serde::de::DeserializeOwned;
use tauri::{image::Image, plugin::PluginApi, AppHandle, Runtime};
@ -85,16 +84,11 @@ impl<R: Runtime> Clipboard<R> {
match &self.clipboard {
Ok(clipboard) => {
let image = clipboard.lock().unwrap().get_image()?;
let mut buffer: Vec<u8> = Vec::new();
image::codecs::png::PngEncoder::new(&mut buffer).write_image(
&image.bytes,
let image = Image::new_owned(
image.bytes.to_vec(),
image.width as u32,
image.height as u32,
image::ExtendedColorType::Rgba8,
)?;
let image = Image::new_owned(buffer, image.width as u32, image.height as u32);
);
Ok(image)
}
Err(e) => Err(crate::Error::Clipboard(e.to_string())),

@ -15,9 +15,6 @@ pub enum Error {
Clipboard(String),
#[error(transparent)]
Tauri(#[from] tauri::Error),
#[cfg(desktop)]
#[error("invalid image: {0}")]
Image(#[from] image::ImageError),
}
impl Serialize for Error {

@ -2,8 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! [![](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/clipboard-manager/banner.png)](https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/clipboard-manager)
//!
//! Read and write to the system clipboard.
#![doc(

@ -1 +1 @@
if("__TAURI__"in window){var __TAURI_PLUGIN_DEEP_LINK__=function(e){"use strict";function n(e,n=!1){return window.__TAURI_INTERNALS__.transformCallback(e,n)}async function r(e,n={},r){return window.__TAURI_INTERNALS__.invoke(e,n,r)}var t;async function i(e,t,i){const a={kind:"Any"};return r("plugin:event|listen",{event:e,target:a,handler:n(t)}).then((n=>async()=>async function(e,n){await r("plugin:event|unlisten",{event:e,eventId:n})}(e,n)))}async function a(){return await r("plugin:deep-link|get_current")}return"function"==typeof SuppressedError&&SuppressedError,function(e){e.WINDOW_RESIZED="tauri://resize",e.WINDOW_MOVED="tauri://move",e.WINDOW_CLOSE_REQUESTED="tauri://close-requested",e.WINDOW_DESTROYED="tauri://destroyed",e.WINDOW_FOCUS="tauri://focus",e.WINDOW_BLUR="tauri://blur",e.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",e.WINDOW_THEME_CHANGED="tauri://theme-changed",e.WINDOW_CREATED="tauri://window-created",e.WEBVIEW_CREATED="tauri://webview-created",e.DRAG_ENTER="tauri://drag-enter",e.DRAG_OVER="tauri://drag-over",e.DRAG_DROP="tauri://drag-drop",e.DRAG_LEAVE="tauri://drag-leave"}(t||(t={})),e.getCurrent=a,e.isRegistered=async function(e){return await r("plugin:deep-link|is_registered",{protocol:e})},e.onOpenUrl=async function(e){const n=await a();return n&&e(n),await i("deep-link://new-url",(n=>{e(n.payload)}))},e.register=async function(e){return await r("plugin:deep-link|register",{protocol:e})},e.unregister=async function(e){return await r("plugin:deep-link|unregister",{protocol:e})},e}({});Object.defineProperty(window.__TAURI__,"deepLink",{value:__TAURI_PLUGIN_DEEP_LINK__})}
if("__TAURI__"in window){var __TAURI_PLUGIN_DEEP_LINK__=function(e){"use strict";function n(e,n=!1){return window.__TAURI_INTERNALS__.transformCallback(e,n)}async function r(e,n={},r){return window.__TAURI_INTERNALS__.invoke(e,n,r)}var t;async function i(e,t,i){const a={kind:"Any"};return r("plugin:event|listen",{event:e,target:a,handler:n(t)}).then((n=>async()=>async function(e,n){await r("plugin:event|unlisten",{event:e,eventId:n})}(e,n)))}return"function"==typeof SuppressedError&&SuppressedError,function(e){e.WINDOW_RESIZED="tauri://resize",e.WINDOW_MOVED="tauri://move",e.WINDOW_CLOSE_REQUESTED="tauri://close-requested",e.WINDOW_DESTROYED="tauri://destroyed",e.WINDOW_FOCUS="tauri://focus",e.WINDOW_BLUR="tauri://blur",e.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",e.WINDOW_THEME_CHANGED="tauri://theme-changed",e.WINDOW_CREATED="tauri://window-created",e.WEBVIEW_CREATED="tauri://webview-created",e.DRAG_ENTER="tauri://drag-enter",e.DRAG_OVER="tauri://drag-over",e.DRAG_DROP="tauri://drag-drop",e.DRAG_LEAVE="tauri://drag-leave"}(t||(t={})),e.getCurrent=async function(){return await r("plugin:deep-link|get_current")},e.isRegistered=async function(e){return await r("plugin:deep-link|is_registered",{protocol:e})},e.onOpenUrl=async function(e){return await i("deep-link://new-url",(n=>{e(n.payload)}))},e.register=async function(e){return await r("plugin:deep-link|register",{protocol:e})},e.unregister=async function(e){return await r("plugin:deep-link|unregister",{protocol:e})},e}({});Object.defineProperty(window.__TAURI__,"deepLink",{value:__TAURI_PLUGIN_DEEP_LINK__})}

@ -10,11 +10,11 @@
"tauri": "tauri"
},
"dependencies": {
"@tauri-apps/api": "2.0.2",
"@tauri-apps/api": "2.1.1",
"@tauri-apps/plugin-deep-link": "2.0.0"
},
"devDependencies": {
"@tauri-apps/cli": "2.0.3",
"@tauri-apps/cli": "2.1.0",
"typescript": "^5.2.2",
"vite": "^5.4.7"
}

@ -99,11 +99,6 @@ export async function isRegistered(protocol: string): Promise<boolean> {
export async function onOpenUrl(
handler: (urls: string[]) => void
): Promise<UnlistenFn> {
const current = await getCurrent()
if (current) {
handler(current)
}
return await listen<string[]>('deep-link://new-url', (event) => {
handler(event.payload)
})

@ -2,8 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::sync::Arc;
use tauri::{
plugin::{Builder, PluginApi, TauriPlugin},
AppHandle, EventId, Listener, Manager, Runtime,
@ -478,13 +476,10 @@ impl OpenUrlEvent {
}
impl<R: Runtime> DeepLink<R> {
/// Handle a new deep link being triggered to open the app.
/// Helper function for the `deep-link://new-url` event to run a function each time the protocol is triggered while the app is running.
///
/// To avoid race conditions, if the app was started with a deep link,
/// the closure gets immediately called with the deep link URL.
/// Use `get_current` on app load to check whether your app was started via a deep link.
pub fn on_open_url<F: Fn(OpenUrlEvent) + Send + Sync + 'static>(&self, f: F) -> EventId {
let f = Arc::new(f);
let f_ = f.clone();
let event_id = self.app.listen("deep-link://new-url", move |event| {
if let Ok(urls) = serde_json::from_str(event.payload()) {
f(OpenUrlEvent {
@ -494,13 +489,6 @@ impl<R: Runtime> DeepLink<R> {
}
});
if let Ok(Some(current)) = self.get_current() {
f_(OpenUrlEvent {
id: event_id,
urls: current,
})
}
event_id
}
}

@ -2,8 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! [![](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/dialog/banner.png)](https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/dialog)
//!
//! Native system dialogs for opening and saving files along with message dialogs.
#![doc(

@ -1,5 +1,9 @@
# Changelog
## \[2.0.2]
- [`77149dc4`](https://github.com/tauri-apps/plugins-workspace/commit/77149dc4320d26b413e4a6bbe82c654367c51b32) ([#1965](https://github.com/tauri-apps/plugins-workspace/pull/1965) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Fix `writeTextFile` converting UTF-8 characters (for example `äöü`) in the given path into replacement character (`<60>`)
## \[2.0.3]
- [`14cee64c`](https://github.com/tauri-apps/plugins-workspace/commit/14cee64c82a72655ae6a4ac0892736a2959dbda5) ([#1958](https://github.com/tauri-apps/plugins-workspace/pull/1958) by [@bWanShiTong](https://github.com/tauri-apps/plugins-workspace/../../bWanShiTong)) Fix compilation on targets with pointer width of `16` or `32`

@ -34,9 +34,13 @@ thiserror = { workspace = true }
url = { workspace = true }
anyhow = "1"
uuid = { version = "1", features = ["v4"] }
glob = "0.3"
notify = { version = "6", optional = true, features = ["serde"] }
notify-debouncer-full = { version = "0.3", optional = true }
glob = { workspace = true }
# TODO: Remove `serialization-compat-6` in v3
notify = { version = "7", optional = true, features = [
"serde",
"serialization-compat-6",
] }
notify-debouncer-full = { version = "0.4", optional = true }
dunce = { workspace = true }
percent-encoding = "2"

File diff suppressed because one or more lines are too long

@ -16,10 +16,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,
},
}

@ -14,16 +14,29 @@
*
* The API has a scope configuration that forces you to restrict the paths that can be accessed using glob patterns.
*
* The scope configuration is an array of glob patterns describing folder paths that are allowed.
* For instance, this scope configuration only allows accessing files on the
* *databases* folder of the {@link https://v2.tauri.app/reference/javascript/api/namespacepath/#appdatadir | `$APPDATA` directory}:
* The scope configuration is an array of glob patterns describing file/directory paths that are allowed.
* For instance, this scope configuration allows **all** enabled `fs` APIs to (only) access files in the
* *databases* directory of the {@link https://v2.tauri.app/reference/javascript/api/namespacepath/#appdatadir | `$APPDATA` directory}:
* ```json
* {
* "plugins": {
* "fs": {
* "scope": ["$APPDATA/databases/*"]
* "permissions": [
* {
* "identifier": "fs:scope",
* "allow": [{ "path": "$APPDATA/databases/*" }]
* }
* }
* ]
* }
* ```
*
* Scopes can also be applied to specific `fs` APIs by using the API's identifier instead of `fs:scope`:
* ```json
* {
* "permissions": [
* {
* "identifier": "fs:allow-exists",
* "allow": [{ "path": "$APPDATA/databases/*" }]
* }
* ]
* }
* ```
*
@ -56,8 +69,6 @@
*
* Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
*
* Note that this scope applies to **all** APIs on this module.
*
* @module
*/
@ -1093,7 +1104,7 @@ async function writeTextFile(
await invoke('plugin:fs|write_text_file', encoder.encode(data), {
headers: {
path: path instanceof URL ? path.toString() : path,
path: encodeURIComponent(path instanceof URL ? path.toString() : path),
options: JSON.stringify(options)
}
})

@ -1,6 +1,6 @@
{
"name": "@tauri-apps/plugin-fs",
"version": "2.0.1",
"version": "2.0.2",
"description": "Access the file system.",
"license": "MIT OR Apache-2.0",
"authors": [

@ -24,6 +24,7 @@ This default permission set prevents access to critical components
of the Tauri application by default.
On Windows the webview data folder access is denied.
#### Included permissions within this default permission set:
- `create-app-specific-dirs`

@ -26,6 +26,7 @@ This default permission set prevents access to critical components
of the Tauri application by default.
On Windows the webview data folder access is denied.
#### Included permissions within this default permission set:
"""
permissions = [
"create-app-specific-dirs",

@ -1665,7 +1665,7 @@
"const": "create-app-specific-dirs"
},
{
"description": "This set of permissions describes the what kind of\nfile system access the `fs` plugin has enabled or denied by default.\n\n#### Granted Permissions\n\nThis default permission set enables read access to the\napplication specific directories (AppConfig, AppData, AppLocalData, AppCache,\nAppLog) and all files and sub directories created in it.\nThe location of these directories depends on the operating system,\nwhere the application is run.\n\nIn general these directories need to be manually created\nby the application at runtime, before accessing files or folders\nin it is possible.\n\nTherefore, it is also allowed to create all of these folders via\nthe `mkdir` command.\n\n#### Denied Permissions\n\nThis default permission set prevents access to critical components\nof the Tauri application by default.\nOn Windows the webview data folder access is denied.\n\n",
"description": "This set of permissions describes the what kind of\nfile system access the `fs` plugin has enabled or denied by default.\n\n#### Granted Permissions\n\nThis default permission set enables read access to the\napplication specific directories (AppConfig, AppData, AppLocalData, AppCache,\nAppLog) and all files and sub directories created in it.\nThe location of these directories depends on the operating system,\nwhere the application is run.\n\nIn general these directories need to be manually created\nby the application at runtime, before accessing files or folders\nin it is possible.\n\nTherefore, it is also allowed to create all of these folders via\nthe `mkdir` command.\n\n#### Denied Permissions\n\nThis default permission set prevents access to critical components\nof the Tauri application by default.\nOn Windows the webview data folder access is denied.\n\n#### Included permissions within this default permission set:\n",
"type": "string",
"const": "default"
},

@ -245,32 +245,12 @@ pub fn mkdir<R: Runtime>(
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DirEntry {
pub name: Option<String>,
pub name: String,
pub is_directory: bool,
pub is_file: bool,
pub is_symlink: bool,
}
fn read_dir_inner<P: AsRef<Path>>(path: P) -> crate::Result<Vec<DirEntry>> {
let mut files_and_dirs: Vec<DirEntry> = vec![];
for entry in std::fs::read_dir(path)? {
let path = entry?.path();
let file_type = path.metadata()?.file_type();
files_and_dirs.push(DirEntry {
is_directory: file_type.is_dir(),
is_file: file_type.is_file(),
is_symlink: std::fs::symlink_metadata(&path)
.map(|md| md.file_type().is_symlink())
.unwrap_or(false),
name: path
.file_name()
.map(|name| name.to_string_lossy())
.map(|name| name.to_string()),
});
}
Result::Ok(files_and_dirs)
}
#[tauri::command]
pub async fn read_dir<R: Runtime>(
webview: Webview<R>,
@ -287,14 +267,37 @@ pub async fn read_dir<R: Runtime>(
options.as_ref().and_then(|o| o.base_dir),
)?;
read_dir_inner(&resolved_path)
.map_err(|e| {
format!(
"failed to read directory at path: {} with error: {e}",
resolved_path.display()
)
let entries = std::fs::read_dir(&resolved_path).map_err(|e| {
format!(
"failed to read directory at path: {} with error: {e}",
resolved_path.display()
)
})?;
let entries = entries
.filter_map(|entry| {
let entry = entry.ok()?;
let name = entry.file_name().into_string().ok()?;
let metadata = entry.file_type();
macro_rules! method_or_false {
($method:ident) => {
if let Ok(metadata) = &metadata {
metadata.$method()
} else {
false
}
};
}
Some(DirEntry {
name,
is_file: method_or_false!(is_file),
is_directory: method_or_false!(is_dir),
is_symlink: method_or_false!(is_symlink),
})
})
.map_err(Into::into)
.collect();
Ok(entries)
}
#[tauri::command]

@ -2,8 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! [![](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/fs/banner.png)](https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/fs)
//!
//! Access the file system.
#![doc(

@ -3,7 +3,7 @@
// SPDX-License-Identifier: MIT
use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};
use notify_debouncer_full::{new_debouncer, DebounceEventResult, Debouncer, FileIdMap};
use notify_debouncer_full::{new_debouncer, DebounceEventResult, Debouncer, RecommendedCache};
use serde::Deserialize;
use tauri::{
ipc::{Channel, CommandScope, GlobalScope},
@ -47,7 +47,7 @@ impl WatcherResource {
impl Resource for WatcherResource {}
enum WatcherKind {
Debouncer(Debouncer<RecommendedWatcher, FileIdMap>),
Debouncer(Debouncer<RecommendedWatcher, RecommendedCache>),
Watcher(RecommendedWatcher),
}
@ -111,8 +111,7 @@ pub async fn watch<R: Runtime>(
let (tx, rx) = channel();
let mut debouncer = new_debouncer(Duration::from_millis(delay), None, tx)?;
for path in &resolved_paths {
debouncer.watcher().watch(path.as_ref(), recursive_mode)?;
debouncer.cache().add_root(path, recursive_mode);
debouncer.watch(path, recursive_mode)?;
}
watch_debounced(on_event, rx);
WatcherKind::Debouncer(debouncer)
@ -120,7 +119,7 @@ pub async fn watch<R: Runtime>(
let (tx, rx) = channel();
let mut watcher = RecommendedWatcher::new(tx, Config::default())?;
for path in &resolved_paths {
watcher.watch(path.as_ref(), recursive_mode)?;
watcher.watch(path, recursive_mode)?;
}
watch_raw(on_event, rx);
WatcherKind::Watcher(watcher)
@ -140,14 +139,14 @@ pub async fn unwatch<R: Runtime>(webview: Webview<R>, rid: ResourceId) -> Comman
match &mut watcher.kind {
WatcherKind::Debouncer(ref mut debouncer) => {
for path in &watcher.paths {
debouncer.watcher().unwatch(path.as_ref()).map_err(|e| {
debouncer.unwatch(path).map_err(|e| {
format!("failed to unwatch path: {} with error: {e}", path.display())
})?;
}
}
WatcherKind::Watcher(ref mut w) => {
for path in &watcher.paths {
w.unwatch(path.as_ref()).map_err(|e| {
w.unwatch(path).map_err(|e| {
format!("failed to unwatch path: {} with error: {e}", path.display())
})?;
}

@ -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
@ -100,7 +114,7 @@ import {
requestPermissions,
getCurrentPosition,
watchPosition
} from '@tauri-apps/plugin-log'
} from '@tauri-apps/plugin-geolocation'
let permissions = await checkPermissions()
if (

@ -1 +1 @@
if("__TAURI__"in window){var __TAURI_PLUGIN_GEOLOCATION__=function(t){"use strict";function e(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)}function n(t,e,n,i,o){if("function"==typeof e?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}var i,o,s;"function"==typeof SuppressedError&&SuppressedError;class r{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,i.set(this,(()=>{})),o.set(this,0),s.set(this,{}),this.id=function(t,e=!1){return window.__TAURI_INTERNALS__.transformCallback(t,e)}((({message:t,id:r})=>{if(r===e(this,o,"f")){n(this,o,r+1),e(this,i,"f").call(this,t);const a=Object.keys(e(this,s,"f"));if(a.length>0){let t=r+1;for(const n of a.sort()){if(parseInt(n)!==t)break;{const o=e(this,s,"f")[n];delete e(this,s,"f")[n],e(this,i,"f").call(this,o),t+=1}}n(this,o,t)}}else e(this,s,"f")[r.toString()]=t}))}set onmessage(t){n(this,i,t)}get onmessage(){return e(this,i,"f")}toJSON(){return`__CHANNEL__:${this.id}`}}async function a(t,e={},n){return window.__TAURI_INTERNALS__.invoke(t,e,n)}return i=new WeakMap,o=new WeakMap,s=new WeakMap,t.checkPermissions=async function(){return await async function(t){return a(`plugin:${t}|check_permissions`)}("geolocation")},t.clearWatch=async function(t){await a("plugin:geolocation|clear_watch",{channelId:t})},t.getCurrentPosition=async function(t){return await a("plugin:geolocation|get_current_position",{options:t})},t.requestPermissions=async function(t){return await a("plugin:geolocation|request_permissions",{permissions:t})},t.watchPosition=async function(t,e){const n=new r;return n.onmessage=t=>{"string"==typeof t?e(null,t):e(t)},await a("plugin:geolocation|watch_position",{options:t,channel:n}),n.id},t}({});Object.defineProperty(window.__TAURI__,"geolocation",{value:__TAURI_PLUGIN_GEOLOCATION__})}
if("__TAURI__"in window){var __TAURI_PLUGIN_GEOLOCATION__=function(t){"use strict";function e(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)}function n(t,e,n,i,o){if("function"==typeof e?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}var i,o,s;"function"==typeof SuppressedError&&SuppressedError;const r="__TAURI_TO_IPC_KEY__";class a{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,i.set(this,(()=>{})),o.set(this,0),s.set(this,{}),this.id=function(t,e=!1){return window.__TAURI_INTERNALS__.transformCallback(t,e)}((({message:t,id:r})=>{if(r===e(this,o,"f")){n(this,o,r+1),e(this,i,"f").call(this,t);const a=Object.keys(e(this,s,"f"));if(a.length>0){let t=r+1;for(const n of a.sort()){if(parseInt(n)!==t)break;{const o=e(this,s,"f")[n];delete e(this,s,"f")[n],e(this,i,"f").call(this,o),t+=1}}n(this,o,t)}}else e(this,s,"f")[r.toString()]=t}))}set onmessage(t){n(this,i,t)}get onmessage(){return e(this,i,"f")}[(i=new WeakMap,o=new WeakMap,s=new WeakMap,r)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[r]()}}async function c(t,e={},n){return window.__TAURI_INTERNALS__.invoke(t,e,n)}return t.checkPermissions=async function(){return await async function(t){return c(`plugin:${t}|check_permissions`)}("geolocation")},t.clearWatch=async function(t){await c("plugin:geolocation|clear_watch",{channelId:t})},t.getCurrentPosition=async function(t){return await c("plugin:geolocation|get_current_position",{options:t})},t.requestPermissions=async function(t){return await c("plugin:geolocation|request_permissions",{permissions:t})},t.watchPosition=async function(t,e){const n=new a;return n.onmessage=t=>{"string"==typeof t?e(null,t):e(t)},await c("plugin:geolocation|watch_position",{options:t,channel:n}),n.id},t}({});Object.defineProperty(window.__TAURI__,"geolocation",{value:__TAURI_PLUGIN_GEOLOCATION__})}

@ -1 +1 @@
if("__TAURI__"in window){var __TAURI_PLUGIN_GLOBAL_SHORTCUT__=function(t){"use strict";function e(t,e,r,s){if("a"===r&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?s:"a"===r?s.call(t):s?s.value:e.get(t)}function r(t,e,r,s,n){if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,r),r}var s,n,i;"function"==typeof SuppressedError&&SuppressedError;class o{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,s.set(this,(()=>{})),n.set(this,0),i.set(this,{}),this.id=function(t,e=!1){return window.__TAURI_INTERNALS__.transformCallback(t,e)}((({message:t,id:o})=>{if(o===e(this,n,"f")){r(this,n,o+1),e(this,s,"f").call(this,t);const a=Object.keys(e(this,i,"f"));if(a.length>0){let t=o+1;for(const r of a.sort()){if(parseInt(r)!==t)break;{const n=e(this,i,"f")[r];delete e(this,i,"f")[r],e(this,s,"f").call(this,n),t+=1}}r(this,n,t)}}else e(this,i,"f")[o.toString()]=t}))}set onmessage(t){r(this,s,t)}get onmessage(){return e(this,s,"f")}toJSON(){return`__CHANNEL__:${this.id}`}}async function a(t,e={},r){return window.__TAURI_INTERNALS__.invoke(t,e,r)}return s=new WeakMap,n=new WeakMap,i=new WeakMap,t.isRegistered=async function(t){return await a("plugin:global-shortcut|is_registered",{shortcut:t})},t.register=async function(t,e){const r=new o;return r.onmessage=e,await a("plugin:global-shortcut|register",{shortcuts:Array.isArray(t)?t:[t],handler:r})},t.unregister=async function(t){return await a("plugin:global-shortcut|unregister",{shortcuts:Array.isArray(t)?t:[t]})},t.unregisterAll=async function(){return await a("plugin:global-shortcut|unregister_all",{})},t}({});Object.defineProperty(window.__TAURI__,"globalShortcut",{value:__TAURI_PLUGIN_GLOBAL_SHORTCUT__})}
if("__TAURI__"in window){var __TAURI_PLUGIN_GLOBAL_SHORTCUT__=function(t){"use strict";function e(t,e,r,s){if("a"===r&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?s:"a"===r?s.call(t):s?s.value:e.get(t)}function r(t,e,r,s,n){if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,r),r}var s,n,i;"function"==typeof SuppressedError&&SuppressedError;const o="__TAURI_TO_IPC_KEY__";class a{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,s.set(this,(()=>{})),n.set(this,0),i.set(this,{}),this.id=function(t,e=!1){return window.__TAURI_INTERNALS__.transformCallback(t,e)}((({message:t,id:o})=>{if(o===e(this,n,"f")){r(this,n,o+1),e(this,s,"f").call(this,t);const a=Object.keys(e(this,i,"f"));if(a.length>0){let t=o+1;for(const r of a.sort()){if(parseInt(r)!==t)break;{const n=e(this,i,"f")[r];delete e(this,i,"f")[r],e(this,s,"f").call(this,n),t+=1}}r(this,n,t)}}else e(this,i,"f")[o.toString()]=t}))}set onmessage(t){r(this,s,t)}get onmessage(){return e(this,s,"f")}[(s=new WeakMap,n=new WeakMap,i=new WeakMap,o)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[o]()}}async function _(t,e={},r){return window.__TAURI_INTERNALS__.invoke(t,e,r)}return t.isRegistered=async function(t){return await _("plugin:global-shortcut|is_registered",{shortcut:t})},t.register=async function(t,e){const r=new a;return r.onmessage=e,await _("plugin:global-shortcut|register",{shortcuts:Array.isArray(t)?t:[t],handler:r})},t.unregister=async function(t){return await _("plugin:global-shortcut|unregister",{shortcuts:Array.isArray(t)?t:[t]})},t.unregisterAll=async function(){return await _("plugin:global-shortcut|unregister_all",{})},t}({});Object.defineProperty(window.__TAURI__,"globalShortcut",{value:__TAURI_PLUGIN_GLOBAL_SHORTCUT__})}

@ -2,8 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! [![](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/global-shortcut/banner.png)](https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/global-shortcut)
//!
//! Register global shortcuts.
//!
//! - Supported platforms: Windows, Linux and macOS.

@ -191,6 +191,11 @@ pub async fn fetch<R: Runtime>(
let name = HeaderName::from_str(&h)?;
#[cfg(not(feature = "unsafe-headers"))]
if is_unsafe_header(&name) {
#[cfg(debug_assertions)]
{
eprintln!("[\x1b[33mWARNING\x1b[0m] Skipping {name} header as it is a forbidden header per fetch spec https://fetch.spec.whatwg.org/#terminology-headers");
eprintln!("[\x1b[33mWARNING\x1b[0m] if keeping the header is a desired behavior, you can enable `unsafe-headers` feature flag in your Cargo.toml");
}
continue;
}

@ -2,8 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! [![](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/http/banner.png)](https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/http)
//!
//! Access the HTTP client written in Rust.
pub use reqwest;

@ -2,8 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! [![](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/localhost/banner.png)](https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/localhost)
//!
//! Expose your apps assets through a localhost server instead of the default custom protocol.
//!
//! **Note: This plugins brings considerable security risks and you should only use it if you know what your are doing. If in doubt, use the default custom protocol implementation.**
@ -46,6 +44,7 @@ type OnRequest = Option<Box<dyn Fn(&Request, &mut Response) + Send + Sync>>;
pub struct Builder {
port: u16,
host: Option<String>,
on_request: OnRequest,
}
@ -53,10 +52,17 @@ impl Builder {
pub fn new(port: u16) -> Self {
Self {
port,
host: None,
on_request: None,
}
}
// Change the host the plugin binds to. Defaults to `localhost`.
pub fn host<H: Into<String>>(mut self, host: H) -> Self {
self.host = Some(host.into());
self
}
pub fn on_request<F: Fn(&Request, &mut Response) + Send + Sync + 'static>(
mut self,
f: F,
@ -67,6 +73,7 @@ impl Builder {
pub fn build<R: Runtime>(mut self) -> TauriPlugin<R> {
let port = self.port;
let host = self.host.unwrap_or("localhost".to_string());
let on_request = self.on_request.take();
PluginBuilder::new("localhost")
@ -74,7 +81,7 @@ impl Builder {
let asset_resolver = app.asset_resolver();
std::thread::spawn(move || {
let server =
Server::http(format!("localhost:{port}")).expect("Unable to spawn server");
Server::http(format!("{host}:{port}")).expect("Unable to spawn server");
for req in server.incoming_requests() {
let path = req
.url()

@ -1,5 +1,9 @@
# Changelog
## \[2.0.2]
- [`606fa08d`](https://github.com/tauri-apps/plugins-workspace/commit/606fa08dae1acd074b961fb360623f4c86f13ee8) ([#1997](https://github.com/tauri-apps/plugins-workspace/pull/1997) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) **Potentially breaking:** Updated `fern` from 0.6 to 0.7. This is technically a breaking change because `fern` is re-exported in `tauri-plugin-log`.
## \[2.0.1]
- [`a1a82208`](https://github.com/tauri-apps/plugins-workspace/commit/a1a82208ed4ab87f83310be0dc95428aec9ab241) ([#1873](https://github.com/tauri-apps/plugins-workspace/pull/1873) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Downgrade MSRV to 1.77.2 to support Windows 7.

@ -1,6 +1,6 @@
[package]
name = "tauri-plugin-log"
version = "2.0.1"
version = "2.0.2"
description = "Configurable logging for your Tauri app."
authors = { workspace = true }
license = { workspace = true }
@ -27,12 +27,12 @@ tauri-plugin = { workspace = true, features = ["build"] }
serde = { workspace = true }
serde_json = { workspace = true }
tauri = { workspace = true }
thiserror = { workspace = true }
serde_repr = "0.1"
byte-unit = "5"
log = { workspace = true, features = ["kv_unstable"] }
time = { version = "0.3", features = ["formatting", "local-offset"] }
fern = "0.6"
thiserror = "1"
fern = "0.7"
[target."cfg(target_os = \"android\")".dependencies]
android_logger = "0.14"

@ -1 +1 @@
if("__TAURI__"in window){var __TAURI_PLUGIN_LOG__=function(e){"use strict";function n(e,n=!1){return window.__TAURI_INTERNALS__.transformCallback(e,n)}async function r(e,n={},r){return window.__TAURI_INTERNALS__.invoke(e,n,r)}var a,t;async function o(e,a,t){const o={kind:"Any"};return r("plugin:event|listen",{event:e,target:o,handler:n(a)}).then((n=>async()=>async function(e,n){await r("plugin:event|unlisten",{event:e,eventId:n})}(e,n)))}async function i(e,n,a){const t=(new Error).stack?.split("\n").map((e=>e.split("@"))),o=t?.filter((([e,n])=>e.length>0&&"[native code]"!==n)),{file:i,line:c,keyValues:u}=a??{};let l=o?.[0]?.filter((e=>e.length>0)).join("@");"Error"===l&&(l="webview::unknown"),await r("plugin:log|log",{level:e,message:n,location:l,file:i,line:c,keyValues:u})}async function c(e){return await o("log://log",(n=>{const{level:r}=n.payload;let{message:a}=n.payload;a=a.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),e({message:a,level:r})}))}return"function"==typeof SuppressedError&&SuppressedError,function(e){e.WINDOW_RESIZED="tauri://resize",e.WINDOW_MOVED="tauri://move",e.WINDOW_CLOSE_REQUESTED="tauri://close-requested",e.WINDOW_DESTROYED="tauri://destroyed",e.WINDOW_FOCUS="tauri://focus",e.WINDOW_BLUR="tauri://blur",e.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",e.WINDOW_THEME_CHANGED="tauri://theme-changed",e.WINDOW_CREATED="tauri://window-created",e.WEBVIEW_CREATED="tauri://webview-created",e.DRAG_ENTER="tauri://drag-enter",e.DRAG_OVER="tauri://drag-over",e.DRAG_DROP="tauri://drag-drop",e.DRAG_LEAVE="tauri://drag-leave"}(a||(a={})),function(e){e[e.Trace=1]="Trace",e[e.Debug=2]="Debug",e[e.Info=3]="Info",e[e.Warn=4]="Warn",e[e.Error=5]="Error"}(t||(t={})),e.attachConsole=async function(){return await c((({level:e,message:n})=>{switch(e){case t.Trace:console.log(n);break;case t.Debug:console.debug(n);break;case t.Info:console.info(n);break;case t.Warn:console.warn(n);break;case t.Error:console.error(n);break;default:throw new Error(`unknown log level ${e}`)}}))},e.attachLogger=c,e.debug=async function(e,n){await i(t.Debug,e,n)},e.error=async function(e,n){await i(t.Error,e,n)},e.info=async function(e,n){await i(t.Info,e,n)},e.trace=async function(e,n){await i(t.Trace,e,n)},e.warn=async function(e,n){await i(t.Warn,e,n)},e}({});Object.defineProperty(window.__TAURI__,"log",{value:__TAURI_PLUGIN_LOG__})}
if("__TAURI__"in window){var __TAURI_PLUGIN_LOG__=function(e){"use strict";function n(e,n=!1){return window.__TAURI_INTERNALS__.transformCallback(e,n)}async function r(e,n={},r){return window.__TAURI_INTERNALS__.invoke(e,n,r)}var a,t;async function o(e,a,t){const o={kind:"Any"};return r("plugin:event|listen",{event:e,target:o,handler:n(a)}).then((n=>async()=>async function(e,n){await r("plugin:event|unlisten",{event:e,eventId:n})}(e,n)))}async function i(e,n,a){const t=function(e){if(e){if(!e.startsWith("Error"))return e.split("\n").map((e=>e.split("@"))).filter((([e,n])=>e.length>0&&"[native code]"!==n))[2].filter((e=>e.length>0)).join("@");{const n=e.split("\n")[3].trim(),r=/at\s+(?<functionName>.*?)\s+\((?<fileName>.*?):(?<lineNumber>\d+):(?<columnNumber>\d+)\)/,a=n.match(r);if(a){const{functionName:e,fileName:n,lineNumber:r,columnNumber:t}=a.groups;return`${e}@${n}:${r}:${t}`}{const e=/at\s+(?<fileName>.*?):(?<lineNumber>\d+):(?<columnNumber>\d+)/,r=n.match(e);if(r){const{fileName:e,lineNumber:n,columnNumber:a}=r.groups;return`<anonymous>@${e}:${n}:${a}`}}}}}((new Error).stack),{file:o,line:i,keyValues:u}=a??{};await r("plugin:log|log",{level:e,message:n,location:t,file:o,line:i,keyValues:u})}async function u(e){return await o("log://log",(n=>{const{level:r}=n.payload;let{message:a}=n.payload;a=a.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),e({message:a,level:r})}))}return"function"==typeof SuppressedError&&SuppressedError,function(e){e.WINDOW_RESIZED="tauri://resize",e.WINDOW_MOVED="tauri://move",e.WINDOW_CLOSE_REQUESTED="tauri://close-requested",e.WINDOW_DESTROYED="tauri://destroyed",e.WINDOW_FOCUS="tauri://focus",e.WINDOW_BLUR="tauri://blur",e.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",e.WINDOW_THEME_CHANGED="tauri://theme-changed",e.WINDOW_CREATED="tauri://window-created",e.WEBVIEW_CREATED="tauri://webview-created",e.DRAG_ENTER="tauri://drag-enter",e.DRAG_OVER="tauri://drag-over",e.DRAG_DROP="tauri://drag-drop",e.DRAG_LEAVE="tauri://drag-leave"}(a||(a={})),function(e){e[e.Trace=1]="Trace",e[e.Debug=2]="Debug",e[e.Info=3]="Info",e[e.Warn=4]="Warn",e[e.Error=5]="Error"}(t||(t={})),e.attachConsole=async function(){return await u((({level:e,message:n})=>{switch(e){case t.Trace:console.log(n);break;case t.Debug:console.debug(n);break;case t.Info:console.info(n);break;case t.Warn:console.warn(n);break;case t.Error:console.error(n);break;default:throw new Error(`unknown log level ${e}`)}}))},e.attachLogger=u,e.debug=async function(e,n){await i(t.Debug,e,n)},e.error=async function(e,n){await i(t.Error,e,n)},e.info=async function(e,n){await i(t.Info,e,n)},e.trace=async function(e,n){await i(t.Trace,e,n)},e.warn=async function(e,n){await i(t.Warn,e,n)},e}({});Object.defineProperty(window.__TAURI__,"log",{value:__TAURI_PLUGIN_LOG__})}

@ -44,24 +44,78 @@ enum LogLevel {
Error
}
function getCallerLocation(stack?: string) {
if (!stack) {
return
}
if (stack.startsWith('Error')) {
// Assume it's Chromium V8
//
// Error
// at baz (filename.js:10:15)
// at bar (filename.js:6:3)
// at foo (filename.js:2:3)
// at filename.js:13:1
const lines = stack.split('\n')
// Find the third line (caller's caller of the current location)
const callerLine = lines[3].trim()
const regex =
/at\s+(?<functionName>.*?)\s+\((?<fileName>.*?):(?<lineNumber>\d+):(?<columnNumber>\d+)\)/
const match = callerLine.match(regex)
if (match) {
const { functionName, fileName, lineNumber, columnNumber } =
match.groups as {
functionName: string
fileName: string
lineNumber: string
columnNumber: string
}
return `${functionName}@${fileName}:${lineNumber}:${columnNumber}`
} else {
// Handle cases where the regex does not match (e.g., last line without function name)
const regexNoFunction =
/at\s+(?<fileName>.*?):(?<lineNumber>\d+):(?<columnNumber>\d+)/
const matchNoFunction = callerLine.match(regexNoFunction)
if (matchNoFunction) {
const { fileName, lineNumber, columnNumber } =
matchNoFunction.groups as {
fileName: string
lineNumber: string
columnNumber: string
}
return `<anonymous>@${fileName}:${lineNumber}:${columnNumber}`
}
}
} else {
// Assume it's Webkit JavaScriptCore, example:
//
// baz@filename.js:10:24
// bar@filename.js:6:6
// foo@filename.js:2:6
// global code@filename.js:13:4
const traces = stack.split('\n').map((line) => line.split('@'))
const filtered = traces.filter(([name, location]) => {
return name.length > 0 && location !== '[native code]'
})
// Find the third line (caller's caller of the current location)
return filtered[2].filter((v) => v.length > 0).join('@')
}
}
async function log(
level: LogLevel,
message: string,
options?: LogOptions
): Promise<void> {
const traces = new Error().stack?.split('\n').map((line) => line.split('@'))
const filtered = traces?.filter(([name, location]) => {
return name.length > 0 && location !== '[native code]'
})
const location = getCallerLocation(new Error().stack)
const { file, line, keyValues } = options ?? {}
let location = filtered?.[0]?.filter((v) => v.length > 0).join('@')
if (location === 'Error') {
location = 'webview::unknown'
}
await invoke('plugin:log|log', {
level,
message,

@ -2,8 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! [![](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/log/banner.png)](https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/log)
//!
//! Logging for Tauri applications.
#![doc(
@ -33,7 +31,7 @@ use tauri::{AppHandle, Emitter};
pub use fern;
use time::OffsetDateTime;
pub const WEBVIEW_TARGET: &str = "Webview";
pub const WEBVIEW_TARGET: &str = "webview";
#[cfg(target_os = "ios")]
mod ios {
@ -230,22 +228,16 @@ fn log(
line: Option<u32>,
key_values: Option<HashMap<String, String>>,
) {
let location = location.unwrap_or("webview");
let level = log::Level::from(level);
let metadata = log::MetadataBuilder::new()
.level(level)
.target(WEBVIEW_TARGET)
.build();
let target = if let Some(location) = location {
format!("{WEBVIEW_TARGET}:{location}")
} else {
WEBVIEW_TARGET.to_string()
};
let mut builder = RecordBuilder::new();
builder
.level(level)
.metadata(metadata)
.target(location)
.file(file)
.line(line);
builder.level(level).target(&target).file(file).line(line);
let key_values = key_values.unwrap_or_default();
let mut kv = HashMap::new();
@ -380,8 +372,8 @@ impl Builder {
/// .clear_targets()
/// .targets([
/// Target::new(TargetKind::Webview),
/// Target::new(TargetKind::LogDir { file_name: Some("webview".into()) }).filter(|metadata| metadata.target() == WEBVIEW_TARGET),
/// Target::new(TargetKind::LogDir { file_name: Some("rust".into()) }).filter(|metadata| metadata.target() != WEBVIEW_TARGET),
/// Target::new(TargetKind::LogDir { file_name: Some("webview".into()) }).filter(|metadata| metadata.target().starts_with(WEBVIEW_TARGET)),
/// Target::new(TargetKind::LogDir { file_name: Some("rust".into()) }).filter(|metadata| !metadata.target().starts_with(WEBVIEW_TARGET)),
/// ]);
/// ```
pub fn targets(mut self, targets: impl IntoIterator<Item = Target>) -> Self {

@ -1 +1 @@
if("__TAURI__"in window){var __TAURI_PLUGIN_NOTIFICATION__=function(i){"use strict";function t(i,t,n,e){if("a"===n&&!e)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?i!==t||!e:!t.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?e:"a"===n?e.call(i):e?e.value:t.get(i)}function n(i,t,n,e,o){if("function"==typeof t?i!==t||!o:!t.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(i,n),n}var e,o,a,r,c,s;"function"==typeof SuppressedError&&SuppressedError;class l{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,e.set(this,(()=>{})),o.set(this,0),a.set(this,{}),this.id=function(i,t=!1){return window.__TAURI_INTERNALS__.transformCallback(i,t)}((({message:i,id:r})=>{if(r===t(this,o,"f")){n(this,o,r+1),t(this,e,"f").call(this,i);const c=Object.keys(t(this,a,"f"));if(c.length>0){let i=r+1;for(const n of c.sort()){if(parseInt(n)!==i)break;{const o=t(this,a,"f")[n];delete t(this,a,"f")[n],t(this,e,"f").call(this,o),i+=1}}n(this,o,i)}}else t(this,a,"f")[r.toString()]=i}))}set onmessage(i){n(this,e,i)}get onmessage(){return t(this,e,"f")}toJSON(){return`__CHANNEL__:${this.id}`}}e=new WeakMap,o=new WeakMap,a=new WeakMap;class u{constructor(i,t,n){this.plugin=i,this.event=t,this.channelId=n}async unregister(){return d(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}}async function f(i,t,n){const e=new l;return e.onmessage=n,d(`plugin:${i}|register_listener`,{event:t,handler:e}).then((()=>new u(i,t,e.id)))}async function d(i,t={},n){return window.__TAURI_INTERNALS__.invoke(i,t,n)}i.ScheduleEvery=void 0,(r=i.ScheduleEvery||(i.ScheduleEvery={})).Year="year",r.Month="month",r.TwoWeeks="twoWeeks",r.Week="week",r.Day="day",r.Hour="hour",r.Minute="minute",r.Second="second";return i.Importance=void 0,(c=i.Importance||(i.Importance={}))[c.None=0]="None",c[c.Min=1]="Min",c[c.Low=2]="Low",c[c.Default=3]="Default",c[c.High=4]="High",i.Visibility=void 0,(s=i.Visibility||(i.Visibility={}))[s.Secret=-1]="Secret",s[s.Private=0]="Private",s[s.Public=1]="Public",i.Schedule=class{static at(i,t=!1,n=!1){return{at:{date:i,repeating:t,allowWhileIdle:n},interval:void 0,every:void 0}}static interval(i,t=!1){return{at:void 0,interval:{interval:i,allowWhileIdle:t},every:void 0}}static every(i,t,n=!1){return{at:void 0,interval:void 0,every:{interval:i,count:t,allowWhileIdle:n}}}},i.active=async function(){return await d("plugin:notification|get_active")},i.cancel=async function(i){await d("plugin:notification|cancel",{notifications:i})},i.cancelAll=async function(){await d("plugin:notification|cancel")},i.channels=async function(){return await d("plugin:notification|listChannels")},i.createChannel=async function(i){await d("plugin:notification|create_channel",{...i})},i.isPermissionGranted=async function(){return"default"!==window.Notification.permission?await Promise.resolve("granted"===window.Notification.permission):await d("plugin:notification|is_permission_granted")},i.onAction=async function(i){return await f("notification","actionPerformed",i)},i.onNotificationReceived=async function(i){return await f("notification","notification",i)},i.pending=async function(){return await d("plugin:notification|get_pending")},i.registerActionTypes=async function(i){await d("plugin:notification|register_action_types",{types:i})},i.removeActive=async function(i){await d("plugin:notification|remove_active",{notifications:i})},i.removeAllActive=async function(){await d("plugin:notification|remove_active")},i.removeChannel=async function(i){await d("plugin:notification|delete_channel",{id:i})},i.requestPermission=async function(){return await window.Notification.requestPermission()},i.sendNotification=function(i){"string"==typeof i?new window.Notification(i):new window.Notification(i.title,i)},i}({});Object.defineProperty(window.__TAURI__,"notification",{value:__TAURI_PLUGIN_NOTIFICATION__})}
if("__TAURI__"in window){var __TAURI_PLUGIN_NOTIFICATION__=function(i){"use strict";function t(i,t,n,e){if("a"===n&&!e)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?i!==t||!e:!t.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?e:"a"===n?e.call(i):e?e.value:t.get(i)}function n(i,t,n,e,o){if("function"==typeof t?i!==t||!o:!t.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(i,n),n}var e,o,a;"function"==typeof SuppressedError&&SuppressedError;const r="__TAURI_TO_IPC_KEY__";class c{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,e.set(this,(()=>{})),o.set(this,0),a.set(this,{}),this.id=function(i,t=!1){return window.__TAURI_INTERNALS__.transformCallback(i,t)}((({message:i,id:r})=>{if(r===t(this,o,"f")){n(this,o,r+1),t(this,e,"f").call(this,i);const c=Object.keys(t(this,a,"f"));if(c.length>0){let i=r+1;for(const n of c.sort()){if(parseInt(n)!==i)break;{const o=t(this,a,"f")[n];delete t(this,a,"f")[n],t(this,e,"f").call(this,o),i+=1}}n(this,o,i)}}else t(this,a,"f")[r.toString()]=i}))}set onmessage(i){n(this,e,i)}get onmessage(){return t(this,e,"f")}[(e=new WeakMap,o=new WeakMap,a=new WeakMap,r)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[r]()}}class s{constructor(i,t,n){this.plugin=i,this.event=t,this.channelId=n}async unregister(){return u(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}}async function l(i,t,n){const e=new c;return e.onmessage=n,u(`plugin:${i}|registerListener`,{event:t,handler:e}).then((()=>new s(i,t,e.id)))}async function u(i,t={},n){return window.__TAURI_INTERNALS__.invoke(i,t,n)}var f,d,w;i.ScheduleEvery=void 0,(f=i.ScheduleEvery||(i.ScheduleEvery={})).Year="year",f.Month="month",f.TwoWeeks="twoWeeks",f.Week="week",f.Day="day",f.Hour="hour",f.Minute="minute",f.Second="second";return i.Importance=void 0,(d=i.Importance||(i.Importance={}))[d.None=0]="None",d[d.Min=1]="Min",d[d.Low=2]="Low",d[d.Default=3]="Default",d[d.High=4]="High",i.Visibility=void 0,(w=i.Visibility||(i.Visibility={}))[w.Secret=-1]="Secret",w[w.Private=0]="Private",w[w.Public=1]="Public",i.Schedule=class{static at(i,t=!1,n=!1){return{at:{date:i,repeating:t,allowWhileIdle:n},interval:void 0,every:void 0}}static interval(i,t=!1){return{at:void 0,interval:{interval:i,allowWhileIdle:t},every:void 0}}static every(i,t,n=!1){return{at:void 0,interval:void 0,every:{interval:i,count:t,allowWhileIdle:n}}}},i.active=async function(){return await u("plugin:notification|get_active")},i.cancel=async function(i){await u("plugin:notification|cancel",{notifications:i})},i.cancelAll=async function(){await u("plugin:notification|cancel")},i.channels=async function(){return await u("plugin:notification|listChannels")},i.createChannel=async function(i){await u("plugin:notification|create_channel",{...i})},i.isPermissionGranted=async function(){return"default"!==window.Notification.permission?await Promise.resolve("granted"===window.Notification.permission):await u("plugin:notification|is_permission_granted")},i.onAction=async function(i){return await l("notification","actionPerformed",i)},i.onNotificationReceived=async function(i){return await l("notification","notification",i)},i.pending=async function(){return await u("plugin:notification|get_pending")},i.registerActionTypes=async function(i){await u("plugin:notification|register_action_types",{types:i})},i.removeActive=async function(i){await u("plugin:notification|remove_active",{notifications:i})},i.removeAllActive=async function(){await u("plugin:notification|remove_active")},i.removeChannel=async function(i){await u("plugin:notification|delete_channel",{id:i})},i.requestPermission=async function(){return await window.Notification.requestPermission()},i.sendNotification=function(i){"string"==typeof i?new window.Notification(i):new window.Notification(i.title,i)},i}({});Object.defineProperty(window.__TAURI__,"notification",{value:__TAURI_PLUGIN_NOTIFICATION__})}

@ -2,8 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! [![](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/notification/banner.png)](https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/notification)
//!
//! Send message notifications (brief auto-expiring OS window element) to your user. Can also be used with the Notification Web API.
#![doc(

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

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

Loading…
Cancel
Save