Compare commits

...

189 Commits

Author SHA1 Message Date
github-actions[bot]
0af553da72 Apply Version Updates From Current Changes (v1) (#7261)
Co-authored-by: lucasfernog <lucasfernog@users.noreply.github.com>
2023-09-28 14:01:19 -03:00
Lucas Fernandes Nogueira
e9e68abb33 fix(ci): downgrade async-executor to 1.5.2 (#7911) 2023-09-28 10:48:52 -03:00
Lucas Fernandes Nogueira
c68fbfcb2d fix: Returns a warning instead of panicking if an AppImage is not mounted, closes #7736 (#7912)
Co-authored-by: Benjamin Demetz <50681275+Benji377@users.noreply.github.com>
2023-09-28 10:46:17 -03:00
Fabian-Lars
d1858de7a0 fix(cli): help output mixed up for private-key and private-key-path (#7901) 2023-09-26 14:41:32 -03:00
Fabian-Lars
9aa34ada57 feat(core): Allow http origin on Windows, fixes: #3007 (#7645)
Co-authored-by: Lucas Nogueira <118899497+lucasfernog-crabnebula@users.noreply.github.com>
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-09-26 14:40:38 -03:00
Fabian-Lars
e8ff6b153e docs: change icon help output to ask for 1024px source icons, closes #7886 (#7896) 2023-09-25 14:44:27 +03:00
Trey Smith
5ecb46b341 fix: rpath missing from app, closes #7710 (#7773)
Co-authored-by: Lucas Nogueira <lucas@tauri.app>
Co-authored-by: Lucas Fernandes Nogueira <lucas@tauri.studio>
fix: codesign doesn't sign frameworks or sidecar, closes #7690 (#7774)
2023-09-24 19:11:20 -03:00
Trey Smith
dcdbe3eb6c fix: codesign doesn't sign frameworks or sidecar, closes #7690 (#7774)
Co-authored-by: Lucas Nogueira <lucas@tauri.app>
2023-09-15 12:09:10 -03:00
Trey Smith
2f8881c010 feat: add team_id option for apple notarization (#7775)
Co-authored-by: Lucas Nogueira <lucas@tauri.app>
2023-09-15 08:30:27 -03:00
Lucas Fernandes Nogueira
995ffc629b fix(ci): recreate symlink so the integration tests works (#7833) 2023-09-13 21:55:47 -03:00
Lucas Fernandes Nogueira
b3ebe4de3c chore(config-schema): remove unused deps (#7824) 2023-09-12 23:55:27 +03:00
Amr Bashir
4bf1e85e6b fix(windows): respect focused: false for webview, closes #7519 (#7722)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
fix(windows): respect `focused: false` for webview, closes #7519
2023-09-11 17:00:06 -03:00
Davis Silverman
0b0bc81710 Extend context.rs to dynamically find the OUT_DIR for certain assets (#7534)
Co-authored-by: Lucas Fernandes Nogueira <lucas@tauri.studio>
2023-09-11 16:59:30 -03:00
Lucas Fernandes Nogueira
1945dec81f fix(ci): adjust downgrade crates step (#7812) 2023-09-11 15:30:37 -03:00
Jason Tsai
e3bfb01411 feat(nsis): support choosing compression algorithms, closes #7685 (#7776) 2023-09-07 18:45:15 +03:00
Lucas Fernandes Nogueira
dfbbca423b feat(bundler): try to find API key file for notarization, ref #7616 (#7771) 2023-09-07 10:01:12 -03:00
Jason Tsai
0797a002ca fix: use button property for data-tauri-drag-region mouse button detection, closes #7694 (#7746) 2023-09-07 09:55:47 -03:00
Amr Bashir
53ab2042fd refactor: remove unnecessary mutex (#7728) 2023-09-07 09:09:59 -03:00
martin frances
50878901ba chore: resolves a warning seen while running cargo update (#7753)
* chore: resolves a warning seen while running cargo update

warning: some crates are on edition 2021 which defaults to `resolver = "2"`, but virtual workspaces default to `resolver = "1"`
note: to keep the current resolver, specify `workspace.resolver = "1"` in the workspace root's manifest
note: to use the edition 2021 resolver, specify `workspace.resolver = "2"` in the workspace root's manifest

* Now using resolver 2.
2023-09-05 14:28:33 +03:00
Amr Bashir
49beb67dab ci: fix clippy lints (#7721)
* ci: fix clippy lints

* more lints
2023-08-31 13:53:15 +03:00
Colin McDonnell
e152662687 feat: support Bun package manager (#7723)
* Support bun

* clippy
2023-08-31 02:48:36 +03:00
i-c-b
13279917d4 enhance(cli): Add Cargo Tauri CLI version to tauri info output (#7713)
* enhance(cli): Add Cargo Tauri CLI version to `tauri info` output

* Create enhance-cli-cargo-tauri-cli-version-info.md
2023-08-31 01:53:37 +03:00
Fabian-Lars
85112e7f8f ci: downgrade h2 and reqwest (#7717)
* ci: downgrade h2 to 0.3.20

* reqwest

* Update test-core.yml

---------

Co-authored-by: Amr Bashir <amr.bashir2015@gmail.com>
2023-08-30 20:43:01 +03:00
Amr Bashir
09f7f57eea chore(deps): update nsis_tuari_utils to 0.2.1 (#7711)
* chore(deps): update nsis_tuari_utils to 0.2.1

* Update .changes/nsis-kill-own-process.md
2023-08-30 15:49:47 +03:00
Fabian-Lars
f19c7fc5c3 ci: Update serde_with downgrade to match 3.3.0 (#7654) 2023-08-30 03:44:05 +03:00
Fabian-Lars
8c5fcf41e3 ci: Downgrade tokio to 1.29 and flate2 to 1.0.26 (#7646)
* ci: Downgrade tokio to 1.29

* downgrade flate2 too
2023-08-18 03:14:38 +03:00
Fabian-Lars
58d6b899e2 feat(api): Add append option to writeFile apis (#7636)
* feat(api): Add `append` option to writeFile apis.

* wording

* fmt

* Update .changes/fs-append-file.md


* clippeeeyyyy
2023-08-16 19:09:05 +03:00
Lucas Fernandes Nogueira
964d81ff01 refactor(bundler): switch to notarytool, closes #4300 (#7616) 2023-08-16 11:10:02 +09:00
Amr Bashir
a7777ff485 feat(bundler/NSIS): Add Bulgarian to supported NSIS languages. (#7624) (#7626)
* Create Bulgarian.nsh

* Update nsis.rs

* Create nsis-bulgarian.md

Co-authored-by: Angelo II <62988428+AngeloCore@users.noreply.github.com>
2023-08-16 11:09:45 +09:00
Amr Bashir
72a3d75e8f chore(deps): update nsis_tuari_utils to 0.2 (#7625) 2023-08-15 23:23:26 +03:00
Jet Li
ca977f4b87 fix(bundler/nsis): revert shell context change before deleting appdata, closes #7588 (#7591)
* fix(bundler/nsis): delete app data of current user when uninstall, closes #7588

* fix(bundler/nsis): delete app data of current user when uninstall, closes #7588

* Update .changes/fix-nsis-uninstall-delete-app-data.md

---------
2023-08-15 18:59:44 +03:00
Fabian-Lars
9308dee0a1 docs: Be more specific about plugin names in ipc scope (#7605) 2023-08-15 10:56:05 -03:00
Graeme McHale
10e362d098 feat: allow more flexible http requests in updater closes #7422 (#7432)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-08-10 07:23:52 -03:00
renovate[bot]
b420962377 chore(deps) Update Tauri API Definitions (1.x) (#7577)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-08-10 07:22:45 -03:00
Lucas Fernandes Nogueira
cca5301b88 added missing futures-util (#7260) (#7565)
Co-authored-by: Simon Hyll <hyllsimon@gmail.com>
2023-08-09 17:39:27 -03:00
Isaac Cambron
eeb6be5422 feat(core): Manager::emit_filter and optimize serialization (#7512)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-08-08 16:57:30 -03:00
Amr Bashir
a6b52e44f2 fix(tauri-utils): include \n in io::read_line, closes #6388 (#6519)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
fix(tauri-utils): include `\n` in `io::read_line`, closes #6388
2023-08-08 16:43:19 -03:00
Alejandro González
9edebbba4e fix(driver): bump locked dependencies to fix build issue on Windows (#7475) 2023-08-08 15:46:32 -03:00
Fabian-Lars
cb1d4164e7 fix(bundler): sign the exe before the bundler step (#7487) 2023-08-08 15:16:00 -03:00
Amr Bashir
6c408b736c feat: add notification sound (#7269)
Co-authored-by: Lucas Fernandes Nogueira <lucas@tauri.studio>
Co-authored-by: Lucas Nogueira <lucas@tauri.app>
2023-08-08 15:09:04 -03:00
Lorenzo Lewis
c272e4afbf chore: remove typedoc integration (#7515)
Signed-off-by: Lorenzo Lewis <lorenzo_lewis@icloud.com>
2023-07-28 15:37:27 +03:00
Fabian-Lars
e374bc130d ci: lock tempfile and serde_with versions in CI (#7495)
* ci: lock tempfile and serde_with versions in CI

* Update test-core.yml
2023-07-25 18:25:14 +03:00
Jet Li
57f73f1b6a fix(bundler/nsis): use temp dir for webview2 installer, closes #7409 (#7486)
* fix(bundler/nsis): use temp dir for webview2 installer, closes #7409

* Update .changes/fix-nsis-webview2-installer-use-tempdir.md

---------

Co-authored-by: Amr Bashir <amr.bashir2015@gmail.com>
2023-07-25 17:29:59 +03:00
Alejandro González
2d35f937de fix(bundler): do not skip updater bundle target if only a macOS DMG is generated (#7481) 2023-07-24 09:27:11 -03:00
Lucas Fernandes Nogueira
4dd4893d7d feat: allow specifying a resource map, closes #5844 (#5950)
Co-authored-by: amrbashir <amr.bashir2015@gmail.com>
closes #5844
2023-07-13 18:28:52 -03:00
Dave Ceddia
ef962c43af fix(cli): handle symlinks in updater bundler, closes #3933 (#3934)
Co-authored-by: chip <chip@chip.sh>
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
Co-authored-by: Lucas Fernandes Nogueira <lucas@tauri.app>
2023-07-13 14:35:22 -03:00
Fabian-Lars
290e366ae9 fix(build): Copy wv2 runtime in dev, fixes #7373 (#7419) 2023-07-13 14:34:31 -03:00
Lucas Fernandes Nogueira
c98273387c feat(core): enhance readDir error message, closes #7379 (#7416) 2023-07-13 08:00:51 -07:00
Amr Bashir
2eab150563 feat(api/http): properly handle Files in Body.form, closes #7390 (#7394)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
closes #7390
2023-07-13 08:58:21 -03:00
Amr Bashir
fdaee9a5ce feat(core/plugin): add register_uri_scheme_protocol, closes #7330 (#7350)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
closes #7330
2023-07-12 16:49:32 -03:00
Amr Bashir
71a0240166 chore: remove hotkey.js script and replace var with const (#7343)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-07-12 08:44:26 -03:00
Amr Bashir
a2be88a21d refactor: remove bitness crate from bundler (#7405)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-07-12 07:38:25 -03:00
清茶
907425df55 feat(cli): check cwd for config file before traversing (#7395) 2023-07-11 18:29:15 +03:00
Amr Bashir
764968ab38 feat(bundler/nsis): sign uninstaller, closes #7348 (#7398)
* feat(bundler/nsis): sign uninstaller, closes #7348

* Update bundler-nsis-sign-uninstaller.md

* clippy
2023-07-11 15:54:59 +03:00
Amr Bashir
757e959eb2 feat: respect base tag's target attribute, closes #7285 (#7344)
* feat: respect `base` tag's `target` attribute, closes #7285

* Update core.js

* fix condition
2023-07-11 15:11:23 +03:00
Amr Bashir
fa7f9b77ab fix(core/updater): set max_redirections of 5, closes #7329 (#7341)
* fix(core/updater): set `max_redirections` of 5, closes #7329

* Update .changes/updater-redirect.md
2023-07-11 15:08:53 +03:00
Lucas Fernandes Nogueira
eeff1784e1 chore(deps): update unmaintained dependency from kuchiki to kuchikiki (#7359) (#7367)
Co-authored-by: Davide Baldo <davide@baldo.me>
Co-authored-by: Amr Bashir <amr.bashir2015@gmail.com>
2023-07-11 19:19:13 +09:00
Amr Bashir
e05cd940d6 ci: fix audit workflow and add resolutions for vuln packages (#7392)
* ci: fix audit workflow and add resolutions for vuln packages

* revert rust audit changes
2023-07-11 00:25:18 +03:00
Amr Bashir
f6a13f6f23 ci: downgrade more crates is-terminal, colored and toml:0.7.6 (#7391)
* ci: downgrade more crates `is-terminal`, `colored` and `toml:0.7.6`

* downgrade all versions of toml and cargo_toml

* revert
2023-07-10 16:45:50 +03:00
luofei
eba8e1315e fix(bundler/nsis): fix installer incorrect copyright info (#7386)
Signed-off-by: luofei <luoffei@outlook.com>
2023-07-10 14:56:13 +03:00
Amr Bashir
6e36ebbf84 fix(nsis): set correct ShellVarContext for uninstaller, closes #7315 (#7342) 2023-07-10 14:46:15 +03:00
luofei
32218a6f8c fix(bundler/nsis): use uninstallstring to find wix installation (#7326)
* add change file

Signed-off-by: luofei <luoffei@outlook.com>

* fix(bundler/nsis): Check if the previous installation was done using WiX

Signed-off-by: luofei <luoffei@outlook.com>

* Update .changes/fix-nsis-previous-installation-method.md

---------

Signed-off-by: luofei <luoffei@outlook.com>
2023-07-08 04:26:40 +03:00
luofei
0ae53f4139 fix(bundler/nsis): fix error message appears even after successful uninstall, closes #7317 (#7361)
* fix(bundler/nsis): Uninstall the previous installation package

* Update .changes/fix-nsis-uninstall-previous-version.md

---------

Co-authored-by: Amr Bashir <amr.bashir2015@gmail.com>
2023-07-08 03:43:35 +03:00
Amr Bashir
46df2c9b91 fix(bundler): sort package types before bundling, closes #7349 (#7360)
fix(bundler): sort package types before bundling, closes #7349
2023-07-05 17:17:31 -03:00
Lucas Fernandes Nogueira
f4aedce96c fix(ci): adjust crate downgrades for test-core MSRV (#7346) 2023-07-03 15:42:34 -07:00
Lucas Fernandes Nogueira
539247aacf fix(ci): adjust downgrade crates version step on test-core workflow (#7309) 2023-06-30 09:04:09 -07:00
Fabian-Lars
dad4f54eec fix(cli): Disable version check, fixes #7273 (#7277) 2023-06-21 19:19:31 +08:00
Lucas Fernandes Nogueira
df6712cfb3 docs(core): fix panic section on manage documentation (#7251) 2023-06-21 07:50:41 -03:00
Raphii
1a3dcdb830 fix(core): fix nsis updater unable to launch installers requiring elevation, closes #7184 (#7185)
* Launch NSIS updaters requiring elevation from non-elevated process

* Add changes file

* remove detached process, use powershell

* Update updater-admin-launch-fix.md

---------

Co-authored-by: Amr Bashir <amr.bashir2015@gmail.com>
2023-06-19 18:11:16 +03:00
Amr Bashir
8c0166f459 ci: use toJSON (#7248) 2023-06-18 06:58:34 -03:00
Lucas Fernandes Nogueira
fdf68405a4 chore(ci): use a separate covector workflor for 1.x (#7243) 2023-06-18 06:57:37 -03:00
Lucas Fernandes Nogueira
be6f4319ff fix(ci): correctly set tag for tauri-cli release (#7246) 2023-06-17 19:14:12 -03:00
Lucas Fernandes Nogueira
2acc474ccb fix(ci): only check change tags on added or modified files (#7236) 2023-06-17 16:57:25 +03:00
github-actions[bot]
4b3d66c793 Apply Version Updates From Current Changes (v1) (#7234)
Co-authored-by: lucasfernog <lucasfernog@users.noreply.github.com>
2023-06-17 10:45:52 -03:00
Lucas Fernandes Nogueira
49dbbbbcdf feat(ci): prepare CI for 1.x branch (#7231) 2023-06-17 09:41:22 -03:00
Amr Bashir
6afd34727f fix(core): revert #6680, remove default notification sound on Windows (#7229)
fix(core): revert #6680, remove default notification sound on Windows
2023-06-17 09:18:16 -03:00
Amr Bashir
066c09a6ea fix(core): fix require_literal_leading_dot flipped behavior (#7227) 2023-06-17 09:17:36 -03:00
Amr Bashir
28921cb8e8 ci: fix getting release id (#7207) 2023-06-15 08:36:05 -03:00
Lucas Fernandes Nogueira
2071265fea add to additionals (#7206) 2023-06-14 16:10:52 -07:00
Fabian-Lars
3fb3f11fc8 docs(api.js): fix since version for locale() (#7205) 2023-06-14 20:30:57 +03:00
github-actions[bot]
b7ae725c5e Apply Version Updates From Current Changes (#6901)
Co-authored-by: lucasfernog <lucasfernog@users.noreply.github.com>
2023-06-14 12:59:28 -03:00
Lucas Fernandes Nogueira
bd96edd2b9 fix: bump macros, codegen and build crates with minor (#7203) 2023-06-14 12:09:11 -03:00
Lucas Fernandes Nogueira
aa94f049c1 fix(tests): adjust default bundle target for updater integration test (#7201) 2023-06-14 11:17:02 -03:00
Lucas Fernandes Nogueira
c1d36e4953 chore: remove duplicated crate in change file (#7198) 2023-06-14 15:05:44 +03:00
Fabian-Lars
4cfb686d2b fix(cli): Pin minisign to 0.7.3 to prevent issues with empty key passwords (#7197) 2023-06-14 08:00:28 -03:00
renovate[bot]
d5769b3bfb chore(deps) Update Rust crate log to 0.4.19 (#7193)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-06-14 07:37:06 -03:00
renovate[bot]
066417d3f0 chore(deps) Update Rust crate log to 0.4.19 (#7194)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-06-14 07:36:46 -03:00
renovate[bot]
29a287ee82 chore(deps) Update Tauri API Definitions to v5.59.11 (#7195)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-06-14 07:36:26 -03:00
Amr Bashir
d75c1b829b fix(cli): warn about bundling updater target without appropriate targets, closes #7181 (#7189)
* fix(cli): warn about bundling updater target without appropriate targets, closes #7181

* change tags

* cleanup

---------

Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-06-14 02:14:35 +03:00
Lucas Fernandes Nogueira
696d77c3ce fix(core): global events now reaches window listeners, closes #4493 (#7163)
Co-authored-by: Amr Bashir <amr.bashir2015@gmail.com>
2023-06-13 08:05:58 -03:00
Fabian-Lars
5d85d0990c fix(core): Send updater status events when default dialog is enabled, closes #7128 (#7157) 2023-06-13 08:05:42 -03:00
Amr Bashir
076e1a81a5 fix(core): use u32 for js listeners ids, closes #7119 (#7159) 2023-06-07 17:54:04 -03:00
Amr Bashir
fc2e4083b0 ci: check for change tag (#7149)
* ci: check for change tag

* fix workflow

* Update .scripts/ci/check-change-tags.js

* feat: also check if tag is known

seems like covector does not check that so we can do it here for now

* remove push run

* only check changed files

* add missing tag

---------

Co-authored-by: Lucas Fernandes Nogueira <lucas@tauri.studio>
2023-06-07 16:32:36 +03:00
Lucas Fernandes Nogueira
1d99f8a3c2 feat(core): expose test utils (#4752) 2023-06-07 10:22:14 -03:00
renovate[bot]
d33672cffe chore(deps) Update Tauri Bundler (#7152)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-06-07 09:39:31 -03:00
renovate[bot]
ba6e5813e6 chore(deps) Update Tauri API Definitions (#7151)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-06-07 09:38:27 -03:00
dependabot[bot]
a6da7ef8af chore(deps-dev): bump vite from 2.9.13 to 2.9.16 in /examples/api (#7138)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-06-06 14:06:29 -03:00
Fabian-Lars
db7c5fbf2e refactor(core): Remove attohttpc in favor of reqwest (#7143)
Co-authored-by: Lucas Fernandes Nogueira <lucas@tauri.studio>
2023-06-06 13:29:52 -03:00
Lucas Fernandes Nogueira
52474e479d feat(cli): enhance Cargo features injection, add tests (#7141) 2023-06-06 13:29:28 -03:00
Amr Bashir
b41b57ebb2 fix(core): avoid panics in global shortcut, closes #7105 (#7136) 2023-06-05 16:43:44 -03:00
Lucas Fernandes Nogueira
647800c563 refactor(cli): use rewrite manifest logic on table entry (#7134) 2023-06-05 14:38:26 -03:00
renovate[bot]
3a8bb4c153 chore(deps) Update Tauri JS CLI (#7093)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-06-05 10:06:45 -03:00
renovate[bot]
c2acf96306 chore(deps) Update Tauri API Definitions to v5.59.8 (#7091)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-06-05 09:52:05 -03:00
renovate[bot]
f8bdc7be62 chore(deps) Update Rust crate log to 0.4.18 (#7090)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-06-05 09:51:40 -03:00
Amr Bashir
0503eb69ce fix(core): account for data: uri when calculating origin, closes #7078 (#7133)
Co-authored-by: Lucas Nogueira <lucas@tauri.app>
2023-06-05 09:47:21 -03:00
Reupen Shah
85e77fb797 fix: correct MIME type of .txt files (ref: #6762) (#7111)
Co-authored-by: Lucas Nogueira <lucas@tauri.app>
2023-06-05 09:16:05 -03:00
fcfangcc
3327dd641d fix(bundler/macos): clean up .app bundle if only .dmg is enabled #7081 (#7116)
Co-authored-by: Lucas Nogueira <lucas@tauri.app>
2023-06-05 08:49:37 -03:00
icedrocket
c596aaefcf fix(examples): make video fits within window (#7129) 2023-06-05 08:11:32 -03:00
Raphii
4d4b72ba38 Fix missing quote in Japanese NSIS language file. (#7086)
* Update Japanese.nsh

* Create nsis-japanese-fix.md

* Update .changes/nsis-japanese-fix.md

Co-authored-by: Fabian-Lars <fabianlars@fabianlars.de>

---------

Co-authored-by: Fabian-Lars <fabianlars@fabianlars.de>
2023-06-03 13:08:10 +02:00
Fabian-Lars
d7a0a2cd1a ci: Use correct native-tls feature flags for win32-arm64 cli, ref #7098 (#7107) 2023-06-02 19:04:48 +08:00
Fabian-Lars
0ddbb3a1dc feat(cli): Build the CLI for Windows ARM64, closes #7015 (#7098)
* feat(cli): Build the CLI for Windows ARM64

* lockfile
2023-06-01 11:04:14 +08:00
Lucas Fernandes Nogueira
3303041c92 chore(api): document new options from #6665 (#7072) 2023-05-27 04:39:37 -07:00
Lucas Fernandes Nogueira
27c5f364a8 fix(macros): use full path to Result to avoid issues with type aliases (#7071) 2023-05-27 04:37:19 -07:00
Amr Bashir
000104bc3b feat: add is_focused APIs, closes #6472 (#6530)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-05-26 13:37:28 -03:00
Kevin Yue
8fd9cfa1f2 fix(doc): correct the doc of content_protected() (#7065) 2023-05-26 09:23:57 -03:00
Bo
17d5a4f51f feat(core): early panic if the PNG icon is not RGBA, closes #6706 (#6712) 2023-05-26 15:26:21 +08:00
Pascal Sommer
d68a25e32e Improve compile errors for async commands without Result return type (#6124)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-05-26 01:04:30 -03:00
Lucas Fernandes Nogueira
154ccbe503 fix(tests): only download update when it is available (#7061) 2023-05-25 21:22:55 -03:00
Jonas Kruckenberg
6c5ade08d9 feat(cli.rs) Shell completions (#4537)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
Co-authored-by: Simon Hyll <hyllsimon@gmail.com>
Co-authored-by: Lucas Nogueira <lucas@tauri.app>
2023-05-25 11:34:37 -03:00
Amr Bashir
1b8001b8b8 fix(bundler/nsis): calculate accurate app size, closes #7056 (#7057) 2023-05-25 11:34:05 -03:00
Tomáš Diblík
c4d6fb4b1e feat(core): Ability to disable minimize/maximize/close native window's buttons, closes #2353 (#6665)
Co-authored-by: Amr Bashir <amr.bashir2015@gmail.com>
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
Co-authored-by: Lucas Nogueira <lucas@tauri.app>
2023-05-24 17:23:32 -03:00
Lej77
65fd674f50 fix: sound for notifications on windows (fix #6652) (#6680) 2023-05-24 17:20:13 -03:00
Francis The Basilisk
35cd751adc feat(bundler): custom desktop file template, closes #5176 (#5180)
Co-authored-by: Fabian-Lars <fabianlars@fabianlars.de>
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-05-24 16:04:54 -03:00
Amr Bashir
ff5e4dbbb0 fix(core): populate webview_attrs from config, closes #6794 (#6797)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-05-24 15:39:51 -03:00
Amr Bashir
df89ccc191 feat(nsis): implement passive mode, closes #6955 (#6998)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-05-24 14:16:12 -03:00
Amr Bashir
60334f9e02 feat(bundler/NSIS): uninstall previous wix if exist, closes #6859 (#6933) 2023-05-24 13:33:30 -03:00
renovate[bot]
0f707d2b53 chore(deps) Update Rust crate serde_with to v3 (#7048)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-05-24 13:17:21 -03:00
Amr Bashir
2317913b71 fix(core): use safe_block_on (#7047)
fixes regression introduced in 45330e3819

ref: https://github.com/tauri-apps/tauri/issues/6375#issuecomment-1560063696
2023-05-24 05:07:31 +03:00
Amr Bashir
359058cecc feat(api): add locale function, closes #5939 (#5960) 2023-05-23 16:02:33 -03:00
Amr Bashir
45330e3819 fix(core): rewrite asset protocol streaming, closes #6375 (#6390)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-05-23 15:30:31 -03:00
Amr Bashir
17da87d3cd fix(bundler/nsis): write installer templates UTF16LE encoded, closes #7036 (#7040)
* fix(bundler/nsis): write installer templates UTF16LE encoded, closes #7036

* cleanup

* lint

* return err instead of panic

* Update .changes/nsis-encoding.md [skip ci]

---------

Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-05-23 19:00:21 +03:00
Amr Bashir
8b9f6cf868 chore: add change tags for existing change files (#7041) 2023-05-23 18:56:47 +03:00
Amirhossein Akhlaghpour
4c39e46a3b feat: current_version feature (#7026)
* feat: reexport webview_verion

* chore: clippy problems

* fix: add .changes md file

* Update .changes/add-webview-version.md
2023-05-23 18:35:49 +03:00
Usman Rajab
43858a3197 feat(bundler/NSIS): Add Swedish to supported NSIS languages (#7038) 2023-05-23 17:41:40 +03:00
Amr Bashir
3cb7a3e642 fix(cli/devserver): inject autoreload into HTML only, closes #6997 (#7032) 2023-05-23 17:39:11 +03:00
Amr Bashir
baa581b814 ci: fix version-or-publish workflow (#7031)
* ci: fix version-or-publish workflow

* test syntax

* how about this?

* just use jq

* Delete test.js
2023-05-23 17:38:31 +03:00
Nathanael Rea
fb7ef8dacd fix(cli.js): detect node-20 binary (#6667)
* fix nodejs binary regex

* Update clijs-node-version-20.md
2023-05-23 01:09:49 +03:00
dependabot[bot]
1161b6788e chore(deps): bump h2 from 0.3.15 to 0.3.19 in /examples/api/src-tauri (#7030)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-22 16:35:19 -03:00
renovate[bot]
76714dc628 chore(deps) Update Tauri API Definitions (#6798)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-05-22 16:34:55 -03:00
Amr Bashir
af93729031 fix: add missing file properties on Windows, closes #6676 (#6693)
Co-authored-by: Lucas Fernandes Nogueira <lucas@tauri.studio>
2023-05-22 16:34:33 -03:00
Amr Bashir
262776d8d8 docs(tauri-build): clarify common-controls-v6 dependency, closes #6732 (#6736) 2023-05-22 15:07:08 -03:00
renovate[bot]
86d3c0cc0f chore(deps) Update Tauri CLI (major) (#6688)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-05-22 14:22:46 -03:00
Lucas Fernandes Nogueira
a541820aa8 fix(cli): revert metadata.json field rename from #6795 (#7029) 2023-05-22 14:07:53 -03:00
renovate[bot]
0974ecccd6 chore(deps) Update Tauri Bundler (#6683)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-05-22 14:06:16 -03:00
Amr Bashir
5ec6353a60 refactor: change package names to match published packages (#6795)
Co-authored-by: Fabian-Lars <fabianlars@fabianlars.de>
2023-05-22 12:52:44 -03:00
renovate[bot]
9e67ec68ac chore(deps) Update dependency prettier to v2.8.8 (#6799)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-05-22 11:41:03 -03:00
dependabot[bot]
ffd4db5ae4 chore(deps): bump enumflags2 from 0.7.5 to 0.7.7 in /examples/api/src-tauri (#6786)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-22 11:40:40 -03:00
Gökçe Merdun
ac183948d6 feat(bundler/NSIS): Add Turkish to supported NSIS languages (#7018) 2023-05-21 19:15:17 +03:00
Risto Stevcev
0032daf2a3 Docs: Added void linux to readme (#6711) 2023-05-21 11:29:09 -03:00
Amr Bashir
5eba069b1d docs: curate and document tauri's env vars (#6983)
* docs: curate and document tauri's env vars

* fill apple env vars

---------

Co-authored-by: Lucas Nogueira <lucas@tauri.app>
2023-05-21 13:23:47 +03:00
yutotnh
2b487c9467 Fix typo (#7012)
Co-authored-by: Lucas Fernandes Nogueira <lucas@tauri.app>
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-05-20 08:24:07 -03:00
Amr Bashir
b9eac96cdc ci: pin toml to 0.7.3 (#7011)
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-05-20 07:52:21 -03:00
Lucas Fernandes Nogueira
1253bbf7ae fix(cli): correctly remove Cargo features (#7013) 2023-05-20 00:12:11 -03:00
Soumt
61e3ad89e9 feat(bundler/NSIS): Add Korean to supported NSIS languages (#7010)
* Feat: Add Korean language

* fmt
2023-05-20 01:49:20 +03:00
Simon Hyll
fc7f9ebada feat: adding copyright text to BrandingText (#7001) 2023-05-19 19:42:24 +08:00
Risto Stevcev
0302138f2f fix: updated appimage script to follow symlinks for /usr/lib* (fix: #6992) (#6996)
* Updated appimage script to follow symlinks for /usr/lib*

* Added appimage-follow-symlinks change file
2023-05-19 13:22:22 +08:00
Fabian-Lars
c7056d1b20 fix(cli): improve vs build tools detection (#6982)
* fix(cli): improve vs build tools detection

* clean up

* typos

* changefile

* patch instead of minor

* update vswhere

* use vswhere instead of custom logic. update wording

* sort and dedup manually
2023-05-18 22:47:28 +03:00
Amr Bashir
acc36fe117 feat(core): add option for require_literal_leading_dot, closes #6158 (#6969)
* feat(core): add option for `require_literal_leading_dot`, closes #6158

* change to `Option<bool>`

* fix to tokens impl

* Apply suggestions from code review

Co-authored-by: Simon Hyll <hyllsimon@gmail.com>

---------

Co-authored-by: Simon Hyll <hyllsimon@gmail.com>
2023-05-18 16:11:50 +03:00
Amr Bashir
cd3846c8ce feat(nsis): restart app after updating, closes #6955 (#6987)
* feat(nsis): restart app after updating, closes #6955

* Apply suggestions from code review
2023-05-18 16:11:31 +03:00
Amr Bashir
fd3b5a16b1 fix(cli): find correct binary when --profile is used, closes #6954 (#6979)
* fix(cli): find correct binary when `--profile` is used, closes #6954

* clippy
2023-05-17 16:17:47 +03:00
Amr Bashir
82169e69fc fix(core): remove trailing slash in http scope url, closes #5208 (#6974)
* fix(core): remove trailing slash in http scope url, closes #5208

* fix tests

* one more tests fix

* clippy
2023-05-17 14:33:10 +03:00
Amr Bashir
aecf146909 fix(core/ipc): access url through webview native object, closes #6889 (#6976) 2023-05-17 14:32:45 +03:00
Fabian-Lars
2b26b2e611 fix(bundler): Add new lang_file option in persian variant. (#6972) 2023-05-16 15:33:08 +03:00
Fabian-Lars
d2710e9d2e fix(core): unpin all dependencies, closes #6944 (#6966) 2023-05-16 19:27:15 +08:00
Amr Bashir
3700793a2f fix(updater): emit UPTODATE when server responds with 204, closes #6934 (#6970) 2023-05-16 13:00:00 +08:00
Amirhossein Akhlaghpour
21d5eb84ab feat: add Persian language to NSIS installer (#6965) 2023-05-16 12:58:30 +08:00
Amr Bashir
46a58afd9e chore: remove duplicate tauri in tauri-config-schema name (#6967) 2023-05-15 15:12:51 -03:00
Amr Bashir
3cc295e997 fix(nsis): prefill $INSTDIR with previous install path and respect /D flag, closes #6928 (#6935)
* fix(bundler/nsis): prefill $INSTDIR with previous install path

* fix(nsis): prefill $INSTDIR with previous install path and respect `/D` flag, closes #6928
2023-05-15 18:14:15 +03:00
Amr Bashir
2948820579 feat(bundler/NSIS): allow specifying custom lang files (#6867)
* feat(bundler/NSIS): allow specifying custom lang files

* add dunc as dep on all platforms

* clippy

* Update tooling/bundler/src/bundle/windows/nsis.rs

Co-authored-by: Fabian-Lars <fabianlars@fabianlars.de>

* Update core/tauri-utils/src/config.rs

Co-authored-by: Fabian-Lars <fabianlars@fabianlars.de>

* schema files

---------

Co-authored-by: Fabian-Lars <fabianlars@fabianlars.de>
Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
2023-05-15 18:11:10 +03:00
Amr Bashir
e0c30a7e8b refactor: use const instead of a function (#6958) 2023-05-14 17:03:40 -03:00
Jack Wills
441f964654 feat(core/tauri): add try_get_item for SystemTray and WindowMenu, closes #5491 (#6408)
* feat: try_get_item() for window menu

Add a method in the MenuHandle struct, that will return an Optional MenuItemHandle

feat: try_get_item() for systemtray

Add a method in the SystemTrayHandle struct, that will return an Optional SystemTrayMenuItemHandle

docs: features documented in ./changes/minor.md

fix: suggested changes

fix CI

* Update .changes/tray_get_item.md

---------
2023-05-12 16:15:36 +03:00
Pierre Cashon
2c1fd570f8 fix(bundler): ensure that there are no duplicate extension arguments when bundling on Windows, fixes #6103 (#6917)
* fix(bundler): ensure that there are no duplicate extension arguments during bundling on Windows (fix #6103)

* fix(bundler): ensure that there are no duplicate extension arguments during bundling on Windows (fix #6103)
2023-05-12 15:52:26 +03:00
Guilherme Oenning
7c23720920 feat: add tauri::version, similar to getTauriVersion available on JS API (#6546)
Signed-off-by: goenning <me@goenning.net>

Apply suggestions from code review
2023-05-12 15:36:31 +03:00
KurikoMoe
fb485d25a0 fix(cli): fix cli connection timeout to dev server (fix #6045) (#6046)
Fix tauri-cli connection to dev server stucks and waits for TCP timeout.
2023-05-12 15:01:24 +03:00
Akshay
a08d1b248f chore: fix broken symlinks in license files (#6336)
symlink to repo root
2023-05-12 14:56:32 +03:00
Amr Bashir
dc682155de fix(core): Fix WindowBuilder::on_navigation handler never registerd, closes #6865 (#6921)
* fix(core): Fix `WindowBuilder::on_navigation` handler never registerd, closes #6865

* clippy
2023-05-12 14:03:42 +03:00
Amr Bashir
e092f79946 feat(bundler/nsis): allow specifying custom template, closes #6887 (#6922) 2023-05-12 14:02:07 +03:00
Fabian-Lars
c2b0dab7ef docs: Fix api.js docs pipeline with updated typedoc dependencies (#6945) 2023-05-12 07:54:15 -03:00
nathan-fall
b257bebf9e feat(bundler): Add Japanese to supported NSIS languages, ref #6906 (#6940) 2023-05-11 09:50:35 +02:00
hanaTsuk1
bf49a7679a update bundler nsis template(SimpChinese, TradChinese) (#6939) 2023-05-11 14:30:13 +08:00
Simon Hyll
469d9f8a4a docs(tauri-utils): described behavior of version field when omitted (#6938) 2023-05-11 14:18:45 +08:00
Simon Hyll
41e10b22fa chore: fixed grammar and typos (#6937) 2023-05-11 02:21:15 +03:00
Ronie Martinez
96d346222f docs: Update Github workflow status shields (#6910)
* docs: Update Github workflow status shields

* Update with name, icon and fix
2023-05-10 04:04:12 +03:00
Amr Bashir
2b47426be8 chore: explain covector tags (#6923) 2023-05-09 21:59:01 +03:00
Amr Bashir
aa2a30e96b chore: setup covector change tags/sections/groups (#6920)
![image](https://github.com/tauri-apps/tauri/assets/48618675/ac4f22dd-630d-4bfc-8966-48d19492593f)
2023-05-09 17:45:50 +03:00
Raphii
540ddd4e6a feat(bundler): Add Dutch to supported NSIS languages, ref #6906 (#6907)
* Add Dutch to supported NSIS languages

* Added change file

* Reference Dutch language in nsis bundler

* Fix formatting
2023-05-09 15:37:05 +02:00
Lucas Fernandes Nogueira
2659ca1ab4 feat(cli): add rustls as default Cargo feature (#6900) 2023-05-08 09:29:17 -03:00
chip
24490bca19 use handlebars::no_escape instead of closures (#6899) 2023-05-08 08:39:54 -03:00
github-actions[bot]
73a0ad41c7 apply version updates (#6858)
Co-authored-by: wusyong <wusyong@users.noreply.github.com>
2023-05-08 18:51:23 +08:00
238 changed files with 9993 additions and 4457 deletions

View File

@@ -1,6 +1,16 @@
{
"gitSiteUrl": "https://www.github.com/tauri-apps/tauri/",
"timeout": 3600000,
"changeTags": {
"feat": "New Features",
"enhance": "Enhancements",
"bug": "Bug Fixes",
"pref": "Performance Improvements",
"changes": "What's Changed",
"sec": "Security fixes",
"deps": "Dependencies",
"breaking": "Breaking Changes"
},
"defaultChangeTag": "changes",
"pkgManagers": {
"rust": {
"errorOnVersionRange": "^2.0.0-0",
@@ -123,13 +133,13 @@
}
},
"packages": {
"api": {
"@tauri-apps/api": {
"path": "./tooling/api",
"manager": "javascript",
"assets": [
{
"path": "./tooling/api/dist/tauri-apps-api-${ pkgFile.version }.tgz",
"name": "api-${ pkgFile.version }.tgz"
"name": "tauri-apps-api-${ pkgFile.version }.tgz"
}
],
"prepublish": [
@@ -231,11 +241,11 @@
],
"postversion": "node ../../.scripts/covector/sync-cli-metadata.js ${ pkg.pkg } ${ release.type }"
},
"cli.js": {
"@tauri-apps/cli": {
"path": "./tooling/cli/node",
"manager": "javascript",
"getPublishedVersion": "node ../../../.scripts/covector/package-latest-version.js npm ${ pkgFile.pkg.name } ${ pkgFile.pkg.version }",
"dependencies": ["cli.rs"],
"dependencies": ["tauri-cli"],
"postversion": [
"node ../../../.scripts/covector/sync-cli-metadata.js ${ pkg.pkg } ${ release.type }",
"cargo build --manifest-path ../../../core/tauri-config-schema/Cargo.toml"
@@ -244,7 +254,7 @@
"publish": [],
"postpublish": []
},
"cli.rs": {
"tauri-cli": {
"path": "./tooling/cli",
"manager": "rust",
"dependencies": ["tauri-bundler", "tauri-utils"],

View File

@@ -1,5 +0,0 @@
---
'tauri-bundler': 'patch'
---
Correctly escape XML for resource files in WiX bundler.

View File

@@ -1,8 +0,0 @@
---
'tauri-bundler': 'patch'
---
Added the following languages to the NSIS bundler:
- `Spanish`
- `SpanishInternational`

View File

@@ -1,5 +0,0 @@
---
'tauri-bundler': 'patch'
---
Correctly escape arguments in NSIS script to fix bundling apps that use non-default WebView2 install modes.

View File

@@ -1,31 +1,44 @@
# Changes
##### via https://github.com/jbolda/covector
As you create PRs and make changes that require a version bump, please add a new markdown file in this folder. You do not note the version _number_, but rather the type of bump that you expect: major, minor, or patch. The filename is not important, as long as it is a `.md`, but we recommend that it represents the overall change for organizational purposes.
When you select the version bump required, you do _not_ need to consider dependencies. Only note the package with the actual change, and any packages that depend on that package will be bumped automatically in the process.
Use the following format:
```md
---
"package-a": patch
"package-b": patch
---
Change summary goes here
```
Summaries do not have a specific character limit, but are text only. These summaries are used within the (future implementation of) changelogs. They will give context to the change and also point back to the original PR if more details and context are needed.
Changes will be designated as a `major`, `minor` or `patch` as further described in [semver](https://semver.org/).
Given a version number MAJOR.MINOR.PATCH, increment the:
- MAJOR version when you make incompatible API changes,
- MINOR version when you add functionality in a backwards compatible manner, and
- PATCH version when you make backwards compatible bug fixes.
Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format, but will be discussed prior to usage (as extra steps will be necessary in consideration of merging and publishing).
# Changes
##### via https://github.com/jbolda/covector
As you create PRs and make changes that require a version bump, please add a new markdown file in this folder. You do not note the version _number_, but rather the type of bump that you expect: major, minor, or patch. The filename is not important, as long as it is a `.md`, but we recommend that it represents the overall change for organizational purposes.
When you select the version bump required, you do _not_ need to consider dependencies. Only note the package with the actual change, and any packages that depend on that package will be bumped automatically in the process.
Use the following format:
```md
---
'package-a': patch
'package-b': patch
---
Change summary goes here
```
Summaries do not have a specific character limit, but are text only. These summaries are used within the (future implementation of) changelogs. They will give context to the change and also point back to the original PR if more details and context are needed.
Changes will be designated as a `major`, `minor` or `patch` as further described in [semver](https://semver.org/).
Given a version number MAJOR.MINOR.PATCH, increment the:
- MAJOR version when you make incompatible API changes,
- MINOR version when you add functionality in a backwards compatible manner, and
- PATCH version when you make backwards compatible bug fixes.
Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format, but will be discussed prior to usage (as extra steps will be necessary in consideration of merging and publishing).
Additionally you could specify a tag for the change file to group it with other changes by prefixing the bump with `:<tag>`, for example:
```md
---
'package-a': patch:bug
---
Change summary goes here
```
which will group this change file with other changes that specify the `bug` tag.
For list of available tags, see the `changeTags` key in [./config.json](./config.json)

View File

@@ -54,20 +54,20 @@ Some Tauri packages will be automatically built when running one of the examples
### Packages Overview
- The JS API (`/tooling/api`) contains JS bindings to the builtin Rust functions in the Rust API.
- cli.rs (`/tooling/cli`) is the primary CLI for creating and developing Tauri apps.
- cli.js (`/tooling/cli/node`) is a Node.js CLI wrapper for `cli.rs`.
- Tauri Bundler (`/tooling/bundler`) is used by the Rust CLI to package executables into installers.
- Tauri Core (`/core/tauri`) is the heart of Tauri. It contains the code that starts the app, configures communication between Rust and the Webview, and ties all the other packages together.
- The Macros (`/core/tauri-macros`) are used by Tauri Core for various functions.
### Developing The Node.js CLI (cli.js)
`cli.js` is a wrapper to `cli.rs` so most changes should be written on the Rust CLI. The `[Tauri repo root]/tooling/cli/node` folder contains only packaging scripts to properly publish the Rust CLI binaries to NPM.
- Tauri Bundler (`/tooling/bundler`) is used by the Rust CLI to package executables into installers.
- The Rust CLI aka `tauri-cli` (`/tooling/cli`) is the primary CLI for creating and developing Tauri apps.
- The JS CLI aka `@tauri-apps/cli` (`/tooling/cli/node`) is a Node.js CLI wrapper for `tauri-cli`.
- The JS API aka `@tauri-apps/api` (`/tooling/api`) contains JS bindings to the builtin Rust functions in the Rust API.
### Developing Tauri Bundler and Rust CLI
The code for the bundler is located in `[Tauri repo root]/tooling/bundler`, and the code for the Rust CLI is located in `[Tauri repo root]/tooling/cli`. If you are using your local copy of cli.js (see above), any changes you make to the bundler and CLI will be automatically built and applied when running the build or dev command. Otherwise, running `cargo install --path .` in the Rust CLI directory will allow you to run `cargo tauri build` and `cargo tauri dev` anywhere, using the updated copy of the bundler and cli. You will have to run this command each time you make a change in either package.
The code for the bundler is located in `[Tauri repo root]/tooling/bundler`, and the code for the Rust CLI is located in `[Tauri repo root]/tooling/cli`. If you are using your local copy of `@tauri-apps/cli` (see above), any changes you make to the bundler and CLI will be automatically built and applied when running the build or dev command. Otherwise, running `cargo install --path .` in the Rust CLI directory will allow you to run `cargo tauri build` and `cargo tauri dev` anywhere, using the updated copy of the bundler and cli. You will have to run this command each time you make a change in either package.
### Developing The Node.js CLI (`@tauri-apps/cli`)
`@tauri-apps/cli` is a wrapper to `tauri-cli` so most changes should be written on the Rust CLI. The `[Tauri repo root]/tooling/cli/node` folder contains only packaging scripts to properly publish the Rust CLI binaries to NPM.
### Developing Tauri Core and Related Components (Rust API, Macros, Codegen, and Utils)

View File

@@ -10,6 +10,7 @@ on:
- cron: '0 0 * * *'
push:
paths:
- '.github/workflows/audit.yml'
- '**/Cargo.lock'
- '**/Cargo.toml'
- '**/package.json'
@@ -33,6 +34,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: yarn audit
- name: audit workspace
run: yarn audit
- name: audit @tauri-apps/api
working-directory: tooling/api
run: yarn audit
- name: audit @tauri-apps/cli
working-directory: tooling/cli/node
run: yarn audit

View File

@@ -2,13 +2,13 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: benches
name: bench
on:
push:
branches:
- dev
- next
- 1.x
workflow_dispatch:
env:

32
.github/workflows/check-change-tags.yml vendored Normal file
View File

@@ -0,0 +1,32 @@
# Copyright 2019-2023 Tauri Programme within The Commons Conservancy
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: check change tags
on:
pull_request:
paths:
- '.changes/*.md'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: dorny/paths-filter@v2
id: filter
with:
list-files: shell
filters: |
changes:
- added|modified: '.changes/*.md'
- name: check
run: node ./.scripts/ci/check-change-tags.js ${{ steps.filter.outputs.changes_files }}
if: ${{ steps.filter.outputs.changes == 'true' }}

View File

@@ -2,7 +2,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: Check generated files
name: check generated files
on:
pull_request:
@@ -13,16 +13,6 @@ on:
- 'core/tauri-utils/src/config.rs'
- 'tooling/cli/schema.json'
- 'core/tauri-config-schema/schema.json'
push:
branches:
- dev
paths:
- '.github/workflows/check-generated-files.yml'
- 'tooling/api/src/**'
- 'core/tauri/scripts/bundle.global.js'
- 'core/tauri-utils/src/config.rs'
- 'tooling/cli/schema.json'
- 'core/tauri-config-schema/schema.json'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -42,14 +32,13 @@ jobs:
filters: |
api:
- 'tooling/api/src/**'
- 'tooling/api/docs/js-api.json'
- 'core/tauri/scripts/bundle.global.js'
schema:
- 'core/tauri-utils/src/config.rs'
- 'tooling/cli/schema.json'
- 'core/tauri-config-schema/schema.json'
check-api:
api:
runs-on: ubuntu-latest
needs: changes
if: needs.changes.outputs.api == 'true'
@@ -60,11 +49,9 @@ jobs:
working-directory: tooling/api
run: yarn && yarn build
- name: check api
run: |
git restore tooling/api/docs/js-api.json
./.scripts/ci/has-diff.sh
run: ./.scripts/ci/has-diff.sh
check-schema:
schema:
runs-on: ubuntu-latest
needs: changes
if: needs.changes.outputs.schema == 'true'

View File

@@ -2,7 +2,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: Check generated files
name: check license headers
on:
pull_request:
@@ -25,4 +25,4 @@ jobs:
- added: '**'
- name: check header license on new files
if: ${{ steps.filter.outputs.added == 'true' }}
run: node check-license-header.js ${{ steps.filter.outputs.added_files }}
run: node ./.scripts/ci/check-license-header.js ${{ steps.filter.outputs.added_files }}

View File

@@ -0,0 +1,148 @@
# Copyright 2019-2023 Tauri Programme within The Commons Conservancy
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: covector version or publish
on:
push:
branches:
- 1.x
jobs:
run-integration-tests:
runs-on: ${{ matrix.platform }}
strategy:
fail-fast: false
matrix:
platform: [ubuntu-latest, macos-latest, windows-latest]
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: install stable
uses: actions-rs/toolchain@v1
with:
toolchain: stable
- name: install Linux dependencies
if: matrix.platform == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y webkit2gtk-4.0 libayatana-appindicator3-dev libfuse2
- uses: Swatinem/rust-cache@v2
with:
workspaces: |
core -> ../target
tooling/cli
- name: build CLI
uses: actions-rs/cargo@v1
with:
command: build
args: --manifest-path ./tooling/cli/Cargo.toml
- name: run integration tests
run: cargo test --test '*' -- --ignored
- name: run CLI tests
timeout-minutes: 30
run: |
cd ./tooling/cli/node
yarn
yarn build
yarn test
version-or-publish:
runs-on: ubuntu-latest
timeout-minutes: 65
outputs:
change: ${{ steps.covector.outputs.change }}
commandRan: ${{ steps.covector.outputs.commandRan }}
successfulPublish: ${{ steps.covector.outputs.successfulPublish }}
needs:
- run-integration-tests
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- uses: actions/setup-node@v2
with:
node-version: 14
registry-url: 'https://registry.npmjs.org'
cache: yarn
cache-dependency-path: tooling/*/yarn.lock
- name: cargo login
run: cargo login ${{ secrets.ORG_CRATES_IO_TOKEN }}
- name: git config
run: |
git config --global user.name "${{ github.event.pusher.name }}"
git config --global user.email "${{ github.event.pusher.email }}"
- name: covector version or publish (publish when no change files present)
uses: jbolda/covector/packages/action@covector-v0
id: covector
env:
NODE_AUTH_TOKEN: ${{ secrets.ORG_NPM_TOKEN }}
CARGO_AUDIT_OPTIONS: ${{ secrets.CARGO_AUDIT_OPTIONS }}
with:
token: ${{ secrets.GITHUB_TOKEN }}
command: 'version-or-publish'
createRelease: true
- name: Create Pull Request With Versions Bumped
if: steps.covector.outputs.commandRan == 'version'
uses: tauri-apps/create-pull-request@v3
with:
token: ${{ secrets.GITHUB_TOKEN }}
branch: release/version-updates-v1
title: Apply Version Updates From Current Changes (v1)
commit-message: 'apply version updates'
labels: 'version updates'
body: ${{ steps.covector.outputs.change }}
- name: Trigger doc update
if: |
steps.covector.outputs.successfulPublish == 'true' &&
steps.covector.outputs.packagesPublished != ''
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.ORG_TAURI_BOT_PAT }}
repository: tauri-apps/tauri-docs
event-type: update-docs
- name: Get `@tauri-apps/cli` release id
id: cliReleaseId
if: |
steps.covector.outputs.successfulPublish == 'true' &&
contains(steps.covector.outputs.packagesPublished, '@tauri-apps/cli')
run: |
echo '${{ steps.covector.outputs }}' > output.json
id=$(jq '.["-tauri-apps-cli-releaseId"]' < output.json)
rm output.json
echo "cliReleaseId=$id" >> "$GITHUB_OUTPUT"
- name: Trigger `@tauri-apps/cli` publishing workflow
if: |
steps.covector.outputs.successfulPublish == 'true' &&
contains(steps.covector.outputs.packagesPublished, '@tauri-apps/cli')
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.ORG_TAURI_BOT_PAT }}
repository: tauri-apps/tauri
event-type: publish-js-cli
client-payload: '{"releaseId": "${{ steps.cliReleaseId.outputs.cliReleaseId }}" }'
- name: Trigger `tauri-cli` publishing workflow
if: |
steps.covector.outputs.successfulPublish == 'true' &&
contains(steps.covector.outputs.packagesPublished, 'tauri-cli')
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.ORG_TAURI_BOT_PAT }}
repository: tauri-apps/tauri
event-type: publish-clirs

View File

@@ -2,7 +2,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: version or publish
name: covector version or publish
on:
push:
@@ -115,21 +115,32 @@ jobs:
repository: tauri-apps/tauri-docs
event-type: update-docs
- name: Trigger cli.js publishing workflow
- name: Get `@tauri-apps/cli` release id
id: cliReleaseId
if: |
steps.covector.outputs.successfulPublish == 'true' &&
contains(steps.covector.outputs.packagesPublished, 'cli.rs')
contains(steps.covector.outputs.packagesPublished, '@tauri-apps/cli')
run: |
echo '${{ toJSON(steps.covector.outputs) }}' > output.json
id=$(jq '.["-tauri-apps-cli-releaseId"]' < output.json)
rm output.json
echo "cliReleaseId=$id" >> "$GITHUB_OUTPUT"
- name: Trigger `@tauri-apps/cli` publishing workflow
if: |
steps.covector.outputs.successfulPublish == 'true' &&
contains(steps.covector.outputs.packagesPublished, '@tauri-apps/cli')
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.ORG_TAURI_BOT_PAT }}
repository: tauri-apps/tauri
event-type: publish-clijs
client-payload: '{"releaseId": "${{ steps.covector.outputs.cli.js-releaseId }}" }'
event-type: publish-js-cli
client-payload: '{"releaseId": "${{ steps.cliReleaseId.outputs.cliReleaseId }}" }'
- name: Trigger cli.rs publishing workflow
- name: Trigger `tauri-cli` publishing workflow
if: |
steps.covector.outputs.successfulPublish == 'true' &&
contains(steps.covector.outputs.packagesPublished, 'cli.rs')
contains(steps.covector.outputs.packagesPublished, 'tauri-cli')
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.ORG_TAURI_BOT_PAT }}

View File

@@ -2,16 +2,16 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: cli clippy and fmt check
name: lint cli
on:
push:
branches:
- dev
- next
- 1.x
pull_request:
paths:
- '.github/workflows/lint-fmt-cli.yml'
- '.github/workflows/lint-cli.yml'
- 'tooling/cli/**'
env:
@@ -23,7 +23,7 @@ concurrency:
cancel-in-progress: true
jobs:
fmt_check:
fmt:
runs-on: ubuntu-latest
steps:
@@ -41,7 +41,7 @@ jobs:
command: fmt
args: --manifest-path ./tooling/cli/Cargo.toml --all -- --check
cli_clippy_check:
clippy:
runs-on: ubuntu-latest
steps:

View File

@@ -2,16 +2,16 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: core clippy and fmt check
name: lint core
on:
push:
branches:
- dev
- next
- 1.x
pull_request:
paths:
- '.github/workflows/lint-fmt-core.yml'
- '.github/workflows/lint-core.yml'
- 'core/**'
- '!core/tauri/scripts/**'
- 'examples/**'
@@ -25,7 +25,7 @@ concurrency:
cancel-in-progress: true
jobs:
fmt_check:
fmt:
runs-on: ubuntu-latest
steps:
@@ -43,14 +43,14 @@ jobs:
command: fmt
args: --all -- --check
core_clippy_check:
clippy:
runs-on: ubuntu-latest
strategy:
matrix:
clippy:
- { args: '', key: 'empty' }
- {
args: '--features compression,wry,linux-protocol-headers,isolation,custom-protocol,api-all,cli,updater,system-tray,windows7-compat,http-multipart',
args: '--features compression,wry,linux-protocol-headers,isolation,custom-protocol,api-all,cli,updater,system-tray,windows7-compat,http-multipart,test',
key: 'all'
}
- { args: '--features custom-protocol', key: 'custom-protocol' }

View File

@@ -2,7 +2,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: api and cli.js lint check
name: lint js
on:
pull_request:
@@ -16,7 +16,7 @@ concurrency:
cancel-in-progress: true
jobs:
eslint-check:
eslint-cli:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
@@ -24,24 +24,34 @@ jobs:
with:
node-version: '14'
cache: yarn
cache-dependency-path: tooling/*/yarn.lock
- name: install cli.js deps via yarn
cache-dependency-path: tooling/cli/node/yarn.lock
- name: install deps via yarn
working-directory: ./tooling/cli/node/
run: yarn
# nothing to lint
#- name: run cli.js lint
#- name: run lint
# working-directory: ./tooling/cli/node/
# run: yarn lint
- name: run cli.js format
- name: run format
working-directory: ./tooling/cli/node/
run: yarn format:check
- name: install api deps via yarn
eslint-api:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '14'
cache: yarn
cache-dependency-path: tooling/api/yarn.lock
- name: install deps via yarn
working-directory: ./tooling/api/
run: yarn
- name: run api lint
- name: run lint
working-directory: ./tooling/api/
run: yarn lint
- name: run api format
- name: run format
working-directory: ./tooling/api/
run: yarn format:check

View File

@@ -2,7 +2,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: publish cli.js
name: publish `@tauri-apps/cli`
env:
DEBUG: napi:*
APP_NAME: cli
@@ -11,10 +11,10 @@ on:
workflow_dispatch:
inputs:
releaseId:
description: 'ID of the cli.js release'
description: 'ID of the `@tauri-apps/cli` release'
required: true
repository_dispatch:
types: [publish-clijs]
types: [publish-js-cli]
defaults:
run:
@@ -30,41 +30,45 @@ jobs:
target: x86_64-apple-darwin
architecture: x64
build: |
yarn build:release --features rustls
yarn build:release
strip -x *.node
- host: windows-latest
build: yarn build:release --features rustls
build: yarn build:release
target: x86_64-pc-windows-msvc
architecture: x64
- host: windows-latest
build: yarn build:release --features rustls --target i686-pc-windows-msvc
build: yarn build:release --target i686-pc-windows-msvc
target: i686-pc-windows-msvc
architecture: x64
- host: windows-latest
architecture: x64
target: aarch64-pc-windows-msvc
build: yarn build:release --target aarch64-pc-windows-msvc --features native-tls,native-tls-vendored --cargo-flags="--no-default-features"
- host: ubuntu-20.04
target: x86_64-unknown-linux-gnu
docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-debian
build: |
cd tooling/cli/node
yarn build:release --features rustls --target x86_64-unknown-linux-gnu
yarn build:release --target x86_64-unknown-linux-gnu
strip *.node
- host: ubuntu-20.04
target: x86_64-unknown-linux-musl
docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-alpine
build: |
cd tooling/cli/node
yarn build:release --features rustls
yarn build:release
strip *.node
- host: macos-latest
target: aarch64-apple-darwin
build: |
yarn build:release --features rustls --target=aarch64-apple-darwin
yarn build:release --target=aarch64-apple-darwin
strip -x *.node
- host: ubuntu-20.04
target: aarch64-unknown-linux-gnu
docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-debian-aarch64
build: |
cd tooling/cli/node
yarn build:release --features rustls --target aarch64-unknown-linux-gnu
yarn build:release --target aarch64-unknown-linux-gnu
aarch64-unknown-linux-gnu-strip *.node
- host: ubuntu-20.04
architecture: x64
@@ -73,7 +77,7 @@ jobs:
sudo apt-get update
sudo apt-get install gcc-arm-linux-gnueabihf g++-arm-linux-gnueabihf -y
build: |
yarn build:release --features rustls --target=armv7-unknown-linux-gnueabihf
yarn build:release --target=armv7-unknown-linux-gnueabihf
arm-linux-gnueabihf-strip *.node
- host: ubuntu-20.04
architecture: x64
@@ -82,12 +86,8 @@ jobs:
build: |
cd tooling/cli/node
rustup target add aarch64-unknown-linux-musl
yarn build:release --features rustls --target aarch64-unknown-linux-musl
yarn build:release --target aarch64-unknown-linux-musl
/aarch64-linux-musl-cross/bin/aarch64-linux-musl-strip *.node
#- host: windows-latest
# architecture: x64
# target: aarch64-pc-windows-msvc
# build: yarn build:release --features rustls --target aarch64-pc-windows-msvc
name: stable - ${{ matrix.settings.target }} - node@16
runs-on: ${{ matrix.settings.host }}
steps:
@@ -179,7 +179,7 @@ jobs:
# freebsd-version
# cd ./tooling/cli/node/
# yarn install --ignore-scripts --frozen-lockfile --registry https://registry.npmjs.org --network-timeout 300000
# yarn build:release --features rustls
# yarn build:release
# strip -x *.node
# rm -rf node_modules
# rm -rf ../target

View File

@@ -2,7 +2,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: publish cli.rs
name: publish `tauri-cli`
env:
MACOSX_DEPLOYMENT_TARGET: '10.13'
on:
@@ -21,15 +21,23 @@ jobs:
- os: ubuntu-20.04
rust_target: x86_64-unknown-linux-gnu
ext: ''
args: ''
- os: macos-latest
rust_target: x86_64-apple-darwin
ext: ''
args: ''
- os: macos-latest
rust_target: aarch64-apple-darwin
ext: ''
args: ''
- os: windows-latest
rust_target: x86_64-pc-windows-msvc
ext: '.exe'
args: ''
- os: windows-latest
rust_target: aarch64-pc-windows-msvc
ext: '.exe'
args: '--no-default-features --features native-tls,native-tls-vendored'
steps:
- name: Checkout
@@ -54,7 +62,7 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: build
args: --manifest-path ./tooling/cli/Cargo.toml --release
args: --manifest-path ./tooling/cli/Cargo.toml --release ${{ matrix.config.args }}
- name: Upload CLI
uses: actions/upload-artifact@v3
@@ -85,7 +93,7 @@ jobs:
- name: Publish release
uses: softprops/action-gh-release@50195ba7f6f93d1ac97ba8332a178e008ad176aa
with:
tag_name: cli.rs-v${{ env.CLI_VERSION }}
tag_name: tauri-cli-v${{ env.CLI_VERSION }}
files: |
outputs/cargo-tauri-*.zip
outputs/cargo-tauri-*.tgz

View File

@@ -2,17 +2,17 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: test cli.js
name: test `@tauri-apps/cli`
on:
push:
branches:
- dev
- next
- 1.x
pull_request:
paths:
- '.github/workflows/test-cli-js.yml'
# currently cli.js only tests the template
# currently` @tauri-apps/cli` only tests the template
- 'tooling/cli/templates/app/**'
env:
@@ -24,7 +24,7 @@ concurrency:
cancel-in-progress: true
jobs:
test-tauri-js-cli:
test:
runs-on: ${{ matrix.platform }}
strategy:

View File

@@ -2,13 +2,13 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: test cli.rs
name: test `tauri-cli`
on:
push:
branches:
- dev
- next
- 1.x
pull_request:
paths:
- '.github/workflows/test-cli-rs.yml'
@@ -23,7 +23,7 @@ concurrency:
cancel-in-progress: true
jobs:
test-tauri-cli:
test:
runs-on: ${{ matrix.platform }}
strategy:

View File

@@ -8,7 +8,7 @@ on:
push:
branches:
- dev
- next
- 1.x
pull_request:
paths:
- '.github/workflows/test-core.yml'
@@ -24,7 +24,7 @@ concurrency:
cancel-in-progress: true
jobs:
test-tauri-core:
test:
runs-on: ${{ matrix.platform.os }}
strategy:
@@ -56,7 +56,7 @@ jobs:
key: api-all
}
- {
args: --features compression,wry,linux-protocol-headers,isolation,custom-protocol,api-all,cli,updater,system-tray,windows7-compat,http-multipart,
args: --features compression,wry,linux-protocol-headers,isolation,custom-protocol,api-all,cli,updater,system-tray,windows7-compat,http-multipart,test,
key: all
}
@@ -82,5 +82,31 @@ jobs:
workspaces: core -> ../target
save-if: ${{ matrix.features.key == 'all' }}
- name: Downgrade crates with MSRV conflict
# The --precise flag can only be used once per invocation.
run: |
cargo update -p toml:0.7.8 --precise 0.7.3
cargo update -p toml_edit --precise 0.19.8
cargo update -p toml_datetime --precise 0.6.1
cargo update -p serde_spanned --precise 0.6.1
cargo update -p winnow --precise 0.4.1
cargo update -p time --precise 0.3.15
cargo update -p ignore --precise 0.4.18
cargo update -p raw-window-handle --precise 0.5.0
cargo update -p cargo_toml:0.15.3 --precise 0.15.2
cargo update -p zbus --precise 3.13.0
cargo update -p zbus_names --precise 2.5.0
cargo update -p is-terminal --precise 0.4.7
cargo update -p colored --precise 2.0.2
cargo update -p tempfile --precise 3.6.0
cargo update -p serde_with:3.3.0 --precise 3.0.0
cargo update -p tokio --precise 1.29.0
cargo update -p flate2 --precise 1.0.26
cargo update -p h2 --precise 0.3.20
cargo update -p reqwest --precise 0.11.18
cargo update -p cfg-expr:0.15.5 --precise 0.15.4
cargo update -p memchr --precise 2.6.2
cargo update -p async-executor --precise 1.5.1
- name: test
run: cargo test --target ${{ matrix.platform.target }} ${{ matrix.features.args }}

View File

@@ -2,13 +2,13 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: test bundler
name: test and lint bundler
on:
push:
branches:
- dev
- next
- 1.x
pull_request:
paths:
- '.github/workflows/test-bundler.yml'
@@ -23,7 +23,7 @@ concurrency:
cancel-in-progress: true
jobs:
build-tauri-bundler:
test:
runs-on: ${{ matrix.platform }}
strategy:
@@ -48,7 +48,7 @@ jobs:
cd ./tooling/bundler
cargo test
fmt_check:
fmt:
runs-on: ubuntu-latest
steps:
@@ -66,7 +66,7 @@ jobs:
command: fmt
args: --manifest-path ./tooling/bundler/Cargo.toml --all -- --check
clippy-check:
clippy:
runs-on: ubuntu-latest
steps:

View File

@@ -2,13 +2,13 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
name: updater test artifacts
name: test updater artifacts
on:
schedule:
- cron: '0 0 * * *'
pull_request:
paths:
- '.github/workflows/artifacts-updater.yml'
- '.github/workflows/test-updater-artifacts.yml'
- 'examples/updater/**'
workflow_dispatch:
@@ -21,7 +21,7 @@ concurrency:
cancel-in-progress: true
jobs:
build-artifacts:
test:
runs-on: ${{ matrix.platform }}
strategy:
@@ -48,7 +48,7 @@ jobs:
core -> ../target
tooling/cli
- name: build and install cli.rs
- name: build and install `tauri-cli`
run: cargo install --path tooling/cli --force
- name: Check whether code signing should be enabled
id: enablecodesigning

View File

@@ -8,7 +8,7 @@ on:
push:
branches:
- dev
- next
- 1.x
env:
RUST_BACKTRACE: 1

View File

@@ -16,7 +16,7 @@ else
fi
if [ -z "$(git diff --name-only tooling/cli/node)" ]; then
echo "skipping cli.js - no changes detected"
echo "skipping \`@tauri-apps/cli\` - no changes detected"
else
cd tooling/cli/node
yarn format

View File

@@ -9,5 +9,4 @@ dist
/tooling/cli/templates
/tooling/cli/node
/tooling/cli/schema.json
/tooling/api/docs/js-api.json
/core/tauri-config-schema/schema.json

View File

@@ -1,4 +1,5 @@
#!/usr/bin/env pwsh
# Copyright 2019-2023 Tauri Programme within The Commons Conservancy
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT

View File

@@ -1,4 +1,5 @@
#!/usr/bin/env sh
# Copyright 2019-2023 Tauri Programme within The Commons Conservancy
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT

View File

@@ -0,0 +1,79 @@
#!/usr/bin/env node
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
const fs = require('fs')
const path = require('path')
const ignorePackages = [
'tauri-macros',
'tauri-codegen',
'tauri-runtime',
'tauri-runtime-wry',
'tauri-driver'
]
const covectorConfig = JSON.parse(
fs.readFileSync('.changes/config.json', 'utf8')
)
const tags = Object.keys(covectorConfig.changeTags)
const missingTagsFiles = {}
const unknownTagsFiles = {}
function checkChangeFiles(changeFiles) {
for (const file of changeFiles) {
const content = fs.readFileSync(file, 'utf8')
const [frontMatter] = /^---[\s\S.]*---\n/i.exec(content)
const packages = frontMatter
.split('\n')
.filter((l) => !(l === '---' || !l))
.map((l) => l.replace(/('|")/g, '').split(':'))
for (const [package, _, tag] of packages) {
if (!tag) {
if (ignorePackages.includes(package)) continue
if (!missingTagsFiles[file]) missingTagsFiles[file] = []
missingTagsFiles[file].push(package)
} else if (!tags.includes(tag)) {
if (!unknownTagsFiles[file]) unknownTagsFiles[file] = []
unknownTagsFiles[file].push({ package, tag })
}
}
}
const missingTagsEntries = Object.entries(missingTagsFiles)
const unknownTagsEntries = Object.entries(unknownTagsFiles)
if (missingTagsEntries.length > 0 || unknownTagsEntries.length > 0) {
for (const [file, packages] of missingTagsEntries) {
for (const package of packages) {
console.error(
`Package \`${package}\` is missing a change tag in ${file} `
)
}
}
for (const [file, packages] of unknownTagsEntries) {
for (const { package, tag } of packages) {
console.error(
`Package \`${package}\` has an uknown change tag ${tag} in ${file} `
)
}
}
process.exit(1)
}
}
const [_bin, _script, ...files] = process.argv
if (files.length > 0) {
checkChangeFiles(files.filter((f) => f.toLowerCase() !== 'readme.md'))
} else {
const changeFiles = fs
.readdirSync('.changes')
.filter((f) => f.endsWith('.md') && f.toLowerCase() !== 'readme.md')
.map((p) => path.join('.changes', p))
checkChangeFiles(changeFiles)
}

View File

@@ -1,3 +1,5 @@
#!/usr/bin/env node
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
@@ -9,13 +11,22 @@ const readline = require('readline')
const header = `Copyright 2019-2023 Tauri Programme within The Commons Conservancy
SPDX-License-Identifier: Apache-2.0
SPDX-License-Identifier: MIT`
const bundlerLicense = '// Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>'
const bundlerLicense =
'// Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>'
const extensions = ['.rs', '.js', '.ts', '.yml']
const ignore = ['target', 'templates', 'node_modules', 'gen', 'dist', 'bundle.js', 'bundle.global.js']
const ignore = [
'target',
'templates',
'node_modules',
'gen',
'dist',
'bundle.js',
'bundle.global.js'
]
async function checkFile(file) {
if (extensions.some(e => file.endsWith(e))) {
if (extensions.some((e) => file.endsWith(e))) {
const fileStream = fs.createReadStream(file)
const rl = readline.createInterface({
input: fileStream,
@@ -26,7 +37,11 @@ async function checkFile(file) {
let i = 0
for await (let line of rl) {
// ignore empty lines, allow shebang and bundler license
if (line.length === 0 || line.startsWith("#!") || line === bundlerLicense) {
if (
line.length === 0 ||
line.startsWith('#!') ||
line === bundlerLicense
) {
continue
}
@@ -93,7 +108,7 @@ if (files.length > 0) {
run()
} else {
check('.').then(missing => {
check('.').then((missing) => {
if (missing.length > 0) {
console.log(missing.join('\n'))
process.exit(1)

View File

@@ -1,5 +1,9 @@
#!/bin/bash
# Copyright 2019-2023 Tauri Programme within The Commons Conservancy
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
if git diff --quiet --ignore-submodules HEAD
then
echo "working directory is clean"

View File

@@ -1,4 +1,9 @@
#!/bin/bash
# Copyright 2019-2023 Tauri Programme within The Commons Conservancy
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
set -euxo pipefail
for o in outputs/*; do

View File

@@ -1,4 +1,5 @@
#!/usr/bin/env node
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

View File

@@ -1,4 +1,5 @@
#!/usr/bin/env node
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
@@ -6,7 +7,7 @@
/*
This script is solely intended to be run as part of the `covector version` step to
keep the `../tooling/cli/metadata.json` up to date with other version bumps. Long term
we should look to find a more "rusty way" to import / "pin" a version value in our cli.rs
we should look to find a more "rusty way" to import / "pin" a version value in our tauri-cli
rust binaries.
*/
@@ -14,7 +15,7 @@ const { readFileSync, writeFileSync } = require('fs')
const packageNickname = process.argv[2]
const filePath =
packageNickname === 'cli.js'
packageNickname === '@tauri-apps/cli'
? `../../../tooling/cli/metadata.json`
: `../../tooling/cli/metadata.json`
const bump = process.argv[3]
@@ -51,9 +52,9 @@ const metadata = JSON.parse(readFileSync(filePath, 'utf-8'))
// set field version
let version
if (packageNickname === 'cli.js') {
version = inc(metadata[packageNickname].version)
metadata[packageNickname].version = version
if (packageNickname === '@tauri-apps/cli') {
version = inc(metadata['cli.js'].version)
metadata['cli.js'].version = version
} else {
version = inc(metadata[packageNickname])
metadata[packageNickname] = version

View File

@@ -1,3 +1,7 @@
#!/bin/sh
# Copyright 2019-2023 Tauri Programme within The Commons Conservancy
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT
docker build -t aarch64-unknown-linux-gnu:latest --file .docker/cross/aarch64.Dockerfile .docker/cross

View File

@@ -1,4 +1,5 @@
#!/usr/bin/env pwsh
# Copyright 2019-2023 Tauri Programme within The Commons Conservancy
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT

View File

@@ -1,4 +1,5 @@
#!/usr/bin/env bash
# Copyright 2019-2023 Tauri Programme within The Commons Conservancy
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT

View File

@@ -1,4 +1,5 @@
#!/usr/bin/env sh
# Copyright 2019-2023 Tauri Programme within The Commons Conservancy
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: MIT

View File

@@ -1,3 +1,7 @@
: Copyright 2019-2023 Tauri Programme within The Commons Conservancy
: SPDX-License-Identifier: Apache-2.0
: SPDX-License-Identifier: MIT
@ECHO OFF
REM Copyright 2019-2023 Tauri Programme within The Commons Conservancy

View File

@@ -39,16 +39,16 @@ This is common code that is reused in many places and offers useful utilities li
### Tauri Tooling
#### [api](https://github.com/tauri-apps/tauri/tree/dev/tooling/api) [TS -> JS]
#### [@tauri-apps/api](https://github.com/tauri-apps/tauri/tree/dev/tooling/api) [TS -> JS]
A TypeScript library that creates `cjs` and `esm` JavaScript endpoints for you to import into your Frontend framework so that the Webview can call and listen to backend activity. We also ship the pure TypeScript, because for some frameworks this is more optimal. It uses the message passing of webviews to their hosts.
#### [bundler](https://github.com/tauri-apps/tauri/tree/dev/tooling/bundler) [RUST / SHELL]
The bundler is a library that builds a Tauri App for the platform triple it detects / is told. At the moment it currently supports macOS, Windows and Linux - but in the near future will support mobile platforms as well. May be used outside of Tauri projects.
#### [cli.js](https://github.com/tauri-apps/tauri/tree/dev/tooling/cli/node) [JS]
It is a wrapper around [cli.rs](https://github.com/tauri-apps/tauri/blob/dev/tooling/cli) using [napi-rs](https://github.com/napi-rs/napi-rs) to produce NPM packages for each platform.
#### [@tauri-apps/cli](https://github.com/tauri-apps/tauri/tree/dev/tooling/cli/node) [JS]
It is a wrapper around [tauri-cli](https://github.com/tauri-apps/tauri/blob/dev/tooling/cli) using [napi-rs](https://github.com/napi-rs/napi-rs) to produce NPM packages for each platform.
#### [cli.rs](https://github.com/tauri-apps/tauri/tree/dev/tooling/cli) [RUST]
#### [tauri-cli](https://github.com/tauri-apps/tauri/tree/dev/tooling/cli) [RUST]
This rust executable provides the full interface to all of the required activities for which the CLI is required. It will run on macOS, Windows, and Linux.
#### [create-tauri-app](https://github.com/tauri-apps/create-tauri-app) [JS]
@@ -67,9 +67,6 @@ Tauri uses WRY as the abstract layer responsible to determine which webview is u
# Additional tooling
## [binary-releases](https://github.com/tauri-apps/binary-releases)
This is the delivery mechanism for tauri prebuilt binaries: currently the cli.rs (used by cli.js) and rustup binaries (used by the deps install command of cli.js). These artifacts are automatically created on release.
## [tauri-action](https://github.com/tauri-apps/tauri-action)
This is a github workflow that builds tauri binaries for all platforms. It is not the fastest out there, but it gets the job done and is highly configurable. Even allowing you to create a (very basic) tauri app even if tauri is not setup.
@@ -119,7 +116,7 @@ This will do several things:
1. start the JS Framework devserver
2. begin the long process of downloading and compiling the rust libraries
3. open an application window with devtools enabled
4. keep a long-lived console alive
4. keep a long-lived console alive
If you change your HTML/CSS/TS/JS, your framework devserver should give you its best shot at instant hot module reloading and you will see the changes instantly.
@@ -149,7 +146,7 @@ After some time, the process will end and you can see the results in the `./src-
End users will be provided with binaries in ways that are appropriate for their systems. Whether macOS, Linux, or Windows, direct download or store installations - they will be able to follow procedures for installing and removing that they are used to.
## What does the Updating flow look like?
When a new version is ready, the developer publishes the new signed artifacts to a server (that they have configured within `tauri.conf.json`).
When a new version is ready, the developer publishes the new signed artifacts to a server (that they have configured within `tauri.conf.json`).
The application can poll this server to see if there is a new release. When there is a new release, the user is prompted to update. The application update is downloaded, verified (checksum & signature), updated, closed, and restarted.

View File

@@ -1,4 +1,5 @@
[workspace]
resolver = "2"
members = [
# core
"core/tauri",

View File

@@ -2,7 +2,7 @@
[![status](https://img.shields.io/badge/status-stable-blue.svg)](https://github.com/tauri-apps/tauri/tree/dev)
[![License](https://img.shields.io/badge/License-MIT%20or%20Apache%202-green.svg)](https://opencollective.com/tauri)
[![test library](https://img.shields.io/github/workflow/status/tauri-apps/tauri/test%20library?label=test%20library)](https://github.com/tauri-apps/tauri/actions?query=workflow%3A%22test+library%22)
[![test core](https://img.shields.io/github/actions/workflow/status/tauri-apps/tauri/test-core.yml?label=test%20core&logo=github)](https://github.com/tauri-apps/tauri/actions/workflows/test-core.yml)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Ftauri-apps%2Ftauri.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Ftauri-apps%2Ftauri?ref=badge_shield)
[![Chat Server](https://img.shields.io/badge/chat-discord-7289da.svg)](https://discord.gg/SpmNs4S)
[![website](https://img.shields.io/badge/website-tauri.app-purple.svg)](https://tauri.app)
@@ -25,12 +25,12 @@
### Tooling
| Component | Description | Version | Lin | Win | Mac |
| --------------------------------------------------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------ | --- | --- | --- |
| [**bundler**](https://github.com/tauri-apps/tauri/tree/dev/tooling/bundler) | manufacture the final binaries | [![](https://img.shields.io/crates/v/tauri-bundler.svg)](https://crates.io/crates/tauri-bundler) | ✅ | ✅ | ✅ |
| [**api.js**](https://github.com/tauri-apps/tauri/tree/dev/tooling/api) | JS API for interaction with Rust backend | [![](https://img.shields.io/npm/v/@tauri-apps/api.svg)](https://www.npmjs.com/package/@tauri-apps/api) | ✅ | ✅ | ✅ |
| [**cli.rs**](https://github.com/tauri-apps/tauri/tree/dev/tooling/cli) | create, develop and build apps | [![](https://img.shields.io/crates/v/tauri-cli.svg)](https://crates.io/crates/tauri-cli) | ✅ | ✅ | ✅ |
| [**cli.js**](https://github.com/tauri-apps/tauri/tree/dev/tooling/cli/node) | Node.js CLI wrapper for cli.rs | [![](https://img.shields.io/npm/v/@tauri-apps/cli.svg)](https://www.npmjs.com/package/@tauri-apps/cli) | ✅ | ✅ | ✅ |
| Component | Description | Version | Lin | Win | Mac |
| ------------------------------------------------------------------------------------ | ---------------------------------------- | ------------------------------------------------------------------------------------------------------ | --- | --- | --- |
| [**bundler**](https://github.com/tauri-apps/tauri/tree/dev/tooling/bundler) | manufacture the final binaries | [![](https://img.shields.io/crates/v/tauri-bundler.svg)](https://crates.io/crates/tauri-bundler) | ✅ | ✅ | ✅ |
| [**tauri-cli**](https://github.com/tauri-apps/tauri/tree/dev/tooling/cli) | create, develop and build apps | [![](https://img.shields.io/crates/v/tauri-cli.svg)](https://crates.io/crates/tauri-cli) | ✅ | ✅ | ✅ |
| [**@tauri-apps/cli**](https://github.com/tauri-apps/tauri/tree/dev/tooling/cli/node) | Node.js CLI wrapper for `tauri-cli` | [![](https://img.shields.io/npm/v/@tauri-apps/cli.svg)](https://www.npmjs.com/package/@tauri-apps/cli) | ✅ | ✅ | ✅ |
| [**@tauri-apps/api**](https://github.com/tauri-apps/tauri/tree/dev/tooling/api) | JS API for interaction with Rust backend | [![](https://img.shields.io/npm/v/@tauri-apps/api.svg)](https://www.npmjs.com/package/@tauri-apps/api) | ✅ | ✅ | ✅ |
### Utilities and Plugins
@@ -75,6 +75,8 @@ For **running** Tauri apps we support the below configurations (these are automa
- `webkit2gtk`, `gtk3`, `libayatana-appindicator`<sup>1</sup>
- Fedora (latest 2 versions) with the following packages installed:
- `webkit2gtk3`, `gtk3`, `libappindicator-gtk3`<sup>1</sup>
- Void with the following packages installed:
- `webkit2gtk`, `gtk+3`, `libappindicator`<sup>1</sup>
<sup>1</sup> `appindicator` is only required if system trays are used

View File

@@ -1,5 +1,25 @@
# Changelog
## \[1.4.1]
### Bug Fixes
- [`5ecb46b3`](https://www.github.com/tauri-apps/tauri/commit/5ecb46b3410afd1b5c82494c1e0a91d5a358c41a)([#7773](https://www.github.com/tauri-apps/tauri/pull/7773)) Automatically set rpath on macOS if frameworks are bundled and copy frameworks to `src-tauri/target/Frameworks` for usage in development.
- [`290e366a`](https://www.github.com/tauri-apps/tauri/commit/290e366ae98e9a52b1b43bfd3e285150427ebffa)([#7419](https://www.github.com/tauri-apps/tauri/pull/7419)) Correctly copy the WebView2 runtime in development when `webviewInstallMode` is used instead of `webviewFixedRuntimePath`.
### Dependencies
- Upgraded to `tauri-utils@1.5.0`
- Upgraded to `tauri-codegen@1.4.1`
## \[1.4.0]
### Enhancements
- [`52474e47`](https://www.github.com/tauri-apps/tauri/commit/52474e479d695865299d8c8d868fb98b99731020)([#7141](https://www.github.com/tauri-apps/tauri/pull/7141)) Enhance Cargo features check.
- [`af937290`](https://www.github.com/tauri-apps/tauri/commit/af93729031565a69d1fde6cf16bea3b9b6e43a65)([#6676](https://www.github.com/tauri-apps/tauri/pull/6676)) On Windows, set `LegalCopyright` and `FileDescription` file properties on the executable from `tauri.bundle.copyright` and `tauri.bundle.shortDescription`,
- [`d2710e9d`](https://www.github.com/tauri-apps/tauri/commit/d2710e9d2e8fd93975ef6494512370faa8cb3b7e)([#6944](https://www.github.com/tauri-apps/tauri/pull/6944)) Unpin `time`, `ignore`, and `winnow` crate versions. Developers now have to pin crates if needed themselves. A list of crates that need pinning to adhere to Tauri's MSRV will be visible in Tauri's GitHub workflow: https://github.com/tauri-apps/tauri/blob/dev/.github/workflows/test-core.yml#L85.
## \[1.3.0]
- Bump minimum supported Rust version to 1.60.

View File

@@ -1,6 +1,6 @@
[package]
name = "tauri-build"
version = "1.3.0"
version = "1.4.1"
authors = [ "Tauri Programme within The Commons Conservancy" ]
categories = [ "gui", "web-programming" ]
license = "Apache-2.0 OR MIT"
@@ -19,16 +19,17 @@ rustdoc-args = [ "--cfg", "doc_cfg" ]
[dependencies]
anyhow = "1"
quote = { version = "1", optional = true }
tauri-codegen = { version = "1.3.0", path = "../tauri-codegen", optional = true }
tauri-utils = { version = "1.3.0", path = "../tauri-utils", features = [ "build", "resources" ] }
tauri-codegen = { version = "1.4.1", path = "../tauri-codegen", optional = true }
tauri-utils = { version = "1.5.0", path = "../tauri-utils", features = [ "build", "resources" ] }
cargo_toml = "0.15"
winnow = "=0.4.1"
serde = "1"
serde_json = "1"
heck = "0.4"
json-patch = "1.0"
tauri-winres = "0.1"
semver = "1"
walkdir = "2"
dirs-next = "2"
[features]
codegen = [ "tauri-codegen", "quote" ]

View File

@@ -4,7 +4,7 @@
[![status](https://img.shields.io/badge/status-stable-blue.svg)](https://github.com/tauri-apps/tauri/tree/dev)
[![License](https://img.shields.io/badge/License-MIT%20or%20Apache%202-green.svg)](https://opencollective.com/tauri)
[![test library](https://img.shields.io/github/workflow/status/tauri-apps/tauri/test%20library?label=test%20library)](https://github.com/tauri-apps/tauri/actions?query=workflow%3A%22test+library%22)
[![test core](https://img.shields.io/github/actions/workflow/status/tauri-apps/tauri/test-core.yml?label=test%20core&logo=github)](https://github.com/tauri-apps/tauri/actions/workflows/test-core.yml)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Ftauri-apps%2Ftauri.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Ftauri-apps%2Ftauri?ref=badge_shield)
[![Chat Server](https://img.shields.io/badge/chat-discord-7289da.svg)](https://discord.gg/SpmNs4S)
[![website](https://img.shields.io/badge/website-tauri.app-purple.svg)](https://tauri.app)

View File

@@ -0,0 +1,211 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use anyhow::{anyhow, Result};
use cargo_toml::{Dependency, Manifest};
use tauri_utils::config::{Config, PatternKind, TauriConfig};
#[derive(Debug, Default, PartialEq, Eq)]
struct Diff {
remove: Vec<String>,
add: Vec<String>,
}
#[derive(Debug, Clone, Copy)]
enum DependencyKind {
Build,
Normal,
}
#[derive(Debug)]
struct AllowlistedDependency {
name: String,
alias: Option<String>,
kind: DependencyKind,
all_cli_managed_features: Option<Vec<&'static str>>,
expected_features: Vec<String>,
}
pub fn check(config: &Config, manifest: &mut Manifest) -> Result<()> {
let dependencies = vec![
AllowlistedDependency {
name: "tauri-build".into(),
alias: None,
kind: DependencyKind::Build,
all_cli_managed_features: Some(vec!["isolation"]),
expected_features: match config.tauri.pattern {
PatternKind::Isolation { .. } => vec!["isolation".to_string()],
_ => vec![],
},
},
AllowlistedDependency {
name: "tauri".into(),
alias: None,
kind: DependencyKind::Normal,
all_cli_managed_features: Some(TauriConfig::all_features()),
expected_features: config
.tauri
.features()
.into_iter()
.map(|f| f.to_string())
.collect::<Vec<String>>(),
},
];
for metadata in dependencies {
let mut name = metadata.name.clone();
let mut deps = find_dependency(manifest, &metadata.name, metadata.kind);
if deps.is_empty() {
if let Some(alias) = &metadata.alias {
deps = find_dependency(manifest, alias, metadata.kind);
name = alias.clone();
}
}
for dep in deps {
if let Err(error) = check_features(dep, &metadata) {
return Err(anyhow!("
The `{}` dependency features on the `Cargo.toml` file does not match the allowlist defined under `tauri.conf.json`.
Please run `tauri dev` or `tauri build` or {}.
", name, error));
}
}
}
Ok(())
}
fn find_dependency(manifest: &mut Manifest, name: &str, kind: DependencyKind) -> Vec<Dependency> {
let dep = match kind {
DependencyKind::Build => manifest.build_dependencies.remove(name),
DependencyKind::Normal => manifest.dependencies.remove(name),
};
if let Some(dep) = dep {
vec![dep]
} else {
let mut deps = Vec::new();
for target in manifest.target.values_mut() {
if let Some(dep) = match kind {
DependencyKind::Build => target.build_dependencies.remove(name),
DependencyKind::Normal => target.dependencies.remove(name),
} {
deps.push(dep);
}
}
deps
}
}
fn features_diff(current: &[String], expected: &[String]) -> Diff {
let mut remove = Vec::new();
let mut add = Vec::new();
for feature in current {
if !expected.contains(feature) {
remove.push(feature.clone());
}
}
for feature in expected {
if !current.contains(feature) {
add.push(feature.clone());
}
}
Diff { remove, add }
}
fn check_features(dependency: Dependency, metadata: &AllowlistedDependency) -> Result<(), String> {
let features = match dependency {
Dependency::Simple(_) => Vec::new(),
Dependency::Detailed(dep) => dep.features,
Dependency::Inherited(dep) => dep.features,
};
let diff = if let Some(all_cli_managed_features) = &metadata.all_cli_managed_features {
features_diff(
&features
.into_iter()
.filter(|f| all_cli_managed_features.contains(&f.as_str()))
.collect::<Vec<String>>(),
&metadata.expected_features,
)
} else {
features_diff(
&features
.into_iter()
.filter(|f| f.starts_with("allow-"))
.collect::<Vec<String>>(),
&metadata.expected_features,
)
};
let mut error_message = String::new();
if !diff.remove.is_empty() {
error_message.push_str("remove the `");
error_message.push_str(&diff.remove.join(", "));
error_message.push_str(if diff.remove.len() == 1 {
"` feature"
} else {
"` features"
});
if !diff.add.is_empty() {
error_message.push_str(" and ");
}
}
if !diff.add.is_empty() {
error_message.push_str("add the `");
error_message.push_str(&diff.add.join(", "));
error_message.push_str(if diff.add.len() == 1 {
"` feature"
} else {
"` features"
});
}
if error_message.is_empty() {
Ok(())
} else {
Err(error_message)
}
}
#[cfg(test)]
mod tests {
use super::Diff;
#[test]
fn array_diff() {
for (current, expected, result) in [
(vec![], vec![], Default::default()),
(
vec!["a".into()],
vec![],
Diff {
remove: vec!["a".into()],
add: vec![],
},
),
(vec!["a".into()], vec!["a".into()], Default::default()),
(
vec!["a".into(), "b".into()],
vec!["a".into()],
Diff {
remove: vec!["b".into()],
add: vec![],
},
),
(
vec!["a".into(), "b".into()],
vec!["a".into(), "c".into()],
Diff {
remove: vec!["b".into()],
add: vec!["c".into()],
},
),
] {
assert_eq!(super::features_diff(&current, &expected), result);
}
}
}

View File

@@ -4,17 +4,19 @@
#![cfg_attr(doc_cfg, feature(doc_cfg))]
use anyhow::Context;
pub use anyhow::Result;
use cargo_toml::{Dependency, Manifest};
use cargo_toml::Manifest;
use heck::AsShoutySnakeCase;
use tauri_utils::{
config::Config,
resources::{external_binaries, resource_relpath, ResourcePaths},
config::{BundleResources, Config, WebviewInstallMode},
resources::{external_binaries, ResourcePaths},
};
use std::path::{Path, PathBuf};
mod allowlist;
#[cfg(feature = "codegen")]
mod codegen;
mod static_vcruntime;
@@ -71,11 +73,117 @@ fn copy_binaries(
/// Copies resources to a path.
fn copy_resources(resources: ResourcePaths<'_>, path: &Path) -> Result<()> {
for src in resources {
let src = src?;
println!("cargo:rerun-if-changed={}", src.display());
let dest = path.join(resource_relpath(&src));
copy_file(&src, dest)?;
for resource in resources.iter() {
let resource = resource?;
println!("cargo:rerun-if-changed={}", resource.path().display());
copy_file(resource.path(), path.join(resource.target()))?;
}
Ok(())
}
#[cfg(unix)]
fn symlink_dir(src: &Path, dst: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(src, dst)
}
/// Makes a symbolic link to a directory.
#[cfg(windows)]
fn symlink_dir(src: &Path, dst: &Path) -> std::io::Result<()> {
std::os::windows::fs::symlink_dir(src, dst)
}
/// Makes a symbolic link to a file.
#[cfg(unix)]
fn symlink_file(src: &Path, dst: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(src, dst)
}
/// Makes a symbolic link to a file.
#[cfg(windows)]
fn symlink_file(src: &Path, dst: &Path) -> std::io::Result<()> {
std::os::windows::fs::symlink_file(src, dst)
}
fn copy_dir(from: &Path, to: &Path) -> Result<()> {
for entry in walkdir::WalkDir::new(from) {
let entry = entry?;
debug_assert!(entry.path().starts_with(from));
let rel_path = entry.path().strip_prefix(from)?;
let dest_path = to.join(rel_path);
if entry.file_type().is_symlink() {
let target = std::fs::read_link(entry.path())?;
if entry.path().is_dir() {
symlink_dir(&target, &dest_path)?;
} else {
symlink_file(&target, &dest_path)?;
}
} else if entry.file_type().is_dir() {
std::fs::create_dir(dest_path)?;
} else {
std::fs::copy(entry.path(), dest_path)?;
}
}
Ok(())
}
// Copies the framework under `{src_dir}/{framework}.framework` to `{dest_dir}/{framework}.framework`.
fn copy_framework_from(src_dir: &Path, framework: &str, dest_dir: &Path) -> Result<bool> {
let src_name = format!("{}.framework", framework);
let src_path = src_dir.join(&src_name);
if src_path.exists() {
copy_dir(&src_path, &dest_dir.join(&src_name))?;
Ok(true)
} else {
Ok(false)
}
}
// Copies the macOS application bundle frameworks to the target folder
fn copy_frameworks(dest_dir: &Path, frameworks: &[String]) -> Result<()> {
std::fs::create_dir_all(dest_dir).with_context(|| {
format!(
"Failed to create frameworks output directory at {:?}",
dest_dir
)
})?;
for framework in frameworks.iter() {
if framework.ends_with(".framework") {
let src_path = PathBuf::from(framework);
let src_name = src_path
.file_name()
.expect("Couldn't get framework filename");
let dest_path = dest_dir.join(src_name);
copy_dir(&src_path, &dest_path)?;
continue;
} else if framework.ends_with(".dylib") {
let src_path = PathBuf::from(framework);
if !src_path.exists() {
return Err(anyhow::anyhow!("Library not found: {}", framework));
}
let src_name = src_path.file_name().expect("Couldn't get library filename");
let dest_path = dest_dir.join(src_name);
copy_file(&src_path, &dest_path)?;
continue;
} else if framework.contains('/') {
return Err(anyhow::anyhow!(
"Framework path should have .framework extension: {}",
framework
));
}
if let Some(home_dir) = dirs_next::home_dir() {
if copy_framework_from(&home_dir.join("Library/Frameworks/"), framework, dest_dir)? {
continue;
}
}
if copy_framework_from(&PathBuf::from("/Library/Frameworks/"), framework, dest_dir)?
|| copy_framework_from(
&PathBuf::from("/Network/Library/Frameworks/"),
framework,
dest_dir,
)?
{
continue;
}
}
Ok(())
}
@@ -116,10 +224,28 @@ pub struct WindowsAttributes {
/// A string containing an [application manifest] to be included with the application on Windows.
///
/// Defaults to:
/// ```ignore
/// ```text
#[doc = include_str!("window-app-manifest.xml")]
/// ```
///
/// ## Warning
///
/// if you are using tauri's dialog APIs, you need to specify a dependency on Common Control v6 by adding the following to your custom manifest:
/// ```text
/// <dependency>
/// <dependentAssembly>
/// <assemblyIdentity
/// type="win32"
/// name="Microsoft.Windows.Common-Controls"
/// version="6.0.0.0"
/// processorArchitecture="*"
/// publicKeyToken="6595b64144ccf1df"
/// language="*"
/// />
/// </dependentAssembly>
/// </dependency>
/// ```
///
/// [application manifest]: https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests
app_manifest: Option<String>,
}
@@ -148,39 +274,57 @@ impl WindowsAttributes {
self
}
/// Sets the Windows app [manifest].
/// Sets the [application manifest] to be included with the application on Windows.
///
/// Defaults to:
/// ```text
#[doc = include_str!("window-app-manifest.xml")]
/// ```
///
/// ## Warning
///
/// if you are using tauri's dialog APIs, you need to specify a dependency on Common Control v6 by adding the following to your custom manifest:
/// ```text
/// <dependency>
/// <dependentAssembly>
/// <assemblyIdentity
/// type="win32"
/// name="Microsoft.Windows.Common-Controls"
/// version="6.0.0.0"
/// processorArchitecture="*"
/// publicKeyToken="6595b64144ccf1df"
/// language="*"
/// />
/// </dependentAssembly>
/// </dependency>
/// ```
///
/// # Example
///
/// The following manifest will brand the exe as requesting administrator privileges.
/// Thus, everytime it is executed, a Windows UAC dialog will appear.
///
/// Note that you can move the manifest contents to a separate file and use `include_str!("manifest.xml")`
/// instead of the inline string.
///
/// ```rust,no_run
/// let mut windows = tauri_build::WindowsAttributes::new();
/// windows = windows.app_manifest(r#"
/// <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
/// <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
/// <security>
/// <requestedPrivileges>
/// <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
/// </requestedPrivileges>
/// </security>
/// </trustInfo>
/// <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
/// <security>
/// <requestedPrivileges>
/// <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
/// </requestedPrivileges>
/// </security>
/// </trustInfo>
/// </assembly>
/// "#);
/// tauri_build::try_build(
/// tauri_build::Attributes::new().windows_attributes(windows)
/// ).expect("failed to run build script");
/// let attrs = tauri_build::Attributes::new().windows_attributes(windows);
/// tauri_build::try_build(attrs).expect("failed to run build script");
/// ```
///
/// Defaults to:
/// ```ignore
#[doc = include_str!("window-app-manifest.xml")]
/// Note that you can move the manifest contents to a separate file and use `include_str!("manifest.xml")`
/// instead of the inline string.
///
/// [manifest]: https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests
/// ```
#[must_use]
pub fn app_manifest<S: AsRef<str>>(mut self, manifest: S) -> Self {
self.app_manifest = Some(manifest.as_ref().to_string());
@@ -284,27 +428,7 @@ pub fn try_build(attributes: Attributes) -> Result<()> {
Manifest::complete_from_path(&mut manifest, Path::new("Cargo.toml"))?;
}
if let Some(tauri_build) = manifest.build_dependencies.remove("tauri-build") {
let error_message = check_features(&config, tauri_build, true);
if !error_message.is_empty() {
return Err(anyhow!("
The `tauri-build` dependency features on the `Cargo.toml` file does not match the allowlist defined under `tauri.conf.json`.
Please run `tauri dev` or `tauri build` or {}.
", error_message));
}
}
if let Some(tauri) = manifest.dependencies.remove("tauri") {
let error_message = check_features(&config, tauri, false);
if !error_message.is_empty() {
return Err(anyhow!("
The `tauri` dependency features on the `Cargo.toml` file does not match the allowlist defined under `tauri.conf.json`.
Please run `tauri dev` or `tauri build` or {}.
", error_message));
}
}
allowlist::check(&config, &mut manifest)?;
let target_triple = std::env::var("TARGET").unwrap();
let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());
@@ -327,24 +451,53 @@ pub fn try_build(attributes: Attributes) -> Result<()> {
}
#[allow(unused_mut, clippy::redundant_clone)]
let mut resources = config.tauri.bundle.resources.clone().unwrap_or_default();
let mut resources = config
.tauri
.bundle
.resources
.clone()
.unwrap_or_else(|| BundleResources::List(Vec::new()));
if target_triple.contains("windows") {
if let Some(fixed_webview2_runtime_path) =
&config.tauri.bundle.windows.webview_fixed_runtime_path
match &config.tauri.bundle.windows.webview_fixed_runtime_path {
Some(path) => Some(path),
None => match &config.tauri.bundle.windows.webview_install_mode {
WebviewInstallMode::FixedRuntime { path } => Some(path),
_ => None,
},
}
{
resources.push(fixed_webview2_runtime_path.display().to_string());
}
}
copy_resources(ResourcePaths::new(resources.as_slice(), true), target_dir)?;
match resources {
BundleResources::List(res) => {
copy_resources(ResourcePaths::new(res.as_slice(), true), target_dir)?
}
BundleResources::Map(map) => copy_resources(ResourcePaths::from_map(&map, true), target_dir)?,
}
if target_triple.contains("darwin") {
if let Some(frameworks) = &config.tauri.bundle.macos.frameworks {
if !frameworks.is_empty() {
let frameworks_dir = target_dir.parent().unwrap().join("Frameworks");
let _ = std::fs::remove_dir_all(&frameworks_dir);
// copy frameworks to the root `target` folder (instead of `target/debug` for instance)
// because the rpath is set to `@executable_path/../Frameworks`.
copy_frameworks(&frameworks_dir, frameworks)?;
// If we have frameworks, we need to set the @rpath
// https://github.com/tauri-apps/tauri/issues/7710
println!("cargo:rustc-link-arg=-Wl,-rpath,@executable_path/../Frameworks");
}
}
if let Some(version) = &config.tauri.bundle.macos.minimum_system_version {
println!("cargo:rustc-env=MACOSX_DEPLOYMENT_TARGET={version}");
}
}
if target_triple.contains("windows") {
use anyhow::Context;
use semver::Version;
use tauri_winres::{VersionInfo, WindowsResource};
@@ -374,27 +527,23 @@ pub fn try_build(attributes: Attributes) -> Result<()> {
res.set_manifest(include_str!("window-app-manifest.xml"));
}
if let Some(sdk_dir) = &attributes.windows_attributes.sdk_dir {
if let Some(sdk_dir_str) = sdk_dir.to_str() {
res.set_toolkit_path(sdk_dir_str);
} else {
return Err(anyhow!(
"sdk_dir path is not valid; only UTF-8 characters are allowed"
));
}
}
if let Some(version) = &config.package.version {
if let Ok(v) = Version::parse(version) {
if let Some(version_str) = &config.package.version {
if let Ok(v) = Version::parse(version_str) {
let version = v.major << 48 | v.minor << 32 | v.patch << 16;
res.set_version_info(VersionInfo::FILEVERSION, version);
res.set_version_info(VersionInfo::PRODUCTVERSION, version);
}
res.set("FileVersion", version);
res.set("ProductVersion", version);
res.set("FileVersion", version_str);
res.set("ProductVersion", version_str);
}
if let Some(product_name) = &config.package.product_name {
res.set("ProductName", product_name);
res.set("FileDescription", product_name);
}
if let Some(short_description) = &config.tauri.bundle.short_description {
res.set("FileDescription", short_description);
}
if let Some(copyright) = &config.tauri.bundle.copyright {
res.set("LegalCopyright", copyright);
}
res.set_icon_with_id(&window_icon_path.display().to_string(), "32512");
res.compile().with_context(|| {
@@ -446,93 +595,6 @@ pub fn try_build(attributes: Attributes) -> Result<()> {
Ok(())
}
#[derive(Debug, Default, PartialEq, Eq)]
struct Diff {
remove: Vec<String>,
add: Vec<String>,
}
fn features_diff(current: &[String], expected: &[String]) -> Diff {
let mut remove = Vec::new();
let mut add = Vec::new();
for feature in current {
if !expected.contains(feature) {
remove.push(feature.clone());
}
}
for feature in expected {
if !current.contains(feature) {
add.push(feature.clone());
}
}
Diff { remove, add }
}
fn check_features(config: &Config, dependency: Dependency, is_tauri_build: bool) -> String {
use tauri_utils::config::{PatternKind, TauriConfig};
let features = match dependency {
Dependency::Simple(_) => Vec::new(),
Dependency::Detailed(dep) => dep.features,
Dependency::Inherited(dep) => dep.features,
};
let all_cli_managed_features = if is_tauri_build {
vec!["isolation"]
} else {
TauriConfig::all_features()
};
let expected = if is_tauri_build {
match config.tauri.pattern {
PatternKind::Isolation { .. } => vec!["isolation".to_string()],
_ => vec![],
}
} else {
config
.tauri
.features()
.into_iter()
.map(|f| f.to_string())
.collect::<Vec<String>>()
};
let diff = features_diff(
&features
.into_iter()
.filter(|f| all_cli_managed_features.contains(&f.as_str()))
.collect::<Vec<String>>(),
&expected,
);
let mut error_message = String::new();
if !diff.remove.is_empty() {
error_message.push_str("remove the `");
error_message.push_str(&diff.remove.join(", "));
error_message.push_str(if diff.remove.len() == 1 {
"` feature"
} else {
"` features"
});
if !diff.add.is_empty() {
error_message.push_str(" and ");
}
}
if !diff.add.is_empty() {
error_message.push_str("add the `");
error_message.push_str(&diff.add.join(", "));
error_message.push_str(if diff.add.len() == 1 {
"` feature"
} else {
"` features"
});
}
error_message
}
#[derive(serde::Deserialize)]
struct CargoMetadata {
workspace_root: PathBuf,
@@ -552,42 +614,3 @@ fn get_workspace_dir() -> Result<PathBuf> {
Ok(serde_json::from_slice::<CargoMetadata>(&output.stdout)?.workspace_root)
}
#[cfg(test)]
mod tests {
use super::Diff;
#[test]
fn array_diff() {
for (current, expected, result) in [
(vec![], vec![], Default::default()),
(
vec!["a".into()],
vec![],
Diff {
remove: vec!["a".into()],
add: vec![],
},
),
(vec!["a".into()], vec!["a".into()], Default::default()),
(
vec!["a".into(), "b".into()],
vec!["a".into()],
Diff {
remove: vec!["b".into()],
add: vec![],
},
),
(
vec!["a".into(), "b".into()],
vec!["a".into(), "c".into()],
Diff {
remove: vec!["b".into()],
add: vec!["c".into()],
},
),
] {
assert_eq!(super::features_diff(&current, &expected), result);
}
}
}

View File

@@ -1,5 +1,18 @@
# Changelog
## \[1.4.1]
### Dependencies
- Upgraded to `tauri-utils@1.5.0`
## \[1.4.0]
### Enhancements
- [`17d5a4f5`](https://www.github.com/tauri-apps/tauri/commit/17d5a4f51f244d3ff42014b5d1b075fad7c636a5)([#6706](https://www.github.com/tauri-apps/tauri/pull/6706)) Early panic if the PNG icon is not RGBA.
- [`d2710e9d`](https://www.github.com/tauri-apps/tauri/commit/d2710e9d2e8fd93975ef6494512370faa8cb3b7e)([#6944](https://www.github.com/tauri-apps/tauri/pull/6944)) Unpin `time`, `ignore`, and `winnow` crate versions. Developers now have to pin crates if needed themselves. A list of crates that need pinning to adhere to Tauri's MSRV will be visible in Tauri's GitHub workflow: https://github.com/tauri-apps/tauri/blob/dev/.github/workflows/test-core.yml#L85.
## \[1.3.0]
- Bump minimum supported Rust version to 1.60.

View File

@@ -1,6 +1,6 @@
[package]
name = "tauri-codegen"
version = "1.3.0"
version = "1.4.1"
authors = [ "Tauri Programme within The Commons Conservancy" ]
categories = [ "gui", "web-programming" ]
license = "Apache-2.0 OR MIT"
@@ -19,7 +19,7 @@ proc-macro2 = "1"
quote = "1"
serde = { version = "1", features = [ "derive" ] }
serde_json = "1"
tauri-utils = { version = "1.3.0", path = "../tauri-utils", features = [ "build" ] }
tauri-utils = { version = "1.5.0", path = "../tauri-utils", features = [ "build" ] }
thiserror = "1"
walkdir = "2"
brotli = { version = "3", optional = true, default-features = false, features = [ "std" ] }
@@ -32,7 +32,7 @@ json-patch = "1.0"
[target."cfg(target_os = \"macos\")".dependencies]
plist = "1"
time = { version = "=0.3.15", features = [ "parsing", "formatting" ] }
time = { version = "0.3", features = [ "parsing", "formatting" ] }
[features]
default = [ "compression" ]

View File

@@ -6,7 +6,7 @@
[![Chat Server](https://img.shields.io/badge/chat-on%20discord-7289da.svg)](https://discord.gg/SpmNs4S)
[![devto](https://img.shields.io/badge/blog-dev.to-black.svg)](https://dev.to/tauri)
![](https://img.shields.io/github/workflow/status/tauri-apps/tauri/test%20library?label=test%20library)
[![test core](https://img.shields.io/github/actions/workflow/status/tauri-apps/tauri/test-core.yml?label=test%20core&logo=github)](https://github.com/tauri-apps/tauri/actions/workflows/test-core.yml)
[![devto](https://img.shields.io/badge/documentation-site-purple.svg)](https://tauri.app)
[![https://good-labs.github.io/greater-good-affirmation/assets/images/badge.svg](https://good-labs.github.io/greater-good-affirmation/assets/images/badge.svg)](https://good-labs.github.io/greater-good-affirmation)

View File

@@ -176,10 +176,10 @@ pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsE
.tauri
.security
.dev_csp
.clone()
.or_else(|| config.tauri.security.csp.clone())
.as_ref()
.or(config.tauri.security.csp.as_ref())
} else {
config.tauri.security.csp.clone()
config.tauri.security.csp.as_ref()
};
if csp.is_some() {
options = options.with_csp();
@@ -350,14 +350,11 @@ pub fn context_codegen(data: ContextData) -> Result<TokenStream, EmbeddedAssetsE
}
}
let out_path = out_dir.join("Info.plist");
info_plist
.to_file_xml(&out_path)
.to_file_xml(out_dir.join("Info.plist"))
.expect("failed to write Info.plist");
let info_plist_path = out_path.display().to_string();
quote!({
tauri::embed_plist::embed_info_plist!(#info_plist_path);
tauri::embed_plist::embed_info_plist!(concat!(std::env!("OUT_DIR"), "/Info.plist"));
})
} else {
quote!(())
@@ -473,15 +470,20 @@ fn ico_icon<P: AsRef<Path>>(
let width = entry.width();
let height = entry.height();
let out_path = out_dir.join(path.file_name().unwrap());
let icon_file_name = path.file_name().unwrap();
let out_path = out_dir.join(icon_file_name);
write_if_changed(&out_path, &rgba).map_err(|error| EmbeddedAssetsError::AssetWrite {
path: path.to_owned(),
error,
})?;
let out_path = out_path.display().to_string();
let icon = quote!(Some(#root::Icon::Rgba { rgba: include_bytes!(#out_path).to_vec(), width: #width, height: #height }));
let icon_file_name = icon_file_name.to_str().unwrap();
let icon = quote!(Some(
#root::Icon::Rgba {
rgba: include_bytes!(concat!(std::env!("OUT_DIR"), "/", #icon_file_name)).to_vec(),
width: #width,
height: #height
}));
Ok(icon)
}
@@ -497,9 +499,10 @@ fn raw_icon<P: AsRef<Path>>(out_dir: &Path, path: P) -> Result<TokenStream, Embe
error,
})?;
let out_path = out_path.display().to_string();
let icon = quote!(Some(include_bytes!(#out_path).to_vec()));
let icon_path = path.file_name().unwrap().to_str().unwrap().to_string();
let icon = quote!(::std::option::Option::Some(
include_bytes!(concat!(std::env!("OUT_DIR"), "/", #icon_path)).to_vec()
));
Ok(icon)
}
@@ -516,6 +519,13 @@ fn png_icon<P: AsRef<Path>>(
let mut reader = decoder
.read_info()
.unwrap_or_else(|e| panic!("failed to read icon {}: {}", path.display(), e));
let (color_type, _) = reader.output_color_type();
if color_type != png::ColorType::Rgba {
panic!("icon {} is not RGBA", path.display());
}
let mut buffer: Vec<u8> = Vec::new();
while let Ok(Some(row)) = reader.next_row() {
buffer.extend(row.data());
@@ -523,15 +533,21 @@ fn png_icon<P: AsRef<Path>>(
let width = reader.info().width;
let height = reader.info().height;
let out_path = out_dir.join(path.file_name().unwrap());
let icon_file_name = path.file_name().unwrap();
let out_path = out_dir.join(icon_file_name);
write_if_changed(&out_path, &buffer).map_err(|error| EmbeddedAssetsError::AssetWrite {
path: path.to_owned(),
error,
})?;
let out_path = out_path.display().to_string();
let icon = quote!(Some(#root::Icon::Rgba { rgba: include_bytes!(#out_path).to_vec(), width: #width, height: #height }));
let icon_file_name = icon_file_name.to_str().unwrap();
let icon = quote!(Some(
#root::Icon::Rgba {
rgba: include_bytes!(concat!(std::env!("OUT_DIR"), "/", #icon_file_name)).to_vec(),
width: #width,
height: #height,
}
));
Ok(icon)
}

View File

@@ -1,5 +1,5 @@
[package]
name = "tauri-tauri-config-schema"
name = "tauri-config-schema"
version = "0.0.0"
edition = "2021"
publish = false
@@ -11,5 +11,4 @@ tauri-utils = { version = "1.0.0", features = [
schemars = { version = "0.8", features = ["url", "preserve_order"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_with = "1.12"
url = { version = "2.3", features = ["serde"] }

View File

@@ -105,6 +105,7 @@
"print": false,
"requestUserAttention": false,
"setAlwaysOnTop": false,
"setClosable": false,
"setContentProtected": false,
"setCursorGrab": false,
"setCursorIcon": false,
@@ -116,7 +117,9 @@
"setIcon": false,
"setIgnoreCursorEvents": false,
"setMaxSize": false,
"setMaximizable": false,
"setMinSize": false,
"setMinimizable": false,
"setPosition": false,
"setResizable": false,
"setSize": false,
@@ -164,6 +167,7 @@
"security": {
"dangerousDisableAssetCspModification": false,
"dangerousRemoteDomainIpcAccess": [],
"dangerousUseHttpScheme": false,
"freezePrototype": false
},
"updater": {
@@ -221,7 +225,7 @@
"pattern": "^[^/\\:*?\"<>|]+$"
},
"version": {
"description": "App version. It is a semver version number or a path to a `package.json` file containing the `version` field.",
"description": "App version. It is a semver version number or a path to a `package.json` file containing the `version` field. If removed the version number from `Cargo.toml` is used.",
"default": null,
"type": [
"string",
@@ -383,6 +387,7 @@
"print": false,
"requestUserAttention": false,
"setAlwaysOnTop": false,
"setClosable": false,
"setContentProtected": false,
"setCursorGrab": false,
"setCursorIcon": false,
@@ -394,7 +399,9 @@
"setIcon": false,
"setIgnoreCursorEvents": false,
"setMaxSize": false,
"setMaximizable": false,
"setMinSize": false,
"setMinimizable": false,
"setPosition": false,
"setResizable": false,
"setSize": false,
@@ -417,6 +424,7 @@
"default": {
"dangerousDisableAssetCspModification": false,
"dangerousRemoteDomainIpcAccess": [],
"dangerousUseHttpScheme": false,
"freezePrototype": false
},
"allOf": [
@@ -605,7 +613,22 @@
"format": "double"
},
"resizable": {
"description": "Whether the window is resizable or not.",
"description": "Whether the window is resizable or not. When resizable is set to false, native window's maximize button is automatically disabled.",
"default": true,
"type": "boolean"
},
"maximizable": {
"description": "Whether the window's native maximize button is enabled or not. If resizable is set to false, this setting is ignored.\n\n## Platform-specific\n\n- **macOS:** Disables the \"zoom\" button in the window titlebar, which is also used to enter fullscreen mode. - **Linux / iOS / Android:** Unsupported.",
"default": true,
"type": "boolean"
},
"minimizable": {
"description": "Whether the window's native minimize button is enabled or not.\n\n## Platform-specific\n\n- **Linux / iOS / Android:** Unsupported.",
"default": true,
"type": "boolean"
},
"closable": {
"description": "Whether the window's native close button is enabled or not.\n\n## Platform-specific\n\n- **Linux:** \"GTK+ will do its best to convince the window manager not to show a close button. Depending on the system, this function may not have any effect when called on a window that is already visible\" - **iOS / Android:** Unsupported.",
"default": true,
"type": "boolean"
},
@@ -1053,13 +1076,14 @@
},
"resources": {
"description": "App resources to bundle. Each resource is a path to a file or directory. Glob patterns are supported.",
"type": [
"array",
"null"
],
"items": {
"type": "string"
}
"anyOf": [
{
"$ref": "#/definitions/BundleResources"
},
{
"type": "null"
}
]
},
"copyright": {
"description": "A copyright string associated with your application.",
@@ -1237,6 +1261,25 @@
}
]
},
"BundleResources": {
"description": "Definition for bundle resources. Can be either a list of paths to include or a map of source to target paths.",
"anyOf": [
{
"description": "A list of paths to include.",
"type": "array",
"items": {
"type": "string"
}
},
{
"description": "A map of source to target paths.",
"type": "object",
"additionalProperties": {
"type": "string"
}
}
]
},
"AppImageConfig": {
"description": "Configuration for AppImage bundles.\n\nSee more: https://tauri.app/v1/api/config#appimageconfig",
"type": "object",
@@ -1270,6 +1313,13 @@
"additionalProperties": {
"type": "string"
}
},
"desktopTemplate": {
"description": "Path to a custom desktop file Handlebars template.\n\nAvailable variables: `categories`, `comment` (optional), `exec`, `icon` and `name`.",
"type": [
"string",
"null"
]
}
},
"additionalProperties": false
@@ -1661,6 +1711,13 @@
"description": "Configuration for the Installer bundle using NSIS.",
"type": "object",
"properties": {
"template": {
"description": "A custom .nsi template to use.",
"type": [
"string",
"null"
]
},
"license": {
"description": "The path to the license file to render on the installer.",
"type": [
@@ -1708,10 +1765,31 @@
"type": "string"
}
},
"customLanguageFiles": {
"description": "A key-value pair where the key is the language and the value is the path to a custom `.nsh` file that holds the translated text for tauri's custom messages.\n\nSee <https://github.com/tauri-apps/tauri/blob/dev/tooling/bundler/src/bundle/windows/templates/nsis-languages/English.nsh> for an example `.nsh` file.\n\n**Note**: the key must be a valid NSIS language and it must be added to [`NsisConfig`] languages array,",
"type": [
"object",
"null"
],
"additionalProperties": {
"type": "string"
}
},
"displayLanguageSelector": {
"description": "Whether to display a language selector dialog before the installer and uninstaller windows are rendered or not. By default the OS language is selected, with a fallback to the first language in the `languages` array.",
"default": false,
"type": "boolean"
},
"compression": {
"description": "Set the compression algorithm used to compress files in the installer.\n\nSee <https://nsis.sourceforge.io/Reference/SetCompressor>",
"anyOf": [
{
"$ref": "#/definitions/NsisCompression"
},
{
"type": "null"
}
]
}
},
"additionalProperties": false
@@ -1742,6 +1820,32 @@
}
]
},
"NsisCompression": {
"description": "Compression algorithms used in the NSIS installer.\n\nSee <https://nsis.sourceforge.io/Reference/SetCompressor>",
"oneOf": [
{
"description": "ZLIB uses the deflate algorithm, it is a quick and simple method. With the default compression level it uses about 300 KB of memory.",
"type": "string",
"enum": [
"zlib"
]
},
{
"description": "BZIP2 usually gives better compression ratios than ZLIB, but it is a bit slower and uses more memory. With the default compression level it uses about 4 MB of memory.",
"type": "string",
"enum": [
"bzip2"
]
},
{
"description": "LZMA (default) is a new compression method that gives very good compression ratios. The decompression speed is high (10-20 MB/s on a 2 GHz CPU), the compression speed is lower. The memory size that will be used for decompression is the dictionary size plus a few KBs, the default is 8 MB.",
"type": "string",
"enum": [
"lzma"
]
}
]
},
"AllowlistConfig": {
"description": "Allowlist configuration. The allowlist is a translation of the [Cargo allowlist features](https://docs.rs/tauri/latest/tauri/#cargo-allowlist-features).\n\n# Notes\n\n- Endpoints that don't have their own allowlist option are enabled by default. - There is only \"opt-in\", no \"opt-out\". Setting an option to `false` has no effect.\n\n# Examples\n\n- * [`\"app-all\": true`](https://tauri.app/v1/api/config/#appallowlistconfig.all) will make the [hide](https://tauri.app/v1/api/js/app#hide) endpoint be available regardless of whether `hide` is set to `false` or `true` in the allowlist.",
"type": "object",
@@ -1785,6 +1889,7 @@
"print": false,
"requestUserAttention": false,
"setAlwaysOnTop": false,
"setClosable": false,
"setContentProtected": false,
"setCursorGrab": false,
"setCursorIcon": false,
@@ -1796,7 +1901,9 @@
"setIcon": false,
"setIgnoreCursorEvents": false,
"setMaxSize": false,
"setMaximizable": false,
"setMinSize": false,
"setMinimizable": false,
"setPosition": false,
"setResizable": false,
"setSize": false,
@@ -2052,6 +2159,13 @@
"items": {
"type": "string"
}
},
"requireLiteralLeadingDot": {
"description": "Whether or not paths that contain components that start with a `.` will require that `.` appears literally in the pattern; `*`, `?`, `**`, or `[...]` will not match. This is useful because such files are conventionally considered hidden on Unix systems and it might be desirable to skip them when listing files.\n\nDefaults to `true` on Unix systems and `false` on Windows",
"type": [
"boolean",
"null"
]
}
}
}
@@ -2086,6 +2200,21 @@
"default": false,
"type": "boolean"
},
"setMaximizable": {
"description": "Allows setting whether the window's native maximize button is enabled or not.",
"default": false,
"type": "boolean"
},
"setMinimizable": {
"description": "Allows setting whether the window's native minimize button is enabled or not.",
"default": false,
"type": "boolean"
},
"setClosable": {
"description": "Allows setting whether the window's native close button is enabled or not.",
"default": false,
"type": "boolean"
},
"setTitle": {
"description": "Allows changing the window title.",
"default": false,
@@ -2414,7 +2543,7 @@
"additionalProperties": false
},
"HttpAllowlistScope": {
"description": "HTTP API scope definition. It is a list of URLs that can be accessed by the webview when using the HTTP APIs. The scoped URL is matched against the request URL using a glob pattern.\n\nExamples: - \"https://**\": allows all HTTPS urls - \"https://*.github.com/tauri-apps/tauri\": allows any subdomain of \"github.com\" with the \"tauri-apps/api\" path - \"https://myapi.service.com/users/*\": allows access to any URLs that begins with \"https://myapi.service.com/users/\"",
"description": "HTTP API scope definition. It is a list of URLs that can be accessed by the webview when using the HTTP APIs. The scoped URL is matched against the request URL using a glob pattern.\n\nExamples: - \"https://*\": allows all HTTPS urls - \"https://*.github.com/tauri-apps/tauri\": allows any subdomain of \"github.com\" with the \"tauri-apps/api\" path - \"https://myapi.service.com/users/*\": allows access to any URLs that begins with \"https://myapi.service.com/users/\"",
"type": "array",
"items": {
"type": "string",
@@ -2613,6 +2742,11 @@
"items": {
"$ref": "#/definitions/RemoteDomainAccessScope"
}
},
"dangerousUseHttpScheme": {
"description": "Sets whether the custom protocols should use `http://<scheme>.localhost` instead of the default `https://<scheme>.localhost` on Windows.\n\n**WARNING:** Using a `http` scheme will allow mixed content when trying to fetch `http` endpoints and is therefore less secure but will match the behavior of the `<scheme>://localhost` protocols used on macOS and Linux.",
"default": false,
"type": "boolean"
}
},
"additionalProperties": false
@@ -2692,7 +2826,7 @@
}
},
"plugins": {
"description": "The list of plugins that are allowed in this scope.",
"description": "The list of plugins that are allowed in this scope. The names should be without the `tauri-plugin-` prefix, for example `\"store\"` for `tauri-plugin-store`.",
"default": [],
"type": "array",
"items": {
@@ -2791,7 +2925,7 @@
]
},
{
"description": "The quiet mode means there's no user interaction required. Requires admin privileges if the installer does (WiX).",
"description": "The quiet mode means there's no user interaction required. Requires admin privileges if the installer does.",
"type": "string",
"enum": [
"quiet"

View File

@@ -1,5 +1,18 @@
# Changelog
## \[1.4.1]
### Dependencies
- Upgraded to `tauri-utils@1.5.0`
- Upgraded to `tauri-codegen@1.4.1`
## \[1.4.0]
### Enhancements
- [`d68a25e3`](https://www.github.com/tauri-apps/tauri/commit/d68a25e32e012e57a9e5225b589b9ecbea70a887)([#6124](https://www.github.com/tauri-apps/tauri/pull/6124)) Improve compiler error message when generating an async command that has a reference input and don't return a Result.
## \[1.3.0]
- Bump minimum supported Rust version to 1.60.

View File

@@ -1,6 +1,6 @@
[package]
name = "tauri-macros"
version = "1.3.0"
version = "1.4.1"
authors = [ "Tauri Programme within The Commons Conservancy" ]
categories = [ "gui", "os", "filesystem", "web-programming" ]
license = "Apache-2.0 OR MIT"
@@ -20,8 +20,8 @@ proc-macro2 = "1"
quote = "1"
syn = { version = "1", features = [ "full" ] }
heck = "0.4"
tauri-codegen = { version = "1.3.0", default-features = false, path = "../tauri-codegen" }
tauri-utils = { version = "1.3.0", path = "../tauri-utils" }
tauri-codegen = { version = "1.4.1", default-features = false, path = "../tauri-codegen" }
tauri-utils = { version = "1.5.0", path = "../tauri-utils" }
[features]
custom-protocol = [ ]

View File

@@ -4,7 +4,7 @@
[![status](https://img.shields.io/badge/status-stable-blue.svg)](https://github.com/tauri-apps/tauri/tree/dev)
[![License](https://img.shields.io/badge/License-MIT%20or%20Apache%202-green.svg)](https://opencollective.com/tauri)
[![test library](https://img.shields.io/github/workflow/status/tauri-apps/tauri/test%20library?label=test%20library)](https://github.com/tauri-apps/tauri/actions?query=workflow%3A%22test+library%22)
[![test core](https://img.shields.io/github/actions/workflow/status/tauri-apps/tauri/test-core.yml?label=test%20core&logo=github)](https://github.com/tauri-apps/tauri/actions/workflows/test-core.yml)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Ftauri-apps%2Ftauri.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Ftauri-apps%2Ftauri?ref=badge_shield)
[![Chat Server](https://img.shields.io/badge/chat-discord-7289da.svg)](https://discord.gg/SpmNs4S)
[![website](https://img.shields.io/badge/website-tauri.app-purple.svg)](https://tauri.app)

View File

@@ -5,7 +5,7 @@
use heck::{ToLowerCamelCase, ToSnakeCase};
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use quote::{format_ident, quote, quote_spanned};
use syn::{
ext::IdentExt,
parse::{Parse, ParseStream},
@@ -103,6 +103,63 @@ pub fn wrapper(attributes: TokenStream, item: TokenStream) -> TokenStream {
resolver: format_ident!("__tauri_resolver__"),
};
// Tauri currently doesn't support async commands that take a reference as input and don't return
// a result. See: https://github.com/tauri-apps/tauri/issues/2533
//
// For now, we provide an informative error message to the user in that case. Once #2533 is
// resolved, this check can be removed.
let mut async_command_check = TokenStream2::new();
if function.sig.asyncness.is_some() {
// This check won't catch all possible problems but it should catch the most common ones.
let mut ref_argument_span = None;
for arg in &function.sig.inputs {
if let syn::FnArg::Typed(pat) = arg {
match &*pat.ty {
syn::Type::Reference(_) => {
ref_argument_span = Some(pat.span());
}
syn::Type::Path(path) => {
// Check if the type contains a lifetime argument
let last = path.path.segments.last().unwrap();
if let syn::PathArguments::AngleBracketed(args) = &last.arguments {
if args
.args
.iter()
.any(|arg| matches!(arg, syn::GenericArgument::Lifetime(_)))
{
ref_argument_span = Some(pat.span());
}
}
}
_ => {}
}
if let Some(span) = ref_argument_span {
if let syn::ReturnType::Type(_, return_type) = &function.sig.output {
// To check if the return type is `Result` we require it to check a trait that is
// only implemented by `Result`. That way we don't exclude renamed result types
// which we wouldn't otherwise be able to detect purely from the token stream.
// The "error message" displayed to the user is simply the trait name.
async_command_check = quote_spanned! {return_type.span() =>
#[allow(unreachable_code, clippy::diverging_sub_expression)]
const _: () = if false {
trait AsyncCommandMustReturnResult {}
impl<A, B> AsyncCommandMustReturnResult for ::std::result::Result<A, B> {}
let _check: #return_type = unreachable!();
let _: &dyn AsyncCommandMustReturnResult = &_check;
};
};
} else {
return quote_spanned! {
span => compile_error!("async commands that contain references as inputs must return a `Result`");
}.into();
}
}
}
}
}
// body to the command wrapper or a `compile_error!` of an error occurred while parsing it.
let body = syn::parse::<WrapperAttributes>(attributes)
.map(|mut attrs| {
@@ -121,6 +178,8 @@ pub fn wrapper(attributes: TokenStream, item: TokenStream) -> TokenStream {
// Rely on rust 2018 edition to allow importing a macro from a path.
quote!(
#async_command_check
#function
#maybe_macro_export

View File

@@ -272,12 +272,12 @@ pub fn command_handler(attributes: HandlerAttributes, function: ItemFn) -> Token
pub fn command_test(attributes: HandlerTestAttributes, function: ItemFn) -> TokenStream2 {
let allowlist = attributes.allowlist;
let error_message = attributes.error_message.as_str();
let signature = function.sig.clone();
let signature = &function.sig;
let enum_variant_name = function.sig.ident.to_string().to_lower_camel_case();
let response = match attributes.allowlist_check_kind {
AllowlistCheckKind::Runtime => {
let test_name = function.sig.ident.clone();
let test_name = &signature.ident;
quote!(super::Cmd::#test_name(crate::test::mock_invoke_context()))
}
AllowlistCheckKind::Serde => quote! {

View File

@@ -1,5 +1,40 @@
# Changelog
## \[0.14.1]
### Enhancements
- [`9aa34ada`](https://www.github.com/tauri-apps/tauri/commit/9aa34ada5769dbefa7dfe5f7a6288b3d20b294e4)([#7645](https://www.github.com/tauri-apps/tauri/pull/7645)) Add setting to switch to `http://<scheme>.localhost/` for custom protocols on Windows.
### Bug Fixes
- [`4bf1e85e`](https://www.github.com/tauri-apps/tauri/commit/4bf1e85e6bf85a7ec92d50c8465bc0588a6399d8)([#7722](https://www.github.com/tauri-apps/tauri/pull/7722)) Properly respect the `focused` option when creating the webview.
### Dependencies
- Upgraded to `tauri-utils@1.5.0`
- Upgraded to `tauri-runtime@0.14.1`
## \[0.14.0]
### New Features
- [`c4d6fb4b`](https://www.github.com/tauri-apps/tauri/commit/c4d6fb4b1ea8acf02707a9fe5dcab47c1c5bae7b)([#2353](https://www.github.com/tauri-apps/tauri/pull/2353)) Added the `maximizable`, `minimizable` and `closable` methods to `WindowBuilder`.
- [`c4d6fb4b`](https://www.github.com/tauri-apps/tauri/commit/c4d6fb4b1ea8acf02707a9fe5dcab47c1c5bae7b)([#2353](https://www.github.com/tauri-apps/tauri/pull/2353)) Added `set_maximizable`, `set_minimizable`, `set_closable`, `is_maximizable`, `is_minimizable` and `is_closable` methods to the `Dispatch` trait.
- [`000104bc`](https://www.github.com/tauri-apps/tauri/commit/000104bc3bc0c9ff3d20558ab9cf2080f126e9e0)([#6472](https://www.github.com/tauri-apps/tauri/pull/6472)) Add `Window::is_focused` getter.
### Enhancements
- [`d2710e9d`](https://www.github.com/tauri-apps/tauri/commit/d2710e9d2e8fd93975ef6494512370faa8cb3b7e)([#6944](https://www.github.com/tauri-apps/tauri/pull/6944)) Unpin `time`, `ignore`, and `winnow` crate versions. Developers now have to pin crates if needed themselves. A list of crates that need pinning to adhere to Tauri's MSRV will be visible in Tauri's GitHub workflow: https://github.com/tauri-apps/tauri/blob/dev/.github/workflows/test-core.yml#L85.
### Bug Fixes
- [`b41b57eb`](https://www.github.com/tauri-apps/tauri/commit/b41b57ebb27befd366db5befaafb6043c18fdfef)([#7105](https://www.github.com/tauri-apps/tauri/pull/7105)) Fix panics when registering an invalid global shortcuts or checking it is registered and return proper errors instead.
### What's Changed
- [`076e1a81`](https://www.github.com/tauri-apps/tauri/commit/076e1a81a50468e3dfb34ae9ca7e77c5e1758daa)([#7119](https://www.github.com/tauri-apps/tauri/pull/7119)) Use `u32` instead of `u64` for js event listener ids
## \[0.13.0]
- Added the `additional_browser_args` option when creating a window.

View File

@@ -1,6 +1,6 @@
[package]
name = "tauri-runtime-wry"
version = "0.13.0"
version = "0.14.1"
authors = [ "Tauri Programme within The Commons Conservancy" ]
categories = [ "gui", "web-programming" ]
license = "Apache-2.0 OR MIT"
@@ -13,12 +13,12 @@ exclude = [ "CHANGELOG.md", "/target" ]
readme = "README.md"
[dependencies]
wry = { version = "0.24.1", default-features = false, features = [ "file-drop", "protocol" ] }
tauri-runtime = { version = "0.13.0", path = "../tauri-runtime" }
tauri-utils = { version = "1.3.0", path = "../tauri-utils" }
wry = { version = "0.24.4", default-features = false, features = [ "file-drop", "protocol" ] }
tauri-runtime = { version = "0.14.1", path = "../tauri-runtime" }
tauri-utils = { version = "1.5.0", path = "../tauri-utils" }
uuid = { version = "1", features = [ "v4" ] }
rand = "0.8"
raw-window-handle = "=0.5.0"
raw-window-handle = "0.5"
[target."cfg(windows)".dependencies]
webview2-com = "0.19.1"

View File

@@ -6,8 +6,7 @@
[![Chat Server](https://img.shields.io/badge/chat-on%20discord-7289da.svg)](https://discord.gg/SpmNs4S)
[![devto](https://img.shields.io/badge/blog-dev.to-black.svg)](https://dev.to/tauri)
![](https://img.shields.io/github/workflow/status/tauri-apps/tauri/test%20library?label=test%20library
)
[![test core](https://img.shields.io/github/actions/workflow/status/tauri-apps/tauri/test-core.yml?label=test%20core&logo=github)](https://github.com/tauri-apps/tauri/actions/workflows/test-core.yml)
[![devto](https://img.shields.io/badge/documentation-site-purple.svg)](https://tauri.app)
[![https://good-labs.github.io/greater-good-affirmation/assets/images/badge.svg](https://good-labs.github.io/greater-good-affirmation/assets/images/badge.svg)](https://good-labs.github.io/greater-good-affirmation)

View File

@@ -6,6 +6,7 @@
use std::{
collections::HashMap,
error::Error as StdError,
fmt,
sync::{
mpsc::{channel, Sender},
@@ -18,7 +19,7 @@ use crate::{getter, Context, Message};
use tauri_runtime::{Error, GlobalShortcutManager, Result, UserEvent};
#[cfg(desktop)]
pub use wry::application::{
accelerator::{Accelerator, AcceleratorId},
accelerator::{Accelerator, AcceleratorId, AcceleratorParseError},
global_shortcut::{GlobalShortcut, ShortcutManager as WryShortcutManager},
};
@@ -39,6 +40,15 @@ pub struct GlobalShortcutWrapper(GlobalShortcut);
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for GlobalShortcutWrapper {}
#[derive(Debug, Clone)]
struct AcceleratorParseErrorWrapper(AcceleratorParseError);
impl fmt::Display for AcceleratorParseErrorWrapper {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl StdError for AcceleratorParseErrorWrapper {}
/// Wrapper around [`WryShortcutManager`].
#[derive(Clone)]
pub struct GlobalShortcutManagerHandle<T: UserEvent> {
@@ -67,14 +77,21 @@ impl<T: UserEvent> GlobalShortcutManager for GlobalShortcutManagerHandle<T> {
self,
rx,
Message::GlobalShortcut(GlobalShortcutMessage::IsRegistered(
accelerator.parse().expect("invalid accelerator"),
accelerator
.parse()
.map_err(|e: AcceleratorParseError| Error::GlobalShortcut(Box::new(
AcceleratorParseErrorWrapper(e)
)))?,
tx
))
)
}
fn register<F: Fn() + Send + 'static>(&mut self, accelerator: &str, handler: F) -> Result<()> {
let wry_accelerator: Accelerator = accelerator.parse().expect("invalid accelerator");
let wry_accelerator: Accelerator =
accelerator.parse().map_err(|e: AcceleratorParseError| {
Error::GlobalShortcut(Box::new(AcceleratorParseErrorWrapper(e)))
})?;
let id = wry_accelerator.clone().id();
let (tx, rx) = channel();
let shortcut = getter!(

View File

@@ -5,6 +5,7 @@
//! The [`wry`] Tauri [`Runtime`].
use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle, RawDisplayHandle};
use std::rc::Rc;
use tauri_runtime::{
http::{header::CONTENT_TYPE, Request as HttpRequest, RequestParts, Response as HttpResponse},
menu::{AboutMetadata, CustomMenuItem, Menu, MenuEntry, MenuHash, MenuId, MenuItem, MenuUpdate},
@@ -68,6 +69,7 @@ use wry::{
};
pub use wry::application::window::{Window, WindowBuilder as WryWindowBuilder, WindowId};
pub use wry::webview::webview_version;
#[cfg(windows)]
use wry::webview::WebviewExtWindows;
@@ -214,7 +216,6 @@ impl<T: UserEvent> Context<T> {
impl<T: UserEvent> Context<T> {
fn create_webview(&self, pending: PendingWindow<T, Wry<T>>) -> Result<DetachedWindow<T, Wry<T>>> {
let label = pending.label.clone();
let current_url = pending.current_url.clone();
let menu_ids = pending.menu_ids.clone();
let js_event_listeners = pending.js_event_listeners.clone();
let context = self.clone();
@@ -236,7 +237,6 @@ impl<T: UserEvent> Context<T> {
};
Ok(DetachedWindow {
label,
current_url,
dispatcher,
menu_ids,
js_event_listeners,
@@ -252,7 +252,7 @@ pub struct DispatcherMainThreadContext<T: UserEvent> {
pub global_shortcut_manager: Arc<Mutex<WryShortcutManager>>,
#[cfg(feature = "clipboard")]
pub clipboard_manager: Arc<Mutex<Clipboard>>,
pub windows: Arc<RefCell<HashMap<WebviewId, WindowWrapper>>>,
pub windows: Rc<RefCell<HashMap<WebviewId, WindowWrapper>>>,
#[cfg(all(desktop, feature = "system-tray"))]
system_tray_manager: SystemTrayManager,
}
@@ -718,6 +718,9 @@ impl WindowBuilder for WindowBuilderWrapper {
.inner_size(config.width, config.height)
.visible(config.visible)
.resizable(config.resizable)
.maximizable(config.maximizable)
.minimizable(config.minimizable)
.closable(config.closable)
.fullscreen(config.fullscreen)
.decorations(config.decorations)
.maximized(config.maximized)
@@ -816,6 +819,21 @@ impl WindowBuilder for WindowBuilderWrapper {
self
}
fn maximizable(mut self, maximizable: bool) -> Self {
self.inner = self.inner.with_maximizable(maximizable);
self
}
fn minimizable(mut self, minimizable: bool) -> Self {
self.inner = self.inner.with_minimizable(minimizable);
self
}
fn closable(mut self, closable: bool) -> Self {
self.inner = self.inner.with_closable(closable);
self
}
fn title<S: Into<String>>(mut self, title: S) -> Self {
self.inner = self.inner.with_title(title.into());
self
@@ -1055,8 +1073,12 @@ pub enum WindowMessage {
IsFullscreen(Sender<bool>),
IsMinimized(Sender<bool>),
IsMaximized(Sender<bool>),
IsFocused(Sender<bool>),
IsDecorated(Sender<bool>),
IsResizable(Sender<bool>),
IsMaximizable(Sender<bool>),
IsMinimizable(Sender<bool>),
IsClosable(Sender<bool>),
IsVisible(Sender<bool>),
Title(Sender<String>),
IsMenuVisible(Sender<bool>),
@@ -1077,6 +1099,9 @@ pub enum WindowMessage {
Center,
RequestUserAttention(Option<UserAttentionTypeWrapper>),
SetResizable(bool),
SetMaximizable(bool),
SetMinimizable(bool),
SetClosable(bool),
SetTitle(String),
Maximize,
Unmaximize,
@@ -1285,6 +1310,10 @@ impl<T: UserEvent> Dispatch<T> for WryDispatcher<T> {
window_getter!(self, WindowMessage::IsMaximized)
}
fn is_focused(&self) -> Result<bool> {
window_getter!(self, WindowMessage::IsFocused)
}
/// Gets the windows current decoration state.
fn is_decorated(&self) -> Result<bool> {
window_getter!(self, WindowMessage::IsDecorated)
@@ -1295,6 +1324,21 @@ impl<T: UserEvent> Dispatch<T> for WryDispatcher<T> {
window_getter!(self, WindowMessage::IsResizable)
}
/// Gets the current native window's maximize button state
fn is_maximizable(&self) -> Result<bool> {
window_getter!(self, WindowMessage::IsMaximizable)
}
/// Gets the current native window's minimize button state
fn is_minimizable(&self) -> Result<bool> {
window_getter!(self, WindowMessage::IsMinimizable)
}
/// Gets the current native window's close button state
fn is_closable(&self) -> Result<bool> {
window_getter!(self, WindowMessage::IsClosable)
}
fn is_visible(&self) -> Result<bool> {
window_getter!(self, WindowMessage::IsVisible)
}
@@ -1386,6 +1430,27 @@ impl<T: UserEvent> Dispatch<T> for WryDispatcher<T> {
)
}
fn set_maximizable(&self, maximizable: bool) -> Result<()> {
send_user_message(
&self.context,
Message::Window(self.window_id, WindowMessage::SetMaximizable(maximizable)),
)
}
fn set_minimizable(&self, minimizable: bool) -> Result<()> {
send_user_message(
&self.context,
Message::Window(self.window_id, WindowMessage::SetMinimizable(minimizable)),
)
}
fn set_closable(&self, closable: bool) -> Result<()> {
send_user_message(
&self.context,
Message::Window(self.window_id, WindowMessage::SetClosable(closable)),
)
}
fn set_title<S: Into<String>>(&self, title: S) -> Result<()> {
send_user_message(
&self.context,
@@ -1607,7 +1672,7 @@ impl<T: UserEvent> Dispatch<T> for WryDispatcher<T> {
#[derive(Clone)]
enum WindowHandle {
Webview {
inner: Arc<WebView>,
inner: Rc<WebView>,
context_store: WebContextStore,
// the key of the WebContext if it's not shared
context_key: Option<PathBuf>,
@@ -1623,7 +1688,7 @@ impl Drop for WindowHandle {
context_key,
} = self
{
if Arc::get_mut(inner).is_some() {
if Rc::get_mut(inner).is_some() {
context_store.lock().unwrap().remove(context_key);
}
}
@@ -1877,7 +1942,7 @@ impl<T: UserEvent> Wry<T> {
#[cfg(feature = "clipboard")]
let clipboard_manager = Arc::new(Mutex::new(Clipboard::new()));
let windows = Arc::new(RefCell::new(HashMap::default()));
let windows = Rc::new(RefCell::new(HashMap::default()));
let webview_id_map = WebviewIdStore::default();
#[cfg(all(desktop, feature = "system-tray"))]
@@ -1987,7 +2052,6 @@ impl<T: UserEvent> Runtime<T> for Wry<T> {
fn create_window(&self, pending: PendingWindow<T, Self>) -> Result<DetachedWindow<T, Self>> {
let label = pending.label.clone();
let current_url = pending.current_url.clone();
let menu_ids = pending.menu_ids.clone();
let js_event_listeners = pending.js_event_listeners.clone();
let window_id = rand::random();
@@ -2014,7 +2078,6 @@ impl<T: UserEvent> Runtime<T> for Wry<T> {
Ok(DetachedWindow {
label,
current_url,
dispatcher,
menu_ids,
js_event_listeners,
@@ -2026,7 +2089,7 @@ impl<T: UserEvent> Runtime<T> for Wry<T> {
let id = system_tray.id;
let mut listeners = Vec::new();
if let Some(l) = system_tray.on_event.take() {
listeners.push(Arc::new(l));
listeners.push(Rc::new(l));
}
let (tray, items) = create_tray(WryTrayId(id), system_tray, &self.event_loop)?;
self
@@ -2039,9 +2102,9 @@ impl<T: UserEvent> Runtime<T> for Wry<T> {
.insert(
id,
TrayContext {
tray: Arc::new(Mutex::new(Some(tray))),
listeners: Arc::new(Mutex::new(listeners)),
items: Arc::new(Mutex::new(items)),
tray: Rc::new(RefCell::new(Some(tray))),
listeners: Rc::new(RefCell::new(listeners)),
items: Rc::new(RefCell::new(items)),
},
);
@@ -2242,7 +2305,7 @@ impl<T: UserEvent> Runtime<T> for Wry<T> {
pub struct EventLoopIterationContext<'a, T: UserEvent> {
pub callback: &'a mut (dyn FnMut(RunEvent<T>) + 'static),
pub webview_id_map: WebviewIdStore,
pub windows: Arc<RefCell<HashMap<WebviewId, WindowWrapper>>>,
pub windows: Rc<RefCell<HashMap<WebviewId, WindowWrapper>>>,
#[cfg(all(desktop, feature = "global-shortcut"))]
pub global_shortcut_manager: Arc<Mutex<WryShortcutManager>>,
#[cfg(all(desktop, feature = "global-shortcut"))]
@@ -2254,7 +2317,7 @@ pub struct EventLoopIterationContext<'a, T: UserEvent> {
}
struct UserMessageContext {
windows: Arc<RefCell<HashMap<WebviewId, WindowWrapper>>>,
windows: Rc<RefCell<HashMap<WebviewId, WindowWrapper>>>,
webview_id_map: WebviewIdStore,
#[cfg(all(desktop, feature = "global-shortcut"))]
global_shortcut_manager: Arc<Mutex<WryShortcutManager>>,
@@ -2410,8 +2473,12 @@ fn handle_user_message<T: UserEvent>(
WindowMessage::IsFullscreen(tx) => tx.send(window.fullscreen().is_some()).unwrap(),
WindowMessage::IsMinimized(tx) => tx.send(window.is_minimized()).unwrap(),
WindowMessage::IsMaximized(tx) => tx.send(window.is_maximized()).unwrap(),
WindowMessage::IsFocused(tx) => tx.send(window.is_focused()).unwrap(),
WindowMessage::IsDecorated(tx) => tx.send(window.is_decorated()).unwrap(),
WindowMessage::IsResizable(tx) => tx.send(window.is_resizable()).unwrap(),
WindowMessage::IsMaximizable(tx) => tx.send(window.is_maximizable()).unwrap(),
WindowMessage::IsMinimizable(tx) => tx.send(window.is_minimizable()).unwrap(),
WindowMessage::IsClosable(tx) => tx.send(window.is_closable()).unwrap(),
WindowMessage::IsVisible(tx) => tx.send(window.is_visible()).unwrap(),
WindowMessage::Title(tx) => tx.send(window.title()).unwrap(),
WindowMessage::IsMenuVisible(tx) => tx.send(window.is_menu_visible()).unwrap(),
@@ -2444,6 +2511,9 @@ fn handle_user_message<T: UserEvent>(
window.request_user_attention(request_type.map(|r| r.0));
}
WindowMessage::SetResizable(resizable) => window.set_resizable(resizable),
WindowMessage::SetMaximizable(maximizable) => window.set_maximizable(maximizable),
WindowMessage::SetMinimizable(minimizable) => window.set_minimizable(minimizable),
WindowMessage::SetClosable(closable) => window.set_closable(closable),
WindowMessage::SetTitle(title) => window.set_title(&title),
WindowMessage::Maximize => window.set_maximized(true),
WindowMessage::Unmaximize => window.set_maximized(false),
@@ -2576,16 +2646,16 @@ fn handle_user_message<T: UserEvent>(
if let TrayMessage::Create(mut tray, tx) = tray_message {
let mut listeners = Vec::new();
if let Some(l) = tray.on_event.take() {
listeners.push(Arc::new(l));
listeners.push(Rc::new(l));
}
match create_tray(WryTrayId(tray_id), tray, event_loop) {
Ok((tray, items)) => {
trays.insert(
tray_id,
TrayContext {
tray: Arc::new(Mutex::new(Some(tray))),
listeners: Arc::new(Mutex::new(listeners)),
items: Arc::new(Mutex::new(items)),
tray: Rc::new(RefCell::new(Some(tray))),
listeners: Rc::new(RefCell::new(listeners)),
items: Rc::new(RefCell::new(items)),
},
);
@@ -2599,7 +2669,7 @@ fn handle_user_message<T: UserEvent>(
} else if let Some(tray_context) = trays.get(&tray_id) {
match tray_message {
TrayMessage::UpdateItem(menu_id, update) => {
let mut tray = tray_context.items.as_ref().lock().unwrap();
let mut tray = tray_context.items.as_ref().borrow_mut();
let item = tray.get_mut(&menu_id).expect("menu item not found");
match update {
MenuUpdate::SetEnabled(enabled) => item.set_enabled(enabled),
@@ -2612,14 +2682,14 @@ fn handle_user_message<T: UserEvent>(
}
}
TrayMessage::UpdateMenu(menu) => {
if let Some(tray) = &mut *tray_context.tray.lock().unwrap() {
if let Some(tray) = &mut *tray_context.tray.borrow_mut() {
let mut items = HashMap::new();
tray.set_menu(&to_wry_context_menu(&mut items, menu));
*tray_context.items.lock().unwrap() = items;
*tray_context.items.borrow_mut() = items;
}
}
TrayMessage::UpdateIcon(icon) => {
if let Some(tray) = &mut *tray_context.tray.lock().unwrap() {
if let Some(tray) = &mut *tray_context.tray.borrow_mut() {
if let Ok(icon) = TrayIcon::try_from(icon) {
tray.set_icon(icon.0);
}
@@ -2627,18 +2697,18 @@ fn handle_user_message<T: UserEvent>(
}
#[cfg(target_os = "macos")]
TrayMessage::UpdateIconAsTemplate(is_template) => {
if let Some(tray) = &mut *tray_context.tray.lock().unwrap() {
if let Some(tray) = &mut *tray_context.tray.borrow_mut() {
tray.set_icon_as_template(is_template);
}
}
#[cfg(target_os = "macos")]
TrayMessage::UpdateTitle(title) => {
if let Some(tray) = &mut *tray_context.tray.lock().unwrap() {
if let Some(tray) = &mut *tray_context.tray.borrow_mut() {
tray.set_title(&title);
}
}
TrayMessage::UpdateTooltip(tooltip) => {
if let Some(tray) = &mut *tray_context.tray.lock().unwrap() {
if let Some(tray) = &mut *tray_context.tray.borrow_mut() {
tray.set_tooltip(&tooltip);
}
}
@@ -2646,9 +2716,9 @@ fn handle_user_message<T: UserEvent>(
// already handled
}
TrayMessage::Destroy(tx) => {
*tray_context.tray.lock().unwrap() = None;
tray_context.listeners.lock().unwrap().clear();
tray_context.items.lock().unwrap().clear();
*tray_context.tray.borrow_mut() = None;
tray_context.listeners.borrow_mut().clear();
tray_context.items.borrow_mut().clear();
tx.send(Ok(())).unwrap();
}
}
@@ -2774,11 +2844,11 @@ fn handle_event_loop<T: UserEvent>(
let (mut listeners, mut tray_id) = (None, 0);
for (id, tray_context) in trays_iter {
let has_menu = {
let items = tray_context.items.lock().unwrap();
let items = tray_context.items.borrow();
items.contains_key(&menu_id.0)
};
if has_menu {
listeners.replace(tray_context.listeners.lock().unwrap().clone());
listeners.replace(tray_context.listeners.borrow().clone());
tray_id = *id;
break;
}
@@ -2817,7 +2887,7 @@ fn handle_event_loop<T: UserEvent>(
};
let trays = system_tray_manager.trays.lock().unwrap();
if let Some(tray_context) = trays.get(&id.0) {
let listeners = tray_context.listeners.lock().unwrap();
let listeners = tray_context.listeners.borrow();
let iter = listeners.iter();
for handler in iter {
handler(&event);
@@ -2947,7 +3017,7 @@ fn handle_event_loop<T: UserEvent>(
fn on_close_requested<'a, T: UserEvent>(
callback: &'a mut (dyn FnMut(RunEvent<T>) + 'static),
window_id: WebviewId,
windows: Arc<RefCell<HashMap<WebviewId, WindowWrapper>>>,
windows: Rc<RefCell<HashMap<WebviewId, WindowWrapper>>>,
) {
let (tx, rx) = channel();
let windows_ref = windows.borrow();
@@ -2975,8 +3045,8 @@ fn on_close_requested<'a, T: UserEvent>(
}
}
fn on_window_close(window_id: WebviewId, windows: Arc<RefCell<HashMap<WebviewId, WindowWrapper>>>) {
if let Some(mut window_wrapper) = windows.borrow_mut().get_mut(&window_id) {
fn on_window_close(window_id: WebviewId, windows: Rc<RefCell<HashMap<WebviewId, WindowWrapper>>>) {
if let Some(window_wrapper) = windows.borrow_mut().get_mut(&window_id) {
window_wrapper.inner = None;
}
}
@@ -3044,7 +3114,7 @@ fn create_webview<T: UserEvent>(
mut window_builder,
ipc_handler,
label,
current_url,
url,
menu_ids,
js_event_listeners,
..
@@ -3084,6 +3154,7 @@ fn create_webview<T: UserEvent>(
} else {
None
};
let focused = window_builder.inner.window.focused;
let window = window_builder.inner.build(event_loop).unwrap();
webview_id_map.insert(window.id(), window_id);
@@ -3093,7 +3164,8 @@ fn create_webview<T: UserEvent>(
}
let mut webview_builder = WebViewBuilder::new(window)
.map_err(|e| Error::CreateWebview(Box::new(e)))?
.with_url(current_url.lock().unwrap().as_str())
.with_focused(focused)
.with_url(&url)
.unwrap() // safe to unwrap because we validate the URL beforehand
.with_transparent(is_window_transparent)
.with_accept_first_mouse(webview_attributes.accept_first_mouse);
@@ -3124,11 +3196,15 @@ fn create_webview<T: UserEvent>(
});
}
#[cfg(windows)]
{
webview_builder = webview_builder.with_https_scheme(!pending.http_scheme);
}
if let Some(handler) = ipc_handler {
webview_builder = webview_builder.with_ipc_handler(create_ipc_handler(
context,
label.clone(),
current_url,
menu_ids,
js_event_listeners,
handler,
@@ -3221,7 +3297,7 @@ fn create_webview<T: UserEvent>(
Ok(WindowWrapper {
label,
inner: Some(WindowHandle::Webview {
inner: Arc::new(webview),
inner: Rc::new(webview),
context_store: web_context_store.clone(),
context_key: if automation_enabled {
None
@@ -3239,16 +3315,14 @@ fn create_webview<T: UserEvent>(
fn create_ipc_handler<T: UserEvent>(
context: Context<T>,
label: String,
current_url: Arc<Mutex<Url>>,
menu_ids: Arc<Mutex<HashMap<MenuHash, MenuId>>>,
js_event_listeners: Arc<Mutex<HashMap<JsEventListenerKey, HashSet<u64>>>>,
js_event_listeners: Arc<Mutex<HashMap<JsEventListenerKey, HashSet<u32>>>>,
handler: WebviewIpcHandler<T, Wry<T>>,
) -> Box<IpcHandler> {
Box::new(move |window, request| {
let window_id = context.webview_id_map.get(&window.id()).unwrap();
handler(
DetachedWindow {
current_url: current_url.clone(),
dispatcher: WryDispatcher {
window_id,
context: context.clone(),

View File

@@ -32,8 +32,10 @@ use crate::{send_user_message, Context, Error, Message, Result, TrayId, TrayMess
use tauri_runtime::{menu::MenuHash, SystemTray, UserEvent};
use std::{
cell::RefCell,
collections::HashMap,
fmt,
rc::Rc,
sync::{Arc, Mutex},
};
@@ -41,12 +43,12 @@ pub type GlobalSystemTrayEventHandler = Box<dyn Fn(TrayId, &SystemTrayEvent) + S
pub type GlobalSystemTrayEventListeners = Arc<Mutex<Vec<Arc<GlobalSystemTrayEventHandler>>>>;
pub type SystemTrayEventHandler = Box<dyn Fn(&SystemTrayEvent) + Send>;
pub type SystemTrayEventListeners = Arc<Mutex<Vec<Arc<SystemTrayEventHandler>>>>;
pub type SystemTrayItems = Arc<Mutex<HashMap<u16, WryCustomMenuItem>>>;
pub type SystemTrayEventListeners = Rc<RefCell<Vec<Rc<SystemTrayEventHandler>>>>;
pub type SystemTrayItems = Rc<RefCell<HashMap<u16, WryCustomMenuItem>>>;
#[derive(Clone, Default)]
pub struct TrayContext {
pub tray: Arc<Mutex<Option<WrySystemTray>>>,
pub tray: Rc<RefCell<Option<WrySystemTray>>>,
pub listeners: SystemTrayEventListeners,
pub items: SystemTrayItems,
}

View File

@@ -1,5 +1,36 @@
# Changelog
## \[0.14.1]
### Enhancements
- [`9aa34ada`](https://www.github.com/tauri-apps/tauri/commit/9aa34ada5769dbefa7dfe5f7a6288b3d20b294e4)([#7645](https://www.github.com/tauri-apps/tauri/pull/7645)) Add setting to switch to `http://<scheme>.localhost/` for custom protocols on Windows.
### Dependencies
- Upgraded to `tauri-utils@1.5.0`
## \[0.14.0]
### New Features
- [`c4d6fb4b`](https://www.github.com/tauri-apps/tauri/commit/c4d6fb4b1ea8acf02707a9fe5dcab47c1c5bae7b)([#2353](https://www.github.com/tauri-apps/tauri/pull/2353)) Added the `maximizable`, `minimizable` and `closable` methods to `WindowBuilder`.
- [`c4d6fb4b`](https://www.github.com/tauri-apps/tauri/commit/c4d6fb4b1ea8acf02707a9fe5dcab47c1c5bae7b)([#2353](https://www.github.com/tauri-apps/tauri/pull/2353)) Added `set_maximizable`, `set_minimizable`, `set_closable`, `is_maximizable`, `is_minimizable` and `is_closable` methods to the `Dispatch` trait.
- [`000104bc`](https://www.github.com/tauri-apps/tauri/commit/000104bc3bc0c9ff3d20558ab9cf2080f126e9e0)([#6472](https://www.github.com/tauri-apps/tauri/pull/6472)) Add `Window::is_focused` getter.
### Enhancements
- [`d2710e9d`](https://www.github.com/tauri-apps/tauri/commit/d2710e9d2e8fd93975ef6494512370faa8cb3b7e)([#6944](https://www.github.com/tauri-apps/tauri/pull/6944)) Unpin `time`, `ignore`, and `winnow` crate versions. Developers now have to pin crates if needed themselves. A list of crates that need pinning to adhere to Tauri's MSRV will be visible in Tauri's GitHub workflow: https://github.com/tauri-apps/tauri/blob/dev/.github/workflows/test-core.yml#L85.
### Bug Fixes
- [`2b487c94`](https://www.github.com/tauri-apps/tauri/commit/2b487c946737352187d7e042dd6142873e62a4ca)([#7012](https://www.github.com/tauri-apps/tauri/pull/7012)) Fixes typo in `CursorIcon` deserialization of the `ZoomIn` variant.
### What's Changed
- [`076e1a81`](https://www.github.com/tauri-apps/tauri/commit/076e1a81a50468e3dfb34ae9ca7e77c5e1758daa)([#7119](https://www.github.com/tauri-apps/tauri/pull/7119)) Use `u32` instead of `u64` for js event listener ids
- [`ff5e4dbb`](https://www.github.com/tauri-apps/tauri/commit/ff5e4dbbb01bf3fc9c5143df732c75eef6fd98cb)([#6794](https://www.github.com/tauri-apps/tauri/pull/6794)) impl `From<&WindowConfig>` for `WebviewAttributes`.
## \[0.13.0]
- Added the `additional_browser_args` option when creating a window.

View File

@@ -1,6 +1,6 @@
[package]
name = "tauri-runtime"
version = "0.13.0"
version = "0.14.1"
authors = [ "Tauri Programme within The Commons Conservancy" ]
categories = [ "gui", "web-programming" ]
license = "Apache-2.0 OR MIT"
@@ -26,11 +26,11 @@ targets = [
serde = { version = "1.0", features = [ "derive" ] }
serde_json = "1.0"
thiserror = "1.0"
tauri-utils = { version = "1.3.0", path = "../tauri-utils" }
tauri-utils = { version = "1.5.0", path = "../tauri-utils" }
uuid = { version = "1", features = [ "v4" ] }
http = "0.2.4"
http-range = "0.1.4"
raw-window-handle = "=0.5.0"
raw-window-handle = "0.5"
rand = "0.8"
url = { version = "2" }

View File

@@ -6,7 +6,7 @@
[![Chat Server](https://img.shields.io/badge/chat-on%20discord-7289da.svg)](https://discord.gg/SpmNs4S)
[![devto](https://img.shields.io/badge/blog-dev.to-black.svg)](https://dev.to/tauri)
![](https://img.shields.io/github/workflow/status/tauri-apps/tauri/test%20library?label=test%20library)
[![test core](https://img.shields.io/github/actions/workflow/status/tauri-apps/tauri/test-core.yml?label=test%20core&logo=github)](https://github.com/tauri-apps/tauri/actions/workflows/test-core.yml)
[![devto](https://img.shields.io/badge/documentation-site-purple.svg)](https://tauri.app)
[![https://good-labs.github.io/greater-good-affirmation/assets/images/badge.svg](https://good-labs.github.io/greater-good-affirmation/assets/images/badge.svg)](https://good-labs.github.io/greater-good-affirmation)

View File

@@ -576,12 +576,36 @@ pub trait Dispatch<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'static
/// Gets the window's current maximized state.
fn is_maximized(&self) -> Result<bool>;
/// Gets the window's current focus state.
fn is_focused(&self) -> Result<bool>;
/// Gets the windows current decoration state.
fn is_decorated(&self) -> Result<bool>;
/// Gets the windows current resizable state.
fn is_resizable(&self) -> Result<bool>;
/// Gets the window's native maximize button state.
///
/// ## Platform-specific
///
/// - **Linux / iOS / Android:** Unsupported.
fn is_maximizable(&self) -> Result<bool>;
/// Gets the window's native minize button state.
///
/// ## Platform-specific
///
/// - **Linux / iOS / Android:** Unsupported.
fn is_minimizable(&self) -> Result<bool>;
/// Gets the window's native close button state.
///
/// ## Platform-specific
///
/// - **iOS / Android:** Unsupported.
fn is_closable(&self) -> Result<bool>;
/// Gets the window's current visibility state.
fn is_visible(&self) -> Result<bool>;
/// Gets the window's current title.
@@ -640,6 +664,30 @@ pub trait Dispatch<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'static
/// Updates the window resizable flag.
fn set_resizable(&self, resizable: bool) -> Result<()>;
/// Updates the window's native maximize button state.
///
/// ## Platform-specific
///
/// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
/// - **Linux / iOS / Android:** Unsupported.
fn set_maximizable(&self, maximizable: bool) -> Result<()>;
/// Updates the window's native minimize button state.
///
/// ## Platform-specific
///
/// - **Linux / iOS / Android:** Unsupported.
fn set_minimizable(&self, minimizable: bool) -> Result<()>;
/// Updates the window's native close button state.
///
/// ## Platform-specific
///
/// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
/// Depending on the system, this function may not have any effect when called on a window that is already visible"
/// - **iOS / Android:** Unsupported.
fn set_closable(&self, closable: bool) -> Result<()>;
/// Updates the window title.
fn set_title<S: Into<String>>(&self, title: S) -> Result<()>;

View File

@@ -31,6 +31,23 @@ pub struct WebviewAttributes {
pub additional_browser_args: Option<String>,
}
impl From<&WindowConfig> for WebviewAttributes {
fn from(config: &WindowConfig) -> Self {
let mut builder = Self::new(config.url.clone());
builder = builder.accept_first_mouse(config.accept_first_mouse);
if !config.file_drop_enabled {
builder = builder.disable_file_drop_handler();
}
if let Some(user_agent) = &config.user_agent {
builder = builder.user_agent(user_agent);
}
if let Some(additional_browser_args) = &config.additional_browser_args {
builder = builder.additional_browser_args(additional_browser_args);
}
builder
}
}
impl WebviewAttributes {
/// Initializes the default attributes for a webview.
pub fn new(url: WindowUrl) -> Self {
@@ -140,9 +157,38 @@ pub trait WindowBuilder: WindowBuilderBase {
fn max_inner_size(self, max_width: f64, max_height: f64) -> Self;
/// Whether the window is resizable or not.
/// When resizable is set to false, native window's maximize button is automatically disabled.
#[must_use]
fn resizable(self, resizable: bool) -> Self;
/// Whether the window's native maximize button is enabled or not.
/// If resizable is set to false, this setting is ignored.
///
/// ## Platform-specific
///
/// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
/// - **Linux / iOS / Android:** Unsupported.
#[must_use]
fn maximizable(self, maximizable: bool) -> Self;
/// Whether the window's native minimize button is enabled or not.
///
/// ## Platform-specific
///
/// - **Linux / iOS / Android:** Unsupported.
#[must_use]
fn minimizable(self, minimizable: bool) -> Self;
/// Whether the window's native close button is enabled or not.
///
/// ## Platform-specific
///
/// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
/// Depending on the system, this function may not have any effect when called on a window that is already visible"
/// - **iOS / Android:** Unsupported.
#[must_use]
fn closable(self, closable: bool) -> Self;
/// The title of the window in the title bar.
#[must_use]
fn title<S: Into<String>>(self, title: S) -> Self;

View File

@@ -24,6 +24,8 @@ use std::{
type UriSchemeProtocol =
dyn Fn(&HttpRequest) -> Result<HttpResponse, Box<dyn std::error::Error>> + Send + Sync + 'static;
type WebResourceRequestHandler = dyn Fn(&HttpRequest, &mut HttpResponse) + Send + Sync;
/// UI scaling utilities.
pub mod dpi;
@@ -182,7 +184,7 @@ impl<'de> Deserialize<'de> for CursorIcon {
"grab" => CursorIcon::Grab,
"grabbing" => CursorIcon::Grabbing,
"allscroll" => CursorIcon::AllScroll,
"zoomun" => CursorIcon::ZoomIn,
"zoomin" => CursorIcon::ZoomIn,
"zoomout" => CursorIcon::ZoomOut,
"eresize" => CursorIcon::EResize,
"nresize" => CursorIcon::NResize,
@@ -222,6 +224,9 @@ pub struct PendingWindow<T: UserEvent, R: Runtime<T>> {
pub uri_scheme_protocols: HashMap<String, Box<UriSchemeProtocol>>,
// Whether custom protocols on windows should use http://<scheme>.localhost/ instead of https://<scheme>.localhost/
pub http_scheme: bool,
/// How to handle IPC calls on the webview window.
pub ipc_handler: Option<WebviewIpcHandler<T, R>>,
@@ -229,13 +234,15 @@ pub struct PendingWindow<T: UserEvent, R: Runtime<T>> {
pub menu_ids: Arc<Mutex<HashMap<MenuHash, MenuId>>>,
/// A HashMap mapping JS event names with associated listener ids.
pub js_event_listeners: Arc<Mutex<HashMap<JsEventListenerKey, HashSet<u64>>>>,
pub js_event_listeners: Arc<Mutex<HashMap<JsEventListenerKey, HashSet<u32>>>>,
/// A handler to decide if incoming url is allowed to navigate.
pub navigation_handler: Option<Box<dyn Fn(Url) -> bool + Send>>,
/// The current webview URL.
pub current_url: Arc<Mutex<Url>>,
pub web_resource_request_handler: Option<Box<WebResourceRequestHandler>>,
/// The resolved URL to load on the webview.
pub url: String,
}
pub fn is_label_valid(label: &str) -> bool {
@@ -275,7 +282,9 @@ impl<T: UserEvent, R: Runtime<T>> PendingWindow<T, R> {
menu_ids: Arc::new(Mutex::new(menu_ids)),
js_event_listeners: Default::default(),
navigation_handler: Default::default(),
current_url: Arc::new(Mutex::new("tauri://localhost".parse().unwrap())),
web_resource_request_handler: Default::default(),
url: "tauri://localhost".to_string(),
http_scheme: false,
})
}
}
@@ -305,7 +314,9 @@ impl<T: UserEvent, R: Runtime<T>> PendingWindow<T, R> {
menu_ids: Arc::new(Mutex::new(menu_ids)),
js_event_listeners: Default::default(),
navigation_handler: Default::default(),
current_url: Arc::new(Mutex::new("tauri://localhost".parse().unwrap())),
web_resource_request_handler: Default::default(),
url: "tauri://localhost".to_string(),
http_scheme: false,
})
}
}
@@ -346,9 +357,6 @@ pub struct JsEventListenerKey {
/// A webview window that is not yet managed by Tauri.
#[derive(Debug)]
pub struct DetachedWindow<T: UserEvent, R: Runtime<T>> {
/// The current webview URL.
pub current_url: Arc<Mutex<Url>>,
/// Name of the window
pub label: String,
@@ -359,13 +367,12 @@ pub struct DetachedWindow<T: UserEvent, R: Runtime<T>> {
pub menu_ids: Arc<Mutex<HashMap<MenuHash, MenuId>>>,
/// A HashMap mapping JS event names with associated listener ids.
pub js_event_listeners: Arc<Mutex<HashMap<JsEventListenerKey, HashSet<u64>>>>,
pub js_event_listeners: Arc<Mutex<HashMap<JsEventListenerKey, HashSet<u32>>>>,
}
impl<T: UserEvent, R: Runtime<T>> Clone for DetachedWindow<T, R> {
fn clone(&self) -> Self {
Self {
current_url: self.current_url.clone(),
label: self.label.clone(),
dispatcher: self.dispatcher.clone(),
menu_ids: self.menu_ids.clone(),

View File

@@ -1,5 +1,36 @@
# Changelog
## \[1.5.0]
### New Features
- [`4dd4893d`](https://www.github.com/tauri-apps/tauri/commit/4dd4893d7d166ac3a3b6dc2e3bd2540326352a78)([#5950](https://www.github.com/tauri-apps/tauri/pull/5950)) Allow specifying resources as a map specifying source and target paths.
### Enhancements
- [`9aa34ada`](https://www.github.com/tauri-apps/tauri/commit/9aa34ada5769dbefa7dfe5f7a6288b3d20b294e4)([#7645](https://www.github.com/tauri-apps/tauri/pull/7645)) Add setting to switch to `http://<scheme>.localhost/` for custom protocols on Windows.
### Bug Fixes
- [`a6b52e44`](https://www.github.com/tauri-apps/tauri/commit/a6b52e44f22844009e273fb0250368d7a463f095)([#6519](https://www.github.com/tauri-apps/tauri/pull/6519)) Fix `io::read_line` not including the new line character `\n`.
### Security fixes
- [`eeff1784`](https://www.github.com/tauri-apps/tauri/commit/eeff1784e1ffa568e4ba024e17dd611f8e086784)([#7367](https://www.github.com/tauri-apps/tauri/pull/7367)) Changed HTML implementation from unmaintained `kuchiki` to `kuchikiki`.
## \[1.4.0]
### New Features
- [`acc36fe1`](https://www.github.com/tauri-apps/tauri/commit/acc36fe1176cc8aa9063bde932abeb94796c5c72)([#6158](https://www.github.com/tauri-apps/tauri/pull/6158)) Add option to configure `require_literal_leading_dot` on `fs` and `asset` protcol scopes.
- [`35cd751a`](https://www.github.com/tauri-apps/tauri/commit/35cd751adc6fef1f792696fa0cfb471b0bf99374)([#5176](https://www.github.com/tauri-apps/tauri/pull/5176)) Added the `desktop_template` option on `tauri.conf.json > tauri > bundle > deb`.
- [`c4d6fb4b`](https://www.github.com/tauri-apps/tauri/commit/c4d6fb4b1ea8acf02707a9fe5dcab47c1c5bae7b)([#2353](https://www.github.com/tauri-apps/tauri/pull/2353)) Added the `maximizable`, `minimizable` and `closable` options to the window configuration.
- [`3cb7a3e6`](https://www.github.com/tauri-apps/tauri/commit/3cb7a3e642bb10ee90dc1d24daa48b8c8c15c9ce)([#6997](https://www.github.com/tauri-apps/tauri/pull/6997)) Add `MimeType::parse_with_fallback` and `MimeType::parse_from_uri_with_fallback`
- [`29488205`](https://www.github.com/tauri-apps/tauri/commit/2948820579d20dfaa0861c2f0a58bd7737a7ffd1)([#6867](https://www.github.com/tauri-apps/tauri/pull/6867)) Allow specifying custom language files of Tauri's custom messages for the NSIS installer
- [`e092f799`](https://www.github.com/tauri-apps/tauri/commit/e092f799469ff32c7d1595d0f07d06fd2dab5c29)([#6887](https://www.github.com/tauri-apps/tauri/pull/6887)) Add `nsis > template` option to specify custom NSIS installer template.
- [`cd3846c8`](https://www.github.com/tauri-apps/tauri/commit/cd3846c8ce61ab2879b3911e831525e6242aaab2)([#6955](https://www.github.com/tauri-apps/tauri/pull/6955)) Add `WindowsUpdateInstallMode::nsis_args`
- [`85e77fb7`](https://www.github.com/tauri-apps/tauri/commit/85e77fb797ec17882f55d0944578d929fc6c9c1f)([#6762](https://www.github.com/tauri-apps/tauri/pull/6762)) Correctly determine MIME type of `.txt` files.
## \[1.3.0]
- Added the `additional_browser_args` option to the window configuration.

View File

@@ -1,6 +1,6 @@
[package]
name = "tauri-utils"
version = "1.3.0"
version = "1.5.0"
authors = [ "Tauri Programme within The Commons Conservancy" ]
license = "Apache-2.0 OR MIT"
homepage = "https://tauri.app"
@@ -18,12 +18,12 @@ thiserror = "1"
phf = { version = "0.10", features = [ "macros" ] }
brotli = { version = "3", optional = true, default-features = false, features = [ "std" ] }
url = { version = "2", features = [ "serde" ] }
kuchiki = "0.8"
html5ever = "0.25"
html5ever = "0.26"
kuchiki = { package = "kuchikiki", version = "0.8" }
proc-macro2 = { version = "1", optional = true }
quote = { version = "1", optional = true }
schemars = { version = "0.8", features = [ "url" ], optional = true }
serde_with = "2"
serde_with = "3"
aes-gcm = { version = "0.10", optional = true }
getrandom = { version = "0.2", optional = true, features = [ "std" ] }
serialize-to-javascript = { version = "=0.1.1", optional = true }
@@ -36,6 +36,8 @@ walkdir = { version = "2", optional = true }
memchr = "2"
semver = "1"
infer = "0.12"
dunce = "1"
log = "0.4.20"
[target."cfg(target_os = \"linux\")".dependencies]
heck = "0.4"

View File

@@ -4,7 +4,7 @@
[![status](https://img.shields.io/badge/status-stable-blue.svg)](https://github.com/tauri-apps/tauri/tree/dev)
[![License](https://img.shields.io/badge/License-MIT%20or%20Apache%202-green.svg)](https://opencollective.com/tauri)
[![test library](https://img.shields.io/github/workflow/status/tauri-apps/tauri/test%20library?label=test%20library)](https://github.com/tauri-apps/tauri/actions?query=workflow%3A%22test+library%22)
[![test core](https://img.shields.io/github/actions/workflow/status/tauri-apps/tauri/test-core.yml?label=test%20core&logo=github)](https://github.com/tauri-apps/tauri/actions/workflows/test-core.yml)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Ftauri-apps%2Ftauri.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Ftauri-apps%2Ftauri?ref=badge_shield)
[![Chat Server](https://img.shields.io/badge/chat-discord-7289da.svg)](https://discord.gg/SpmNs4S)
[![website](https://img.shields.io/badge/website-tauri.app-purple.svg)](https://tauri.app)

View File

@@ -38,6 +38,10 @@ use crate::TitleBarStyle;
pub use self::parse::parse;
fn default_true() -> bool {
true
}
/// An URL to open on a Tauri webview window.
#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
@@ -272,6 +276,10 @@ pub struct DebConfig {
/// The files to include on the package.
#[serde(default)]
pub files: HashMap<PathBuf, PathBuf>,
/// Path to a custom desktop file Handlebars template.
///
/// Available variables: `categories`, `comment` (optional), `exec`, `icon` and `name`.
pub desktop_template: Option<PathBuf>,
}
fn de_minimum_system_version<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
@@ -430,11 +438,28 @@ pub struct WixConfig {
pub dialog_image_path: Option<PathBuf>,
}
/// Compression algorithms used in the NSIS installer.
///
/// See <https://nsis.sourceforge.io/Reference/SetCompressor>
#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub enum NsisCompression {
/// ZLIB uses the deflate algorithm, it is a quick and simple method. With the default compression level it uses about 300 KB of memory.
Zlib,
/// BZIP2 usually gives better compression ratios than ZLIB, but it is a bit slower and uses more memory. With the default compression level it uses about 4 MB of memory.
Bzip2,
/// LZMA (default) is a new compression method that gives very good compression ratios. The decompression speed is high (10-20 MB/s on a 2 GHz CPU), the compression speed is lower. The memory size that will be used for decompression is the dictionary size plus a few KBs, the default is 8 MB.
Lzma,
}
/// Configuration for the Installer bundle using NSIS.
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct NsisConfig {
/// A custom .nsi template to use.
pub template: Option<PathBuf>,
/// The path to the license file to render on the installer.
pub license: Option<PathBuf>,
/// The path to a bitmap file to display on the header of installers pages.
@@ -459,10 +484,21 @@ pub struct NsisConfig {
///
/// See <https://github.com/kichik/nsis/tree/9465c08046f00ccb6eda985abbdbf52c275c6c4d/Contrib/Language%20files> for the complete list of languages.
pub languages: Option<Vec<String>>,
/// A key-value pair where the key is the language and the
/// value is the path to a custom `.nsh` file that holds the translated text for tauri's custom messages.
///
/// See <https://github.com/tauri-apps/tauri/blob/dev/tooling/bundler/src/bundle/windows/templates/nsis-languages/English.nsh> for an example `.nsh` file.
///
/// **Note**: the key must be a valid NSIS language and it must be added to [`NsisConfig`] languages array,
pub custom_language_files: Option<HashMap<String, PathBuf>>,
/// Whether to display a language selector dialog before the installer and uninstaller windows are rendered or not.
/// By default the OS language is selected, with a fallback to the first language in the `languages` array.
#[serde(default, alias = "display-language-selector")]
pub display_language_selector: bool,
/// Set the compression algorithm used to compress files in the installer.
///
/// See <https://nsis.sourceforge.io/Reference/SetCompressor>
pub compression: Option<NsisCompression>,
}
/// Install Modes for the NSIS installer.
@@ -510,7 +546,7 @@ pub enum WebviewInstallMode {
/// Results in a smaller installer size, but is not recommended on Windows 7.
DownloadBootstrapper {
/// Instructs the installer to run the bootstrapper in silent mode. Defaults to `true`.
#[serde(default = "default_webview_install_silent")]
#[serde(default = "default_true")]
silent: bool,
},
/// Embed the bootstrapper and run it.
@@ -518,7 +554,7 @@ pub enum WebviewInstallMode {
/// Increases the installer size by around 1.8MB, but offers better support on Windows 7.
EmbedBootstrapper {
/// Instructs the installer to run the bootstrapper in silent mode. Defaults to `true`.
#[serde(default = "default_webview_install_silent")]
#[serde(default = "default_true")]
silent: bool,
},
/// Embed the offline installer and run it.
@@ -526,7 +562,7 @@ pub enum WebviewInstallMode {
/// Increases the installer size by around 127MB.
OfflineInstaller {
/// Instructs the installer to run the installer in silent mode. Defaults to `true`.
#[serde(default = "default_webview_install_silent")]
#[serde(default = "default_true")]
silent: bool,
},
/// Embed a fixed webview2 version and use it at runtime.
@@ -540,15 +576,9 @@ pub enum WebviewInstallMode {
},
}
fn default_webview_install_silent() -> bool {
true
}
impl Default for WebviewInstallMode {
fn default() -> Self {
Self::DownloadBootstrapper {
silent: default_webview_install_silent(),
}
Self::DownloadBootstrapper { silent: true }
}
}
@@ -589,7 +619,7 @@ pub struct WindowsConfig {
/// For instance, if `1.2.1` is installed, the user won't be able to install app version `1.2.0` or `1.1.5`.
///
/// The default value of this flag is `true`.
#[serde(default = "default_allow_downgrades", alias = "allow-downgrades")]
#[serde(default = "default_true", alias = "allow-downgrades")]
pub allow_downgrades: bool,
/// Configuration for the MSI generated with WiX.
pub wix: Option<WixConfig>,
@@ -606,15 +636,36 @@ impl Default for WindowsConfig {
tsp: false,
webview_install_mode: Default::default(),
webview_fixed_runtime_path: None,
allow_downgrades: default_allow_downgrades(),
allow_downgrades: true,
wix: None,
nsis: None,
}
}
}
fn default_allow_downgrades() -> bool {
true
/// Definition for bundle resources.
/// Can be either a list of paths to include or a map of source to target paths.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
pub enum BundleResources {
/// A list of paths to include.
List(Vec<String>),
/// A map of source to target paths.
Map(HashMap<String, String>),
}
impl BundleResources {
/// Adds a path to the resource collection.
pub fn push(&mut self, path: impl Into<String>) {
match self {
Self::List(l) => l.push(path.into()),
Self::Map(l) => {
let path = path.into();
l.insert(path.clone(), path);
}
}
}
}
/// Configuration for tauri-bundler.
@@ -646,7 +697,7 @@ pub struct BundleConfig {
/// App resources to bundle.
/// Each resource is a path to a file or directory.
/// Glob patterns are supported.
pub resources: Option<Vec<String>>,
pub resources: Option<BundleResources>,
/// A copyright string associated with your application.
pub copyright: Option<String>,
/// The application kind.
@@ -892,7 +943,7 @@ pub struct WindowConfig {
/// Whether the file drop is enabled or not on the webview. By default it is enabled.
///
/// Disabling it is required to use drag and drop on the frontend on Windows.
#[serde(default = "default_file_drop_enabled", alias = "file-drop-enabled")]
#[serde(default = "default_true", alias = "file-drop-enabled")]
pub file_drop_enabled: bool,
/// Whether or not the window starts centered or not.
#[serde(default)]
@@ -919,9 +970,34 @@ pub struct WindowConfig {
/// The max window height.
#[serde(alias = "max-height")]
pub max_height: Option<f64>,
/// Whether the window is resizable or not.
#[serde(default = "default_resizable")]
/// Whether the window is resizable or not. When resizable is set to false, native window's maximize button is automatically disabled.
#[serde(default = "default_true")]
pub resizable: bool,
/// Whether the window's native maximize button is enabled or not.
/// If resizable is set to false, this setting is ignored.
///
/// ## Platform-specific
///
/// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
/// - **Linux / iOS / Android:** Unsupported.
#[serde(default = "default_true")]
pub maximizable: bool,
/// Whether the window's native minimize button is enabled or not.
///
/// ## Platform-specific
///
/// - **Linux / iOS / Android:** Unsupported.
#[serde(default = "default_true")]
pub minimizable: bool,
/// Whether the window's native close button is enabled or not.
///
/// ## Platform-specific
///
/// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
/// Depending on the system, this function may not have any effect when called on a window that is already visible"
/// - **iOS / Android:** Unsupported.
#[serde(default = "default_true")]
pub closable: bool,
/// The window title.
#[serde(default = "default_title")]
pub title: String,
@@ -929,7 +1005,7 @@ pub struct WindowConfig {
#[serde(default)]
pub fullscreen: bool,
/// Whether the window will be initially focused or not.
#[serde(default = "default_focus")]
#[serde(default = "default_true")]
pub focus: bool,
/// Whether the window is transparent or not.
///
@@ -941,10 +1017,10 @@ pub struct WindowConfig {
#[serde(default)]
pub maximized: bool,
/// Whether the window is visible or not.
#[serde(default = "default_visible")]
#[serde(default = "default_true")]
pub visible: bool,
/// Whether the window should have borders and bars.
#[serde(default = "default_decorations")]
#[serde(default = "default_true")]
pub decorations: bool,
/// Whether the window should always be on top of other windows.
#[serde(default, alias = "always-on-top")]
@@ -986,7 +1062,7 @@ impl Default for WindowConfig {
label: default_window_label(),
url: WindowUrl::default(),
user_agent: None,
file_drop_enabled: default_file_drop_enabled(),
file_drop_enabled: true,
center: false,
x: None,
y: None,
@@ -996,14 +1072,17 @@ impl Default for WindowConfig {
min_height: None,
max_width: None,
max_height: None,
resizable: default_resizable(),
resizable: true,
maximizable: true,
minimizable: true,
closable: true,
title: default_title(),
fullscreen: false,
focus: false,
transparent: false,
maximized: false,
visible: default_visible(),
decorations: default_decorations(),
visible: true,
decorations: true,
always_on_top: false,
content_protected: false,
skip_taskbar: false,
@@ -1029,30 +1108,10 @@ fn default_height() -> f64 {
600f64
}
fn default_resizable() -> bool {
true
}
fn default_title() -> String {
"Tauri App".to_string()
}
fn default_focus() -> bool {
true
}
fn default_visible() -> bool {
true
}
fn default_decorations() -> bool {
true
}
fn default_file_drop_enabled() -> bool {
true
}
/// A Content-Security-Policy directive source list.
/// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources#sources>.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
@@ -1208,6 +1267,7 @@ pub struct RemoteDomainAccessScope {
/// The list of window labels this scope applies to.
pub windows: Vec<String>,
/// The list of plugins that are allowed in this scope.
/// The names should be without the `tauri-plugin-` prefix, for example `"store"` for `tauri-plugin-store`.
#[serde(default)]
pub plugins: Vec<String>,
/// Enables access to the Tauri API.
@@ -1266,6 +1326,11 @@ pub struct SecurityConfig {
/// vulnerable to dangerous Tauri command related attacks otherwise.
#[serde(default, alias = "dangerous-remote-domain-ipc-access")]
pub dangerous_remote_domain_ipc_access: Vec<RemoteDomainAccessScope>,
/// Sets whether the custom protocols should use `http://<scheme>.localhost` instead of the default `https://<scheme>.localhost` on Windows.
///
/// **WARNING:** Using a `http` scheme will allow mixed content when trying to fetch `http` endpoints and is therefore less secure but will match the behavior of the `<scheme>://localhost` protocols used on macOS and Linux.
#[serde(default, alias = "dangerous-use-http-scheme")]
pub dangerous_use_http_scheme: bool,
}
/// Defines an allowlist type.
@@ -1293,12 +1358,13 @@ macro_rules! check_feature {
/// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`,
/// `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(untagged)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub enum FsAllowlistScope {
/// A list of paths that are allowed by this scope.
AllowedPaths(Vec<PathBuf>),
/// A complete scope configuration.
#[serde(rename_all = "camelCase")]
Scope {
/// A list of paths that are allowed by this scope.
#[serde(default)]
@@ -1307,6 +1373,16 @@ pub enum FsAllowlistScope {
/// This gets precedence over the [`Self::Scope::allow`] list.
#[serde(default)]
deny: Vec<PathBuf>,
/// Whether or not paths that contain components that start with a `.`
/// will require that `.` appears literally in the pattern; `*`, `?`, `**`,
/// or `[...]` will not match. This is useful because such files are
/// conventionally considered hidden on Unix systems and it might be
/// desirable to skip them when listing files.
///
/// Defaults to `true` on Unix systems and `false` on Windows
// dotfiles are not supposed to be exposed by default on unix
#[serde(alias = "require-literal-leading-dot")]
require_literal_leading_dot: Option<bool>,
},
}
@@ -1437,6 +1513,15 @@ pub struct WindowAllowlistConfig {
/// Allows setting the resizable flag of the window.
#[serde(default, alias = "set-resizable")]
pub set_resizable: bool,
/// Allows setting whether the window's native maximize button is enabled or not.
#[serde(default, alias = "set-maximizable")]
pub set_maximizable: bool,
/// Allows setting whether the window's native minimize button is enabled or not.
#[serde(default, alias = "set-minimizable")]
pub set_minimizable: bool,
/// Allows setting whether the window's native close button is enabled or not.
#[serde(default, alias = "set-closable")]
pub set_closable: bool,
/// Allows changing the window title.
#[serde(default, alias = "set-title")]
pub set_title: bool,
@@ -1525,6 +1610,9 @@ impl Allowlist for WindowAllowlistConfig {
center: true,
request_user_attention: true,
set_resizable: true,
set_maximizable: true,
set_minimizable: true,
set_closable: true,
set_title: true,
maximize: true,
unmaximize: true,
@@ -1571,6 +1659,9 @@ impl Allowlist for WindowAllowlistConfig {
"window-request-user-attention"
);
check_feature!(self, features, set_resizable, "window-set-resizable");
check_feature!(self, features, set_maximizable, "window-set-maximizable");
check_feature!(self, features, set_minimizable, "window-set-minimizable");
check_feature!(self, features, set_closable, "window-set-closable");
check_feature!(self, features, set_title, "window-set-title");
check_feature!(self, features, maximize, "window-maximize");
check_feature!(self, features, unmaximize, "window-unmaximize");
@@ -1883,11 +1974,13 @@ impl Allowlist for DialogAllowlistConfig {
/// The scoped URL is matched against the request URL using a glob pattern.
///
/// Examples:
/// - "https://**": allows all HTTPS urls
/// - "https://*": allows all HTTPS urls
/// - "https://*.github.com/tauri-apps/tauri": allows any subdomain of "github.com" with the "tauri-apps/api" path
/// - "https://myapi.service.com/users/*": allows access to any URLs that begins with "https://myapi.service.com/users/"
#[allow(rustdoc::bare_urls)]
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
// TODO: in v2, parse into a String or a custom type that perserves the
// glob string because Url type will add a trailing slash
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct HttpAllowlistScope(pub Vec<Url>);
@@ -2391,7 +2484,6 @@ pub struct TauriConfig {
impl TauriConfig {
/// Returns all Cargo features.
#[allow(dead_code)]
pub fn all_features() -> Vec<&'static str> {
let mut features = AllowlistConfig::all_features();
features.extend(vec![
@@ -2405,7 +2497,6 @@ impl TauriConfig {
}
/// Returns the enabled Cargo features.
#[allow(dead_code)]
pub fn features(&self) -> Vec<&str> {
let mut features = self.allowlist.to_features();
if self.cli.is_some() {
@@ -2468,7 +2559,7 @@ pub enum WindowsUpdateInstallMode {
/// Specifies there's a basic UI during the installation process, including a final dialog box at the end.
BasicUi,
/// The quiet mode means there's no user interaction required.
/// Requires admin privileges if the installer does (WiX).
/// Requires admin privileges if the installer does.
Quiet,
/// Specifies unattended mode, which means the installation only shows a progress bar.
Passive,
@@ -2485,6 +2576,15 @@ impl WindowsUpdateInstallMode {
Self::Passive => &["/passive"],
}
}
/// Returns the associated nsis arguments.
pub fn nsis_args(&self) -> &'static [&'static str] {
match self {
Self::Passive => &["/P", "/R"],
Self::Quiet => &["/S", "/R"],
_ => &[],
}
}
}
impl Display for WindowsUpdateInstallMode {
@@ -2561,7 +2661,7 @@ pub struct UpdaterConfig {
#[serde(default)]
pub active: bool,
/// Display built-in dialog or use event system if disabled.
#[serde(default = "default_dialog")]
#[serde(default = "default_true")]
pub dialog: bool,
/// The updater endpoints. TLS is enforced on production.
///
@@ -2592,7 +2692,7 @@ impl<'de> Deserialize<'de> for UpdaterConfig {
struct InnerUpdaterConfig {
#[serde(default)]
active: bool,
#[serde(default = "default_dialog")]
#[serde(default = "default_true")]
dialog: bool,
endpoints: Option<Vec<UpdaterEndpoint>>,
pubkey: Option<String>,
@@ -2622,7 +2722,7 @@ impl Default for UpdaterConfig {
fn default() -> Self {
Self {
active: false,
dialog: default_dialog(),
dialog: true,
endpoints: None,
pubkey: "".into(),
windows: Default::default(),
@@ -2645,26 +2745,12 @@ pub struct SystemTrayConfig {
#[serde(default, alias = "icon-as-template")]
pub icon_as_template: bool,
/// A Boolean value that determines whether the menu should appear when the tray icon receives a left click on macOS.
#[serde(
default = "default_tray_menu_on_left_click",
alias = "menu-on-left-click"
)]
#[serde(default = "default_true", alias = "menu-on-left-click")]
pub menu_on_left_click: bool,
/// Title for MacOS tray
pub title: Option<String>,
}
fn default_tray_menu_on_left_click() -> bool {
true
}
// We enable the unnecessary_wraps because we need
// to use an Option for dialog otherwise the CLI schema will mark
// the dialog as a required field which is not as we default it to true.
fn default_dialog() -> bool {
true
}
/// Defines the URL or assets to embed in the application.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
@@ -2867,7 +2953,7 @@ pub struct PackageConfig {
#[serde(alias = "product-name")]
#[cfg_attr(feature = "schema", validate(regex(pattern = "^[^/\\:*?\"<>|]+$")))]
pub product_name: Option<String>,
/// App version. It is a semver version number or a path to a `package.json` file containing the `version` field.
/// App version. It is a semver version number or a path to a `package.json` file containing the `version` field. If removed the version number from `Cargo.toml` is used.
#[serde(deserialize_with = "version_deserializer", default)]
pub version: Option<String>,
}
@@ -3227,6 +3313,9 @@ mod build {
let max_width = opt_lit(self.max_width.as_ref());
let max_height = opt_lit(self.max_height.as_ref());
let resizable = self.resizable;
let maximizable = self.maximizable;
let minimizable = self.minimizable;
let closable = self.closable;
let title = str_lit(&self.title);
let fullscreen = self.fullscreen;
let focus = self.focus;
@@ -3261,6 +3350,9 @@ mod build {
max_width,
max_height,
resizable,
maximizable,
minimizable,
closable,
title,
fullscreen,
focus,
@@ -3649,6 +3741,7 @@ mod build {
let dev_csp = opt_lit(self.dev_csp.as_ref());
let freeze_prototype = self.freeze_prototype;
let dangerous_disable_asset_csp_modification = &self.dangerous_disable_asset_csp_modification;
let dangerous_use_http_scheme = &self.dangerous_use_http_scheme;
let dangerous_remote_domain_ipc_access =
vec_lit(&self.dangerous_remote_domain_ipc_access, identity);
@@ -3659,7 +3752,8 @@ mod build {
dev_csp,
freeze_prototype,
dangerous_disable_asset_csp_modification,
dangerous_remote_domain_ipc_access
dangerous_remote_domain_ipc_access,
dangerous_use_http_scheme
);
}
}
@@ -3690,10 +3784,11 @@ mod build {
let allowed_paths = vec_lit(allow, path_buf_lit);
quote! { #prefix::AllowedPaths(#allowed_paths) }
}
Self::Scope { allow, deny } => {
Self::Scope { allow, deny , require_literal_leading_dot} => {
let allow = vec_lit(allow, path_buf_lit);
let deny = vec_lit(deny, path_buf_lit);
quote! { #prefix::Scope { allow: #allow, deny: #deny } }
let require_literal_leading_dot = opt_lit(require_literal_leading_dot.as_ref());
quote! { #prefix::Scope { allow: #allow, deny: #deny, require_literal_leading_dot: #require_literal_leading_dot } }
}
});
}
@@ -3925,6 +4020,7 @@ mod test {
freeze_prototype: false,
dangerous_disable_asset_csp_modification: DisabledCspModificationKind::Flag(false),
dangerous_remote_domain_ipc_access: Vec::new(),
dangerous_use_http_scheme: false,
},
allowlist: AllowlistConfig::default(),
system_tray: None,

View File

@@ -302,7 +302,7 @@ mod tests {
assert_eq!(
document.to_string(),
format!(
r#"<html><head><meta content="{}" http-equiv="Content-Security-Policy"></head><body></body></html>"#,
r#"<html><head><meta http-equiv="Content-Security-Policy" content="{}"></head><body></body></html>"#,
super::CSP_TOKEN
)
);

View File

@@ -6,7 +6,7 @@
use std::io::BufRead;
/// Read a line breaking in both \n and \r.
/// Read all bytes until a newline (the `0xA` byte) or a carriage return (`\r`) is reached, and append them to the provided buffer.
///
/// Adapted from <https://doc.rust-lang.org/std/io/trait.BufRead.html#method.read_line>.
pub fn read_line<R: BufRead + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> std::io::Result<usize> {
@@ -16,6 +16,7 @@ pub fn read_line<R: BufRead + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> std::io::
let available = match r.fill_buf() {
Ok(n) => n,
Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(e) => return Err(e),
};
match memchr::memchr(b'\n', available) {
@@ -40,9 +41,6 @@ pub fn read_line<R: BufRead + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> std::io::
r.consume(used);
read += used;
if done || used == 0 {
if buf.ends_with(&[b'\n']) {
buf.pop();
}
return Ok(read);
}
}

View File

@@ -13,6 +13,8 @@ use std::{
use semver::Version;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use log::warn;
pub mod assets;
pub mod config;
pub mod html;
@@ -202,7 +204,7 @@ impl Default for Env {
.unwrap_or(true);
if !is_temp {
panic!("`APPDIR` or `APPIMAGE` environment variable found but this application was not detected as an AppImage; this might be a security issue.");
warn!("`APPDIR` or `APPIMAGE` environment variable found but this application was not detected as an AppImage; this might be a security issue.");
}
}
env
@@ -298,11 +300,9 @@ macro_rules! debug_eprintln {
};
}
/// Reconstructs a path from its components using the platform separator then converts it to String
/// Reconstructs a path from its components using the platform separator then converts it to String and removes UNC prefixes on Windows if it exists.
pub fn display_path<P: AsRef<Path>>(p: P) -> String {
p.as_ref()
.components()
.collect::<PathBuf>()
dunce::simplified(&p.as_ref().components().collect::<PathBuf>())
.display()
.to_string()
}

View File

@@ -18,10 +18,11 @@ pub enum MimeType {
Js,
Json,
Jsonld,
Mp4,
OctetStream,
Rtf,
Svg,
Mp4,
Txt,
}
impl std::fmt::Display for MimeType {
@@ -34,10 +35,11 @@ impl std::fmt::Display for MimeType {
MimeType::Js => "text/javascript",
MimeType::Json => "application/json",
MimeType::Jsonld => "application/ld+json",
MimeType::Mp4 => "video/mp4",
MimeType::OctetStream => "application/octet-stream",
MimeType::Rtf => "application/rtf",
MimeType::Svg => "image/svg+xml",
MimeType::Mp4 => "video/mp4",
MimeType::Txt => MIMETYPE_PLAIN,
};
write!(f, "{mime}")
}
@@ -46,6 +48,11 @@ impl std::fmt::Display for MimeType {
impl MimeType {
/// parse a URI suffix to convert text/plain mimeType to their actual web compatible mimeType.
pub fn parse_from_uri(uri: &str) -> MimeType {
Self::parse_from_uri_with_fallback(uri, Self::Html)
}
/// parse a URI suffix to convert text/plain mimeType to their actual web compatible mimeType with specified fallback for unknown file extensions.
pub fn parse_from_uri_with_fallback(uri: &str, fallback: MimeType) -> MimeType {
let suffix = uri.split('.').last();
match suffix {
Some("bin") => Self::OctetStream,
@@ -57,19 +64,24 @@ impl MimeType {
Some("json") => Self::Json,
Some("jsonld") => Self::Jsonld,
Some("mjs") => Self::Js,
Some("mp4") => Self::Mp4,
Some("rtf") => Self::Rtf,
Some("svg") => Self::Svg,
Some("mp4") => Self::Mp4,
Some("txt") => Self::Txt,
// Assume HTML when a TLD is found for eg. `wry:://tauri.app` | `wry://hello.com`
Some(_) => Self::Html,
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
Some(_) => fallback,
// using octet stream according to this:
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
None => Self::OctetStream,
}
}
/// infer mimetype from content (or) URI if needed.
pub fn parse(content: &[u8], uri: &str) -> String {
Self::parse_with_fallback(content, uri, Self::Html)
}
/// infer mimetype from content (or) URI if needed with specified fallback for unknown file extensions.
pub fn parse_with_fallback(content: &[u8], uri: &str, fallback: MimeType) -> String {
let mime = if uri.ends_with(".svg") {
// when reading svg, we can't use `infer`
None
@@ -78,8 +90,10 @@ impl MimeType {
};
match mime {
Some(mime) if mime == MIMETYPE_PLAIN => Self::parse_from_uri(uri).to_string(),
None => Self::parse_from_uri(uri).to_string(),
Some(mime) if mime == MIMETYPE_PLAIN => {
Self::parse_from_uri_with_fallback(uri, fallback).to_string()
}
None => Self::parse_from_uri_with_fallback(uri, fallback).to_string(),
Some(mime) => mime.to_string(),
}
}
@@ -122,14 +136,17 @@ mod tests {
let mjs: String = MimeType::parse_from_uri("https://example.com/bundled.mjs").to_string();
assert_eq!(mjs, String::from("text/javascript"));
let mp4: String = MimeType::parse_from_uri("https://example.com/video.mp4").to_string();
assert_eq!(mp4, String::from("video/mp4"));
let rtf: String = MimeType::parse_from_uri("https://example.com/document.rtf").to_string();
assert_eq!(rtf, String::from("application/rtf"));
let svg: String = MimeType::parse_from_uri("https://example.com/picture.svg").to_string();
assert_eq!(svg, String::from("image/svg+xml"));
let mp4: String = MimeType::parse_from_uri("https://example.com/video.mp4").to_string();
assert_eq!(mp4, String::from("video/mp4"));
let txt: String = MimeType::parse_from_uri("https://example.com/file.txt").to_string();
assert_eq!(txt, String::from("text/plain"));
let custom_scheme = MimeType::parse_from_uri("wry://tauri.app").to_string();
assert_eq!(custom_scheme, String::from("text/html"));

View File

@@ -2,7 +2,10 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::{Component, Path, PathBuf};
use std::{
collections::HashMap,
path::{Component, Path, PathBuf},
};
/// Given a path (absolute or relative) to a resource file, returns the
/// relative path from the bundle resources directory where that resource
@@ -39,10 +42,58 @@ pub fn external_binaries(external_binaries: &[String], target_triple: &str) -> V
paths
}
enum PatternIter<'a> {
Slice(std::slice::Iter<'a, String>),
Map(std::collections::hash_map::Iter<'a, String, String>),
}
/// A helper to iterate through resources.
pub struct ResourcePaths<'a> {
iter: ResourcePathsIter<'a>,
}
impl<'a> ResourcePaths<'a> {
/// Creates a new ResourcePaths from a slice of patterns to iterate
pub fn new(patterns: &'a [String], allow_walk: bool) -> ResourcePaths<'a> {
ResourcePaths {
iter: ResourcePathsIter {
pattern_iter: PatternIter::Slice(patterns.iter()),
glob_iter: None,
walk_iter: None,
allow_walk,
current_pattern: None,
current_pattern_is_valid: false,
current_dest: None,
},
}
}
/// Creates a new ResourcePaths from a slice of patterns to iterate
pub fn from_map(patterns: &'a HashMap<String, String>, allow_walk: bool) -> ResourcePaths<'a> {
ResourcePaths {
iter: ResourcePathsIter {
pattern_iter: PatternIter::Map(patterns.iter()),
glob_iter: None,
walk_iter: None,
allow_walk,
current_pattern: None,
current_pattern_is_valid: false,
current_dest: None,
},
}
}
/// Returns the resource iterator that yields the source and target paths.
/// Needed when using [`Self::from_map`].
pub fn iter(self) -> ResourcePathsIter<'a> {
self.iter
}
}
/// Iterator of a [`ResourcePaths`].
pub struct ResourcePathsIter<'a> {
/// the patterns to iterate.
pattern_iter: std::slice::Iter<'a, String>,
pattern_iter: PatternIter<'a>,
/// the glob iterator if the path from the current iteration is a glob pattern.
glob_iter: Option<glob::Paths>,
/// the walkdir iterator if the path from the current iteration is a directory.
@@ -50,22 +101,28 @@ pub struct ResourcePaths<'a> {
/// whether the resource paths allows directories or not.
allow_walk: bool,
/// the pattern of the current iteration.
current_pattern: Option<String>,
current_pattern: Option<(String, PathBuf)>,
/// whether the current pattern is valid or not.
current_pattern_is_valid: bool,
/// Current destination path. Only set when the iterator comes from a Map.
current_dest: Option<PathBuf>,
}
impl<'a> ResourcePaths<'a> {
/// Creates a new ResourcePaths from a slice of patterns to iterate
pub fn new(patterns: &'a [String], allow_walk: bool) -> ResourcePaths<'a> {
ResourcePaths {
pattern_iter: patterns.iter(),
glob_iter: None,
walk_iter: None,
allow_walk,
current_pattern: None,
current_pattern_is_valid: false,
}
/// Information for a resource.
pub struct Resource {
path: PathBuf,
target: PathBuf,
}
impl Resource {
/// The path of the resource.
pub fn path(&self) -> &Path {
&self.path
}
/// The target location of the resource.
pub fn target(&self) -> &Path {
&self.target
}
}
@@ -73,6 +130,28 @@ impl<'a> Iterator for ResourcePaths<'a> {
type Item = crate::Result<PathBuf>;
fn next(&mut self) -> Option<crate::Result<PathBuf>> {
self.iter.next().map(|r| r.map(|res| res.path))
}
}
fn normalize(path: &Path) -> PathBuf {
let mut dest = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(_) => {}
Component::RootDir => dest.push("/"),
Component::CurDir => {}
Component::ParentDir => dest.push(".."),
Component::Normal(string) => dest.push(string),
}
}
dest
}
impl<'a> Iterator for ResourcePathsIter<'a> {
type Item = crate::Result<Resource>;
fn next(&mut self) -> Option<crate::Result<Resource>> {
loop {
if let Some(ref mut walk_entries) = self.walk_iter {
if let Some(entry) = walk_entries.next() {
@@ -85,7 +164,20 @@ impl<'a> Iterator for ResourcePaths<'a> {
continue;
}
self.current_pattern_is_valid = true;
return Some(Ok(path.to_path_buf()));
return Some(Ok(Resource {
target: if let (Some(current_dest), Some(current_pattern)) =
(&self.current_dest, &self.current_pattern)
{
if current_pattern.0.contains('*') {
current_dest.join(path.file_name().unwrap())
} else {
current_dest.join(path.strip_prefix(&current_pattern.1).unwrap())
}
} else {
resource_relpath(path)
},
path: path.to_path_buf(),
}));
}
}
self.walk_iter = None;
@@ -105,24 +197,51 @@ impl<'a> Iterator for ResourcePaths<'a> {
}
}
self.current_pattern_is_valid = true;
return Some(Ok(path));
return Some(Ok(Resource {
target: if let Some(current_dest) = &self.current_dest {
current_dest.join(path.file_name().unwrap())
} else {
resource_relpath(&path)
},
path,
}));
} else if let Some(current_path) = &self.current_pattern {
if !self.current_pattern_is_valid {
self.glob_iter = None;
return Some(Err(crate::Error::GlobPathNotFound(current_path.clone())));
return Some(Err(crate::Error::GlobPathNotFound(current_path.0.clone())));
}
}
}
self.glob_iter = None;
if let Some(pattern) = self.pattern_iter.next() {
self.current_pattern = Some(pattern.to_string());
self.current_pattern_is_valid = false;
let glob = match glob::glob(pattern) {
Ok(glob) => glob,
Err(error) => return Some(Err(error.into())),
};
self.glob_iter = Some(glob);
continue;
self.current_dest = None;
match &mut self.pattern_iter {
PatternIter::Slice(iter) => {
if let Some(pattern) = iter.next() {
self.current_pattern = Some((pattern.to_string(), normalize(Path::new(pattern))));
self.current_pattern_is_valid = false;
let glob = match glob::glob(pattern) {
Ok(glob) => glob,
Err(error) => return Some(Err(error.into())),
};
self.glob_iter = Some(glob);
continue;
}
}
PatternIter::Map(iter) => {
if let Some((pattern, dest)) = iter.next() {
self.current_pattern = Some((pattern.to_string(), normalize(Path::new(pattern))));
self.current_pattern_is_valid = false;
let glob = match glob::glob(pattern) {
Ok(glob) => glob,
Err(error) => return Some(Err(error.into())),
};
self
.current_dest
.replace(resource_relpath(&PathBuf::from(dest)));
self.glob_iter = Some(glob);
continue;
}
}
}
return None;
}

View File

@@ -1,5 +1,82 @@
# Changelog
## \[1.5.0]
### New Features
- [`eeb6be54`](https://www.github.com/tauri-apps/tauri/commit/eeb6be54228f3e5463a28c68956abb06a694c010)([#7512](https://www.github.com/tauri-apps/tauri/pull/7512)) Add `tauri::Manager::emit_filter` and only serialize once when emitting to multiple windows.
- [`6c408b73`](https://www.github.com/tauri-apps/tauri/commit/6c408b736c7aa2a0a91f0a40d45a2b7a7dedfe78)([#7269](https://www.github.com/tauri-apps/tauri/pull/7269)) Add option to specify notification sound.
- [`fdaee9a5`](https://www.github.com/tauri-apps/tauri/commit/fdaee9a5ce988c448dd035c2050c339d275e8d15)([#7350](https://www.github.com/tauri-apps/tauri/pull/7350)) Add `tauri::plugin::Builder::register_uri_scheme_protocol`
- [`10e362d0`](https://www.github.com/tauri-apps/tauri/commit/10e362d098c9bed48f832bad471fb2fab83ab0bb)([#7432](https://www.github.com/tauri-apps/tauri/pull/7432)) Added `UpdateBuilder::endpoints` to add request endpoints at runtime.
- [`10e362d0`](https://www.github.com/tauri-apps/tauri/commit/10e362d098c9bed48f832bad471fb2fab83ab0bb)([#7432](https://www.github.com/tauri-apps/tauri/pull/7432)) Added `UpdateResponse::header` and `UpdateResponse::remove_header` to modify the update download request headers.
### Enhancements
- [`757e959e`](https://www.github.com/tauri-apps/tauri/commit/757e959eb276ed535cfddb0dea8897c56441c644)([#7344](https://www.github.com/tauri-apps/tauri/pull/7344)) Open links externally when `<base target="_blank" />` exists
- [`c9827338`](https://www.github.com/tauri-apps/tauri/commit/c98273387c0ffbb8d0de78ce17006411a1f503ee)([#7416](https://www.github.com/tauri-apps/tauri/pull/7416)) Enhance `readDir` API error with path information.
- [`58d6b899`](https://www.github.com/tauri-apps/tauri/commit/58d6b899e21d37bb42810890d289deb57f2273bd)([#7636](https://www.github.com/tauri-apps/tauri/pull/7636)) Add `append` option to `FsOptions` in the `fs` JS module, used in `writeTextFile` and `writeBinaryFile`, to be able to append to existing files instead of overwriting it.
- [`9aa34ada`](https://www.github.com/tauri-apps/tauri/commit/9aa34ada5769dbefa7dfe5f7a6288b3d20b294e4)([#7645](https://www.github.com/tauri-apps/tauri/pull/7645)) Add setting to switch to `http://<scheme>.localhost/` for custom protocols on Windows.
### Bug Fixes
- [`4bf1e85e`](https://www.github.com/tauri-apps/tauri/commit/4bf1e85e6bf85a7ec92d50c8465bc0588a6399d8)([#7722](https://www.github.com/tauri-apps/tauri/pull/7722)) Properly respect the `focused` option when creating the webview.
- [`0797a002`](https://www.github.com/tauri-apps/tauri/commit/0797a002caad29cd8bedccf01f64bf3b45a5e528)([#7746](https://www.github.com/tauri-apps/tauri/pull/7746)) On macOS, fixed tapping on custom title bar doesn't maximize the window.
- [`1a3dcdb8`](https://www.github.com/tauri-apps/tauri/commit/1a3dcdb8302fad511f2c1cd418fbc4cff0bd62ac)([#7185](https://www.github.com/tauri-apps/tauri/pull/7185)) On Windows, fix NSIS installers requiring administrator rights failing to be launched by updater.
- [`fa7f9b77`](https://www.github.com/tauri-apps/tauri/commit/fa7f9b77ab8f0c890e9d7b120901610e0d3e4c46)([#7341](https://www.github.com/tauri-apps/tauri/pull/7341)) Fix updater not following endpoint redirects.
- [`6fbd6dba`](https://www.github.com/tauri-apps/tauri/commit/6fbd6dba5290dc017ab0ba5a44cf4358b022836f)([#17](https://www.github.com/tauri-apps/tauri/pull/17)) Fix the validation of `std::env::current_exe` warn the user if AppImage is not mounted instead of panicking
### Dependencies
- Upgraded to `tauri-utils@1.5.0`
- Upgraded to `tauri-runtime-wry@0.14.1`
- Upgraded to `tauri-runtime@0.14.1`
- Upgraded to `tauri-macros@1.4.1`
## \[1.4.1]
### Bug Fixes
- [`6afd3472`](https://www.github.com/tauri-apps/tauri/commit/6afd34727f153b32dbc568d169dbb17fb8dc3539)([#6680](https://www.github.com/tauri-apps/tauri/pull/6680)) Revert [#6680](https://github.com/tauri-apps/tauri/pull/6680) which added a default sound for notifications on Windows. This introduced inconsistency with other platforms that has silent notifications by default. In the upcoming releases, we will add support for modifying the notification sound across all platforms.
### Security fixes
- [`066c09a6`](https://www.github.com/tauri-apps/tauri/commit/066c09a6ea06f42f550d090715e06beb65cd5564)([#7227](https://www.github.com/tauri-apps/tauri/pull/7227)) Fix regression in `1.4` where the default behavior of the file system scope was changed to allow reading hidden files and directories by default.
## \[1.4.0]
### New Features
- [`7c237209`](https://www.github.com/tauri-apps/tauri/commit/7c237209207cd2938df660b6fd87d3b7d728bd03)([#6546](https://www.github.com/tauri-apps/tauri/pull/6546)) Added `tauri::VERSION` const to get Tauri's version from Rust.
- [`4c39e46a`](https://www.github.com/tauri-apps/tauri/commit/4c39e46a3b438d007f139166ab2a0ba34291a10a)([#7026](https://www.github.com/tauri-apps/tauri/pull/7026)) Added `tauri::webview_version` , to get webview version.
- [`359058ce`](https://www.github.com/tauri-apps/tauri/commit/359058cecca44a9c30b65140c44a8bb3a6dd3be8)([#5939](https://www.github.com/tauri-apps/tauri/pull/5939)) Add `tauri::api::os::locale` function to get the system locale.
- [`c4d6fb4b`](https://www.github.com/tauri-apps/tauri/commit/c4d6fb4b1ea8acf02707a9fe5dcab47c1c5bae7b)([#2353](https://www.github.com/tauri-apps/tauri/pull/2353)) Added the `maximizable`, `minimizable` and `closable` options to the window builder.
- [`c4d6fb4b`](https://www.github.com/tauri-apps/tauri/commit/c4d6fb4b1ea8acf02707a9fe5dcab47c1c5bae7b)([#2353](https://www.github.com/tauri-apps/tauri/pull/2353)) Added the `set_maximizable`, `set_minimizable`, `set_closable`, `is_maximizable`, `is_minimizable` and `is_closable` methods on `Window`.
- [`1d99f8a3`](https://www.github.com/tauri-apps/tauri/commit/1d99f8a3c2f989d1a5ba4d805e3a40b07a3ca8a5)([#4752](https://www.github.com/tauri-apps/tauri/pull/4752)) Expose the `test` module behind the `test` Cargo feature.
- [`000104bc`](https://www.github.com/tauri-apps/tauri/commit/000104bc3bc0c9ff3d20558ab9cf2080f126e9e0)([#6472](https://www.github.com/tauri-apps/tauri/pull/6472)) Add `Window::is_focused` and `Manager::get_focused_window` getters.
- [`441f9646`](https://www.github.com/tauri-apps/tauri/commit/441f96465488a4f8a5731cc51b8ac97b685898c7)([#5491](https://www.github.com/tauri-apps/tauri/pull/5491)) Add `MenuHandle::try_get_item` and `SystemTrayHandle::try_get_item` which returns a `Option` instead of panicking.
### Enhancements
- [`45330e38`](https://www.github.com/tauri-apps/tauri/commit/45330e38193d0b2a01aa926aec433acc6b8f6597)([#6375](https://www.github.com/tauri-apps/tauri/pull/6375)) Enhance the `asset` protocol to support streaming of large files.
- [`df89ccc1`](https://www.github.com/tauri-apps/tauri/commit/df89ccc1912db6b81d43d56c9e6d66980ece2e8d)([#6955](https://www.github.com/tauri-apps/tauri/pull/6955)) Support `passive` mode for NSIS updater.
- [`cd3846c8`](https://www.github.com/tauri-apps/tauri/commit/cd3846c8ce61ab2879b3911e831525e6242aaab2)([#6955](https://www.github.com/tauri-apps/tauri/pull/6955)) Restart the app after the NSIS updater is finished.
- [`db7c5fbf`](https://www.github.com/tauri-apps/tauri/commit/db7c5fbf2e86f3694720f65834eb2c258b7c1291)([#7143](https://www.github.com/tauri-apps/tauri/pull/7143)) Remove `attohttpc` in favor of `reqwest`.
- [`d2710e9d`](https://www.github.com/tauri-apps/tauri/commit/d2710e9d2e8fd93975ef6494512370faa8cb3b7e)([#6944](https://www.github.com/tauri-apps/tauri/pull/6944)) Unpin `time`, `ignore`, and `winnow` crate versions. Developers now have to pin crates if needed themselves. A list of crates that need pinning to adhere to Tauri's MSRV will be visible in Tauri's GitHub workflow: https://github.com/tauri-apps/tauri/blob/dev/.github/workflows/test-core.yml#L85.
- [`5d85d099`](https://www.github.com/tauri-apps/tauri/commit/5d85d0990cd13a1446953a58633edc24eda55afe)([#7128](https://www.github.com/tauri-apps/tauri/pull/7128)) Send updater status events even if default dialog is enabled.
### Bug Fixes
- [`82169e69`](https://www.github.com/tauri-apps/tauri/commit/82169e69fc904d2c7980534c4479bb6f38259fb4)([#5208](https://www.github.com/tauri-apps/tauri/pull/5208)) Fix parsing `allowlist > http > scope` urls that added a trailing slash which broke matching the incoming requests url.
- [`b41b57eb`](https://www.github.com/tauri-apps/tauri/commit/b41b57ebb27befd366db5befaafb6043c18fdfef)([#7105](https://www.github.com/tauri-apps/tauri/pull/7105)) Fix panics when registering an invalid global shortcuts or checking it is registered and return proper errors instead.
- [`aecf1469`](https://www.github.com/tauri-apps/tauri/commit/aecf14690947d109745b4ad823a3e8f4338de47a)([#6889](https://www.github.com/tauri-apps/tauri/pull/6889)) Fix IPC failing after a failed navigation to an external URL.
- [`076e1a81`](https://www.github.com/tauri-apps/tauri/commit/076e1a81a50468e3dfb34ae9ca7e77c5e1758daa)([#7119](https://www.github.com/tauri-apps/tauri/pull/7119)) Fix unlistening to window events failing sometimes.
- [`3f35b452`](https://www.github.com/tauri-apps/tauri/commit/3f35b452637ef1c794a423f1eda62a15d2ddaf42)([#4080](https://www.github.com/tauri-apps/tauri/pull/4080)) Fix `WindowBuilder::on_navigation` handler not registered properly.
- [`0503eb69`](https://www.github.com/tauri-apps/tauri/commit/0503eb69ce7df6b4ed8f5249fdb519b86cd57d8d)([#7078](https://www.github.com/tauri-apps/tauri/pull/7078)) On macOS and Linux, fix app crashing when creating a window with `data:` uri.
- [`3700793a`](https://www.github.com/tauri-apps/tauri/commit/3700793a2f1ea3686b1889c345d73007bb622a29)([#6934](https://www.github.com/tauri-apps/tauri/pull/6934)) Emit `UPTODATE` update status to javascript when the updater server returns status code `204`
- [`ff5e4dbb`](https://www.github.com/tauri-apps/tauri/commit/ff5e4dbbb01bf3fc9c5143df732c75eef6fd98cb)([#6794](https://www.github.com/tauri-apps/tauri/pull/6794)) Fix some configurations not applied when creating the window through Javascript.
- [`65fd674f`](https://www.github.com/tauri-apps/tauri/commit/65fd674f50ba0395d5cea23daf9d2f49f95647fe)([#6652](https://www.github.com/tauri-apps/tauri/pull/6652)) Play a sound when showing a notification on Windows.
- [`696d77c3`](https://www.github.com/tauri-apps/tauri/commit/696d77c3ce480f4a3b4c1c57dae64ff2bb7842ce)([#4493](https://www.github.com/tauri-apps/tauri/pull/4493)) Fixes global events not being received on window-specific event listeners.
## \[1.3.0]
- Added the `additional_browser_args` option when creating a window.

View File

@@ -10,7 +10,7 @@ license = "Apache-2.0 OR MIT"
name = "tauri"
readme = "README.md"
repository = "https://github.com/tauri-apps/tauri"
version = "1.3.0"
version = "1.5.0"
[package.metadata.docs.rs]
no-default-features = true
@@ -26,6 +26,7 @@ features = [
"devtools",
"http-multipart",
"icon-png",
"test",
"dox"
]
rustdoc-args = [ "--cfg", "doc_cfg" ]
@@ -37,7 +38,7 @@ targets = [
]
[package.metadata.cargo-udeps.ignore]
normal = [ "attohttpc", "reqwest" ]
normal = [ "reqwest" ]
[dependencies]
serde_json = { version = "1.0", features = [ "raw_value" ] }
@@ -49,10 +50,10 @@ url = { version = "2.3" }
anyhow = "1.0"
thiserror = "1.0"
once_cell = "1"
tauri-runtime = { version = "0.13.0", path = "../tauri-runtime" }
tauri-macros = { version = "1.3.0", path = "../tauri-macros" }
tauri-utils = { version = "1.3.0", features = [ "resources" ], path = "../tauri-utils" }
tauri-runtime-wry = { version = "0.13.0", path = "../tauri-runtime-wry", optional = true }
tauri-runtime = { version = "0.14.1", path = "../tauri-runtime" }
tauri-macros = { version = "1.4.1", path = "../tauri-macros" }
tauri-utils = { version = "1.5.0", features = [ "resources" ], path = "../tauri-utils" }
tauri-runtime-wry = { version = "0.14.1", path = "../tauri-runtime-wry", optional = true }
rand = "0.8"
semver = { version = "1.0", features = [ "serde" ] }
serde_repr = "0.1"
@@ -60,7 +61,7 @@ state = "0.5"
tar = "0.4.38"
tempfile = "3"
zip = { version = "0.6", default-features = false, optional = true }
ignore = "=0.4.18"
ignore = "0.4"
flate2 = "1.0"
http = "0.2"
dirs-next = "2.0"
@@ -69,13 +70,12 @@ base64 = { version = "0.21", optional = true }
clap = { version = "3", optional = true }
reqwest = { version = "0.11", features = [ "json", "stream" ], optional = true }
bytes = { version = "1", features = [ "serde" ], optional = true }
attohttpc = { version = "0.22", features = [ "compress", "json", "form" ], optional = true }
open = { version = "3.2", optional = true }
shared_child = { version = "1.0", optional = true }
os_pipe = { version = "1.0", optional = true }
raw-window-handle = "=0.5.0"
raw-window-handle = "0.5"
minisign-verify = { version = "0.2", optional = true }
time = { version = "=0.3.15", features = [ "parsing", "formatting" ], optional = true }
time = { version = "0.3", features = [ "parsing", "formatting" ], optional = true }
os_info = { version = "3", optional = true }
regex = { version = "1.6.0", optional = true }
glob = "0.3"
@@ -85,6 +85,7 @@ infer = { version = "0.9", optional = true }
png = { version = "0.17", optional = true }
ico = { version = "0.2.0", optional = true }
encoding_rs = "0.8.31"
sys-locale = { version = "0.2.3", optional = true }
[target."cfg(any(target_os = \"macos\", windows, target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies]
rfd = { version = "0.10", optional = true, features = [ "gtk3", "common-controls-v6" ] }
@@ -102,7 +103,7 @@ objc = "0.2"
[target."cfg(windows)".dependencies]
webview2-com = "0.19.1"
win7-notifications = { version = "0.3.1", optional = true }
win7-notifications = { version = "0.4", optional = true }
[target."cfg(windows)".dependencies.windows]
version = "0.39.0"
@@ -123,10 +124,10 @@ tauri = { path = ".", default-features = false, features = [ "wry" ] }
tokio-test = "0.4.2"
tokio = { version = "1", features = [ "full" ] }
cargo_toml = "0.11"
winnow = "=0.4.1"
[features]
default = [ "wry", "compression", "objc-exception" ]
test = [ ]
compression = [ "tauri-macros/compression", "tauri-utils/compression" ]
wry = [ "tauri-runtime-wry" ]
objc-exception = [ "tauri-runtime-wry/objc-exception" ]
@@ -141,13 +142,14 @@ updater = [
"dialog-ask",
"fs-extract-api"
]
http-api = [ "attohttpc" ]
http-multipart = [ "attohttpc/multipart-form", "reqwest/multipart" ]
http-api = [ "reqwest", "bytes" ]
http-multipart = [ "reqwest/multipart" ]
os-api = [ "sys-locale" ]
shell-open-api = [ "open", "regex", "tauri-macros/shell-scope" ]
fs-extract-api = [ "zip" ]
reqwest-client = [ "reqwest", "bytes" ]
reqwest-native-tls-vendored = [ "reqwest-client", "reqwest/native-tls-vendored" ]
native-tls-vendored = [ "attohttpc/tls-vendored" ]
reqwest-client = [ "http-api" ]
reqwest-native-tls-vendored = [ "native-tls-vendored" ]
native-tls-vendored = [ "reqwest/native-tls-vendored" ]
process-command-api = [ "shared_child", "os_pipe" ]
global-shortcut = [
"tauri-runtime/global-shortcut",
@@ -214,7 +216,7 @@ global-shortcut-all = [ "global-shortcut" ]
http-all = [ "http-request" ]
http-request = [ "http-api" ]
notification-all = [ "notification", "dialog-ask" ]
os-all = [ "os_info" ]
os-all = [ "os_info", "os-api" ]
path-all = [ ]
process-all = [ "process-relaunch", "process-exit" ]
process-exit = [ ]
@@ -231,6 +233,9 @@ window-all = [
"window-center",
"window-request-user-attention",
"window-set-resizable",
"window-set-maximizable",
"window-set-minimizable",
"window-set-closable",
"window-set-title",
"window-maximize",
"window-unmaximize",
@@ -262,6 +267,9 @@ window-create = [ ]
window-center = [ ]
window-request-user-attention = [ ]
window-set-resizable = [ ]
window-set-maximizable = [ ]
window-set-minimizable = [ ]
window-set-closable = [ ]
window-set-title = [ ]
window-maximize = [ ]
window-unmaximize = [ ]

View File

@@ -4,7 +4,7 @@
[![status](https://img.shields.io/badge/status-stable-blue.svg)](https://github.com/tauri-apps/tauri/tree/dev)
[![License](https://img.shields.io/badge/License-MIT%20or%20Apache%202-green.svg)](https://opencollective.com/tauri)
[![test library](https://img.shields.io/github/workflow/status/tauri-apps/tauri/test%20library?label=test%20library)](https://github.com/tauri-apps/tauri/actions?query=workflow%3A%22test+library%22)
[![test core](https://img.shields.io/github/actions/workflow/status/tauri-apps/tauri/test-core.yml?label=test%20core&logo=github)](https://github.com/tauri-apps/tauri/actions/workflows/test-core.yml)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Ftauri-apps%2Ftauri.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Ftauri-apps%2Ftauri?ref=badge_shield)
[![Chat Server](https://img.shields.io/badge/chat-discord-7289da.svg)](https://discord.gg/SpmNs4S)
[![website](https://img.shields.io/badge/website-tauri.app-purple.svg)](https://tauri.app)

View File

@@ -71,6 +71,9 @@ fn main() {
"center",
"request-user-attention",
"set-resizable",
"set-maximizable",
"set-minimizable",
"set-closable",
"set-title",
"maximize",
"unmaximize",

File diff suppressed because one or more lines are too long

View File

@@ -13,12 +13,22 @@
})
}
const osName = __TEMPLATE_os_name__
const protocolScheme = __TEMPLATE_protocol_scheme__
window.__TAURI__.convertFileSrc = function convertFileSrc(filePath, protocol = 'asset') {
const path = encodeURIComponent(filePath)
return osName === 'windows'
? `${protocolScheme}://${protocol}.localhost/${path}`
: `${protocol}://localhost/${path}`
}
window.__TAURI__.transformCallback = function transformCallback(
callback,
once
) {
var identifier = uid()
var prop = `_${identifier}`
const identifier = uid()
const prop = `_${identifier}`
Object.defineProperty(window, prop, {
value: (result) => {
@@ -50,11 +60,11 @@
window.__TAURI_INVOKE__ = function invoke(cmd, args = {}) {
return new Promise(function (resolve, reject) {
var callback = window.__TAURI__.transformCallback(function (r) {
const callback = window.__TAURI__.transformCallback(function (r) {
resolve(r)
delete window[`_${error}`]
}, true)
var error = window.__TAURI__.transformCallback(function (e) {
const error = window.__TAURI__.transformCallback(function (e) {
reject(e)
delete window[`_${callback}`]
}, true)
@@ -91,13 +101,14 @@
document.querySelector('body').addEventListener(
'click',
function (e) {
var target = e.target
let target = e.target
const baseTarget = document.querySelector('head base')?.target
while (target != null) {
if (target.matches('a')) {
if (
target.href &&
(['http://', 'https://', 'mailto:', 'tel:'].some(v => target.href.startsWith(v))) &&
target.target === '_blank'
(target.target === '_blank' || (!target.target && baseTarget === "_blank"))
) {
window.__TAURI_INVOKE__('tauri', {
__tauriModule: 'Shell',
@@ -133,7 +144,7 @@
// drag region
document.addEventListener('mousedown', (e) => {
if (e.target.hasAttribute('data-tauri-drag-region') && e.buttons === 1) {
if (e.target.hasAttribute('data-tauri-drag-region') && e.button === 0) {
// prevents text cursor
e.preventDefault()
// fix #2549: double click on drag region edge causes content to maximize without window sizing change
@@ -210,7 +221,7 @@
}
window.Notification = function (title, options) {
var opts = options || {}
const opts = options || {}
sendNotification(
Object.assign(opts, {
title: title

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,36 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
(function () {
function toggleDevtoolsHotkey() {
const isHotkey = navigator.appVersion.includes("Mac")
? (event) => event.metaKey && event.altKey && event.key === "I"
: (event) => event.ctrlKey && event.shiftKey && event.key === "I";
document.addEventListener("keydown", (event) => {
if (isHotkey(event)) {
window.__TAURI_INVOKE__('tauri', {
__tauriModule: 'Window',
message: {
cmd: 'manage',
data: {
cmd: {
type: '__toggleDevtools'
}
}
}
});
}
});
}
if (
document.readyState === "complete" ||
document.readyState === "interactive"
) {
toggleDevtoolsHotkey();
} else {
window.addEventListener("DOMContentLoaded", toggleDevtoolsHotkey, true);
}
})();

View File

@@ -32,18 +32,10 @@ pub fn is_dir<P: AsRef<Path>>(path: P) -> crate::api::Result<bool> {
}
fn is_symlink<P: AsRef<Path>>(path: P) -> crate::api::Result<bool> {
// TODO: remove the different implementation once we raise tauri's MSRV to at least 1.58
#[cfg(windows)]
let ret = symlink_metadata(path)
let path = path.as_ref();
symlink_metadata(path)
.map(|md| md.is_symlink())
.map_err(Into::into);
#[cfg(not(windows))]
let ret = symlink_metadata(path)
.map(|md| md.file_type().is_symlink())
.map_err(Into::into);
ret
.map_err(|e| crate::api::Error::PathIo(e, path.to_path_buf()))
}
/// Reads a directory. Can perform recursive operations.
@@ -62,20 +54,19 @@ pub(crate) fn read_dir_with_options<P: AsRef<Path>>(
options: ReadDirOptions<'_>,
) -> crate::api::Result<Vec<DiskEntry>> {
let mut files_and_dirs: Vec<DiskEntry> = vec![];
for entry in fs::read_dir(path)? {
let path = path.as_ref();
for entry in fs::read_dir(path).map_err(|e| crate::api::Error::PathIo(e, path.to_path_buf()))? {
let path = entry?.path();
let path_as_string = path.display().to_string();
if let Ok(flag) = is_dir(&path_as_string) {
if let Ok(flag) = is_dir(&path) {
files_and_dirs.push(DiskEntry {
path: path.clone(),
children: if flag {
Some(
if recursive
&& (!is_symlink(&path_as_string)?
|| options.scope.map(|s| s.is_allowed(&path)).unwrap_or(true))
&& (!is_symlink(&path)? || options.scope.map(|s| s.is_allowed(&path)).unwrap_or(true))
{
read_dir_with_options(&path_as_string, true, options)?
read_dir_with_options(&path, true, options)?
} else {
vec![]
},

View File

@@ -22,20 +22,13 @@ pub enum Error {
#[error("user cancelled the dialog")]
DialogCancelled,
/// The network error.
#[cfg(all(feature = "http-api", not(feature = "reqwest-client")))]
#[error("Network Error: {0}")]
Network(#[from] attohttpc::Error),
/// The network error.
#[cfg(feature = "reqwest-client")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "reqwest-client")))]
#[cfg(feature = "http-api")]
#[error("Network Error: {0}")]
Network(#[from] reqwest::Error),
/// HTTP method error.
#[error(transparent)]
HttpMethod(#[from] http::method::InvalidMethod),
/// Invalid HTTP header value.
#[cfg(feature = "reqwest-client")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "reqwest-client")))]
#[error(transparent)]
HttpHeaderValue(#[from] http::header::InvalidHeaderValue),
/// Invalid HTTP header value.
@@ -56,6 +49,9 @@ pub enum Error {
/// IO error.
#[error(transparent)]
Io(#[from] std::io::Error),
/// IO error at the given path.
#[error("{0}, path {1}")]
PathIo(std::io::Error, std::path::PathBuf),
/// Ignore error.
#[error("failed to walkdir: {0}")]
Ignore(#[from] ignore::Error),

View File

@@ -6,7 +6,7 @@ use std::{
borrow::Cow,
fs,
io::{self, Cursor, Read, Seek},
path::{self, Path, PathBuf},
path::{self, Component, Path, PathBuf},
};
/// The archive reader.
@@ -84,10 +84,22 @@ impl<'a, R: Read> Entry<'a, R> {
/// Extract this entry into `into_path`.
/// If it's a directory, the target will be created, if it's a file, it'll be extracted at this location.
/// If it's a symlink, it will be created.
/// Note: You need to include the complete path, with file name and extension.
pub fn extract(self, into_path: &path::Path) -> crate::api::Result<()> {
match self {
Self::Tar(mut entry) => {
// validate path
let path = entry.path()?;
if path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"cannot extract path with parent dir component",
)
.into(),
);
}
// determine if it's a file or a directory
if entry.header().entry_type() == tar::EntryType::Directory {
// this is a directory, lets create it
@@ -100,13 +112,8 @@ impl<'a, R: Read> Entry<'a, R> {
}
}
} else {
let mut out_file = fs::File::create(into_path)?;
io::copy(&mut entry, &mut out_file)?;
// make sure we set permissions
if let Ok(mode) = entry.header().mode() {
set_perms(into_path, Some(&mut out_file), mode, true)?;
}
// handle files, symlinks, hard links, etc. and set permissions
entry.unpack(into_path)?;
}
}
Self::Zip(entry) => {
@@ -270,59 +277,3 @@ impl<'a, R: Read + Seek> Extract<'a, R> {
Ok(())
}
}
fn set_perms(
dst: &Path,
f: Option<&mut std::fs::File>,
mode: u32,
preserve: bool,
) -> crate::api::Result<()> {
_set_perms(dst, f, mode, preserve).map_err(|_| {
crate::api::Error::Extract(format!(
"failed to set permissions to {mode:o} \
for `{}`",
dst.display()
))
})
}
#[cfg(unix)]
fn _set_perms(
dst: &Path,
f: Option<&mut std::fs::File>,
mode: u32,
preserve: bool,
) -> io::Result<()> {
use std::os::unix::prelude::*;
let mode = if preserve { mode } else { mode & 0o777 };
let perm = fs::Permissions::from_mode(mode as _);
match f {
Some(f) => f.set_permissions(perm),
None => fs::set_permissions(dst, perm),
}
}
#[cfg(windows)]
fn _set_perms(
dst: &Path,
f: Option<&mut std::fs::File>,
mode: u32,
_preserve: bool,
) -> io::Result<()> {
if mode & 0o200 == 0o200 {
return Ok(());
}
match f {
Some(f) => {
let mut perm = f.metadata()?.permissions();
perm.set_readonly(true);
f.set_permissions(perm)
}
None => {
let mut perm = fs::metadata(dst)?.permissions();
perm.set_readonly(true);
fs::set_permissions(dst, perm)
}
}
}

View File

@@ -13,12 +13,8 @@ use url::Url;
use std::{collections::HashMap, path::PathBuf, time::Duration};
#[cfg(feature = "reqwest-client")]
pub use reqwest::header;
#[cfg(not(feature = "reqwest-client"))]
pub use attohttpc::header;
use header::{HeaderName, HeaderValue};
#[derive(Deserialize)]
@@ -73,13 +69,6 @@ impl ClientBuilder {
}
/// Builds the Client.
#[cfg(not(feature = "reqwest-client"))]
pub fn build(self) -> crate::api::Result<Client> {
Ok(Client(self))
}
/// Builds the Client.
#[cfg(feature = "reqwest-client")]
pub fn build(self) -> crate::api::Result<Client> {
let mut client_builder = reqwest::Client::builder();
@@ -101,146 +90,9 @@ impl ClientBuilder {
}
/// The HTTP client based on [`reqwest`].
#[cfg(feature = "reqwest-client")]
#[derive(Debug, Clone)]
pub struct Client(reqwest::Client);
/// The HTTP client.
#[cfg(not(feature = "reqwest-client"))]
#[derive(Debug, Clone)]
pub struct Client(ClientBuilder);
#[cfg(not(feature = "reqwest-client"))]
impl Client {
/// Executes an HTTP request.
///
/// # Examples
///
/// ```rust,no_run
/// use tauri::api::http::{ClientBuilder, HttpRequestBuilder, ResponseType};
/// async fn run_request() {
/// let client = ClientBuilder::new().build().unwrap();
/// let response = client.send(
/// HttpRequestBuilder::new("GET", "https://www.rust-lang.org")
/// .unwrap()
/// .response_type(ResponseType::Binary)
/// ).await;
/// if let Ok(response) = response {
/// let bytes = response.bytes();
/// }
/// }
/// ```
pub async fn send(&self, request: HttpRequestBuilder) -> crate::api::Result<Response> {
let method = Method::from_bytes(request.method.to_uppercase().as_bytes())?;
let mut request_builder = attohttpc::RequestBuilder::try_new(method, &request.url)?;
if let Some(query) = request.query {
request_builder = request_builder.params(&query);
}
if let Some(headers) = &request.headers {
for (name, value) in headers.0.iter() {
request_builder = request_builder.header(name, value);
}
}
if let Some(max_redirections) = self.0.max_redirections {
if max_redirections == 0 {
request_builder = request_builder.follow_redirects(false);
} else {
request_builder = request_builder.max_redirections(max_redirections as u32);
}
}
if let Some(timeout) = request.timeout {
request_builder = request_builder.timeout(timeout);
}
let response = if let Some(body) = request.body {
match body {
Body::Bytes(data) => request_builder.body(attohttpc::body::Bytes(data)).send()?,
Body::Text(text) => request_builder.body(attohttpc::body::Bytes(text)).send()?,
Body::Json(json) => request_builder.json(&json)?.send()?,
Body::Form(form_body) => {
#[allow(unused_variables)]
fn send_form(
request_builder: attohttpc::RequestBuilder,
headers: &Option<HeaderMap>,
form_body: FormBody,
) -> crate::api::Result<attohttpc::Response> {
#[cfg(feature = "http-multipart")]
if matches!(
headers
.as_ref()
.and_then(|h| h.0.get("content-type"))
.map(|v| v.as_bytes()),
Some(b"multipart/form-data")
) {
let mut multipart = attohttpc::MultipartBuilder::new();
let mut byte_cache: HashMap<String, Vec<u8>> = Default::default();
for (name, part) in &form_body.0 {
if let FormPart::File { file, .. } = part {
byte_cache.insert(name.to_string(), file.clone().try_into()?);
}
}
for (name, part) in &form_body.0 {
multipart = match part {
FormPart::File {
file,
mime,
file_name,
} => {
// safe to unwrap: always set by previous loop
let mut file =
attohttpc::MultipartFile::new(name, byte_cache.get(name).unwrap());
if let Some(mime) = mime {
file = file.with_type(mime)?;
}
if let Some(file_name) = file_name {
file = file.with_filename(file_name);
}
multipart.with_file(file)
}
FormPart::Text(value) => multipart.with_text(name, value),
};
}
return request_builder
.body(multipart.build()?)
.send()
.map_err(Into::into);
}
let mut form = Vec::new();
for (name, part) in form_body.0 {
match part {
FormPart::File { file, .. } => {
let bytes: Vec<u8> = file.try_into()?;
form.push((name, serde_json::to_string(&bytes)?))
}
FormPart::Text(value) => form.push((name, value)),
}
}
request_builder.form(&form)?.send().map_err(Into::into)
}
send_form(request_builder, &request.headers, form_body)?
}
}
} else {
request_builder.send()?
};
Ok(Response(
request.response_type.unwrap_or(ResponseType::Json),
response,
request.url,
))
}
}
#[cfg(feature = "reqwest-client")]
impl Client {
/// Executes an HTTP request
///
@@ -557,13 +409,8 @@ impl HttpRequestBuilder {
}
/// The HTTP response.
#[cfg(feature = "reqwest-client")]
#[derive(Debug)]
pub struct Response(ResponseType, reqwest::Response);
/// The HTTP response.
#[cfg(not(feature = "reqwest-client"))]
#[derive(Debug)]
pub struct Response(ResponseType, attohttpc::Response, Url);
impl Response {
/// Get the [`StatusCode`] of this Response.
@@ -579,20 +426,10 @@ impl Response {
/// Reads the response as raw bytes.
pub async fn bytes(self) -> crate::api::Result<RawResponse> {
let status = self.status().as_u16();
#[cfg(feature = "reqwest-client")]
let data = self.1.bytes().await?.to_vec();
#[cfg(not(feature = "reqwest-client"))]
let data = self.1.bytes()?;
Ok(RawResponse { status, data })
}
#[cfg(not(feature = "reqwest-client"))]
#[allow(dead_code)]
pub(crate) fn reader(self) -> attohttpc::ResponseReader {
let (_, _, reader) = self.1.split();
reader
}
// Convert the response into a Stream of [`bytes::Bytes`] from the body.
//
// # Examples
@@ -612,7 +449,6 @@ impl Response {
// # Ok(())
// # }
// ```
#[cfg(feature = "reqwest-client")]
#[allow(dead_code)]
pub(crate) fn bytes_stream(
self,
@@ -625,10 +461,7 @@ impl Response {
///
/// Note that the body is serialized to a [`Value`].
pub async fn read(self) -> crate::api::Result<ResponseData> {
#[cfg(feature = "reqwest-client")]
let url = self.1.url().clone();
#[cfg(not(feature = "reqwest-client"))]
let url = self.2;
let mut headers = HashMap::new();
let mut raw_headers = HashMap::new();
@@ -650,20 +483,12 @@ impl Response {
}
let status = self.1.status().as_u16();
#[cfg(feature = "reqwest-client")]
let data = match self.0 {
ResponseType::Json => self.1.json().await?,
ResponseType::Text => Value::String(self.1.text().await?),
ResponseType::Binary => serde_json::to_value(&self.1.bytes().await?)?,
};
#[cfg(not(feature = "reqwest-client"))]
let data = match self.0 {
ResponseType::Json => self.1.json()?,
ResponseType::Text => Value::String(self.1.text()?),
ResponseType::Binary => serde_json::to_value(self.1.bytes()?)?,
};
Ok(ResponseData {
url,
status,

View File

@@ -13,6 +13,9 @@ pub mod file;
#[cfg_attr(doc_cfg, doc(cfg(feature = "http-api")))]
pub mod http;
pub mod ipc;
#[cfg(feature = "os-api")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "os-api")))]
pub mod os;
pub mod path;
pub mod process;
#[cfg(feature = "shell-open-api")]

View File

@@ -40,6 +40,50 @@ pub struct Notification {
icon: Option<String>,
/// The notification identifier
identifier: String,
/// The notification sound
sound: Option<Sound>,
}
/// Notification sound.
#[derive(Debug)]
pub enum Sound {
/// The default notification sound.
Default,
/// A custom notification sound.
///
/// ## Platform-specific
///
/// Each OS has a different sound name so you will need to conditionally specify an appropriate sound
/// based on the OS in use, for a list of sounds see:
/// - **Linux**: can be one of the sounds listed in <https://0pointer.de/public/sound-naming-spec.html>
/// - **Windows**: can be one of the sounds listed in <https://learn.microsoft.com/en-us/uwp/schemas/tiles/toastschema/element-audio>
/// but without the prefix, for example, if `ms-winsoundevent:Notification.Default` you would use `Default` and
/// if `ms-winsoundevent:Notification.Looping.Alarm2`, you would use `Alarm2`.
/// Windows 7 is not supported, if a sound is provided, it will play the default sound, otherwise it will be silent.
/// - **macOS**: you can specify the name of the sound you'd like to play when the notification is shown.
/// Any of the default sounds (under System Preferences > Sound) can be used, in addition to custom sound files.
/// Be sure that the sound file is under one of the following locations:
/// - `~/Library/Sounds`
/// - `/Library/Sounds`
/// - `/Network/Library/Sounds`
/// - `/System/Library/Sounds`
///
/// See the [`NSSound`] docs for more information.
///
/// [`NSSound`]: https://developer.apple.com/documentation/appkit/nssound
Custom(String),
}
impl From<String> for Sound {
fn from(value: String) -> Self {
Self::Custom(value)
}
}
impl From<&str> for Sound {
fn from(value: &str) -> Self {
Self::Custom(value.into())
}
}
impl Notification {
@@ -72,6 +116,15 @@ impl Notification {
self
}
/// Sets the notification sound. By default the notification has no sound.
///
/// See [`Sound`] for more information.
#[must_use]
pub fn sound(mut self, sound: impl Into<Sound>) -> Self {
self.sound.replace(sound.into());
self
}
/// Shows the notification.
///
/// # Examples
@@ -108,6 +161,17 @@ impl Notification {
} else {
notification.auto_icon();
}
if let Some(sound) = self.sound {
notification.sound_name(&match sound {
#[cfg(target_os = "macos")]
Sound::Default => "NSUserNotificationDefaultSoundName".to_string(),
#[cfg(windows)]
Sound::Default => "Default".to_string(),
#[cfg(all(unix, not(target_os = "macos")))]
Sound::Default => "message-new-instant".to_string(),
Sound::Custom(c) => c,
});
}
#[cfg(windows)]
{
let exe = tauri_utils::platform::current_exe()?;
@@ -191,6 +255,7 @@ impl Notification {
if let Some(title) = self.title {
notification.summary(&title);
}
notification.silent(self.sound.is_none());
if let Some(crate::Icon::Rgba {
rgba,
width,

10
core/tauri/src/api/os.rs Normal file
View File

@@ -0,0 +1,10 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Types and functions related to operating system operations.
/// Returns `Some(String)` with a `BCP-47` language tag inside. If the locale couldnt be obtained, `None` is returned instead.
pub fn locale() -> Option<String> {
sys_locale::get_locale()
}

View File

@@ -468,7 +468,7 @@ mod test {
assert_eq!(payload.code, Some(1));
}
CommandEvent::Stderr(line) => {
assert_eq!(line, "cat: test/api/: Is a directory".to_string());
assert_eq!(line, "cat: test/api/: Is a directory\n".to_string());
}
_ => {}
}

View File

@@ -990,7 +990,7 @@ pub struct Builder<R: Runtime> {
invoke_handler: Box<InvokeHandler<R>>,
/// The JS message responder.
invoke_responder: Arc<InvokeResponder<R>>,
pub(crate) invoke_responder: Arc<InvokeResponder<R>>,
/// The script that initializes the `window.__TAURI_POST_MESSAGE__` function.
invoke_initialization_script: String,
@@ -1214,6 +1214,7 @@ impl<R: Runtime> Builder<R> {
/// [`State`](crate::State) guard. In particular, if a value of type `T`
/// is managed by Tauri, adding `State<T>` to the list of arguments in a
/// command handler instructs Tauri to retrieve the managed value.
/// Additionally, [`state`](crate::Manager#method.state) can be used to retrieve the value manually.
///
/// # Panics
///
@@ -1461,6 +1462,15 @@ impl<R: Runtime> Builder<R> {
///
/// * `uri_scheme` The URI scheme to register, such as `example`.
/// * `protocol` the protocol associated with the given URI scheme. It's a function that takes an URL such as `example://localhost/asset.css`.
///
/// # Examples
///
/// ```rust
/// tauri::Builder::default()
/// .register_uri_scheme_protocol("myscheme", |app, req| {
/// tauri::http::ResponseBuilder::new().body(Vec::new())
/// });
/// ```
#[must_use]
pub fn register_uri_scheme_protocol<
N: Into<String>,
@@ -1563,28 +1573,17 @@ impl<R: Runtime> Builder<R> {
(self.invoke_responder, self.invoke_initialization_script),
);
let http_scheme = manager.config().tauri.security.dangerous_use_http_scheme;
// set up all the windows defined in the config
for config in manager.config().tauri.windows.clone() {
let url = config.url.clone();
let label = config.label.clone();
let webview_attributes = WebviewAttributes::from(&config);
let mut webview_attributes =
WebviewAttributes::new(url).accept_first_mouse(config.accept_first_mouse);
if let Some(ua) = &config.user_agent {
webview_attributes = webview_attributes.user_agent(ua);
}
if let Some(args) = &config.additional_browser_args {
webview_attributes = webview_attributes.additional_browser_args(args);
}
if !config.file_drop_enabled {
webview_attributes = webview_attributes.disable_file_drop_handler();
}
let mut pending = PendingWindow::with_config(config, webview_attributes, label)?;
pending.http_scheme = http_scheme;
self.pending_windows.push(PendingWindow::with_config(
config,
webview_attributes,
label,
)?);
self.pending_windows.push(pending);
}
#[cfg(any(windows, target_os = "linux"))]
@@ -1705,10 +1704,9 @@ impl<R: Runtime> Builder<R> {
.collect::<Vec<_>>();
for pending in self.pending_windows {
let pending =
app
.manager
.prepare_window(app.handle.clone(), pending, &window_labels, None)?;
let pending = app
.manager
.prepare_window(app.handle.clone(), pending, &window_labels)?;
let detached = app.runtime.as_ref().unwrap().create_window(pending)?;
let _window = app.manager.attach_window(app.handle(), detached);
}

View File

@@ -610,6 +610,19 @@ impl<R: Runtime> SystemTrayHandle<R> {
panic!("item id not found")
}
/// Attempts to get a handle to the menu item that has the specified `id`, return an error if `id` is not found.
pub fn try_get_item(&self, id: MenuIdRef<'_>) -> Option<SystemTrayMenuItemHandle<R>> {
self
.ids
.lock()
.unwrap()
.iter()
.find(|i| i.1 == id)
.map(|i| SystemTrayMenuItemHandle {
id: *i.0,
tray_handler: self.inner.clone(),
})
}
/// Updates the tray icon.
pub fn set_icon(&self, icon: Icon) -> crate::Result<()> {
self.inner.set_icon(icon.try_into()?).map_err(Into::into)

View File

@@ -0,0 +1,228 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![cfg(protocol_asset)]
use crate::api::file::SafePathBuf;
use crate::scope::FsScope;
use rand::RngCore;
use std::io::SeekFrom;
use tauri_runtime::http::HttpRange;
use tauri_runtime::http::{
header::*, status::StatusCode, MimeType, Request, Response, ResponseBuilder,
};
use tauri_utils::debug_eprintln;
use tokio::fs::File;
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
use url::Position;
use url::Url;
pub fn asset_protocol_handler(
request: &Request,
scope: FsScope,
window_origin: String,
) -> Result<Response, Box<dyn std::error::Error>> {
let parsed_path = Url::parse(request.uri())?;
let filtered_path = &parsed_path[..Position::AfterPath];
let path = filtered_path
.strip_prefix("asset://localhost/")
// the `strip_prefix` only returns None when a request is made to `https://tauri.$P` on Windows
// where `$P` is not `localhost/*`
.unwrap_or("");
let path = percent_encoding::percent_decode(path.as_bytes())
.decode_utf8_lossy()
.to_string();
if let Err(e) = SafePathBuf::new(path.clone().into()) {
debug_eprintln!("asset protocol path \"{}\" is not valid: {}", path, e);
return ResponseBuilder::new().status(403).body(Vec::new());
}
if !scope.is_allowed(&path) {
debug_eprintln!("asset protocol not configured to allow the path: {}", path);
return ResponseBuilder::new().status(403).body(Vec::new());
}
let mut resp = ResponseBuilder::new().header("Access-Control-Allow-Origin", &window_origin);
let (mut file, len, mime_type, read_bytes) = crate::async_runtime::safe_block_on(async move {
let mut file = File::open(&path).await?;
// get file length
let len = {
let old_pos = file.stream_position().await?;
let len = file.seek(SeekFrom::End(0)).await?;
file.seek(SeekFrom::Start(old_pos)).await?;
len
};
// get file mime type
let (mime_type, read_bytes) = {
let nbytes = len.min(8192);
let mut magic_buf = Vec::with_capacity(nbytes as usize);
let old_pos = file.stream_position().await?;
(&mut file).take(nbytes).read_to_end(&mut magic_buf).await?;
file.seek(SeekFrom::Start(old_pos)).await?;
(
MimeType::parse(&magic_buf, &path),
// return the `magic_bytes` if we read the whole file
// to avoid reading it again later if this is not a range request
if len < 8192 { Some(magic_buf) } else { None },
)
};
Ok::<(File, u64, String, Option<Vec<u8>>), anyhow::Error>((file, len, mime_type, read_bytes))
})?;
resp = resp.header(CONTENT_TYPE, &mime_type);
// handle 206 (partial range) http requests
let response = if let Some(range_header) = request
.headers()
.get("range")
.and_then(|r| r.to_str().map(|r| r.to_string()).ok())
{
resp = resp.header(ACCEPT_RANGES, "bytes");
let not_satisfiable = || {
ResponseBuilder::new()
.status(StatusCode::RANGE_NOT_SATISFIABLE)
.header(CONTENT_RANGE, format!("bytes */{len}"))
.body(vec![])
};
// parse range header
let ranges = if let Ok(ranges) = HttpRange::parse(&range_header, len) {
ranges
.iter()
// map the output to spec range <start-end>, example: 0-499
.map(|r| (r.start, r.start + r.length - 1))
.collect::<Vec<_>>()
} else {
return not_satisfiable();
};
/// The Maximum bytes we send in one range
const MAX_LEN: u64 = 1000 * 1024;
// single-part range header
if ranges.len() == 1 {
let &(start, mut end) = ranges.first().unwrap();
// check if a range is not satisfiable
//
// this should be already taken care of by the range parsing library
// but checking here again for extra assurance
if start >= len || end >= len || end < start {
return not_satisfiable();
}
// adjust end byte for MAX_LEN
end = start + (end - start).min(len - start).min(MAX_LEN - 1);
// calculate number of bytes needed to be read
let nbytes = end + 1 - start;
let buf = crate::async_runtime::safe_block_on(async move {
let mut buf = Vec::with_capacity(nbytes as usize);
file.seek(SeekFrom::Start(start)).await?;
file.take(nbytes).read_to_end(&mut buf).await?;
Ok::<Vec<u8>, anyhow::Error>(buf)
})?;
resp = resp.header(CONTENT_RANGE, format!("bytes {start}-{end}/{len}"));
resp = resp.header(CONTENT_LENGTH, end + 1 - start);
resp = resp.status(StatusCode::PARTIAL_CONTENT);
resp.body(buf)
} else {
let ranges = ranges
.iter()
.filter_map(|&(start, mut end)| {
// filter out unsatisfiable ranges
//
// this should be already taken care of by the range parsing library
// but checking here again for extra assurance
if start >= len || end >= len || end < start {
None
} else {
// adjust end byte for MAX_LEN
end = start + (end - start).min(len - start).min(MAX_LEN - 1);
Some((start, end))
}
})
.collect::<Vec<_>>();
let boundary = random_boundary();
let boundary_sep = format!("\r\n--{boundary}\r\n");
let boundary_closer = format!("\r\n--{boundary}\r\n");
resp = resp.header(
CONTENT_TYPE,
format!("multipart/byteranges; boundary={boundary}"),
);
let buf = crate::async_runtime::safe_block_on(async move {
// multi-part range header
let mut buf = Vec::new();
for (end, start) in ranges {
// a new range is being written, write the range boundary
buf.write_all(boundary_sep.as_bytes()).await?;
// write the needed headers `Content-Type` and `Content-Range`
buf
.write_all(format!("{CONTENT_TYPE}: {mime_type}\r\n").as_bytes())
.await?;
buf
.write_all(format!("{CONTENT_RANGE}: bytes {start}-{end}/{len}\r\n").as_bytes())
.await?;
// write the separator to indicate the start of the range body
buf.write_all("\r\n".as_bytes()).await?;
// calculate number of bytes needed to be read
let nbytes = end + 1 - start;
let mut local_buf = Vec::with_capacity(nbytes as usize);
file.seek(SeekFrom::Start(start)).await?;
(&mut file).take(nbytes).read_to_end(&mut local_buf).await?;
buf.extend_from_slice(&local_buf);
}
// all ranges have been written, write the closing boundary
buf.write_all(boundary_closer.as_bytes()).await?;
Ok::<Vec<u8>, anyhow::Error>(buf)
})?;
resp.body(buf)
}
} else {
// avoid reading the file if we already read it
// as part of mime type detection
let buf = if let Some(b) = read_bytes {
b
} else {
crate::async_runtime::safe_block_on(async move {
let mut local_buf = Vec::with_capacity(len as usize);
file.read_to_end(&mut local_buf).await?;
Ok::<Vec<u8>, anyhow::Error>(local_buf)
})?
};
resp = resp.header(CONTENT_LENGTH, len);
resp.body(buf)
};
response
}
fn random_boundary() -> String {
let mut x = [0_u8; 30];
rand::thread_rng().fill_bytes(&mut x);
(x[..])
.iter()
.map(|&x| format!("{x:x}"))
.fold(String::new(), |mut a, x| {
a.push_str(x.as_str());
a
})
}

View File

@@ -37,7 +37,7 @@ impl Cmd {
}
fn get_tauri_version<R: Runtime>(_context: InvokeContext<R>) -> super::Result<&'static str> {
Ok(env!("CARGO_PKG_VERSION"))
Ok(crate::VERSION)
}
#[module_command_handler(app_show)]

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