Revert "chore(deps) Update dependency @types/imagemin to v8 (#2635)"

This reverts commit c0285e873d.
This commit is contained in:
renovate[bot] 2021-09-29 11:05:33 -03:00 committed by Lucas Nogueira
parent c0285e873d
commit ca30dbe2cc
No known key found for this signature in database
GPG Key ID: 2714B66BCFB01F7F
208 changed files with 6183 additions and 5662 deletions

View File

@ -1,5 +0,0 @@
---
"api": patch
---
Remove `.ts` files on the published package.

View File

@ -1,6 +0,0 @@
---
"api": patch
---
`WindowManager` methods `innerPosition` `outerPosition` now correctly return instance of `PhysicalPosition`.
`WindowManager` methods `innerSize` `outerSize` now correctly return instance of `PhysicalSize`.

View File

@ -1,6 +0,0 @@
---
"cli.js": patch
"cli.rs": patch
---
Do not force Tauri application code on `src-tauri` folder and use a glob pattern to look for a subfolder with a `tauri.conf.json` file.

View File

@ -1,5 +0,0 @@
---
"cli.rs": patch
---
Define `PLATFORM`, `ARCH`, `FAMILY` and `PLATFORM_TYPE` environment variables for the `beforeDevCommand` and `beforeBuildCommand` scripts.

View File

@ -1,5 +0,0 @@
---
"tauri": patch
---
Change `Error::ParseCliArguments(clap::Error)` to `Error::ParseCliArguments(String)` because `clap::Error` is not `Send`.

View File

@ -1,5 +0,0 @@
---
"tauri-utils": patch
---
Change `CliArg` numeric types from `u64` to `usize`.

View File

@ -1,5 +0,0 @@
---
"cli.js": patch
---
Added CommonJS output to the `dist` folder.

View File

@ -1,5 +0,0 @@
---
"cli.rs": patch
---
Add `Visual Studio Build Tools` installed versions to the `info` command output.

View File

@ -1,6 +0,0 @@
---
"tauri": patch
"api": patch
---
Now `resolve()`, `join()` and `normalize()` from the `path` module, won't throw errors if the path doesn't exist, which matches NodeJS behavior.

View File

@ -1,5 +0,0 @@
---
"create-tauri-app": patch
---
Add empty description to Cargo.toml in dominator recipe.

View File

@ -1,5 +0,0 @@
---
'create-tauri-app': patch
---
Add SolidJS recipe using the official template.

View File

@ -1,6 +0,0 @@
---
"tauri-runtime-wry": patch
"tauri": patch
---
Fixes `WindowEvent::Focus` and `WindowEvent::Blur` events not firing.

View File

@ -1,5 +0,0 @@
---
"tauri": patch
---
Fixes `tauri://focus` and `tauri://blur` events not firing.

View File

@ -1,6 +0,0 @@
---
"tauri-utils": patch
"tauri": patch
---
Fixes resource directory resolution on Linux.

View File

@ -1,5 +0,0 @@
---
"cli.rs": patch
---
Fixes output directory detection when using Cargo workspaces.

View File

@ -1,5 +0,0 @@
---
"tauri": patch
---
Initialize system tray before windows so `tray_handle` can be accessed on command handlers.

View File

@ -1,6 +0,0 @@
---
"tauri": patch
"tauri-runtime-wry": patch
---
Allow window, global shortcut and clipboard APIs to be called on the main thread.

View File

@ -1,7 +0,0 @@
---
"tauri-runtime-wry": minor
"tauri-runtime": minor
"tauri": minor
---
Change event loop callbacks definition to allow callers to move in mutable values.

View File

@ -1,5 +0,0 @@
---
"cli.rs": patch
---
Added `$ tauri init plugin` command, which initializes a Tauri plugin.

View File

@ -1,5 +0,0 @@
---
"tauri": patch
---
Added `on_event` on the `Plugin` trait, which allows a plugin to react to the event loop.

View File

@ -1,6 +0,0 @@
---
"tauri-runtime-wry": patch
"tauri": patch
---
Refactor `create_tao_window` API to return `Weak<Window>` instead of `Arc<Window>`.

View File

@ -1,5 +0,0 @@
---
"api": patch
---
Change `WindowLabel` type to `string`.

View File

@ -1,5 +0,0 @@
---
'cli.rs': patch
---
Fixes pnpm error when running `pnpm tauri info`.

View File

@ -1,5 +0,0 @@
---
"tauri": patch
---
Adds `unlisten` function to the `Window` struct.

View File

@ -1,7 +0,0 @@
---
"tauri": patch
"tauri-runtime": patch
"tauri-runtime-wry": patch
---
Replace all of the `winapi` crate references with the `windows` crate, and replace `webview2` and `webview2-sys` with `webview2-com` and `webview2-com-sys` built with the `windows` crate. This goes along with updates to the TAO and WRY `next` branches.

View File

@ -1,6 +0,0 @@
---
"tauri-runtime-wry": patch
---
This is a temporary fix of null pointer crash on `get_content` of web resource request.
We will switch it back once upstream is updated.

View File

@ -1,5 +0,0 @@
---
"tauri-bundler": patch
---
Fix registry keys on the WiX template.

View File

@ -2,7 +2,7 @@
name: Bug report
about: Create a report to help us improve Tauri
title: ''
labels: 'type: bug'
labels: bug
assignees: ''
---

View File

@ -2,7 +2,7 @@
name: Docs report
about: Create a report to help us improve Tauri docs
title: "[docs]"
labels: 'type: documentation'
labels: docs
assignees: ''
---

View File

@ -2,7 +2,7 @@
name: Feature request
about: Suggest an idea for Tauri
title: ''
labels: 'type: feature request'
labels: feature request
assignees: ''
---

View File

@ -83,7 +83,7 @@ jobs:
with:
path: tooling/cli.rs/target
# Add date to the cache to keep it up to date
key: ${{ matrix.platform }}-stable-cargo-cli-${{ hashFiles('tooling/cli.rs/Cargo.lock') }}-${{ env.CURRENT_DATE }}
key: ubuntu-latest-nightly-cargo-cli-${{ hashFiles('tooling/cli.rs/Cargo.lock') }}-${{ env.CURRENT_DATE }}
# Restore from outdated cache for speed
restore-keys: |
${{ matrix.platform }}-stable-cargo-cli-${{ hashFiles('tooling/cli.rs/Cargo.lock') }}
@ -136,14 +136,14 @@ jobs:
if: matrix.platform == 'ubuntu-latest'
with:
name: linux-updater-artifacts
path: ./examples/updater/src-tauri/target/release/bundle/appimage/updater-example_*.AppImage.*
path: ./target/release/bundle/appimage/updater-example_*.AppImage.*
- uses: actions/upload-artifact@v2
if: matrix.platform == 'windows-latest'
with:
name: windows-updater-artifacts
path: ./examples/updater/src-tauri/target/release/bundle/msi/*
path: ./target/release/bundle/msi/*
- uses: actions/upload-artifact@v2
if: matrix.platform == 'macos-latest'
with:
name: macos-updater-artifacts
path: ./examples/updater/src-tauri/target/release/bundle/macos/updater-example.app.tar.*
path: ./target/release/bundle/macos/updater-example.app.tar.*

View File

@ -4,7 +4,6 @@ on:
push:
branches:
- dev
- next
workflow_dispatch:
jobs:
@ -84,7 +83,7 @@ jobs:
with:
path: tooling/bench/tests/target
# Add date to the cache to keep it up to date
key: ${{ matrix.platform }}-nightly-cargo-benches-${{ hashFiles('tooling/bench/tests/Cargo.lock') }}-${{ env.CURRENT_DATE }}
key: ubuntu-latest-nightly-cargo-benches-${{ hashFiles('tooling/bench/tests/Cargo.lock') }}-${{ env.CURRENT_DATE }}
# Restore from outdated cache for speed
restore-keys: |
${{ matrix.platform }}-nightly-cargo-benches-${{ hashFiles('tooling/bench/tests/Cargo.lock') }}

View File

@ -72,7 +72,7 @@ jobs:
with:
path: tooling/bundler/target
# Add date to the cache to keep it up to date
key: ${{ matrix.platform }}-stable-cargo-bundler-${{ hashFiles('tooling/bundler/Cargo.lock') }}-${{ env.CURRENT_DATE }}
key: ubuntu-latest-stable-cargo-bundler-${{ hashFiles('tooling/bundler/Cargo.lock') }}-${{ env.CURRENT_DATE }}
# Restore from outdated cache for speed
restore-keys: |
${{ matrix.platform }}-stable-cargo-bundler-${{ hashFiles('tooling/bundler/Cargo.lock') }}

View File

@ -135,7 +135,7 @@ jobs:
with:
path: tooling/cli.rs/target
# Add date to the cache to keep it up to date
key: ${{ matrix.platform }}-stable-cargo-cli-${{ hashFiles('tooling/cli.rs/Cargo.lock') }}-${{ env.CURRENT_DATE }}
key: ubuntu-latest-nightly-cargo-cli-${{ hashFiles('tooling/cli.rs/Cargo.lock') }}-${{ env.CURRENT_DATE }}
# Restore from outdated cache for speed
restore-keys: |
${{ matrix.platform }}-stable-cargo-cli-${{ hashFiles('tooling/cli.rs/Cargo.lock') }}
@ -198,23 +198,12 @@ jobs:
with:
path: tooling/cli.rs/target
# Add date to the cache to keep it up to date
key: ${{ matrix.platform }}-stable-cargo-cli-${{ hashFiles('tooling/cli.rs/Cargo.lock') }}-${{ env.CURRENT_DATE }}
key: ubuntu-latest-nightly-cargo-cli-${{ hashFiles('tooling/cli.rs/Cargo.lock') }}-${{ env.CURRENT_DATE }}
# Restore from outdated cache for speed
restore-keys: |
${{ matrix.platform }}-stable-cargo-cli-${{ hashFiles('tooling/cli.rs/Cargo.lock') }}
${{ matrix.platform }}-stable-cargo-cli-
- name: Cache template cargo target
uses: actions/cache@v2
with:
path: tooling/cli.js/test/jest/fixtures/empty/src-tauri/target
# Add date to the cache to keep it up to date
key: ${{ matrix.platform }}-stable-template-${{ hashFiles('tooling/cli.rs/templates/app/**') }}-${{ env.CURRENT_DATE }}
# Restore from outdated cache for speed
restore-keys: |
${{ matrix.platform }}-stable-template-${{ hashFiles('tooling/cli.rs/templates/app/**') }}
${{ matrix.platform }}-stable-template-
- name: test
timeout-minutes: 30
run: |

View File

@ -5,30 +5,30 @@
name: test create-tauri-app
env:
RUST_BACKTRACE: 1
TAURI_RECIPE: 'vanillajs,cra,vite,ngcli,solid'
TAURI_RECIPE: 'vanillajs,cra,vite,ngcli'
on:
workflow_dispatch:
inputs:
platform:
default: 'ubuntu'
default: "ubuntu"
pull_request:
paths:
- 'tooling/create-tauri-app/**'
- "tooling/create-tauri-app/**"
jobs:
create-recipe-with-npm:
name: 'node@${{ matrix.node }} + npm@${{ matrix.manager }}'
name: "node@${{ matrix.node }} + npm@${{ matrix.manager }}"
runs-on: ${{ github.event.inputs.platform || 'ubuntu' }}-latest
strategy:
fail-fast: false
matrix:
node: ['14', '16']
manager: ['7']
node: ["14", "16"]
manager: ["7"]
exclude:
- node: '16'
manager: '6'
- node: "16"
manager: "6"
steps:
- uses: actions/checkout@v2
@ -61,7 +61,7 @@ jobs:
- run: yarn test
working-directory: tooling/create-tauri-app
env:
TAURI_RUN_MANAGER: 'npm'
TAURI_RUN_MANAGER: "npm"
# create-recipe-with-yarn:
# name: "node@${{ matrix.node }} + yarn@1"

View File

@ -17,7 +17,8 @@ rustdoc-args = [ "--cfg", "doc_cfg" ]
[dependencies]
anyhow = "1"
quote = { version = "1", optional = true }
proc-macro2 = "1"
quote = "1"
tauri-codegen = { version = "1.0.0-beta.4", path = "../tauri-codegen", optional = true }
[target."cfg(windows)".dependencies]
@ -26,4 +27,4 @@ serde_json = "1.0"
tauri-utils = { version = "1.0.0-beta.0", path = "../tauri-utils", features = [ "build" ] }
[features]
codegen = [ "tauri-codegen", "quote" ]
codegen = [ "tauri-codegen" ]

View File

@ -12,8 +12,7 @@ exclude = [ ".license_template", "CHANGELOG.md", "/target" ]
readme = "README.md"
[dependencies]
#wry = { version = "0.12", default-features = false, features = [ "file-drop", "protocol" ] }
wry = { git = "https://github.com/tauri-apps/wry", rev = "e056fb2a15e29de1b8ed85a548cfeb1f85031357", default-features = false, features = [ "file-drop", "protocol" ] }
wry = { version = "0.12", default-features = false, features = [ "file-drop", "protocol" ] }
tauri-runtime = { version = "0.2.1", path = "../tauri-runtime" }
tauri-utils = { version = "1.0.0-beta.3", path = "../tauri-utils" }
uuid = { version = "0.8.2", features = [ "v4" ] }
@ -21,7 +20,7 @@ infer = "0.4"
[target."cfg(windows)".dependencies]
ico = "0.1"
webview2-com = "0.4.0"
winapi = "0.3"
[target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies]
png = "0.16"

File diff suppressed because it is too large Load Diff

View File

@ -32,7 +32,7 @@ http-range = "0.1.4"
infer = "0.4"
[target."cfg(windows)".dependencies]
webview2-com-sys = "0.4.0"
winapi = "0.3"
[target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies]
gtk = { version = "0.14", features = [ "v3_20" ] }

View File

@ -11,7 +11,7 @@ use std::{fmt::Debug, path::PathBuf, sync::mpsc::Sender};
use uuid::Uuid;
#[cfg(windows)]
use webview2_com_sys::Windows::Win32::Foundation::HWND;
use winapi::shared::windef::HWND;
pub mod http;
/// Create window and system tray menus.
@ -37,7 +37,7 @@ use crate::http::{
#[cfg(feature = "system-tray")]
#[non_exhaustive]
#[derive(Debug, Default)]
#[derive(Debug)]
pub struct SystemTray {
pub icon: Option<Icon>,
pub menu: Option<menu::SystemTrayMenu>,
@ -45,6 +45,18 @@ pub struct SystemTray {
pub icon_as_template: bool,
}
#[cfg(feature = "system-tray")]
impl Default for SystemTray {
fn default() -> Self {
Self {
icon: None,
menu: None,
#[cfg(target_os = "macos")]
icon_as_template: false,
}
}
}
#[cfg(feature = "system-tray")]
impl SystemTray {
/// Creates a new system tray that only renders an icon.
@ -263,9 +275,23 @@ pub trait RuntimeHandle: Debug + Send + Sized + Clone + 'static {
/// A global shortcut manager.
pub trait GlobalShortcutManager: Debug {
/// Whether the application has registered the given `accelerator`.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the `tauri::Builder#setup` closure.
/// - Panics when called on the main thread, usually on the `tauri::App#run`closure.
///
/// You can spawn a task to use the API using `tauri::async_runtime::spawn` or [`std::thread::spawn`] to prevent the panic.
fn is_registered(&self, accelerator: &str) -> crate::Result<bool>;
/// Register a global shortcut of `accelerator`.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the `tauri::Builder#setup` closure.
/// - Panics when called on the main thread, usually on the `tauri::App#run`closure.
///
/// You can spawn a task to use the API using `tauri::async_runtime::spawn` or [`std::thread::spawn`] to prevent the panic.
fn register<F: Fn() + Send + 'static>(
&mut self,
accelerator: &str,
@ -273,17 +299,45 @@ pub trait GlobalShortcutManager: Debug {
) -> crate::Result<()>;
/// Unregister all accelerators registered by the manager instance.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the `tauri::Builder#setup` closure.
/// - Panics when called on the main thread, usually on the `tauri::App#run`closure.
///
/// You can spawn a task to use the API using `tauri::async_runtime::spawn` or [`std::thread::spawn`] to prevent the panic.
fn unregister_all(&mut self) -> crate::Result<()>;
/// Unregister the provided `accelerator`.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the `tauri::Builder#setup` closure.
/// - Panics when called on the main thread, usually on the `tauri::App#run`closure.
///
/// You can spawn a task to use the API using `tauri::async_runtime::spawn` or [`std::thread::spawn`] to prevent the panic.
fn unregister(&mut self, accelerator: &str) -> crate::Result<()>;
}
/// Clipboard manager.
pub trait ClipboardManager: Debug {
/// Writes the text into the clipboard as plain text.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the `tauri::Builder#setup` closure.
/// - Panics when called on the main thread, usually on the `tauri::App#run`closure.
///
/// You can spawn a task to use the API using `tauri::async_runtime::spawn` or [`std::thread::spawn`] to prevent the panic.
fn write_text<T: Into<String>>(&mut self, text: T) -> Result<()>;
/// Read the content in the clipboard as plain text.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the `tauri::Builder#setup` closure.
/// - Panics when called on the main thread, usually on the `tauri::App#run`closure.
///
/// You can spawn a task to use the API using `tauri::async_runtime::spawn` or [`std::thread::spawn`] to prevent the panic.
fn read_text(&self) -> Result<Option<String>>;
}
@ -336,7 +390,7 @@ pub trait Runtime: Sized + 'static {
fn run_iteration<F: Fn(RunEvent) + 'static>(&mut self, callback: F) -> RunIteration;
/// Run the webview runtime.
fn run<F: FnMut(RunEvent) + 'static>(self, callback: F);
fn run<F: Fn(RunEvent) + 'static>(self, callback: F);
}
/// Webview dispatcher. A thread-safe handle to the webview API.

View File

@ -154,7 +154,7 @@ pub trait TrayHandle: fmt::Debug {
}
/// A window menu.
#[derive(Debug, Default, Clone)]
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Menu {
pub items: Vec<MenuEntry>,
@ -179,6 +179,12 @@ impl Submenu {
}
}
impl Default for Menu {
fn default() -> Self {
Self { items: Vec::new() }
}
}
impl Menu {
/// Creates a new window menu.
pub fn new() -> Self {
@ -268,12 +274,18 @@ impl CustomMenuItem {
}
/// A system tray menu.
#[derive(Debug, Default, Clone)]
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SystemTrayMenu {
pub items: Vec<SystemTrayMenuEntry>,
}
impl Default for SystemTrayMenu {
fn default() -> Self {
Self { items: Vec::new() }
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SystemTraySubmenu {

View File

@ -13,7 +13,7 @@ use serde_json::Value as JsonValue;
use tauri_utils::config::{WindowConfig, WindowUrl};
#[cfg(windows)]
use webview2_com_sys::Windows::Win32::Foundation::HWND;
use winapi::shared::windef::HWND;
use std::{fmt, path::PathBuf};

View File

@ -13,7 +13,7 @@ readme = "README.md"
[dependencies]
serde = { version = "1.0", features = [ "derive" ] }
serde_json = "1.0"
thiserror = "1.0.29"
thiserror = "1.0.26"
phf = { version = "0.10", features = [ "macros" ] }
zstd = "0.9"
url = { version = "2.2", features = [ "serde" ] }
@ -22,8 +22,5 @@ html5ever = "0.25"
proc-macro2 = { version = "1.0", optional = true }
quote = { version = "1.0", optional = true }
[target."cfg(target_os = \"linux\")".dependencies]
heck = "0.3"
[features]
build = [ "proc-macro2", "quote" ]

View File

@ -238,40 +238,28 @@ pub struct CliArg {
/// - Using an equals and no space such as -o=value or --option=value
/// - Use a short and no space such as -ovalue
pub takes_value: Option<bool>,
/// Specifies that the argument may have an unknown number of multiple values. Without any other settings, this argument may appear only once.
///
/// For example, --opt val1 val2 is allowed, but --opt val1 val2 --opt val3 is not.
///
/// NOTE: Setting this requires `takes_value` to be set to true.
pub multiple: Option<bool>,
/// Specifies that the argument may appear more than once.
/// For flags, this results in the number of occurrences of the flag being recorded. For example -ddd or -d -d -d would count as three occurrences.
/// For options or arguments that take a value, this does not affect how many values they can accept. (i.e. only one at a time is allowed)
///
/// For example, --opt val1 --opt val2 is allowed, but --opt val1 val2 is not.
/// - For flags, this results in the number of occurrences of the flag being recorded.
/// For example -ddd or -d -d -d would count as three occurrences.
/// - For options there is a distinct difference in multiple occurrences vs multiple values.
/// For example, --opt val1 val2 is one occurrence, but two values. Whereas --opt val1 --opt val2 is two occurrences.
pub multiple: Option<bool>,
///
pub multiple_occurrences: Option<bool>,
/// Specifies how many values are required to satisfy this argument. For example, if you had a
/// `-f <file>` argument where you wanted exactly 3 'files' you would set
/// `number_of_values = 3`, and this argument wouldn't be satisfied unless the user provided
/// 3 and only 3 values.
///
/// **NOTE:** Does *not* require `multiple_occurrences = true` to be set. Setting
/// `multiple_occurrences = true` would allow `-f <file> <file> <file> -f <file> <file> <file>` where
/// as *not* setting it would only allow one occurrence of this argument.
///
/// **NOTE:** implicitly sets `takes_value = true` and `multiple_values = true`.
pub number_of_values: Option<usize>,
pub number_of_values: Option<u64>,
/// Specifies a list of possible values for this argument.
/// At runtime, the CLI verifies that only one of the specified values was used, or fails with an error message.
pub possible_values: Option<Vec<String>>,
/// Specifies the minimum number of values for this argument.
/// For example, if you had a -f <file> argument where you wanted at least 2 'files',
/// you would set `minValues: 2`, and this argument would be satisfied if the user provided, 2 or more values.
pub min_values: Option<usize>,
pub min_values: Option<u64>,
/// Specifies the maximum number of values are for this argument.
/// For example, if you had a -f <file> argument where you wanted up to 3 'files',
/// you would set .max_values(3), and this argument would be satisfied if the user provided, 1, 2, or 3 values.
pub max_values: Option<usize>,
pub max_values: Option<u64>,
/// Sets whether or not the argument is required by default.
///
/// - Required by default means it is required, when no other conflicting rules have been evaluated
@ -311,7 +299,7 @@ pub struct CliArg {
/// The index refers to position according to other positional argument.
/// It does not define position in the argument list as a whole. When utilized with multiple=true,
/// only the last positional argument may be defined as multiple (i.e. the one with the highest index).
pub index: Option<usize>,
pub index: Option<u64>,
}
/// The CLI command definition.

View File

@ -23,12 +23,6 @@ impl PackageInfo {
/// Returns the application package name.
/// On macOS and Windows it's the `name` field, and on Linux it's the `name` in `kebab-case`.
pub fn package_name(&self) -> String {
#[cfg(target_os = "linux")]
{
use heck::KebabCase;
self.name.clone().to_kebab_case()
}
#[cfg(not(target_os = "linux"))]
self.name.clone()
}
}

View File

@ -33,7 +33,7 @@ normal = [ "attohttpc" ]
[dependencies]
serde_json = { version = "1.0", features = [ "raw_value" ] }
serde = { version = "1.0", features = [ "derive" ] }
tokio = { version = "1.12", features = [ "rt", "rt-multi-thread", "sync", "fs", "io-util" ] }
tokio = { version = "1.9", features = [ "rt", "rt-multi-thread", "sync", "fs", "io-util" ] }
futures = "0.3"
uuid = { version = "0.8", features = [ "v4" ] }
url = { version = "2.2" }
@ -58,7 +58,7 @@ bincode = "1.3"
dirs-next = "2.0"
percent-encoding = "2.1"
base64 = { version = "0.13", optional = true }
clap = { version = "=3.0.0-beta.4", optional = true }
clap = { version = "=3.0.0-beta.2", optional = true }
notify-rust = { version = "4.5", optional = true }
reqwest = { version = "0.11", features = [ "json", "multipart" ], optional = true }
bytes = { version = "1", features = [ "serde" ], optional = true }
@ -66,10 +66,10 @@ attohttpc = { version = "0.17", features = [ "json", "form" ] }
open = { version = "2.0", optional = true }
shared_child = { version = "0.3", optional = true }
os_pipe = { version = "0.9", optional = true }
rfd = { version = "0.5.0", features = [ "parent" ] }
rfd = { version = "0.4.3", features = [ "parent" ] }
raw-window-handle = "0.3.3"
minisign-verify = { version = "0.1", optional = true }
os_info = { version = "3.0.7", optional = true }
os_info = { version = "3.0.6", optional = true }
futures-lite = "1.12"
[target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies]
@ -90,7 +90,7 @@ serde = { version = "1.0", features = [ "derive" ] }
quickcheck = "1.0.3"
quickcheck_macros = "1.0.0"
tokio-test = "0.4.2"
tokio = { version = "1.12", features = [ "full" ] }
tokio = { version = "1.9", features = [ "full" ] }
mockito = "0.30"
[features]

File diff suppressed because one or more lines are too long

View File

@ -2,7 +2,16 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
;(function () {
// polyfills
if (!String.prototype.startsWith) {
String.prototype.startsWith = function (searchString, position) {
position = position || 0
return this.substr(position, searchString.length) === searchString
}
}
;
(function () {
function uid() {
const length = new Int8Array(1)
window.crypto.getRandomValues(length)
@ -106,8 +115,7 @@
if (window.rpc) {
window.rpc.notify(
cmd,
_objectSpread(
{
_objectSpread({
callback: callback,
error: error,
__invokeKey: key || __TAURI_INVOKE_KEY__
@ -119,8 +127,7 @@
window.addEventListener('DOMContentLoaded', function () {
window.rpc.notify(
cmd,
_objectSpread(
{
_objectSpread({
callback: callback,
error: error,
__invokeKey: key || __TAURI_INVOKE_KEY__
@ -140,15 +147,16 @@
function (e) {
var target = e.target
while (target != null) {
if (target.matches('a')) {
if (
target.matches ? target.matches('a') : target.msMatchesSelector('a')
) {
if (
target.href &&
target.href.startsWith('http') &&
target.target === '_blank'
) {
window.__TAURI_INVOKE__(
'tauri',
{
'tauri', {
__tauriModule: 'Shell',
message: {
cmd: 'open',
@ -188,8 +196,7 @@
if (e.target.hasAttribute('data-tauri-drag-region') && e.buttons === 1) {
// start dragging if the element has a `tauri-drag-region` data attribute and maximize on double-clicking it
window.__TAURI_INVOKE__(
'tauri',
{
'tauri', {
__tauriModule: 'Window',
message: {
cmd: 'manage',
@ -206,8 +213,7 @@
})
window.__TAURI_INVOKE__(
'tauri',
{
'tauri', {
__tauriModule: 'Event',
message: {
cmd: 'listen',
@ -233,8 +239,7 @@
return Promise.resolve(window.Notification.permission === 'granted')
}
return window.__TAURI_INVOKE__(
'tauri',
{
'tauri', {
__tauriModule: 'Notification',
message: {
cmd: 'isNotificationPermissionGranted'
@ -251,10 +256,8 @@
}
function requestPermission() {
return window
.__TAURI_INVOKE__(
'tauri',
{
return window.__TAURI_INVOKE__(
'tauri', {
__tauriModule: 'Notification',
message: {
cmd: 'requestNotificationPermission'
@ -276,17 +279,13 @@
isPermissionGranted().then(function (permission) {
if (permission) {
return window.__TAURI_INVOKE__(
'tauri',
{
'tauri', {
__tauriModule: 'Notification',
message: {
cmd: 'notification',
options:
typeof options === 'string'
? {
options: typeof options === 'string' ? {
title: options
}
: options
} : options
}
},
_KEY_VALUE_
@ -329,8 +328,7 @@
window.alert = function (message) {
window.__TAURI_INVOKE__(
'tauri',
{
'tauri', {
__tauriModule: 'Dialog',
message: {
cmd: 'messageDialog',
@ -343,8 +341,7 @@
window.confirm = function (message) {
return window.__TAURI_INVOKE__(
'tauri',
{
'tauri', {
__tauriModule: 'Dialog',
message: {
cmd: 'askDialog',
@ -359,8 +356,7 @@
if (navigator.userAgent.includes('Mac')) {
window.print = function () {
return window.__TAURI_INVOKE__(
'tauri',
{
'tauri', {
__tauriModule: 'Window',
message: {
cmd: 'manage',

View File

@ -187,9 +187,7 @@ fn get_arg<'a>(arg_name: &'a str, arg: &'a CliArg) -> Arg<'a> {
clap_arg = bind_string_arg!(arg, clap_arg, description, about);
clap_arg = bind_string_arg!(arg, clap_arg, long_description, long_about);
clap_arg = bind_value_arg!(arg, clap_arg, takes_value);
if let Some(value) = arg.multiple {
clap_arg = clap_arg.multiple_values(value);
}
clap_arg = bind_value_arg!(arg, clap_arg, multiple);
clap_arg = bind_value_arg!(arg, clap_arg, multiple_occurrences);
clap_arg = bind_value_arg!(arg, clap_arg, number_of_values);
clap_arg = bind_string_slice_arg!(arg, clap_arg, possible_values);

View File

@ -79,15 +79,8 @@ pub enum Error {
#[cfg(feature = "cli")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "cli")))]
#[error("failed to parse CLI arguments: {0}")]
ParseCliArguments(String),
ParseCliArguments(#[from] clap::Error),
/// Shell error.
#[error("shell error: {0}")]
Shell(String),
}
#[cfg(feature = "cli")]
impl From<clap::Error> for Error {
fn from(error: clap::Error) -> Self {
Self::ParseCliArguments(error.to_string())
}
}

View File

@ -28,7 +28,7 @@ use tauri_utils::PackageInfo;
use std::{
collections::HashMap,
path::PathBuf,
sync::{mpsc::Sender, Arc, Weak},
sync::{mpsc::Sender, Arc},
};
use crate::runtime::menu::{Menu, MenuId, MenuIdRef};
@ -187,7 +187,7 @@ impl AppHandle<crate::Wry> {
>(
&self,
f: F,
) -> crate::Result<Weak<tauri_runtime_wry::Window>> {
) -> crate::Result<Arc<tauri_runtime_wry::Window>> {
self.runtime_handle.create_tao_window(f).map_err(Into::into)
}
@ -425,16 +425,35 @@ impl<R: Runtime> App<R> {
}
/// Runs the application.
pub fn run<F: FnMut(&AppHandle<R>, Event) + 'static>(mut self, mut callback: F) {
pub fn run<F: Fn(&AppHandle<R>, Event) + 'static>(mut self, callback: F) {
let app_handle = self.handle();
let manager = self.manager.clone();
self.runtime.take().unwrap().run(move |event| match event {
RunEvent::Exit => {
app_handle.cleanup_before_exit();
on_event_loop_event(&app_handle, RunEvent::Exit, &manager, Some(&mut callback));
callback(&app_handle, Event::Exit);
}
_ => {
on_event_loop_event(&app_handle, event, &manager, Some(&mut callback));
on_event_loop_event(&event, &manager);
callback(
&app_handle,
match event {
RunEvent::Exit => Event::Exit,
RunEvent::ExitRequested { window_label, tx } => Event::ExitRequested {
window_label,
api: ExitRequestApi(tx),
},
RunEvent::CloseRequested { label, signal_tx } => Event::CloseRequested {
label,
api: CloseRequestApi(signal_tx),
},
RunEvent::WindowClose(label) => Event::WindowClosed(label),
RunEvent::Ready => Event::Ready,
RunEvent::Resumed => Event::Resumed,
RunEvent::MainEventsCleared => Event::MainEventsCleared,
_ => unimplemented!(),
},
);
}
});
}
@ -462,15 +481,11 @@ impl<R: Runtime> App<R> {
#[cfg(any(target_os = "windows", target_os = "macos"))]
pub fn run_iteration(&mut self) -> crate::runtime::RunIteration {
let manager = self.manager.clone();
let app_handle = self.handle();
self.runtime.as_mut().unwrap().run_iteration(move |event| {
on_event_loop_event(
&app_handle,
event,
&manager,
Option::<&mut Box<dyn FnMut(&AppHandle<R>, Event)>>::None,
)
})
self
.runtime
.as_mut()
.unwrap()
.run_iteration(move |event| on_event_loop_event(&event, &manager))
}
}
@ -899,6 +914,29 @@ impl<R: Runtime> Builder<R> {
},
};
app.manager.initialize_plugins(&app.handle())?;
let pending_labels = self
.pending_windows
.iter()
.map(|p| p.label.clone())
.collect::<Vec<_>>();
#[cfg(feature = "updater")]
let mut main_window = None;
for pending in self.pending_windows {
let pending = app
.manager
.prepare_window(app.handle.clone(), pending, &pending_labels)?;
let detached = app.runtime.as_ref().unwrap().create_window(pending)?;
let _window = app.manager.attach_window(app.handle(), detached);
#[cfg(feature = "updater")]
if main_window.is_none() {
main_window = Some(_window);
}
}
#[cfg(feature = "system-tray")]
if let Some(system_tray) = self.system_tray {
let mut ids = HashMap::new();
@ -989,29 +1027,6 @@ impl<R: Runtime> Builder<R> {
}
}
app.manager.initialize_plugins(&app.handle())?;
let pending_labels = self
.pending_windows
.iter()
.map(|p| p.label.clone())
.collect::<Vec<_>>();
#[cfg(feature = "updater")]
let mut main_window = None;
for pending in self.pending_windows {
let pending = app
.manager
.prepare_window(app.handle.clone(), pending, &pending_labels)?;
let detached = app.runtime.as_ref().unwrap().create_window(pending)?;
let _window = app.manager.attach_window(app.handle(), detached);
#[cfg(feature = "updater")]
if main_window.is_none() {
main_window = Some(_window);
}
}
(self.setup)(&mut app).map_err(|e| crate::Error::Setup(e))?;
#[cfg(feature = "updater")]
@ -1027,43 +1042,10 @@ impl<R: Runtime> Builder<R> {
}
}
fn on_event_loop_event<R: Runtime, F: FnMut(&AppHandle<R>, Event) + 'static>(
app_handle: &AppHandle<R>,
event: RunEvent,
manager: &WindowManager<R>,
callback: Option<&mut F>,
) {
if let RunEvent::WindowClose(label) = &event {
fn on_event_loop_event<R: Runtime>(event: &RunEvent, manager: &WindowManager<R>) {
if let RunEvent::WindowClose(label) = event {
manager.on_window_close(label);
}
let event = match event {
RunEvent::Exit => Event::Exit,
RunEvent::ExitRequested { window_label, tx } => Event::ExitRequested {
window_label,
api: ExitRequestApi(tx),
},
RunEvent::CloseRequested { label, signal_tx } => Event::CloseRequested {
label,
api: CloseRequestApi(signal_tx),
},
RunEvent::WindowClose(label) => Event::WindowClosed(label),
RunEvent::Ready => Event::Ready,
RunEvent::Resumed => Event::Resumed,
RunEvent::MainEventsCleared => Event::MainEventsCleared,
_ => unimplemented!(),
};
manager
.inner
.plugins
.lock()
.expect("poisoned plugin store")
.on_event(app_handle, &event);
if let Some(c) = callback {
c(app_handle, event);
}
}
/// Make `Wry` the default `Runtime` for `Builder`

View File

@ -3,6 +3,8 @@
// SPDX-License-Identifier: MIT
use super::InvokeResponse;
#[cfg(any(windows, target_os = "macos"))]
use crate::api::dialog::window_parent;
#[cfg(any(dialog_open, dialog_save))]
use crate::api::dialog::FileDialogBuilder;
use crate::{
@ -143,7 +145,7 @@ pub fn open<R: Runtime>(
let mut dialog_builder = FileDialogBuilder::new();
#[cfg(any(windows, target_os = "macos"))]
{
dialog_builder = dialog_builder.set_parent(&crate::api::dialog::window_parent(window)?);
dialog_builder = dialog_builder.set_parent(&window_parent(window)?);
}
if let Some(default_path) = options.default_path {
if !default_path.exists() {
@ -179,7 +181,7 @@ pub fn save<R: Runtime>(
let mut dialog_builder = FileDialogBuilder::new();
#[cfg(any(windows, target_os = "macos"))]
{
dialog_builder = dialog_builder.set_parent(&crate::api::dialog::window_parent(&window)?);
dialog_builder = dialog_builder.set_parent(&window_parent(&window)?);
}
if let Some(default_path) = options.default_path {
dialog_builder = set_default_path(dialog_builder, default_path);

View File

@ -6,7 +6,7 @@ use super::InvokeResponse;
use crate::{api::path::BaseDirectory, Config, PackageInfo};
use serde::Deserialize;
#[cfg(path_all)]
use std::path::{Component, Path, PathBuf, MAIN_SEPARATOR};
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// The API descriptor.
#[derive(Deserialize)]
@ -77,74 +77,48 @@ pub fn resolve_path_handler(
#[cfg(path_all)]
fn resolve(paths: Vec<String>) -> crate::Result<String> {
// Start with current directory path because users might pass empty or vec!["."]
// then start adding paths from the vector one by one using path.push()
// so if an absolute path is encountered in the iteration, we use it as the current full path
// examples:
// 1. vec!["."] or vec![] will be equal to std::env::current_dir()
// 2. vec!["/foo/bar", "/tmp/file", "baz"] will be equal to PathBuf::from("/tmp/file/baz")
let mut path = std::env::current_dir()?;
for p in paths {
path.push(p);
}
Ok(normalize_path(&path).to_string_lossy().to_string())
}
// start with the current directory
let mut resolved_path = PathBuf::new().join(".");
#[cfg(path_all)]
fn join(paths: Vec<String>) -> crate::Result<String> {
let path = PathBuf::from(
paths
.iter()
.map(|p| {
// Add MAIN_SEPARATOR if this is not the first element in the vector
// and if it doesn't already have a spearator.
// Doing this to ensure that the vector elements are separated in
// the resulting string so path.components() can work correctly when called
// in normalize_path_no_absolute() later
if !p.starts_with('/') && !p.starts_with('\\') && p != &paths[0] {
let mut tmp = String::from(MAIN_SEPARATOR);
tmp.push_str(p);
tmp
for path in paths {
let path_buf = PathBuf::from(path);
// if we encounter an absolute path, we use it as the starting path for next iteration
if path_buf.is_absolute() {
resolved_path = path_buf;
} else {
p.to_string()
resolved_path = resolved_path.join(&path_buf);
}
}
})
.collect::<String>(),
);
let p = normalize_path_no_absolute(&path)
.to_string_lossy()
.to_string();
Ok(if p.is_empty() { ".".into() } else { p })
normalize(resolved_path.to_string_lossy().to_string())
}
#[cfg(path_all)]
fn normalize(path: String) -> crate::Result<String> {
let mut p = normalize_path_no_absolute(Path::new(&path))
.to_string_lossy()
.to_string();
Ok(if p.is_empty() {
// Nodejs will return ".." if we used normalize("..")
// and will return "." if we used normalize("") or normalize(".")
if path == ".." {
path
} else {
".".into()
let path = std::fs::canonicalize(path)?;
let path = path.to_string_lossy().to_string();
// remove `\\\\?\\` on windows, UNC path
#[cfg(target_os = "windows")]
let path = path.replace("\\\\?\\", "");
Ok(path)
}
#[cfg(path_all)]
fn join(paths: Vec<String>) -> crate::Result<String> {
let mut joined_path = PathBuf::new();
for path in paths {
joined_path = joined_path.join(path);
}
} else {
// If the path passed to this function contains a trailing separator,
// we make sure to perserve it. That's how NodeJS works
if (path.ends_with('/') || path.ends_with('\\')) && (!p.ends_with('/') || !p.ends_with('\\')) {
p.push(MAIN_SEPARATOR);
}
p
})
normalize(joined_path.to_string_lossy().to_string())
}
#[cfg(path_all)]
fn dirname(path: String) -> crate::Result<String> {
match Path::new(&path).parent() {
Some(p) => Ok(p.to_string_lossy().to_string()),
Some(path) => Ok(path.to_string_lossy().to_string()),
None => Err(crate::Error::FailedToExecuteApi(crate::api::Error::Path(
"Couldn't get the parent directory".into(),
))),
@ -157,7 +131,7 @@ fn extname(path: String) -> crate::Result<String> {
.extension()
.and_then(std::ffi::OsStr::to_str)
{
Some(p) => Ok(p.to_string()),
Some(path) => Ok(path.to_string()),
None => Err(crate::Error::FailedToExecuteApi(crate::api::Error::Path(
"Couldn't get the extension of the file".into(),
))),
@ -170,87 +144,13 @@ fn basename(path: String, ext: Option<String>) -> crate::Result<String> {
.file_name()
.and_then(std::ffi::OsStr::to_str)
{
Some(p) => Ok(if let Some(ext) = ext {
p.replace(ext.as_str(), "")
Some(path) => Ok(if let Some(ext) = ext {
path.replace(ext.as_str(), "")
} else {
p.to_string()
path.to_string()
}),
None => Err(crate::Error::FailedToExecuteApi(crate::api::Error::Path(
"Couldn't get the basename".into(),
))),
}
}
/// Resolve ".." and "." if there is any , this snippet is taken from cargo's paths util
/// https://github.com/rust-lang/cargo/blob/46fa867ff7043e3a0545bf3def7be904e1497afd/crates/cargo-util/src/paths.rs#L73-L106
#[cfg(path_all)]
fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => {
ret.push(component.as_os_str());
}
Component::CurDir => {}
Component::ParentDir => {
ret.pop();
}
Component::Normal(c) => {
ret.push(c);
}
}
}
ret
}
/// Resolve ".." and "." if there is any , this snippet is taken from cargo's paths util but
/// slightly modified to not resolve absolute paths
/// https://github.com/rust-lang/cargo/blob/46fa867ff7043e3a0545bf3def7be904e1497afd/crates/cargo-util/src/paths.rs#L73-L106
#[cfg(path_all)]
fn normalize_path_no_absolute(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => {
ret.push(component.as_os_str());
}
Component::CurDir => {}
Component::ParentDir => {
ret.pop();
}
Component::Normal(c) => {
// Using PathBuf::push here will replace the whole path if an absolute path is encountered
// which is not the intended behavior, so instead of that, convert the current resolved path
// to a string and do simple string concatenation with the current component then convert it
// back to a PathBuf
let mut p = ret.to_string_lossy().to_string();
// Don't add the separator if the resolved path is empty,
// otherwise we are gonna have unwanted leading separator
if !p.is_empty() && !p.ends_with('/') && !p.ends_with('\\') {
p.push(MAIN_SEPARATOR);
}
if let Some(c) = c.to_str() {
p.push_str(c);
}
ret = PathBuf::from(p);
}
}
}
ret
}

View File

@ -5,7 +5,7 @@
//! The Tauri plugin extension to expand Tauri functionality.
use crate::{
runtime::Runtime, utils::config::PluginConfig, AppHandle, Event, Invoke, PageLoadPayload, Window,
runtime::Runtime, utils::config::PluginConfig, AppHandle, Invoke, PageLoadPayload, Window,
};
use serde_json::Value as JsonValue;
use tauri_macros::default_runtime;
@ -43,10 +43,6 @@ pub trait Plugin<R: Runtime>: Send {
#[allow(unused_variables)]
fn on_page_load(&mut self, window: Window<R>, payload: PageLoadPayload) {}
/// Callback invoked when the event loop receives a new event.
#[allow(unused_variables)]
fn on_event(&mut self, app: &AppHandle<R>, event: &Event) {}
/// Extend commands to [`crate::Builder::invoke_handler`].
#[allow(unused_variables)]
fn extend_api(&mut self, invoke: Invoke<R>) {}
@ -125,14 +121,6 @@ impl<R: Runtime> PluginStore<R> {
.for_each(|plugin| plugin.on_page_load(window.clone(), payload.clone()))
}
/// Runs the on_event hook for all plugins in the store.
pub(crate) fn on_event(&mut self, app: &AppHandle<R>, event: &Event) {
self
.store
.values_mut()
.for_each(|plugin| plugin.on_event(app, event))
}
pub(crate) fn extend_api(&mut self, mut invoke: Invoke<R>) {
let command = invoke.message.command.replace("plugin:", "");
let mut tokens = command.split('|');

View File

@ -389,7 +389,6 @@ pub struct Update {
/// Update publish date
pub date: String,
/// Target
#[allow(dead_code)]
target: String,
/// Extract path
extract_path: PathBuf,

View File

@ -264,11 +264,6 @@ impl<R: Runtime> Window<R> {
self.manager.listen(event.into(), Some(label), handler)
}
/// Unlisten to an event on this window.
pub fn unlisten(&self, handler_id: EventHandler) {
self.manager.unlisten(handler_id)
}
/// Listen to a an event on this window a single time.
pub fn once<F>(&self, event: impl Into<String>, handler: F) -> EventHandler
where
@ -315,16 +310,37 @@ impl<R: Runtime> Window<R> {
}
/// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn scale_factor(&self) -> crate::Result<f64> {
self.window.dispatcher.scale_factor().map_err(Into::into)
}
/// Returns the position of the top-left hand corner of the window's client area relative to the top-left hand corner of the desktop.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn inner_position(&self) -> crate::Result<PhysicalPosition<i32>> {
self.window.dispatcher.inner_position().map_err(Into::into)
}
/// Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn outer_position(&self) -> crate::Result<PhysicalPosition<i32>> {
self.window.dispatcher.outer_position().map_err(Into::into)
}
@ -332,6 +348,13 @@ impl<R: Runtime> Window<R> {
/// Returns the physical size of the window's client area.
///
/// The client area is the content of the window, excluding the title bar and borders.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn inner_size(&self) -> crate::Result<PhysicalSize<u32>> {
self.window.dispatcher.inner_size().map_err(Into::into)
}
@ -339,31 +362,73 @@ impl<R: Runtime> Window<R> {
/// Returns the physical size of the entire window.
///
/// These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn outer_size(&self) -> crate::Result<PhysicalSize<u32>> {
self.window.dispatcher.outer_size().map_err(Into::into)
}
/// Gets the window's current fullscreen state.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn is_fullscreen(&self) -> crate::Result<bool> {
self.window.dispatcher.is_fullscreen().map_err(Into::into)
}
/// Gets the window's current maximized state.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn is_maximized(&self) -> crate::Result<bool> {
self.window.dispatcher.is_maximized().map_err(Into::into)
}
/// Gets the windows current decoration state.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn is_decorated(&self) -> crate::Result<bool> {
self.window.dispatcher.is_decorated().map_err(Into::into)
}
/// Gets the windows current resizable state.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn is_resizable(&self) -> crate::Result<bool> {
self.window.dispatcher.is_resizable().map_err(Into::into)
}
/// Gets the window's current vibility state.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn is_visible(&self) -> crate::Result<bool> {
self.window.dispatcher.is_visible().map_err(Into::into)
}
@ -375,6 +440,13 @@ impl<R: Runtime> Window<R> {
/// ## Platform-specific
///
/// - **Linux:** Unsupported
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn current_monitor(&self) -> crate::Result<Option<Monitor>> {
self
.window
@ -391,6 +463,13 @@ impl<R: Runtime> Window<R> {
/// ## Platform-specific
///
/// - **Linux:** Unsupported
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn primary_monitor(&self) -> crate::Result<Option<Monitor>> {
self
.window
@ -405,6 +484,13 @@ impl<R: Runtime> Window<R> {
/// ## Platform-specific
///
/// - **Linux:** Unsupported
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn available_monitors(&self) -> crate::Result<Vec<Monitor>> {
self
.window
@ -415,18 +501,32 @@ impl<R: Runtime> Window<R> {
}
/// Returns the native handle that is used by this window.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
#[cfg(target_os = "macos")]
pub fn ns_window(&self) -> crate::Result<*mut std::ffi::c_void> {
self.window.dispatcher.ns_window().map_err(Into::into)
}
/// Returns the native handle that is used by this window.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
#[cfg(windows)]
pub fn hwnd(&self) -> crate::Result<*mut std::ffi::c_void> {
self
.window
.dispatcher
.hwnd()
.map(|hwnd| hwnd.0 as *mut _)
.map(|hwnd| hwnd as *mut _)
.map_err(Into::into)
}
@ -528,12 +628,6 @@ impl<R: Runtime> Window<R> {
}
/// Closes this window.
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn close(&self) -> crate::Result<()> {
self.window.dispatcher.close().map_err(Into::into)
}

View File

@ -83,11 +83,25 @@ impl<R: Runtime> MenuHandle<R> {
}
/// Whether the menu is visible or not.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn is_visible(&self) -> crate::Result<bool> {
self.dispatcher.is_menu_visible().map_err(Into::into)
}
/// Toggles the menu visibility.
///
/// # Panics
///
/// - Panics if the event loop is not running yet, usually when called on the [`setup`](crate::Builder#method.setup) closure.
/// - Panics when called on the main thread, usually on the [`run`](crate::App#method.run) closure.
///
/// You can spawn a task to use the API using [`crate::async_runtime::spawn`] or [`std::thread::spawn`] to prevent the panic.
pub fn toggle(&self) -> crate::Result<()> {
if self.is_visible()? {
self.hide()

View File

@ -29,50 +29,17 @@ This command is pretty helpful when you need to have a quick overview of your ap
<Command name="init" />
```
Initializes a Tauri project
USAGE:
cargo tauri init [FLAGS] [OPTIONS] [SUBCOMMAND]
FLAGS:
--ci Skip prompting for values
-f, --force Force init to overwrite the src-tauri folder
-h, --help Print help information
-l, --log Enables logging
-V, --version Print version information
OPTIONS:
-A, --app-name <app-name> Name of your Tauri application
-d, --directory <directory> Set target directory for init
-D, --dist-dir <dist-dir> Web assets location, relative to <project-dir>/src-tauri
-P, --dev-path <dev-path> Url of your dev server
-t, --tauri-path <tauri-path> Path of the Tauri project to use (relative to the cwd)
-W, --window-title <window-title> Window title of your Tauri application
SUBCOMMANDS:
help Print this message or the help of the given subcommand(s)
plugin Initialize a Tauri plugin.
```
### `init plugin`
<Command name="init plugin" />
```
Initializes a Tauri plugin project.
USAGE:
cargo tauri init plugin [FLAGS] [OPTIONS] --name <name>
FLAGS:
-a, --api Initializes a Tauri plugin with TypeScript API.
-h, --help Print help information
-V, --version Print version information
OPTIONS:
-d, --directory <directory> Set target directory for init
-n, --name <name> Name of your Tauri plugin
-t, --tauri-path <tauri-path> Path of the Tauri project to use (relative to the cwd)
Description
Inits the Tauri template. If Tauri cannot find the src-tauri/tauri.conf.json
it will create one.
Usage
$ tauri init
Options
--help, -h Displays this message
--force, -f Force init to overwrite [conf|template|all]
--log, -l Logging [boolean]
--directory, -d Set target directory for init
--tauriPath, -t Path of the Tauri project to use (relative to the cwd)
```
## `dev`
@ -80,25 +47,12 @@ OPTIONS:
<Command name="dev" />
```
Tauri dev.
USAGE:
cargo tauri dev [FLAGS] [OPTIONS] [--] [args]...
ARGS:
<args>... Args passed to the binary
FLAGS:
-e, --exit-on-panic Exit on panic
-h, --help Print help information
--release Run the code in release mode
-V, --version Print version information
OPTIONS:
-c, --config <config> config JSON to merge with tauri.conf.json
-f, --features <features>... list of cargo features to activate
-r, --runner <runner> binary to use to run the application
-t, --target <target>... target triple to build against
Description
Tauri dev.
Usage
$ tauri dev
Options
--help, -h Displays this message
```
This command will open the WebView in development mode. It makes use of the `build.devPath` property from your `src-tauri/tauri.conf.json` file.
@ -129,23 +83,13 @@ If you're not using `build.beforeDevCommand`, make sure your `build.devPath` is
<Command name="build" />
```
Tauri build.
USAGE:
cargo tauri build [FLAGS] [OPTIONS]
FLAGS:
-d, --debug Builds with the debug flag
-h, --help Print help information
-v, --verbose Enables verbose logging
-V, --version Print version information
OPTIONS:
-b, --bundle <bundle>... list of bundles to package
-c, --config <config> config JSON to merge with tauri.conf.json
-f, --features <features>... list of cargo features to activate
-r, --runner <runner> binary to use to build the application
-t, --target <target>... target triple to build against
Description
Tauri build.
Usage
$ tauri build
Options
--help, -h Displays this message
--debug, -d Build a tauri app with debugging
```
This command will bundle your application, either in production mode or debug mode if you used the `--debug` flag. It makes use of the `build.distDir` property from your `src-tauri/tauri.conf.json` file.
@ -189,3 +133,4 @@ This command will show the current version of Tauri.
## CLI usage
See more about the usage through this [complete guide](/docs/usage/development/integration).

View File

@ -27,8 +27,8 @@ In addition to the JSON defined on the `tauri.conf.json` file, Tauri reads a pla
The target directory <em>must</em> contain an index.html file.
</div>`},
{property: "devPath", type: "string", description: `Can be a path to a folder (either absolute or relative to tauri.conf.json) or a URL (like a live reload server).`},
{property: "beforeDevCommand", optional: true, type: "string", description: `A command to run before starting Tauri in dev mode. The PLATFORM, ARCH, FAMILY and PLATFORM_TYPE environment variables are set if you perform conditional compilation.`},
{property: "beforeBuildCommand", optional: true, type: "string", description: `A command to run before starting Tauri's build pipeline. The PLATFORM, ARCH, FAMILY and PLATFORM_TYPE environment variables are set if you perform conditional compilation.`},
{property: "beforeDevCommand", optional: true, type: "string", description: `A command to run before starting Tauri in dev mode.`},
{property: "beforeBuildCommand", optional: true, type: "string", description: `A command to run before starting Tauri in build mode.`},
{property: "withGlobalTauri", optional: true, type: "boolean", description: "Enables the API injection to the window.__TAURI__ object. Useful if you're using Vanilla JS instead of importing the API using Rollup or Webpack. Reduces the command security since any external code can access it, so be careful with XSS attacks."}
]}/>
@ -45,8 +45,8 @@ In addition to the JSON defined on the `tauri.conf.json` file, Tauri reads a pla
## `package`
<Properties anchorRoot="package" rows={[
{ property: "productName", optional: true, type: "string", description: `Application name. Defaults to the package name specified in Cargo.toml. The binary name is converted to snake-case on Linux.` },
{ property: "version", optional: true, type: "string", description: `Application version. Defaults to the version specified in Cargo.toml.` }
{ property: "productName", optional: true, type: "string", description: `Application name. The binary name is converted to snake-case on Linux.` },
{ property: "version", optional: true, type: "string", description: `Application version.` }
]}/>
## `tauri`

View File

@ -37,7 +37,7 @@ $ sudo apt update && sudo apt install libwebkit2gtk-4.0-dev \
<TabItem value="arch">
```sh
$ sudo pacman -Syy && sudo pacman -S --needed webkit2gtk \
$ sudo pacman -Syy && sudo pacman -S webkit2gtk \
base-devel \
curl \
wget \

View File

@ -36,10 +36,11 @@ emit('click', {
Window-specific events are exposed on the `window` module.
```ts
import { appWindow, WebviewWindow } from '@tauri-apps/api/window'
import { getCurrent, WebviewWindow } from '@tauri-apps/api/window'
// emit an event that are only visible to the current window
appWindow.emit('event', { message: 'Tauri is awesome!' })
const current = getCurrent()
current.emit('event', { message: 'Tauri is awesome!' })
// create a new webview window and emit an event only to that window
const webview = new WebviewWindow('window')

View File

@ -5,8 +5,9 @@ title: Write Tauri Plugins
import Alert from '@theme/Alert'
<Alert title="Note" icon="info-alt">
The Tauri CLI can bootstrap a Plugin project with the `$ tauri init plugin --name your-plugin-name` command.
It setups the recommended folder structure, optionally adding a TypeScript API wrapper with the `--api` flag.
Tauri will soon offer Plugin starter kits so the process of writing a Plugin crate will be simplified.
For now it's recommended to follow the [official Tauri plugins](#official-tauri-plugins).
</Alert>
Plugins allow you to hook into the Tauri application lifecycle and introduce new commands.
@ -93,10 +94,7 @@ fn main() {
## Official Tauri Plugins
- [Stronghold](https://github.com/tauri-apps/tauri-plugin-stronghold)
- [Authenticator](https://github.com/tauri-apps/tauri-plugin-authenticator)
- [Logging](https://github.com/tauri-apps/tauri-plugin-log)
- [SQL](https://github.com/tauri-apps/tauri-plugin-sql)
- [WebSocket](https://github.com/tauri-apps/tauri-plugin-websocket)
- [Restoring window state](https://github.com/tauri-apps/tauri-plugin-window-state)
- [Store](https://github.com/tauri-apps/tauri-plugin-store)
- [Stronghold (WIP)](https://github.com/tauri-apps/tauri-plugin-stronghold)
- [Authenticator (WIP)](https://github.com/tauri-apps/tauri-plugin-authenticator)
- [Logging (WIP)](https://github.com/tauri-apps/tauri-plugin-log)
- [SQL (WIP)](https://github.com/tauri-apps/tauri-plugin-sql)

View File

@ -5,7 +5,7 @@ title: Icons
import Command from '@theme/Command'
import Alert from '@theme/Alert'
Tauri ships with a default iconset based on its logo. This is probably NOT what you want when you ship your application. To remedy this common situation, Tauri provides the `icon` command that will take an input file ("./app-icon.png" by default) and create all the icons needed for the various platforms:
Tauri ships with a default iconset based on its logo. This is probably NOT what you want when you ship your application. To remedy this common situation, Tauri provides the `icon` command that will take an input file and create all the icons needed for the various platforms:
<Command name="icon"/>

View File

@ -17,7 +17,7 @@
"svelte": "3.35.0"
},
"dependencies": {
"@tauri-apps/api": "../../tooling/api/dist",
"@tauri-apps/api": "link:../../tooling/api/dist",
"hotkeys-js": "^3.8.5",
"sirv-cli": "1.0.11"
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -15,8 +15,9 @@ use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use tauri::{
api::dialog::ask, http::ResponseBuilder, CustomMenuItem, Event, GlobalShortcutManager, Manager,
SystemTray, SystemTrayEvent, SystemTrayMenu, WindowBuilder, WindowUrl,
api::dialog::ask, async_runtime, http::ResponseBuilder, CustomMenuItem, Event,
GlobalShortcutManager, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, WindowBuilder,
WindowUrl,
};
#[derive(Serialize)]
@ -195,6 +196,9 @@ fn main() {
app.run(|app_handle, e| match e {
// Application is ready (triggered only once)
Event::Ready => {
let app_handle = app_handle.clone();
// launch a new thread so it doesnt block any channel
async_runtime::spawn(async move {
let app_handle = app_handle.clone();
app_handle
.global_shortcut_manager()
@ -204,6 +208,7 @@ fn main() {
window.set_title("New title!").unwrap();
})
.unwrap();
});
}
// Triggered when a window is trying to close
@ -213,19 +218,20 @@ fn main() {
// use the exposed close api, and prevent the event loop to close
api.prevent_close();
// ask the user if he wants to quit
// we need to run this on another thread because this is the event loop callback handler
// and the dialog API needs to communicate with the event loop.
std::thread::spawn(move || {
ask(
Some(&window),
"Tauri API",
"Are you sure that you want to close this window?",
move |answer| {
if answer {
// .close() cannot be called on the main thread
std::thread::spawn(move || {
app_handle.get_window(&label).unwrap().close().unwrap();
});
}
},
);
});
}
// Keep the event loop running even if all windows are closed

View File

@ -1,7 +1,7 @@
{
"build": {
"distDir": "../public",
"devPath": "http://localhost:5000",
"devPath": "../public",
"beforeDevCommand": "yarn dev",
"beforeBuildCommand": "yarn build"
},

View File

@ -1,10 +1,10 @@
<script>
import { appWindow, WebviewWindow, LogicalSize, LogicalPosition, UserAttentionType, PhysicalSize, PhysicalPosition } from "@tauri-apps/api/window";
import { appWindow, WebviewWindow, LogicalSize, LogicalPosition, UserAttentionType, getCurrent } from "@tauri-apps/api/window";
import { open as openDialog } from "@tauri-apps/api/dialog";
import { open } from "@tauri-apps/api/shell";
window.UserAttentionType = UserAttentionType;
let selectedWindow = appWindow.label;
let selectedWindow = getCurrent().label;
const windowMap = {
[selectedWindow]: appWindow
}
@ -26,13 +26,6 @@
let maxHeight = null;
let x = 100;
let y = 100;
let scaleFactor = 1;
let innerPosition = new PhysicalPosition(x, y);
let outerPosition = new PhysicalPosition(x, y);
let innerSize = new PhysicalSize(width, height);
let outerSize = new PhysicalSize(width, height);
let resizeEventUnlisten;
let moveEventUnlisten;
let windowTitle = "Awesome Tauri Example!";
@ -69,39 +62,6 @@
})
}
function handleWindowResize() {
windowMap[selectedWindow].innerSize().then(response => {
innerSize = response
width = innerSize.width
height = innerSize.height
});
windowMap[selectedWindow].outerSize().then(response => {
outerSize = response
});
}
function handleWindowMove() {
windowMap[selectedWindow].innerPosition().then(response => {
innerPosition = response
});
windowMap[selectedWindow].outerPosition().then(response => {
outerPosition = response
x = outerPosition.x
y = outerPosition.y
});
}
function addWindowEventListeners(window) {
if (resizeEventUnlisten) {
resizeEventUnlisten();
}
if(moveEventUnlisten) {
moveEventUnlisten();
}
moveEventUnlisten = window.listen('tauri://move', handleWindowMove);
resizeEventUnlisten = window.listen('tauri://resize', handleWindowResize);
}
async function requestUserAttention_() {
await windowMap[selectedWindow].minimize();
await windowMap[selectedWindow].requestUserAttention(UserAttentionType.Critical);
@ -119,8 +79,6 @@
$: minWidth && minHeight ? windowMap[selectedWindow].setMinSize(new LogicalSize(minWidth, minHeight)) : windowMap[selectedWindow].setMinSize(null);
$: maxWidth && maxHeight ? windowMap[selectedWindow].setMaxSize(new LogicalSize(maxWidth, maxHeight)) : windowMap[selectedWindow].setMaxSize(null);
$: windowMap[selectedWindow].setPosition(new LogicalPosition(x, y));
$: windowMap[selectedWindow].scaleFactor().then(factor => scaleFactor = factor);
$: addWindowEventListeners(windowMap[selectedWindow]);
</script>
<div class="flex col">
@ -213,56 +171,6 @@
</div>
</div>
</div>
<div>
<div class="flex">
<div class="grow window-property">
<div>Inner Size</div>
<span>Width: {innerSize.width}</span>
<span>Height: {innerSize.height}</span>
</div>
<div class="grow window-property">
<div>Outer Size</div>
<span>Width: {outerSize.width}</span>
<span>Height: {outerSize.height}</span>
</div>
</div>
<div class="flex">
<div class="grow window-property">
<div>Inner Logical Size</div>
<span>Width: {innerSize.toLogical(scaleFactor).width}</span>
<span>Height: {innerSize.toLogical(scaleFactor).height}</span>
</div>
<div class="grow window-property">
<div>Outer Logical Size</div>
<span>Width: {outerSize.toLogical(scaleFactor).width}</span>
<span>Height: {outerSize.toLogical(scaleFactor).height}</span>
</div>
</div>
<div class="flex">
<div class="grow window-property">
<div>Inner Position</div>
<span>x: {innerPosition.x}</span>
<span>y: {innerPosition.y}</span>
</div>
<div class="grow window-property">
<div>Outer Position</div>
<span>x: {outerPosition.x}</span>
<span>y: {outerPosition.y}</span>
</div>
</div>
<div class="flex">
<div class="grow window-property">
<div>Inner Logical Position</div>
<span>x: {innerPosition.toLogical(scaleFactor).x}</span>
<span>y: {innerPosition.toLogical(scaleFactor).y}</span>
</div>
<div class="grow window-property">
<div>Outer Logical Position</div>
<span>x: {outerPosition.toLogical(scaleFactor).x}</span>
<span>y: {outerPosition.toLogical(scaleFactor).y}</span>
</div>
</div>
</div>
<form style="margin-top: 24px" on:submit|preventDefault={setTitle_}>
<input id="title" bind:value={windowTitle} />
<button class="button" type="submit">Set title</button>
@ -286,11 +194,4 @@
.window-controls input {
width: 50px;
}
.window-property {
margin-top: 12px;
}
.window-property span {
font-size: 0.8rem;
}
</style>

View File

@ -62,8 +62,8 @@
estree-walker "^1.0.1"
picomatch "^2.2.2"
"@tauri-apps/api@../../tooling/api/dist":
version "1.0.0-beta.7"
"@tauri-apps/api@link:../../tooling/api/dist":
version "0.0.0"
"@types/estree@*":
version "0.0.46"

View File

@ -16,9 +16,7 @@ use tauri::{command, State, Window};
#[derive(Debug)]
pub struct MyState {
#[allow(dead_code)]
value: u64,
#[allow(dead_code)]
label: String,
}

View File

@ -22,7 +22,7 @@ mod rust {
.setup(|app| {
let splashscreen_window = app.get_window("splashscreen").unwrap();
let main_window = app.get_window("main").unwrap();
// we perform the initialization code on a new task so the app doesn't crash
// we perform the initialization code on a new task so the app doesn't freeze
tauri::async_runtime::spawn(async move {
println!("Initializing...");
sleep(Duration::from_secs(2));

3165
examples/streaming/src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -41,35 +41,34 @@
"yarn": ">= 1.19.1"
},
"devDependencies": {
"@babel/core": "7.15.5",
"@babel/preset-env": "7.15.6",
"@babel/core": "7.15.0",
"@babel/preset-env": "7.15.0",
"@babel/preset-typescript": "7.15.0",
"@rollup/plugin-babel": "5.3.0",
"@rollup/plugin-commonjs": "20.0.0",
"@rollup/plugin-node-resolve": "13.0.5",
"@rollup/plugin-node-resolve": "13.0.4",
"@rollup/plugin-sucrase": "4.0.0",
"@rollup/plugin-typescript": "8.2.5",
"@typescript-eslint/eslint-plugin": "4.31.2",
"@typescript-eslint/parser": "4.31.2",
"@typescript-eslint/eslint-plugin": "4.29.1",
"@typescript-eslint/parser": "4.29.1",
"eslint": "7.32.0",
"eslint-config-prettier": "8.3.0",
"eslint-config-standard-with-typescript": "21.0.1",
"eslint-plugin-import": "2.24.2",
"eslint-config-standard-with-typescript": "20.0.0",
"eslint-plugin-import": "2.24.0",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-promise": "5.1.0",
"eslint-plugin-security": "1.4.0",
"fs-extra": "10.0.0",
"lockfile-lint": "4.6.2",
"prettier": "2.4.1",
"prettier": "2.3.2",
"regenerator-runtime": "0.13.9",
"rimraf": "3.0.2",
"rollup": "2.57.0",
"rollup": "2.56.2",
"rollup-plugin-terser": "7.0.2",
"tslib": "2.3.1",
"typedoc": "0.22.4",
"typedoc-plugin-markdown": "3.11.0",
"typescript": "4.4.3"
},
"dependencies": {
"type-fest": "2.3.4"
"type-fest": "2.0.0",
"typedoc": "0.21.5",
"typedoc-plugin-markdown": "3.10.4",
"typescript": "4.3.5"
}
}

View File

@ -3,6 +3,7 @@
// SPDX-License-Identifier: MIT
const { readFileSync, readdirSync, writeFileSync, copyFileSync } = require('fs')
const { copySync } = require('fs-extra')
// append our api modules to `exports` in `package.json` then write it to `./dist`
const pkg = JSON.parse(readFileSync('package.json', 'utf8'))
@ -41,3 +42,6 @@ const files = [
...dir.filter((f) => f.endsWith('.md'))
]
files.forEach((f) => copyFileSync(f, `dist/${f}`))
// copy typescript src files to `./dist`
copySync('src', 'dist')

View File

@ -23,7 +23,6 @@
* @module
*/
import { LiteralUnion } from 'type-fest'
import { isWindows } from './helpers/os-check'
import { invokeTauriCommand } from './helpers/tauri'
@ -34,17 +33,12 @@ import { invokeTauriCommand } from './helpers/tauri'
* */
const EOL = isWindows() ? '\r\n' : '\n'
type Platform = LiteralUnion<
'aix' | 'darwin' | 'freebsd' | 'linux' | 'openbsd' | 'sunos' | 'win32',
string
>
/**
* Returns a string identifying the operating system platform.
* The value is set at compile time. Possible values are `'aix'`, `'darwin'`, `'freebsd'`, `'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`.
*/
async function platform(): Promise<Platform> {
return invokeTauriCommand<Platform>({
async function platform(): Promise<string> {
return invokeTauriCommand<string>({
__tauriModule: 'Os',
message: {
cmd: 'platform'
@ -64,13 +58,11 @@ async function version(): Promise<string> {
})
}
type OsType = LiteralUnion<'Linux' | 'Darwin' | 'Windows_NT', string>
/**
* Returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows.
*/
async function type(): Promise<OsType> {
return invokeTauriCommand<OsType>({
async function type(): Promise<string> {
return invokeTauriCommand<string>({
__tauriModule: 'Os',
message: {
cmd: 'type'
@ -78,26 +70,11 @@ async function type(): Promise<OsType> {
})
}
type Arch = LiteralUnion<
| 'x86'
| 'x86_64'
| 'arm'
| 'aarch64'
| 'mips'
| 'mips64'
| 'powerpc'
| 'powerpc64'
| 'riscv64'
| 's390x'
| 'sparc64',
string
>
/**
* Returns the operating system CPU architecture for which the tauri app was compiled. Possible values are `'x86'`, `'x86_64'`, `'arm'`, `'aarch64'`, `'mips'`, `'mips64'`, `'powerpc'`, `'powerpc64'`, `'riscv64'`, `'s390x'`, `'sparc64'`
*/
async function arch(): Promise<Arch> {
return invokeTauriCommand<Arch>({
async function arch(): Promise<string> {
return invokeTauriCommand<string>({
__tauriModule: 'Os',
message: {
cmd: 'arch'
@ -118,4 +95,3 @@ async function tempdir(): Promise<string> {
}
export { EOL, platform, version, type, arch, tempdir }
export type { Platform, OsType, Arch }

View File

@ -47,7 +47,7 @@ async function appDir(): Promise<string> {
/**
* Returns the path to the user's audio directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$XDG_MUSIC_DIR`.
* - **macOS:** Resolves to `$HOME/Music`.
@ -69,7 +69,7 @@ async function audioDir(): Promise<string> {
/**
* Returns the path to the user's cache directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$XDG_CACHE_HOME` or `$HOME/.cache`.
* - **macOS:** Resolves to `$HOME/Library/Caches`.
@ -91,7 +91,7 @@ async function cacheDir(): Promise<string> {
/**
* Returns the path to the user's config directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$XDG_CONFIG_HOME` or `$HOME/.config`.
* - **macOS:** Resolves to `$HOME/Library/Application Support`.
@ -113,7 +113,7 @@ async function configDir(): Promise<string> {
/**
* Returns the path to the user's data directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$XDG_DATA_HOME` or `$HOME/.local/share`.
* - **macOS:** Resolves to `$HOME/Library/Application Support`.
@ -135,7 +135,7 @@ async function dataDir(): Promise<string> {
/**
* Returns the path to the user's desktop directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$XDG_DESKTOP_DIR`.
* - **macOS:** Resolves to `$HOME/Library/Desktop`.
@ -157,7 +157,7 @@ async function desktopDir(): Promise<string> {
/**
* Returns the path to the user's document directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$XDG_DOCUMENTS_DIR`.
* - **macOS:** Resolves to `$HOME/Documents`.
@ -179,7 +179,7 @@ async function documentDir(): Promise<string> {
/**
* Returns the path to the user's download directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux**: Resolves to `$XDG_DOWNLOAD_DIR`.
* - **macOS**: Resolves to `$HOME/Downloads`.
@ -201,7 +201,7 @@ async function downloadDir(): Promise<string> {
/**
* Returns the path to the user's executable directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$XDG_BIN_HOME/../bin` or `$XDG_DATA_HOME/../bin` or `$HOME/.local/bin`.
* - **macOS:** Not supported.
@ -223,7 +223,7 @@ async function executableDir(): Promise<string> {
/**
* Returns the path to the user's font directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$XDG_DATA_HOME/fonts` or `$HOME/.local/share/fonts`.
* - **macOS:** Resolves to `$HOME/Library/Fonts`.
@ -245,7 +245,7 @@ async function fontDir(): Promise<string> {
/**
* Returns the path to the user's home directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$HOME`.
* - **macOS:** Resolves to `$HOME`.
@ -267,7 +267,7 @@ async function homeDir(): Promise<string> {
/**
* Returns the path to the user's local data directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$XDG_DATA_HOME` or `$HOME/.local/share`.
* - **macOS:** Resolves to `$HOME/Library/Application Support`.
@ -289,7 +289,7 @@ async function localDataDir(): Promise<string> {
/**
* Returns the path to the user's picture directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$XDG_PICTURES_DIR`.
* - **macOS:** Resolves to `$HOME/Pictures`.
@ -311,7 +311,7 @@ async function pictureDir(): Promise<string> {
/**
* Returns the path to the user's public directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$XDG_PUBLICSHARE_DIR`.
* - **macOS:** Resolves to `$HOME/Public`.
@ -349,7 +349,7 @@ async function resourceDir(): Promise<string> {
/**
* Returns the path to the user's runtime directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$XDG_RUNTIME_DIR`.
* - **macOS:** Not supported.
@ -371,7 +371,7 @@ async function runtimeDir(): Promise<string> {
/**
* Returns the path to the user's template directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$XDG_TEMPLATES_DIR`.
* - **macOS:** Not supported.
@ -393,7 +393,7 @@ async function templateDir(): Promise<string> {
/**
* Returns the path to the user's video directory.
*
* #### Platform-specific
* ## Platform-specific
*
* - **Linux:** Resolves to `$XDG_VIDEOS_DIR`.
* - **macOS:** Resolves to `$HOME/Movies`.

View File

@ -176,13 +176,13 @@ declare global {
/** Attention type to request on a window. */
enum UserAttentionType {
/**
* #### Platform-specific
* ## Platform-specific
* - **macOS:** Bounces the dock icon until the application is in focus.
* - **Windows:** Flashes both the window and the taskbar button until the application is in focus.
*/
Critical = 1,
/**
* #### Platform-specific
* ## Platform-specific
* - **macOS:** Bounces the dock icon once.
* - **Windows:** Flashes the taskbar button until the application is in focus.
*/
@ -220,7 +220,7 @@ function getAll(): WebviewWindow[] {
// events that are emitted right here instead of by the created webview
const localTauriEvents = ['tauri://created', 'tauri://error']
/** @ignore */
export type WindowLabel = string
export type WindowLabel = string | null | undefined
/**
* A webview window handle allows emitting and listening to events from the backend that are tied to the window.
*/
@ -230,12 +230,8 @@ class WebviewWindowHandle {
/** Local event listeners. */
listeners: { [key: string]: Array<EventCallback<any>> }
constructor(label: WindowLabel | null | undefined) {
try {
this.label = label ?? window.__TAURI__.__currentWindow.label
} catch {
this.label = ''
}
constructor(label: WindowLabel) {
this.label = label
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.listeners = Object.create(null)
}
@ -334,7 +330,7 @@ class WindowManager extends WebviewWindowHandle {
/** The position of the top-left hand corner of the window's client area relative to the top-left hand corner of the desktop. */
async innerPosition(): Promise<PhysicalPosition> {
return invokeTauriCommand<{ x: number; y: number }>({
return invokeTauriCommand({
__tauriModule: 'Window',
message: {
cmd: 'manage',
@ -345,12 +341,12 @@ class WindowManager extends WebviewWindowHandle {
}
}
}
}).then(({ x, y }) => new PhysicalPosition(x, y))
})
}
/** The position of the top-left hand corner of the window relative to the top-left hand corner of the desktop. */
async outerPosition(): Promise<PhysicalPosition> {
return invokeTauriCommand<{ x: number; y: number }>({
return invokeTauriCommand({
__tauriModule: 'Window',
message: {
cmd: 'manage',
@ -361,7 +357,7 @@ class WindowManager extends WebviewWindowHandle {
}
}
}
}).then(({ x, y }) => new PhysicalPosition(x, y))
})
}
/**
@ -369,7 +365,7 @@ class WindowManager extends WebviewWindowHandle {
* The client area is the content of the window, excluding the title bar and borders.
*/
async innerSize(): Promise<PhysicalSize> {
return invokeTauriCommand<{ width: number; height: number }>({
return invokeTauriCommand({
__tauriModule: 'Window',
message: {
cmd: 'manage',
@ -380,7 +376,7 @@ class WindowManager extends WebviewWindowHandle {
}
}
}
}).then(({ width, height }) => new PhysicalSize(width, height))
})
}
/**
@ -388,7 +384,7 @@ class WindowManager extends WebviewWindowHandle {
* These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
*/
async outerSize(): Promise<PhysicalSize> {
return invokeTauriCommand<{ width: number; height: number }>({
return invokeTauriCommand({
__tauriModule: 'Window',
message: {
cmd: 'manage',
@ -399,7 +395,7 @@ class WindowManager extends WebviewWindowHandle {
}
}
}
}).then(({ width, height }) => new PhysicalSize(width, height))
})
}
/** Gets the window's current fullscreen state. */
@ -513,7 +509,7 @@ class WindowManager extends WebviewWindowHandle {
* Providing `null` will unset the request for user attention. Unsetting the request for
* user attention might not be done automatically by the WM when the window receives input.
*
* #### Platform-specific
* ## Platform-specific
*
* - **macOS:** `null` has no effect.
*
@ -1096,10 +1092,7 @@ class WindowManager extends WebviewWindowHandle {
* ```
*/
class WebviewWindow extends WindowManager {
constructor(
label: WindowLabel | null | undefined,
options: WindowOptions = {}
) {
constructor(label: WindowLabel, options: WindowOptions = {}) {
super(label)
// @ts-expect-error
if (!options?.skip) {

File diff suppressed because it is too large Load Diff

View File

@ -4,9 +4,9 @@ version = 3
[[package]]
name = "anyhow"
version = "1.0.44"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61604a8f862e1d5c3229fdd78f8b02c68dcf73a4c4b05fd636d12240aaa242c1"
checksum = "28b2cd92db5cbd74e8e5028f7e27dd7aa3090e89e4f2a197cc7c8dfb69c7063b"
[[package]]
name = "autocfg"
@ -16,9 +16,9 @@ checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "bitflags"
version = "1.3.2"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
[[package]]
name = "cfg-if"
@ -52,15 +52,15 @@ dependencies = [
[[package]]
name = "itoa"
version = "0.4.8"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4"
checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736"
[[package]]
name = "libc"
version = "0.2.103"
version = "0.2.94"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8f7255a17a627354f321ef0055d63b898c6fb27eff628af4d1b66b7331edf6"
checksum = "18794a8ad5b29321f790b55d93dfba91e125cb1a9edbd4f8e3150acc771c1a5e"
[[package]]
name = "num-integer"
@ -89,9 +89,9 @@ checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857"
[[package]]
name = "proc-macro2"
version = "1.0.29"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9f5105d4fdaab20335ca9565e106a5d9b82b6219b5ba735731124ac6711d23d"
checksum = "f0d8caf72986c1a598726adc988bb5984792ef84f5ee5aa50209145ee8077038"
dependencies = [
"unicode-xid",
]
@ -107,9 +107,9 @@ dependencies = [
[[package]]
name = "rand"
version = "0.8.4"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e7573632e6454cf6b99d7aac4ccca54be06da05aca2ef7423d22d27d4d4bcd8"
checksum = "0ef9e7e66b4468674bfcb0c81af8b7fa0bb154fa9f28eb840da5c447baeb8d7e"
dependencies = [
"libc",
"rand_chacha",
@ -119,9 +119,9 @@ dependencies = [
[[package]]
name = "rand_chacha"
version = "0.3.1"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
checksum = "e12735cf05c9e10bf21534da50a147b924d555dc7a547c42e6bb2d5b6017ae0d"
dependencies = [
"ppv-lite86",
"rand_core",
@ -129,27 +129,27 @@ dependencies = [
[[package]]
name = "rand_core"
version = "0.6.3"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7"
checksum = "34cf66eb183df1c5876e2dcf6b13d57340741e8dc255b48e40a26de954d06ae7"
dependencies = [
"getrandom",
]
[[package]]
name = "rand_hc"
version = "0.3.1"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d51e9f596de227fda2ea6c84607f5558e196eeaf43c986b724ba4fb8fdf497e7"
checksum = "3190ef7066a446f2e7f42e239d161e905420ccab01eb967c9eb27d21b2322a73"
dependencies = [
"rand_core",
]
[[package]]
name = "redox_syscall"
version = "0.2.10"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8383f39639269cde97d255a32bdb68c047337295414940c68bdd30c2e13203ff"
checksum = "742739e41cd49414de871ea5e549afb7e2a3ac77b589bcbebe8c82fab37147fc"
dependencies = [
"bitflags",
]
@ -171,18 +171,18 @@ checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
[[package]]
name = "serde"
version = "1.0.130"
version = "1.0.126"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f12d06de37cf59146fbdecab66aa99f9fe4f78722e3607577a5375d66bd0c913"
checksum = "ec7505abeacaec74ae4778d9d9328fe5a5d04253220a85c4ee022239fc996d03"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.130"
version = "1.0.126"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7bc1a1ab1961464eae040d96713baa5a724a8152c1222492465b54322ec508b"
checksum = "963a7dbc9895aeac7ac90e74f34a5d5261828f79df35cbed41e10189d3804d43"
dependencies = [
"proc-macro2",
"quote",
@ -191,9 +191,9 @@ dependencies = [
[[package]]
name = "serde_json"
version = "1.0.68"
version = "1.0.64"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f690853975602e1bfe1ccbf50504d67174e3bcf340f23b5ea9992e0587a52d8"
checksum = "799e97dc9fdae36a5c8b8f2cae9ce2ee9fdce2058c57a93e6099d919fd982f79"
dependencies = [
"itoa",
"ryu",
@ -202,9 +202,9 @@ dependencies = [
[[package]]
name = "syn"
version = "1.0.77"
version = "1.0.72"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5239bc68e0fef57495900cfea4e8dc75596d9a319d7e16b1e0a440d24e6fe0a0"
checksum = "a1e8cdbefb79a9a5a65e0db8b47b723ee907b7c7f8496c76a1770b5c310bab82"
dependencies = [
"proc-macro2",
"quote",

View File

@ -21,7 +21,7 @@ exclude = [
]
[dependencies]
ar = "0.9.0"
ar = "0.8.0"
glob = "0.3.0"
icns = "0.3"
image = "0.23.14"
@ -45,7 +45,7 @@ regex = "1"
attohttpc = "0.17"
uuid = { version = "0.8", features = [ "v4", "v5" ] }
bitness = "0.4"
winreg = "0.10"
winreg = "0.9"
sha2 = "0.9"
hex = "0.4"

View File

@ -8,7 +8,7 @@ use std::{
};
/// Directory options.
#[derive(Default, Clone)]
#[derive(Clone)]
pub struct DirOpts {
pub depth: u64,
}
@ -51,6 +51,12 @@ impl Default for Options {
}
}
impl Default for DirOpts {
fn default() -> DirOpts {
DirOpts { depth: 0 }
}
}
impl Default for FileOpts {
fn default() -> FileOpts {
FileOpts {

View File

@ -71,7 +71,7 @@
<Component Id="ApplicationShortcutDesktop" Guid="*">
<Shortcut Id="ApplicationDesktopShortcut" Name="{{{product_name}}}" Description="Runs {{{product_name}}}" Target="[!Path]" WorkingDirectory="INSTALLDIR" />
<RemoveFolder Id="DesktopFolder" On="uninstall" />
<RegistryValue Root="HKCU" Key="Software\\{{{product_name}}}" Name="installed" Type="integer" Value="1" KeyPath="yes" />
<RegistryValue Root="HKCU" Key="Software\{{{product_name}}}" Name="installed" Type="integer" Value="1" KeyPath="yes" />
</Component>
</Directory>
<Directory Id="$(var.PlatformProgramFilesFolder)" Name="PFiles">
@ -115,7 +115,7 @@
On="uninstall" />
<RegistryValue Root="HKCR"
Key="Software\\{{{manufacturer}}}\\{{{product_name}}}"
Key="Software\{{{manufacturer}}}\{{{product_name}}}"
Name="installed"
Type="integer"
Value="1"
@ -134,7 +134,7 @@
<ShortcutProperty Key="System.AppUserModel.ID" Value="{{{manufacturer}}}"/>
</Shortcut>
<RemoveFolder Id="ApplicationProgramsFolder" On="uninstall"/>
<RegistryValue Root="HKCU" Key="Software\\{{{manufacturer}}}\\{{{product_name}}}" Name="installed" Type="integer" Value="1" KeyPath="yes"/>
<RegistryValue Root="HKCU" Key="Software\{{{manufacturer}}}\{{{product_name}}}" Name="installed" Type="integer" Value="1" KeyPath="yes"/>
</Component>
</DirectoryRef>

View File

@ -54,64 +54,62 @@
"cross-env": "7.0.3",
"cross-spawn": "7.0.3",
"fs-extra": "10.0.0",
"glob": "7.2.0",
"global-agent": "3.0.0",
"got": "11.8.2",
"imagemin": "8.0.1",
"imagemin-optipng": "8.0.0",
"imagemin-zopfli": "7.0.0",
"inquirer": "8.1.5",
"is-png": "3.0.1",
"inquirer": "8.1.2",
"is-png": "3.0.0",
"minimist": "1.2.5",
"ms": "2.1.3",
"png2icons": "2.0.1",
"read-chunk": "4.0.2",
"read-chunk": "3.2.0",
"semver": "7.3.5",
"sharp": "0.29.1",
"sharp": "0.28.3",
"update-notifier": "5.1.0"
},
"devDependencies": {
"@babel/core": "7.15.5",
"@babel/preset-env": "7.15.6",
"@babel/core": "7.15.0",
"@babel/preset-env": "7.15.0",
"@babel/preset-typescript": "7.15.0",
"@jest/globals": "27.2.1",
"@jest/globals": "27.0.6",
"@rollup/plugin-babel": "5.3.0",
"@rollup/plugin-commonjs": "20.0.0",
"@rollup/plugin-node-resolve": "13.0.5",
"@rollup/plugin-replace": "3.0.0",
"@rollup/plugin-node-resolve": "13.0.4",
"@rollup/plugin-replace": "^3.0.0",
"@rollup/plugin-typescript": "8.2.5",
"@types/cross-spawn": "6.0.2",
"@types/fs-extra": "9.0.13",
"@types/glob": "7.1.4",
"@types/fs-extra": "9.0.12",
"@types/global-agent": "2.1.1",
"@types/imagemin": "8.0.0",
"@types/imagemin": "7.0.1",
"@types/imagemin-optipng": "5.2.1",
"@types/inquirer": "8.1.2",
"@types/inquirer": "7.3.3",
"@types/ms": "0.7.31",
"@types/semver": "7.3.8",
"@types/sharp": "0.29.2",
"@typescript-eslint/eslint-plugin": "4.31.2",
"@typescript-eslint/parser": "4.31.2",
"babel-jest": "27.2.1",
"@types/sharp": "0.28.5",
"@typescript-eslint/eslint-plugin": "4.29.1",
"@typescript-eslint/parser": "4.29.1",
"babel-jest": "27.0.6",
"eslint": "7.32.0",
"eslint-config-prettier": "8.3.0",
"eslint-config-standard-with-typescript": "21.0.1",
"eslint-plugin-import": "2.24.2",
"eslint-config-standard-with-typescript": "20.0.0",
"eslint-plugin-import": "2.24.0",
"eslint-plugin-lodash-template": "0.19.0",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-promise": "5.1.0",
"eslint-plugin-security": "1.4.0",
"is-running": "2.1.0",
"jest": "27.2.1",
"jest": "27.0.6",
"jest-transform-toml": "1.0.0",
"lockfile-lint": "4.6.2",
"prettier": "2.4.1",
"prettier": "2.3.2",
"promise": "8.1.0",
"rimraf": "3.0.2",
"rollup": "2.57.0",
"rollup": "2.56.2",
"rollup-plugin-terser": "7.0.2",
"tslib": "2.3.1",
"typescript": "4.4.3"
"typescript": "4.3.5"
},
"resolutions": {
"**/trim-newlines": "4.0.2"

View File

@ -27,23 +27,13 @@ export default {
},
treeshake: true,
perf: true,
output: [
{
output: {
dir: 'dist/',
entryFileNames: '[name].js',
format: 'esm',
exports: 'named',
globals: {}
},
{
dir: 'dist/',
entryFileNames: '[name].cjs',
format: 'cjs',
chunkFileNames: '[name]-[hash].cjs',
exports: 'named',
globals: {}
}
],
plugins: [
replace({
__RUST_CLI_VERSION__: JSON.stringify(cliManifest.package.version),

View File

@ -25,7 +25,7 @@ import zopfli from 'imagemin-zopfli'
import isPng from 'is-png'
import path from 'path'
import * as png2icons from 'png2icons'
import { readChunk } from 'read-chunk'
import readChunk from 'read-chunk'
import sharp from 'sharp'
import { appDir, tauriDir } from '../helpers/app-paths'
import logger from '../helpers/logger'
@ -74,7 +74,7 @@ const checkSrc = async (src: string): Promise<boolean | sharp.Sharp> => {
warn('[ERROR] Source image for tauricon not found')
process.exit(1)
} else {
const buffer = await readChunk(src, { startPosition: 0, length: 8 })
const buffer = await readChunk(src, 0, 8)
if (isPng(buffer)) {
image = sharp(src)
const meta = await image.metadata()

View File

@ -2,53 +2,36 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import { join, resolve, isAbsolute, dirname } from 'path'
import { existsSync } from 'fs'
import { join, normalize, resolve, sep, isAbsolute } from 'path'
import logger from './logger'
import chalk from 'chalk'
import { createRequire } from 'module'
const warn = logger('tauri', chalk.red)
const require = createRequire(import.meta.url)
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-unsafe-assignment
const glob = require('glob')
function resolvePath(basePath: string, dir: string): string {
return dir && isAbsolute(dir) ? dir : resolve(basePath, dir)
}
const getAppDir = (): string | null => {
const dir = process.env.__TAURI_TEST_APP_DIR ?? process.cwd()
// eslint-disable-next-line
const matches: string[] = glob.sync(join(dir, `**/package.json`), {
ignore: '**/node_modules/**'
})
const getAppDir = (): string => {
let dir = process.env.__TAURI_TEST_APP_DIR ?? process.cwd()
let count = 0
if (matches.length === 0) {
return null
} else {
return dirname(matches[0])
// only go up three folders max
while (dir.length > 0 && !dir.endsWith(sep) && count <= 2) {
if (existsSync(join(dir, 'src-tauri', 'tauri.conf.json'))) {
return dir
}
count++
dir = normalize(join(dir, '..'))
}
}
const getTauriDir = (): string => {
const dir = process.env.__TAURI_TEST_APP_DIR ?? process.cwd()
// eslint-disable-next-line
const matches: string[] = glob.sync(join(dir, `**/tauri.conf.json`))
if (matches.length === 0) {
warn(
"Couldn't recognize the current folder as a part of a Tauri project. It must contain a `tauri.conf.json` file in any subfolder."
)
warn("Couldn't recognize the current folder as a part of a Tauri project")
process.exit(1)
return ''
} else {
return dirname(matches[0])
}
}
const appDir = getAppDir() ?? resolve(getTauriDir(), '..')
const tauriDir = getTauriDir()
const appDir = getAppDir()
const tauriDir = resolve(appDir, 'src-tauri')
const resolveDir = {
app: (dir: string) => resolvePath(appDir, dir),

View File

@ -1,7 +1,6 @@
import * as fixtureSetup from '../fixtures/app-test-setup.js'
import { resolve, dirname } from 'path'
import { existsSync, readFileSync, writeFileSync } from 'fs'
import { move } from 'fs-extra'
import { writeFileSync, readFileSync } from 'fs'
import { init, build } from 'dist/api/cli'
import { fileURLToPath } from 'url'
@ -12,18 +11,11 @@ describe('[CLI] cli.js template', () => {
const cwd = process.cwd()
const fixturePath = resolve(currentDirName, '../fixtures/empty')
const tauriFixturePath = resolve(fixturePath, 'src-tauri')
const outPath = resolve(tauriFixturePath, 'target')
const cacheOutPath = resolve(fixturePath, 'target')
fixtureSetup.initJest('empty')
process.chdir(fixturePath)
const outExists = existsSync(outPath)
if (outExists) {
await move(outPath, cacheOutPath)
}
const { promise } = await init({
directory: process.cwd(),
force: true,
@ -32,10 +24,6 @@ describe('[CLI] cli.js template', () => {
})
await promise
if (outExists) {
await move(cacheOutPath, outPath)
}
process.chdir(tauriFixturePath)
const manifestPath = resolve(tauriFixturePath, 'Cargo.toml')

View File

@ -23,7 +23,7 @@ icon = [
tauri-build = { path = "../../../../../../../core/tauri-build" }
[dependencies]
serde_json = "1.0.68"
serde_json = "1.0.66"
serde = "1.0"
serde_derive = "1.0"
tauri = { path = "../../../../../../../core/tauri", features = ["api-all"] }

File diff suppressed because it is too large Load Diff

View File

@ -31,9 +31,9 @@ checksum = "28ae2b3dec75a406790005a200b1bd89785afc02517a00ca99ecfe093ee9e6cf"
[[package]]
name = "ar"
version = "0.9.0"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d67af77d68a931ecd5cbd8a3b5987d63a1d1d1278f7f6a60ae33db485cdebb69"
checksum = "450575f58f7bee32816abbff470cbc47797397c2a81e0eaced4b98436daf52e1"
[[package]]
name = "attohttpc"
@ -794,15 +794,6 @@ dependencies = [
"libc",
]
[[package]]
name = "itertools"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69ddb889f9d0d08a67338271fa9b62996bc788c7796a5c18cf057420aaed5eaf"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "0.4.7"
@ -1752,9 +1743,9 @@ dependencies = [
[[package]]
name = "serde_with"
version = "1.10.0"
version = "1.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "062b87e45d8f26714eacfaef0ed9a583e2bfd50ebd96bdd3c200733bd5758e2c"
checksum = "1ad9fdbb69badc8916db738c25efd04f0a65297d26c2f8de4b62e57b8c12bc72"
dependencies = [
"rustversion",
"serde",
@ -1763,9 +1754,9 @@ dependencies = [
[[package]]
name = "serde_with_macros"
version = "1.5.0"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98c1fcca18d55d1763e1c16873c4bde0ac3ef75179a28c7b372917e0494625be"
checksum = "e1569374bd54623ec8bd592cf22ba6e03c0f177ff55fbc8c29a49e296e7adecf"
dependencies = [
"darling",
"proc-macro2",
@ -1922,7 +1913,6 @@ dependencies = [
"clap",
"colored",
"encode_unicode",
"glob",
"handlebars",
"heck",
"include_dir",
@ -2061,14 +2051,13 @@ dependencies = [
[[package]]
name = "toml_edit"
version = "0.3.1"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d30834716e93eef7db510648299f647427858e7e2c0beeec2699ea2289c7739"
checksum = "dbbdcf4f749dd33b1f1ea19b547bf789d87442ec40767d6015e5e2d39158d69a"
dependencies = [
"chrono",
"combine",
"indexmap",
"itertools",
"vec1",
"linked-hash-map",
]
[[package]]
@ -2142,9 +2131,9 @@ checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"
[[package]]
name = "ureq"
version = "2.2.0"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3131cd6cb18488da91da1d10ed31e966f453c06b65bf010d35638456976a3fd7"
checksum = "2475a6781e9bc546e7b64f4013d2f4032c8c6a40fcffd7c6f4ee734a890972ab"
dependencies = [
"base64",
"chunked_transfer",
@ -2215,12 +2204,6 @@ version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "vec1"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fc1631c774f0f9570797191e01247cbefde789eebfbf128074cb934115a6133"
[[package]]
name = "vec_map"
version = "0.8.2"
@ -2396,9 +2379,9 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "winreg"
version = "0.10.1"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d"
checksum = "16cdb3898397cf7f624c294948669beafaeebc5577d5ec53d0afb76633593597"
dependencies = [
"winapi 0.3.9",
]

View File

@ -17,17 +17,17 @@ name = "cargo-tauri"
path = "src/main.rs"
[dependencies]
clap = { version = "3.0.0-beta.4", features = [ "yaml" ] }
clap = { version = "3.0.0-beta.2", features = [ "yaml" ] }
anyhow = "1.0"
tauri-bundler = { version = "1.0.0-beta.4", path = "../bundler" }
colored = "2.0"
once_cell = "1.8"
serde = { version = "1.0", features = [ "derive" ] }
serde_json = "1.0"
serde_with = "1.10"
serde_with = "1.9"
notify = "4.0"
shared_child = "0.3"
toml_edit = "0.3"
toml_edit = "0.2"
json-patch = "0.2"
schemars = "0.8"
toml = "0.5"
@ -36,7 +36,7 @@ handlebars = "4.1"
include_dir = "0.6"
minisign = "0.6"
base64 = "0.13.0"
ureq = "2.2"
ureq = "2.1"
os_info = "3.0"
semver = "1.0"
regex = "1.5"
@ -46,13 +46,14 @@ terminal_size = "0.1"
unicode-width = "0.1"
tempfile = "3"
zeroize = "1.4"
glob = "0.3"
heck = "0.3"
[target."cfg(windows)".dependencies]
winapi = { version = "0.3", features = [ "winbase", "winuser", "consoleapi", "processenv", "wincon" ] }
encode_unicode = "0.3"
[target."cfg(target_os = \"linux\")".dependencies]
heck = "0.3"
[target."cfg(target_os = \"linux\")".build-dependencies]
heck = "0.3"
@ -60,4 +61,4 @@ heck = "0.3"
schemars = "0.8"
serde = { version = "1.0", features = [ "derive" ] }
serde_json = "1.0"
serde_with = "1.10"
serde_with = "1.9"

View File

@ -815,18 +815,14 @@ pub struct BuildConfig {
/// The path or URL to use on development.
#[serde(default = "default_dev_path")]
pub dev_path: AppUrl,
/// The path to the app's dist dir. This path must contain your index.html file.
/// the path to the app's dist dir. This path must contain your index.html file.
#[serde(default = "default_dist_dir")]
pub dist_dir: AppUrl,
/// A shell command to run before `tauri dev` kicks in.
///
/// The PLATFORM, ARCH, FAMILY and PLATFORM_TYPE environment variables are set if you perform conditional compilation.
/// a shell command to run before `tauri dev` kicks in
pub before_dev_command: Option<String>,
/// A shell command to run before `tauri build` kicks in.
///
/// The PLATFORM, ARCH, FAMILY and PLATFORM_TYPE environment variables are set if you perform conditional compilation.
/// a shell command to run before `tauri build` kicks in
pub before_build_command: Option<String>,
/// Features passed to `cargo` commands.
/// features passed to `cargo` commands
pub features: Option<Vec<String>>,
/// Whether we should inject the Tauri API on `window.__TAURI__` or not.
#[serde(default)]

View File

@ -261,14 +261,14 @@
"type": "object",
"properties": {
"beforeBuildCommand": {
"description": "A shell command to run before `tauri build` kicks in.\n\nThe PLATFORM, ARCH, FAMILY and PLATFORM_TYPE environment variables are set if you perform conditional compilation.",
"description": "a shell command to run before `tauri build` kicks in",
"type": [
"string",
"null"
]
},
"beforeDevCommand": {
"description": "A shell command to run before `tauri dev` kicks in.\n\nThe PLATFORM, ARCH, FAMILY and PLATFORM_TYPE environment variables are set if you perform conditional compilation.",
"description": "a shell command to run before `tauri dev` kicks in",
"type": [
"string",
"null"
@ -284,7 +284,7 @@
]
},
"distDir": {
"description": "The path to the app's dist dir. This path must contain your index.html file.",
"description": "the path to the app's dist dir. This path must contain your index.html file.",
"default": "../dist",
"allOf": [
{
@ -293,7 +293,7 @@
]
},
"features": {
"description": "Features passed to `cargo` commands.",
"description": "features passed to `cargo` commands",
"type": [
"array",
"null"

View File

@ -9,7 +9,6 @@ use tauri_bundler::bundle::{bundle_project, PackageType};
use crate::helpers::{
app_paths::{app_dir, tauri_dir},
command_env,
config::{get as get_config, AppUrl},
execute_with_output,
manifest::rewrite_manifest,
@ -90,8 +89,7 @@ impl Build {
&mut Command::new("cmd")
.arg("/C")
.arg(before_build)
.current_dir(app_dir())
.envs(command_env()),
.current_dir(app_dir()),
)
.with_context(|| format!("failed to run `{}` with `cmd /C`", before_build))?;
#[cfg(not(target_os = "windows"))]
@ -99,8 +97,7 @@ impl Build {
&mut Command::new("sh")
.arg("-c")
.arg(before_build)
.current_dir(app_dir())
.envs(command_env()),
.current_dir(app_dir()),
)
.with_context(|| format!("failed to run `{}` with `sh -c`", before_build))?;
}
@ -136,11 +133,7 @@ impl Build {
.get_out_dir(self.target.clone(), self.debug)
.with_context(|| "failed to get project out directory")?;
if let Some(product_name) = config_.package.product_name.clone() {
let bin_name = app_settings
.cargo_package_settings()
.name
.clone()
.expect("Cargo manifest must have the `package.name` field");
let bin_name = app_settings.cargo_package_settings().name.clone();
#[cfg(windows)]
let (bin_path, product_path) = {
(

View File

@ -128,7 +128,7 @@ subcommands:
- info:
about: Shows information about Tauri dependencies
- init:
about: Initializes a Tauri project.
about: Initializes a Tauri project
args:
- ci:
long: ci
@ -171,27 +171,3 @@ subcommands:
long: dev-path
about: Url of your dev server
takes_value: true
subcommands:
- plugin:
about: Initializes a Tauri plugin project.
args:
- name:
short: n
long: name
about: Name of your Tauri plugin
takes_value: true
required: true
- directory:
short: d
long: directory
about: Set target directory for init
takes_value: true
- tauri-path:
short: t
long: tauri-path
about: Path of the Tauri project to use (relative to the cwd)
takes_value: true
- api:
short: a
long: api
about: Initializes a Tauri plugin with TypeScript API.

View File

@ -4,7 +4,6 @@
use crate::helpers::{
app_paths::{app_dir, tauri_dir},
command_env,
config::{get as get_config, reload as reload_config},
manifest::{get_workspace_members, rewrite_manifest},
Logger,
@ -142,7 +141,6 @@ impl Dev {
.arg("/C")
.arg(before_dev)
.current_dir(app_dir())
.envs(command_env())
.spawn()
.with_context(|| format!("failed to run `{}` with `cmd /C`", before_dev))?;
#[cfg(not(target_os = "windows"))]
@ -150,7 +148,6 @@ impl Dev {
.arg("-c")
.arg(before_dev)
.current_dir(app_dir())
.envs(command_env())
.spawn()
.with_context(|| format!("failed to run `{}` with `sh -c`", before_dev))?;
BEFORE_DEV.set(Mutex::new(child)).unwrap();

View File

@ -6,42 +6,34 @@ use std::{env::current_dir, path::PathBuf};
use once_cell::sync::Lazy;
fn get_tauri_dir() -> PathBuf {
glob::glob(
&current_dir()
.expect("failed to read cwd")
.join("**/tauri.conf.json")
.to_string_lossy()
.into_owned(),
)
.unwrap()
.filter_map(Result::ok)
.last()
.map(|p| p.parent().unwrap().to_path_buf())
.expect("Couldn't recognize the current folder as a Tauri project. It must contain a `tauri.conf.json` file in any subfolder.")
}
fn get_app_dir() -> PathBuf {
let mut dir = current_dir().expect("failed to read cwd");
fn get_app_dir() -> Option<PathBuf> {
glob::glob(
&current_dir()
.expect("failed to read cwd")
.join("**/package.json")
.to_string_lossy()
.into_owned(),
)
.unwrap()
.filter_map(Result::ok)
.filter(|p| !p.to_string_lossy().into_owned().contains("node_modules"))
.last()
.map(|p| p.parent().unwrap().to_path_buf())
let mut count = 0;
// only go up three folders max
while count <= 2 {
let test_path = dir.join("src-tauri/tauri.conf.json");
if test_path.exists() {
return dir;
}
count += 1;
match dir.parent() {
Some(parent) => {
dir = parent.to_path_buf();
}
None => break,
}
}
panic!("Couldn't recognize the current folder as a Tauri project.")
}
pub fn app_dir() -> &'static PathBuf {
static APP_DIR: Lazy<PathBuf> =
Lazy::new(|| get_app_dir().unwrap_or_else(|| get_tauri_dir().parent().unwrap().to_path_buf()));
static APP_DIR: Lazy<PathBuf> = Lazy::new(get_app_dir);
&APP_DIR
}
pub fn tauri_dir() -> PathBuf {
get_tauri_dir()
app_dir().join("src-tauri")
}

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