diff --git a/.changes/kuchikiki-bump.md b/.changes/kuchikiki-bump.md new file mode 100644 index 000000000000..db28df43aad6 --- /dev/null +++ b/.changes/kuchikiki-bump.md @@ -0,0 +1,7 @@ +--- +"tauri-cli": minor:deps +"@tauri-apps/cli": minor:deps +"tauri-utils": minor:deps +--- + +Update html5ever to 0.29 and kuchikiki to version 0.8.8-speedreader. diff --git a/.changes/tao-wry-bump.md b/.changes/tao-wry-bump.md new file mode 100644 index 000000000000..d11833ca8d09 --- /dev/null +++ b/.changes/tao-wry-bump.md @@ -0,0 +1,6 @@ +--- +"tauri": minor:deps +"tauri-runtime-wry": minor:deps +--- + +Updated tao to 0.34, wry to 0.52 and webview2-com to 0.38. \ No newline at end of file diff --git a/.changes/x11-feature.md b/.changes/x11-feature.md new file mode 100644 index 000000000000..5928407a29cc --- /dev/null +++ b/.changes/x11-feature.md @@ -0,0 +1,7 @@ +--- +"tauri": minor:feat +"tauri-runtime-wry": minor:feat +--- + +Added `x11` Cargo feature (enabled by default). Disabling it is useful for apps that only support Wayland, reducing its size. +**NOTE**: When manually disabling tauri default features, you must enable the `x11` feature to support it. diff --git a/Cargo.lock b/Cargo.lock index a3ef0569933c..c8b666ba4ac9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14,7 +14,7 @@ version = "0.1.0" dependencies = [ "insta", "serde_json", - "tauri-utils 2.4.0", + "tauri-utils", ] [[package]] @@ -569,7 +569,7 @@ dependencies = [ "http-body-util", "hyper 1.5.2", "hyper-util", - "itoa 1.0.14", + "itoa", "matchit", "memchr", "mime", @@ -1084,7 +1084,7 @@ dependencies = [ "serde_json", "textwrap", "thiserror 2.0.10", - "toml 0.8.19", + "toml", "ureq", "which", "windows 0.61.1", @@ -1121,7 +1121,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02260d489095346e5cafd04dea8e8cb54d1d74fcd759022a9b72986ebe9a1257" dependencies = [ "serde", - "toml 0.8.19", + "toml", ] [[package]] @@ -1347,7 +1347,7 @@ checksum = "3b79c4069c6cad78e2e0cdfcbd26275770669fb39fd308a752dc110e83b9af32" dependencies = [ "castaway", "cfg-if", - "itoa 1.0.14", + "itoa", "rustversion", "ryu", "static_assertions", @@ -1617,15 +1617,15 @@ checksum = "42aaeae719fd78ce501d77c6cdf01f7e96f26bcd5617a4903a1c2b97e388543a" [[package]] name = "cssparser" -version = "0.27.2" +version = "0.29.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "754b69d351cdc2d8ee09ae203db831e005560fc6030da058f86ad60c92a9cb0a" +checksum = "f93d03419cb5950ccfd3daf3ff1c7a36ace64609a1a8746d493df1ca0afde0fa" dependencies = [ "cssparser-macros", "dtoa-short", - "itoa 0.4.8", + "itoa", "matches", - "phf 0.8.0", + "phf 0.10.1", "proc-macro2", "quote", "smallvec", @@ -1957,7 +1957,7 @@ dependencies = [ "libc", "option-ext", "redox_users 0.5.0", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] @@ -2183,7 +2183,7 @@ dependencies = [ "cc", "memchr", "rustc_version", - "toml 0.8.19", + "toml", "vswhom", "winreg 0.52.0", ] @@ -2406,7 +2406,7 @@ dependencies = [ "atomic", "pear", "serde", - "toml 0.8.19", + "toml", "uncased", "version_check", ] @@ -3179,16 +3179,14 @@ dependencies = [ [[package]] name = "html5ever" -version = "0.26.0" +version = "0.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bea68cab48b8459f17cf1c944c67ddc572d272d9f2b274140f223ecb1da4a3b7" +checksum = "3b7410cae13cbc75623c98ac4cbfd1f0bedddf3227afc24f370cf0f50a44a11c" dependencies = [ "log", "mac", "markup5ever", - "proc-macro2", - "quote", - "syn 1.0.109", + "match_token", ] [[package]] @@ -3199,7 +3197,7 @@ checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" dependencies = [ "bytes", "fnv", - "itoa 1.0.14", + "itoa", ] [[package]] @@ -3210,7 +3208,7 @@ checksum = "f16ca2af56261c99fba8bac40a10251ce8188205a4c448fbb745a2e4daa76fea" dependencies = [ "bytes", "fnv", - "itoa 1.0.14", + "itoa", ] [[package]] @@ -3286,7 +3284,7 @@ dependencies = [ "http-body 0.4.6", "httparse", "httpdate", - "itoa 1.0.14", + "itoa", "pin-project-lite", "socket2", "tokio", @@ -3309,7 +3307,7 @@ dependencies = [ "http-body 1.0.1", "httparse", "httpdate", - "itoa 1.0.14", + "itoa", "pin-project-lite", "smallvec", "tokio", @@ -3672,15 +3670,6 @@ dependencies = [ "serde", ] -[[package]] -name = "infer" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f551f8c3a39f68f986517db0d1759de85881894fdc7db798bd2a9df9cb04b7fc" -dependencies = [ - "cfb", -] - [[package]] name = "infer" version = "0.19.0" @@ -3825,12 +3814,6 @@ dependencies = [ "either", ] -[[package]] -name = "itoa" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" - [[package]] name = "itoa" version = "1.0.14" @@ -3918,17 +3901,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "json-patch" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec9ad60d674508f3ca8f380a928cfe7b096bc729c4e2dbfe3852bc45da3ab30b" -dependencies = [ - "serde", - "serde_json", - "thiserror 1.0.69", -] - [[package]] name = "json-patch" version = "3.0.1" @@ -4084,7 +4056,7 @@ dependencies = [ "fancy-regex", "fraction", "idna", - "itoa 1.0.14", + "itoa", "num-cmp", "num-traits", "once_cell", @@ -4180,14 +4152,13 @@ dependencies = [ [[package]] name = "kuchikiki" -version = "0.8.2" +version = "0.8.8-speedreader" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f29e4755b7b995046f510a7520c42b2fed58b77bd94d5a87a8eb43d2fd126da8" +checksum = "02cb977175687f33fa4afa0c95c112b987ea1443e5a51c8f8ff27dc618270cc2" dependencies = [ "cssparser", "html5ever", - "indexmap 1.9.3", - "matches", + "indexmap 2.7.0", "selectors", ] @@ -4423,18 +4394,29 @@ dependencies = [ [[package]] name = "markup5ever" -version = "0.11.0" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2629bb1404f3d34c2e921f21fd34ba00b206124c81f65c50b43b6aaefeb016" +checksum = "c7a7213d12e1864c0f002f52c2923d4556935a43dec5e71355c2760e0f6e7a18" dependencies = [ "log", - "phf 0.10.1", - "phf_codegen 0.10.0", + "phf 0.11.3", + "phf_codegen 0.11.3", "string_cache", "string_cache_codegen", "tendril", ] +[[package]] +name = "match_token" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88a9689d8d44bf9964484516275f5cd4c9b59457a6940c1d5d0ecbb94510a36b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.95", +] + [[package]] name = "matches" version = "0.1.10" @@ -5814,9 +5796,7 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3dfb61232e34fcb633f43d12c58f83c1df82962dcdfa565a4e866ffc17dafe12" dependencies = [ - "phf_macros 0.8.0", "phf_shared 0.8.0", - "proc-macro-hack", ] [[package]] @@ -5825,7 +5805,9 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259" dependencies = [ + "phf_macros 0.10.0", "phf_shared 0.10.0", + "proc-macro-hack", ] [[package]] @@ -5850,12 +5832,12 @@ dependencies = [ [[package]] name = "phf_codegen" -version = "0.10.0" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fb1c3a8bc4dd4e5cfce29b44ffc14bedd2ee294559a294e2a4d4c9e9a6a13cd" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" dependencies = [ - "phf_generator 0.10.0", - "phf_shared 0.10.0", + "phf_generator 0.11.3", + "phf_shared 0.11.3", ] [[package]] @@ -5890,12 +5872,12 @@ dependencies = [ [[package]] name = "phf_macros" -version = "0.8.0" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f6fde18ff429ffc8fe78e2bf7f8b7a5a5a6e2a8b58bc5a9ac69198bbda9189c" +checksum = "58fdf3184dd560f160dd73922bea2d5cd6e8f064bf4b13110abd81b03697b4e0" dependencies = [ - "phf_generator 0.8.0", - "phf_shared 0.8.0", + "phf_generator 0.10.0", + "phf_shared 0.10.0", "proc-macro-hack", "proc-macro2", "quote", @@ -7345,22 +7327,20 @@ dependencies = [ [[package]] name = "selectors" -version = "0.22.0" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df320f1889ac4ba6bc0cdc9c9af7af4bd64bb927bccdf32d81140dc1f9be12fe" +checksum = "0c37578180969d00692904465fb7f6b3d50b9a2b952b87c23d0e2e5cb5013416" dependencies = [ "bitflags 1.3.2", "cssparser", "derive_more 0.99.18", "fxhash", "log", - "matches", "phf 0.8.0", "phf_codegen 0.8.0", "precomputed-hash", "servo_arc", "smallvec", - "thin-slice", ] [[package]] @@ -7480,7 +7460,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b0d7ba2887406110130a978386c4e1befb98c674b4fba677954e4db976630d9" dependencies = [ "indexmap 2.7.0", - "itoa 1.0.14", + "itoa", "memchr", "ryu", "serde", @@ -7492,7 +7472,7 @@ version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af99884400da37c88f5e9146b7f1fd0fbcae8f6eec4e9da38b67d05486f814a6" dependencies = [ - "itoa 1.0.14", + "itoa", "serde", ] @@ -7523,7 +7503,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" dependencies = [ "form_urlencoded", - "itoa 1.0.14", + "itoa", "ryu", "serde", ] @@ -7565,7 +7545,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" dependencies = [ "indexmap 2.7.0", - "itoa 1.0.14", + "itoa", "ryu", "serde", "unsafe-libyaml", @@ -7620,9 +7600,9 @@ dependencies = [ [[package]] name = "servo_arc" -version = "0.1.1" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d98238b800e0d1576d8b6e3de32827c2d74bee68bb97748dcf5071fb53965432" +checksum = "d52aa42f8fdf0fed91e5ce7f23d8138441002fa31dca008acf47e6fd4721f741" dependencies = [ "nodrop", "stable_deref_trait", @@ -8097,7 +8077,7 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c01c27a80b6151b0557f9ccbe89c11db571dc5f68113690c1e028d7e974bae94" dependencies = [ - "itoa 1.0.14", + "itoa", "ryu", "sval", ] @@ -8108,7 +8088,7 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0deef63c70da622b2a8069d8600cf4b05396459e665862e7bdb290fd6cf3f155" dependencies = [ - "itoa 1.0.14", + "itoa", "ryu", "sval", ] @@ -8268,15 +8248,15 @@ dependencies = [ "cfg-expr", "heck 0.5.0", "pkg-config", - "toml 0.8.19", + "toml", "version-compare", ] [[package]] name = "tao" -version = "0.33.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e59c1f38e657351a2e822eadf40d6a2ad4627b9c25557bc1180ec1b3295ef82" +checksum = "49c380ca75a231b87b6c9dd86948f035012e7171d1a7c40a9c2890489a7ffd8a" dependencies = [ "bitflags 2.7.0", "core-foundation 0.10.0", @@ -8391,7 +8371,7 @@ dependencies = [ "tauri-macros", "tauri-runtime", "tauri-runtime-wry", - "tauri-utils 2.4.0", + "tauri-utils", "thiserror 2.0.10", "tokio", "tracing", @@ -8414,16 +8394,16 @@ dependencies = [ "dirs 6.0.0", "glob", "heck 0.5.0", - "json-patch 3.0.1", + "json-patch", "quote", "schemars", "semver", "serde", "serde_json", "tauri-codegen", - "tauri-utils 2.4.0", + "tauri-utils", "tauri-winres", - "toml 0.8.19", + "toml", "walkdir", ] @@ -8458,7 +8438,7 @@ dependencies = [ "tar", "tauri-icns", "tauri-macos-sign", - "tauri-utils 2.4.0", + "tauri-utils", "tempfile", "thiserror 2.0.10", "time", @@ -8501,7 +8481,7 @@ dependencies = [ "include_dir", "insta", "itertools 0.13.0", - "json-patch 3.0.1", + "json-patch", "json5", "jsonrpsee", "jsonrpsee-client-transport", @@ -8539,11 +8519,10 @@ dependencies = [ "tauri-bundler", "tauri-icns", "tauri-macos-sign", - "tauri-utils 1.6.0", - "tauri-utils 2.4.0", + "tauri-utils", "tempfile", "tokio", - "toml 0.8.19", + "toml", "toml_edit 0.22.22", "ureq", "url", @@ -8570,7 +8549,7 @@ dependencies = [ "base64 0.22.1", "brotli", "ico", - "json-patch 3.0.1", + "json-patch", "plist", "png", "proc-macro2", @@ -8580,7 +8559,7 @@ dependencies = [ "serde_json", "sha2", "syn 2.0.95", - "tauri-utils 2.4.0", + "tauri-utils", "thiserror 2.0.10", "time", "url", @@ -8658,7 +8637,7 @@ dependencies = [ "quote", "syn 2.0.95", "tauri-codegen", - "tauri-utils 2.4.0", + "tauri-utils", ] [[package]] @@ -8671,8 +8650,8 @@ dependencies = [ "schemars", "serde", "serde_json", - "tauri-utils 2.4.0", - "toml 0.8.19", + "tauri-utils", + "toml", "walkdir", ] @@ -8723,7 +8702,7 @@ dependencies = [ "raw-window-handle", "serde", "serde_json", - "tauri-utils 2.4.0", + "tauri-utils", "thiserror 2.0.10", "url", "windows 0.61.1", @@ -8746,7 +8725,7 @@ dependencies = [ "softbuffer", "tao", "tauri-runtime", - "tauri-utils 2.4.0", + "tauri-utils", "tracing", "url", "webkit2gtk", @@ -8762,7 +8741,7 @@ dependencies = [ "schemars", "serde", "serde_json", - "tauri-utils 2.4.0", + "tauri-utils", "url", ] @@ -8780,37 +8759,6 @@ dependencies = [ "worker-macros", ] -[[package]] -name = "tauri-utils" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2826db448309d382dac14d520f0c0a40839b87b57b977e59cf5f296b3ace6a93" -dependencies = [ - "aes-gcm", - "ctor", - "dunce", - "getrandom 0.2.15", - "heck 0.5.0", - "html5ever", - "infer 0.13.0", - "json-patch 1.4.0", - "json5", - "kuchikiki", - "log", - "memchr", - "phf 0.11.3", - "schemars", - "semver", - "serde", - "serde_json", - "serde_with", - "serialize-to-javascript", - "thiserror 1.0.69", - "toml 0.7.8", - "url", - "windows-version", -] - [[package]] name = "tauri-utils" version = "2.4.0" @@ -8825,8 +8773,8 @@ dependencies = [ "glob", "html5ever", "http 1.2.0", - "infer 0.19.0", - "json-patch 3.0.1", + "infer", + "json-patch", "json5", "kuchikiki", "log", @@ -8845,7 +8793,7 @@ dependencies = [ "serialize-to-javascript", "swift-rs", "thiserror 2.0.10", - "toml 0.8.19", + "toml", "url", "urlpattern", "uuid", @@ -8859,7 +8807,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56eaa45f707bedf34d19312c26d350bc0f3c59a47e58e8adbeecdc850d2c13a0" dependencies = [ "embed-resource", - "toml 0.8.19", + "toml", ] [[package]] @@ -8929,12 +8877,6 @@ dependencies = [ "unicode-width 0.1.14", ] -[[package]] -name = "thin-slice" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eaa81235c7058867fa8c0e7314f33dcce9c215f535d1913822a2b3f5e289f3c" - [[package]] name = "thiserror" version = "1.0.69" @@ -8993,7 +8935,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35e7868883861bd0e56d9ac6efcaaca0d6d5d82a2a7ec8209ff492c07cf37b21" dependencies = [ "deranged", - "itoa 1.0.14", + "itoa", "libc", "num-conv", "num_threads", @@ -9180,18 +9122,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "toml" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd79e69d3b627db300ff956027cc6c3798cef26d22526befdfcd12feeb6d2257" -dependencies = [ - "serde", - "serde_spanned", - "toml_datetime", - "toml_edit 0.19.15", -] - [[package]] name = "toml" version = "0.8.19" @@ -9221,8 +9151,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ "indexmap 2.7.0", - "serde", - "serde_spanned", "toml_datetime", "winnow 0.5.40", ] @@ -10065,9 +9993,9 @@ dependencies = [ [[package]] name = "webview2-com" -version = "0.37.0" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b542b5cfbd9618c46c2784e4d41ba218c336ac70d44c55e47b251033e7d85601" +checksum = "d4ba622a989277ef3886dd5afb3e280e3dd6d974b766118950a08f8f678ad6a4" dependencies = [ "webview2-com-macros", "webview2-com-sys", @@ -10090,9 +10018,9 @@ dependencies = [ [[package]] name = "webview2-com-sys" -version = "0.37.0" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ae2d11c4a686e4409659d7891791254cf9286d3cfe0eef54df1523533d22295" +checksum = "36695906a1b53a3bf5c4289621efedac12b73eeb0b89e7e1a89b517302d5d75c" dependencies = [ "thiserror 2.0.10", "windows 0.61.1", @@ -10778,9 +10706,9 @@ checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" [[package]] name = "wry" -version = "0.51.2" +version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c886a0a9d2a94fd90cfa1d929629b79cfefb1546e2c7430c63a47f0664c0e4e2" +checksum = "b08db04817a654a7e3339647d9cf8b497ed9ddcd4ec7cfda5a3a220c10a3bba3" dependencies = [ "base64 0.22.1", "block2 0.6.0", diff --git a/crates/tauri-build/Cargo.toml b/crates/tauri-build/Cargo.toml index b0fd33a76ce2..c3fa9f00e616 100644 --- a/crates/tauri-build/Cargo.toml +++ b/crates/tauri-build/Cargo.toml @@ -44,8 +44,8 @@ semver = "1" dirs = "6" glob = "0.3" toml = "0.8" -# Our code requires at least 0.8.18 so don't simplify this to 0.8 -schemars = { version = "0.8.18", features = ["preserve_order"] } +# Our code requires at least 0.8.21 so don't simplify this to 0.8 +schemars = { version = "0.8.21", features = ["preserve_order"] } [features] default = ["config-json"] diff --git a/crates/tauri-cli/Cargo.toml b/crates/tauri-cli/Cargo.toml index 620392e82042..a4ebfc9bc23f 100644 --- a/crates/tauri-cli/Cargo.toml +++ b/crates/tauri-cli/Cargo.toml @@ -65,12 +65,6 @@ tauri-utils = { version = "2.4.0", path = "../tauri-utils", features = [ "config-toml", "html-manipulation", ] } -tauri-utils-v1 = { version = "1", package = "tauri-utils", features = [ - "isolation", - "schema", - "config-json5", - "config-toml", -] } toml = "0.8" jsonschema = "0.30" handlebars = "6" @@ -92,8 +86,8 @@ env_logger = "0.11" icns = { package = "tauri-icns", version = "0.1" } image = { version = "0.25", default-features = false, features = ["ico"] } axum = { version = "0.7", features = ["ws"] } -html5ever = "0.26" -kuchiki = { package = "kuchikiki", version = "0.8" } +html5ever = "0.29" +kuchiki = { package = "kuchikiki", version = "=0.8.8-speedreader" } tokio = { version = "1", features = ["macros", "sync"] } common-path = "1" serde-value = "0.7" diff --git a/crates/tauri-cli/src/dev/builtin_dev_server.rs b/crates/tauri-cli/src/dev/builtin_dev_server.rs index 6751d1fac40b..65ba228f8bb3 100644 --- a/crates/tauri-cli/src/dev/builtin_dev_server.rs +++ b/crates/tauri-cli/src/dev/builtin_dev_server.rs @@ -138,7 +138,9 @@ fn inject_address(html_bytes: Vec, address: &SocketAddr) -> Vec { } } - let mut document = kuchiki::parse_html().one(String::from_utf8_lossy(&html_bytes).into_owned()); + let mut document = kuchiki::parse_html() + .one(String::from_utf8_lossy(&html_bytes).into_owned()) + .document_node; with_html_head(&mut document, |head| { let script = RELOAD_SCRIPT.replace("{{reload_url}}", &format!("ws://{address}/__tauri_cli")); let script_el = NodeRef::new_element(QualName::new(None, ns!(html), "script".into()), None); diff --git a/crates/tauri-cli/src/migrate/migrations/v1/config.rs b/crates/tauri-cli/src/migrate/migrations/v1/config.rs index a11625aee951..e6e8d859332b 100644 --- a/crates/tauri-cli/src/migrate/migrations/v1/config.rs +++ b/crates/tauri-cli/src/migrate/migrations/v1/config.rs @@ -18,7 +18,7 @@ use std::{ pub fn migrate(tauri_dir: &Path) -> Result { if let Ok((mut config, config_path)) = - tauri_utils_v1::config::parse::parse_value(tauri_dir.join("tauri.conf.json")) + tauri_utils::config_v1::parse::parse_value(tauri_dir.join("tauri.conf.json")) { let migrated = migrate_config(&mut config)?; if config_path.extension().is_some_and(|ext| ext == "toml") { @@ -375,16 +375,16 @@ fn process_security(security: &mut Map) -> Result<()> { let csp = if csp_value.is_null() { csp_value } else { - let mut csp: tauri_utils_v1::config::Csp = serde_json::from_value(csp_value)?; + let mut csp: tauri_utils::config_v1::Csp = serde_json::from_value(csp_value)?; match &mut csp { - tauri_utils_v1::config::Csp::Policy(csp) => { + tauri_utils::config_v1::Csp::Policy(csp) => { if csp.contains("connect-src") { *csp = csp.replace("connect-src", "connect-src ipc: http://ipc.localhost"); } else { *csp = format!("{csp}; connect-src ipc: http://ipc.localhost"); } } - tauri_utils_v1::config::Csp::DirectiveMap(csp) => { + tauri_utils::config_v1::Csp::DirectiveMap(csp) => { if let Some(connect_src) = csp.get_mut("connect-src") { if !connect_src.contains("ipc: http://ipc.localhost") { connect_src.push("ipc: http://ipc.localhost"); @@ -392,7 +392,7 @@ fn process_security(security: &mut Map) -> Result<()> { } else { csp.insert( "connect-src".into(), - tauri_utils_v1::config::CspDirectiveSources::List(vec![ + tauri_utils::config_v1::CspDirectiveSources::List(vec![ "ipc: http://ipc.localhost".to_string() ]), ); @@ -422,8 +422,8 @@ fn process_security(security: &mut Map) -> Result<()> { fn process_allowlist( tauri_config: &mut Map, allowlist: Value, -) -> Result { - let allowlist: tauri_utils_v1::config::AllowlistConfig = serde_json::from_value(allowlist)?; +) -> Result { + let allowlist: tauri_utils::config_v1::AllowlistConfig = serde_json::from_value(allowlist)?; if allowlist.protocol.asset_scope != Default::default() { let security = tauri_config @@ -447,7 +447,7 @@ fn process_allowlist( } fn allowlist_to_permissions( - allowlist: tauri_utils_v1::config::AllowlistConfig, + allowlist: tauri_utils::config_v1::AllowlistConfig, ) -> Vec { macro_rules! permissions { ($allowlist: ident, $permissions_list: ident, $object: ident, $field: ident => $associated_permission: expr) => {{ @@ -475,8 +475,8 @@ fn allowlist_to_permissions( permissions!(allowlist, permissions, fs, rename_file => "fs:allow-rename"); permissions!(allowlist, permissions, fs, exists => "fs:allow-exists"); let (fs_allowed, fs_denied) = match allowlist.fs.scope { - tauri_utils_v1::config::FsAllowlistScope::AllowedPaths(paths) => (paths, Vec::new()), - tauri_utils_v1::config::FsAllowlistScope::Scope { allow, deny, .. } => (allow, deny), + tauri_utils::config_v1::FsAllowlistScope::AllowedPaths(paths) => (paths, Vec::new()), + tauri_utils::config_v1::FsAllowlistScope::Scope { allow, deny, .. } => (allow, deny), }; if !(fs_allowed.is_empty() && fs_denied.is_empty()) { let fs_allowed = fs_allowed @@ -568,7 +568,7 @@ fn allowlist_to_permissions( || allowlist.shell.all || !matches!( allowlist.shell.open, - tauri_utils_v1::config::ShellAllowlistOpen::Flag(false) + tauri_utils::config_v1::ShellAllowlistOpen::Flag(false) ) { permissions.push(PermissionEntry::PermissionRef( @@ -990,7 +990,7 @@ mod test { #[test] fn can_migrate_default_config() { - let original = serde_json::to_value(tauri_utils_v1::config::Config::default()).unwrap(); + let original = serde_json::to_value(tauri_utils::config_v1::Config::default()).unwrap(); migrate(&original); } diff --git a/crates/tauri-cli/src/migrate/migrations/v1/manifest.rs b/crates/tauri-cli/src/migrate/migrations/v1/manifest.rs index 9ff9276425b2..866159feb432 100644 --- a/crates/tauri-cli/src/migrate/migrations/v1/manifest.rs +++ b/crates/tauri-cli/src/migrate/migrations/v1/manifest.rs @@ -8,7 +8,7 @@ use crate::{ }; use anyhow::Context; -use tauri_utils_v1::config::Allowlist; +use tauri_utils::config_v1::Allowlist; use toml_edit::{DocumentMut, Entry, Item, TableLike, Value}; use std::path::Path; @@ -163,7 +163,7 @@ fn features_to_rename() -> Vec<(&'static str, &'static str)> { } fn features_to_remove() -> Vec<&'static str> { - let mut features_to_remove = tauri_utils_v1::config::AllowlistConfig::all_features(); + let mut features_to_remove = tauri_utils::config_v1::AllowlistConfig::all_features(); features_to_remove.extend(&[ "reqwest-client", "http-multipart", diff --git a/crates/tauri-plugin/Cargo.toml b/crates/tauri-plugin/Cargo.toml index 72fdaacc60b5..ccc6aade2bc6 100644 --- a/crates/tauri-plugin/Cargo.toml +++ b/crates/tauri-plugin/Cargo.toml @@ -36,8 +36,8 @@ tauri-utils = { version = "2.4.0", default-features = false, features = [ serde_json = { version = "1", optional = true } glob = { version = "0.3", optional = true } toml = { version = "0.8", optional = true } -# Our code requires at least 0.8.18 so don't simplify this to 0.8 -schemars = { version = "0.8.18", features = ["preserve_order"] } +# Our code requires at least 0.8.21 so don't simplify this to 0.8 +schemars = { version = "0.8.21", features = ["preserve_order"] } walkdir = { version = "2", optional = true } [target."cfg(target_os = \"macos\")".dependencies] diff --git a/crates/tauri-runtime-wry/Cargo.toml b/crates/tauri-runtime-wry/Cargo.toml index 6678ec81427b..19bca17830c7 100644 --- a/crates/tauri-runtime-wry/Cargo.toml +++ b/crates/tauri-runtime-wry/Cargo.toml @@ -17,13 +17,13 @@ rustc-args = ["--cfg", "docsrs"] rustdoc-args = ["--cfg", "docsrs"] [dependencies] -wry = { version = "0.51.2", default-features = false, features = [ +wry = { version = "0.52", default-features = false, features = [ "drag-drop", "protocol", "os-webview", "linux-body", ] } -tao = { version = "0.33", default-features = false, features = ["rwh_06"] } +tao = { version = "0.34", default-features = false, features = ["rwh_06"] } tauri-runtime = { version = "2.6.0", path = "../tauri-runtime" } tauri-utils = { version = "2.4.0", path = "../tauri-utils" } raw-window-handle = "0.6" @@ -33,7 +33,7 @@ tracing = { version = "0.1", optional = true } log = "0.4.21" [target."cfg(windows)".dependencies] -webview2-com = "0.37" +webview2-com = "0.38" softbuffer = { version = "0.4", default-features = false } once_cell = "1.20" @@ -65,7 +65,9 @@ objc2-app-kit = { version = "0.3", features = [ jni = "0.21" [features] +default = ["x11"] devtools = ["wry/devtools", "tauri-runtime/devtools"] +x11 = ["tao/x11", "wry/x11"] macos-private-api = [ "wry/fullscreen", "wry/transparent", diff --git a/crates/tauri-runtime-wry/src/lib.rs b/crates/tauri-runtime-wry/src/lib.rs index 7551c7d95edc..13d9bc7ab0a1 100644 --- a/crates/tauri-runtime-wry/src/lib.rs +++ b/crates/tauri-runtime-wry/src/lib.rs @@ -4473,7 +4473,7 @@ You may have it installed on another user account, but it is not available for t } }; - let mut webview_builder = WebViewBuilder::with_web_context(&mut web_context.inner) + let mut webview_builder = WebViewBuilder::new_with_web_context(&mut web_context.inner) .with_id(&label) .with_focused(webview_attributes.focus) .with_url(&url) diff --git a/crates/tauri-schema-generator/Cargo.toml b/crates/tauri-schema-generator/Cargo.toml index 06e3cd7c2a34..d2e8801d43bf 100644 --- a/crates/tauri-schema-generator/Cargo.toml +++ b/crates/tauri-schema-generator/Cargo.toml @@ -6,7 +6,7 @@ publish = false [build-dependencies] tauri-utils = { features = ["schema"], path = "../tauri-utils" } -schemars = { version = "0.8.18", features = ["url", "preserve_order"] } +schemars = { version = "0.8.21", features = ["url", "preserve_order"] } serde = { version = "1", features = ["derive"] } serde_json = "1" url = { version = "2", features = ["serde"] } diff --git a/crates/tauri-utils/Cargo.toml b/crates/tauri-utils/Cargo.toml index e04e601ece9e..a592e0d0bb75 100644 --- a/crates/tauri-utils/Cargo.toml +++ b/crates/tauri-utils/Cargo.toml @@ -22,12 +22,12 @@ brotli = { version = "8", optional = true, default-features = false, features = "std", ] } url = { version = "2", features = ["serde"] } -html5ever = { version = "0.26", optional = true } -kuchiki = { package = "kuchikiki", version = "0.8", optional = true } +html5ever = { version = "0.29", optional = true } +kuchiki = { package = "kuchikiki", version = "0.8.8-speedreader", optional = true } proc-macro2 = { version = "1", optional = true } quote = { version = "1", optional = true } -# Our code requires at least 0.8.18 so don't change this to 0.8 -schemars = { version = "0.8.18", features = ["url", "uuid1"], optional = true } +# Our code requires at least 0.8.21 so don't change this to 0.8 +schemars = { version = "0.8.21", features = ["url", "uuid1"], optional = true } serde_with = "3" aes-gcm = { version = "0.10", optional = true } getrandom = { version = "0.2", optional = true, features = ["std"] } diff --git a/crates/tauri-utils/src/config.rs b/crates/tauri-utils/src/config.rs index a591e53eeb6d..ca243902027d 100644 --- a/crates/tauri-utils/src/config.rs +++ b/crates/tauri-utils/src/config.rs @@ -25,6 +25,8 @@ use http::response::Builder; #[cfg(feature = "schema")] +use schemars::schema::Schema; +#[cfg(feature = "schema")] use schemars::JsonSchema; use semver::Version; use serde::{ @@ -44,6 +46,18 @@ use std::{ str::FromStr, }; +#[cfg(feature = "schema")] +fn add_description(schema: Schema, description: impl Into) -> Schema { + let value = description.into(); + if value.is_empty() { + schema + } else { + let mut schema_obj = schema.into_object(); + schema_obj.metadata().description = value.into(); + Schema::Object(schema_obj) + } +} + /// Items to help with parsing content into a [`Config`]. pub mod parse; @@ -221,14 +235,11 @@ impl schemars::JsonSchema for BundleTarget { ..Default::default() } .into(), - schemars::_private::metadata::add_description( + add_description( gen.subschema_for::>(), "A list of bundle targets.", ), - schemars::_private::metadata::add_description( - gen.subschema_for::(), - "A single bundle target.", - ), + add_description(gen.subschema_for::(), "A single bundle target."), ]; schemars::schema::SchemaObject { diff --git a/crates/tauri-utils/src/config_v1/mod.rs b/crates/tauri-utils/src/config_v1/mod.rs new file mode 100644 index 000000000000..b134caad6985 --- /dev/null +++ b/crates/tauri-utils/src/config_v1/mod.rs @@ -0,0 +1,3189 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +//! The Tauri configuration used at runtime. +//! +//! It is pulled from a `tauri.conf.json` file and the [`Config`] struct is generated at compile time. +//! +//! # Stability +//! This is a core functionality that is not considered part of the stable API. +//! If you use it, note that it may include breaking changes in the future. + +use semver::Version; +use serde::{ + de::{Deserializer, Error as DeError, Visitor}, + Deserialize, Serialize, Serializer, +}; +use serde_json::Value as JsonValue; +use serde_with::skip_serializing_none; +use url::Url; + +use std::{ + collections::HashMap, + fmt::{self, Display}, + fs::read_to_string, + path::PathBuf, + str::FromStr, +}; + +/// Items to help with parsing content into a [`Config`]. +pub mod 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(schemars::JsonSchema))] +#[serde(untagged)] +#[non_exhaustive] +pub enum WindowUrl { + /// An external URL. + External(Url), + /// The path portion of an app URL. + /// For instance, to load `tauri://localhost/users/john`, + /// you can simply provide `users/john` in this configuration. + App(PathBuf), +} + +impl fmt::Display for WindowUrl { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::External(url) => write!(f, "{url}"), + Self::App(path) => write!(f, "{}", path.display()), + } + } +} + +impl Default for WindowUrl { + fn default() -> Self { + Self::App("index.html".into()) + } +} + +/// A bundle referenced by tauri-bundler. +#[derive(Debug, PartialEq, Eq, Clone)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "schema", schemars(rename_all = "lowercase"))] +pub enum BundleType { + /// The debian bundle (.deb). + Deb, + /// The AppImage bundle (.appimage). + AppImage, + /// The Microsoft Installer bundle (.msi). + Msi, + /// The NSIS bundle (.exe). + Nsis, + /// The macOS application bundle (.app). + App, + /// The Apple Disk Image bundle (.dmg). + Dmg, + /// The Tauri updater bundle. + Updater, +} + +impl Display for BundleType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + match self { + Self::Deb => "deb", + Self::AppImage => "appimage", + Self::Msi => "msi", + Self::Nsis => "nsis", + Self::App => "app", + Self::Dmg => "dmg", + Self::Updater => "updater", + } + ) + } +} + +impl Serialize for BundleType { + fn serialize(&self, serializer: S) -> std::result::Result + where + S: Serializer, + { + serializer.serialize_str(self.to_string().as_ref()) + } +} + +impl<'de> Deserialize<'de> for BundleType { + fn deserialize(deserializer: D) -> std::result::Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + match s.to_lowercase().as_str() { + "deb" => Ok(Self::Deb), + "appimage" => Ok(Self::AppImage), + "msi" => Ok(Self::Msi), + "nsis" => Ok(Self::Nsis), + "app" => Ok(Self::App), + "dmg" => Ok(Self::Dmg), + "updater" => Ok(Self::Updater), + _ => Err(DeError::custom(format!("unknown bundle target '{s}'"))), + } + } +} + +/// Targets to bundle. Each value is case insensitive. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum BundleTarget { + /// Bundle all targets. + All, + /// A list of bundle targets. + List(Vec), + /// A single bundle target. + One(BundleType), +} + +#[cfg(feature = "schemars")] +pub(crate) trait Merge: Sized { + fn merge(self, other: Self) -> Self; +} + +#[cfg(feature = "schema")] +use schemars::schema::{Metadata, Schema}; + +#[cfg(feature = "schema")] +impl Merge for Option { + fn merge(self, other: Self) -> Self { + match (self, other) { + (Some(x), Some(y)) => Some(x.merge(y)), + (None, y) => y, + (x, None) => x, + } + } +} + +#[cfg(feature = "schema")] +impl Merge for Box { + fn merge(mut self, other: Self) -> Self { + *self = (*self).merge(*other); + self + } +} + +#[cfg(feature = "schema")] +impl Merge for Vec { + fn merge(mut self, other: Self) -> Self { + self.extend(other); + self + } +} + +#[cfg(feature = "schema")] +impl Merge for Metadata { + fn merge(self, other: Self) -> Self { + Metadata { + id: self.id.or(other.id), + title: self.title.or(other.title), + description: self.description.or(other.description), + default: self.default.or(other.default), + deprecated: self.deprecated || other.deprecated, + read_only: self.read_only || other.read_only, + write_only: self.write_only || other.write_only, + examples: self.examples.merge(other.examples), + } + } +} + +#[cfg(feature = "schema")] +fn apply_metadata(schema: Schema, metadata: Metadata) -> Schema { + if metadata == Metadata::default() { + schema + } else { + let mut schema_obj = schema.into_object(); + schema_obj.metadata = Some(Box::new(metadata)).merge(schema_obj.metadata); + Schema::Object(schema_obj) + } +} + +#[cfg(feature = "schema")] +impl schemars::JsonSchema for BundleTarget { + fn schema_name() -> std::string::String { + "BundleTarget".to_owned() + } + + fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + let any_of = vec![ + schemars::schema::SchemaObject { + enum_values: Some(vec!["all".into()]), + metadata: Some(Box::new(schemars::schema::Metadata { + description: Some("Bundle all targets.".to_owned()), + ..Default::default() + })), + ..Default::default() + } + .into(), + apply_metadata( + gen.subschema_for::>(), + schemars::schema::Metadata { + description: Some("A list of bundle targets.".to_owned()), + ..Default::default() + }, + ), + apply_metadata( + gen.subschema_for::(), + schemars::schema::Metadata { + description: Some("A single bundle target.".to_owned()), + ..Default::default() + }, + ), + ]; + + schemars::schema::SchemaObject { + subschemas: Some(Box::new(schemars::schema::SubschemaValidation { + any_of: Some(any_of), + ..Default::default() + })), + metadata: Some(Box::new(schemars::schema::Metadata { + description: Some("Targets to bundle. Each value is case insensitive.".to_owned()), + ..Default::default() + })), + ..Default::default() + } + .into() + } +} + +impl Default for BundleTarget { + fn default() -> Self { + Self::All + } +} + +impl Serialize for BundleTarget { + fn serialize(&self, serializer: S) -> std::result::Result + where + S: Serializer, + { + match self { + Self::All => serializer.serialize_str("all"), + Self::List(l) => l.serialize(serializer), + Self::One(t) => serializer.serialize_str(t.to_string().as_ref()), + } + } +} + +impl<'de> Deserialize<'de> for BundleTarget { + fn deserialize(deserializer: D) -> std::result::Result + where + D: Deserializer<'de>, + { + #[derive(Deserialize, Serialize)] + #[serde(untagged)] + pub enum BundleTargetInner { + List(Vec), + One(BundleType), + All(String), + } + + match BundleTargetInner::deserialize(deserializer)? { + BundleTargetInner::All(s) if s.to_lowercase() == "all" => Ok(Self::All), + BundleTargetInner::All(t) => Err(DeError::custom(format!("invalid bundle type {t}"))), + BundleTargetInner::List(l) => Ok(Self::List(l)), + BundleTargetInner::One(t) => Ok(Self::One(t)), + } + } +} + +/// Configuration for AppImage bundles. +/// +/// See more: https://tauri.app/v1/api/config#appimageconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct AppImageConfig { + /// Include additional gstreamer dependencies needed for audio and video playback. + /// This increases the bundle size by ~15-35MB depending on your build system. + #[serde(default, alias = "bundle-media-framework")] + pub bundle_media_framework: bool, +} + +/// Configuration for Debian (.deb) bundles. +/// +/// See more: https://tauri.app/v1/api/config#debconfig +#[skip_serializing_none] +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DebConfig { + /// The list of deb dependencies your application relies on. + pub depends: Option>, + /// The files to include on the package. + #[serde(default)] + pub files: HashMap, + /// Path to a custom desktop file Handlebars template. + /// + /// Available variables: `categories`, `comment` (optional), `exec`, `icon` and `name`. + pub desktop_template: Option, + /// Define the section in Debian Control file. See : https://www.debian.org/doc/debian-policy/ch-archive.html#s-subsections + pub section: Option, + /// Change the priority of the Debian Package. By default, it is set to `optional`. + /// Recognized Priorities as of now are : `required`, `important`, `standard`, `optional`, `extra` + pub priority: Option, + /// Path of the uncompressed Changelog file, to be stored at /usr/share/doc/package-name/changelog.gz. See + /// https://www.debian.org/doc/debian-policy/ch-docs.html#changelog-files-and-release-notes + pub changelog: Option, +} + +fn de_minimum_system_version<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + let version = Option::::deserialize(deserializer)?; + match version { + Some(v) if v.is_empty() => Ok(minimum_system_version()), + e => Ok(e), + } +} + +/// Configuration for the macOS bundles. +/// +/// See more: https://tauri.app/v1/api/config#macconfig +#[skip_serializing_none] +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct MacConfig { + /// A list of strings indicating any macOS X frameworks that need to be bundled with the application. + /// + /// If a name is used, ".framework" must be omitted and it will look for standard install locations. You may also use a path to a specific framework. + pub frameworks: Option>, + /// A version string indicating the minimum macOS X version that the bundled application supports. Defaults to `10.13`. + /// + /// Setting it to `null` completely removes the `LSMinimumSystemVersion` field on the bundle's `Info.plist` + /// and the `MACOSX_DEPLOYMENT_TARGET` environment variable. + /// + /// An empty string is considered an invalid value so the default value is used. + #[serde( + deserialize_with = "de_minimum_system_version", + default = "minimum_system_version", + alias = "minimum-system-version" + )] + pub minimum_system_version: Option, + /// Allows your application to communicate with the outside world. + /// It should be a lowercase, without port and protocol domain name. + #[serde(alias = "exception-domain")] + pub exception_domain: Option, + /// The path to the license file to add to the DMG bundle. + pub license: Option, + /// Identity to use for code signing. + #[serde(alias = "signing-identity")] + pub signing_identity: Option, + /// Provider short name for notarization. + #[serde(alias = "provider-short-name")] + pub provider_short_name: Option, + /// Path to the entitlements file. + pub entitlements: Option, +} + +impl Default for MacConfig { + fn default() -> Self { + Self { + frameworks: None, + minimum_system_version: minimum_system_version(), + exception_domain: None, + license: None, + signing_identity: None, + provider_short_name: None, + entitlements: None, + } + } +} + +fn minimum_system_version() -> Option { + Some("10.13".into()) +} + +/// Configuration for a target language for the WiX build. +/// +/// See more: https://tauri.app/v1/api/config#wixlanguageconfig +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WixLanguageConfig { + /// The path to a locale (`.wxl`) file. See . + #[serde(alias = "locale-path")] + pub locale_path: Option, +} + +/// The languages to build using WiX. +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(untagged)] +pub enum WixLanguage { + /// A single language to build, without configuration. + One(String), + /// A list of languages to build, without configuration. + List(Vec), + /// A map of languages and its configuration. + Localized(HashMap), +} + +impl Default for WixLanguage { + fn default() -> Self { + Self::One("en-US".into()) + } +} + +/// Configuration for the MSI bundle using WiX. +/// +/// See more: https://tauri.app/v1/api/config#wixconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WixConfig { + /// The installer languages to build. See . + #[serde(default)] + pub language: WixLanguage, + /// A custom .wxs template to use. + pub template: Option, + /// A list of paths to .wxs files with WiX fragments to use. + #[serde(default, alias = "fragment-paths")] + pub fragment_paths: Vec, + /// The ComponentGroup element ids you want to reference from the fragments. + #[serde(default, alias = "component-group-refs")] + pub component_group_refs: Vec, + /// The Component element ids you want to reference from the fragments. + #[serde(default, alias = "component-refs")] + pub component_refs: Vec, + /// The FeatureGroup element ids you want to reference from the fragments. + #[serde(default, alias = "feature-group-refs")] + pub feature_group_refs: Vec, + /// The Feature element ids you want to reference from the fragments. + #[serde(default, alias = "feature-refs")] + pub feature_refs: Vec, + /// The Merge element ids you want to reference from the fragments. + #[serde(default, alias = "merge-refs")] + pub merge_refs: Vec, + /// Disables the Webview2 runtime installation after app install. + /// + /// Will be removed in v2, prefer the [`WindowsConfig::webview_install_mode`] option. + #[serde(default, alias = "skip-webview-install")] + pub skip_webview_install: bool, + /// The path to the license file to render on the installer. + /// + /// Must be an RTF file, so if a different extension is provided, we convert it to the RTF format. + pub license: Option, + /// Create an elevated update task within Windows Task Scheduler. + #[serde(default, alias = "enable-elevated-update-task")] + pub enable_elevated_update_task: bool, + /// Path to a bitmap file to use as the installation user interface banner. + /// This bitmap will appear at the top of all but the first page of the installer. + /// + /// The required dimensions are 493px × 58px. + #[serde(alias = "banner-path")] + pub banner_path: Option, + /// Path to a bitmap file to use on the installation user interface dialogs. + /// It is used on the welcome and completion dialogs. + + /// The required dimensions are 493px × 312px. + #[serde(alias = "dialog-image-path")] + pub dialog_image_path: Option, +} + +/// Compression algorithms used in the NSIS installer. +/// +/// See +#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::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(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct NsisConfig { + /// A custom .nsi template to use. + pub template: Option, + /// The path to the license file to render on the installer. + pub license: Option, + /// The path to a bitmap file to display on the header of installers pages. + /// + /// The recommended dimensions are 150px x 57px. + #[serde(alias = "header-image")] + pub header_image: Option, + /// The path to a bitmap file for the Welcome page and the Finish page. + /// + /// The recommended dimensions are 164px x 314px. + #[serde(alias = "sidebar-image")] + pub sidebar_image: Option, + /// The path to an icon file used as the installer icon. + #[serde(alias = "install-icon")] + pub installer_icon: Option, + /// Whether the installation will be for all users or just the current user. + #[serde(default, alias = "install-mode")] + pub install_mode: NSISInstallerMode, + /// A list of installer languages. + /// By default the OS language is used. If the OS language is not in the list of languages, the first language will be used. + /// To allow the user to select the language, set `display_language_selector` to `true`. + /// + /// See for the complete list of languages. + pub languages: Option>, + /// 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 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>, + /// 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 + pub compression: Option, +} + +/// Install Modes for the NSIS installer. +#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub enum NSISInstallerMode { + /// Default mode for the installer. + /// + /// Install the app by default in a directory that doesn't require Administrator access. + /// + /// Installer metadata will be saved under the `HKCU` registry path. + CurrentUser, + /// Install the app by default in the `Program Files` folder directory requires Administrator + /// access for the installation. + /// + /// Installer metadata will be saved under the `HKLM` registry path. + PerMachine, + /// Combines both modes and allows the user to choose at install time + /// whether to install for the current user or per machine. Note that this mode + /// will require Administrator access even if the user wants to install it for the current user only. + /// + /// Installer metadata will be saved under the `HKLM` or `HKCU` registry path based on the user's choice. + Both, +} + +impl Default for NSISInstallerMode { + fn default() -> Self { + Self::CurrentUser + } +} + +/// Install modes for the Webview2 runtime. +/// Note that for the updater bundle [`Self::DownloadBootstrapper`] is used. +/// +/// For more information see . +#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub enum WebviewInstallMode { + /// Do not install the Webview2 as part of the Windows Installer. + Skip, + /// Download the bootstrapper and run it. + /// Requires an internet connection. + /// 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_true")] + silent: bool, + }, + /// Embed the bootstrapper and run it. + /// Requires an internet connection. + /// 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_true")] + silent: bool, + }, + /// Embed the offline installer and run it. + /// Does not require an internet connection. + /// Increases the installer size by around 127MB. + OfflineInstaller { + /// Instructs the installer to run the installer in silent mode. Defaults to `true`. + #[serde(default = "default_true")] + silent: bool, + }, + /// Embed a fixed webview2 version and use it at runtime. + /// Increases the installer size by around 180MB. + FixedRuntime { + /// The path to the fixed runtime to use. + /// + /// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section). + /// The `.cab` file must be extracted to a folder and this folder path must be defined on this field. + path: PathBuf, + }, +} + +impl Default for WebviewInstallMode { + fn default() -> Self { + Self::DownloadBootstrapper { silent: true } + } +} + +/// Windows bundler configuration. +/// +/// See more: https://tauri.app/v1/api/config#windowsconfig +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WindowsConfig { + /// Specifies the file digest algorithm to use for creating file signatures. + /// Required for code signing. SHA-256 is recommended. + #[serde(alias = "digest-algorithm")] + pub digest_algorithm: Option, + /// Specifies the SHA1 hash of the signing certificate. + #[serde(alias = "certificate-thumbprint")] + pub certificate_thumbprint: Option, + /// Server to use during timestamping. + #[serde(alias = "timestamp-url")] + pub timestamp_url: Option, + /// Whether to use Time-Stamp Protocol (TSP, a.k.a. RFC 3161) for the timestamp server. Your code signing provider may + /// use a TSP timestamp server, like e.g. SSL.com does. If so, enable TSP by setting to true. + #[serde(default)] + pub tsp: bool, + /// The installation mode for the Webview2 runtime. + #[serde(default, alias = "webview-install-mode")] + pub webview_install_mode: WebviewInstallMode, + /// Path to the webview fixed runtime to use. Overwrites [`Self::webview_install_mode`] if set. + /// + /// Will be removed in v2, prefer the [`Self::webview_install_mode`] option. + /// + /// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section). + /// The `.cab` file must be extracted to a folder and this folder path must be defined on this field. + #[serde(alias = "webview-fixed-runtime-path")] + pub webview_fixed_runtime_path: Option, + /// Validates a second app installation, blocking the user from installing an older version if set to `false`. + /// + /// 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_true", alias = "allow-downgrades")] + pub allow_downgrades: bool, + /// Configuration for the MSI generated with WiX. + pub wix: Option, + /// Configuration for the installer generated with NSIS. + pub nsis: Option, +} + +impl Default for WindowsConfig { + fn default() -> Self { + Self { + digest_algorithm: None, + certificate_thumbprint: None, + timestamp_url: None, + tsp: false, + webview_install_mode: Default::default(), + webview_fixed_runtime_path: None, + allow_downgrades: true, + wix: None, + nsis: None, + } + } +} + +/// 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(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)] +pub enum BundleResources { + /// A list of paths to include. + List(Vec), + /// A map of source to target paths. + Map(HashMap), +} + +/// Configuration for tauri-bundler. +/// +/// See more: https://tauri.app/v1/api/config#bundleconfig +#[skip_serializing_none] +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BundleConfig { + /// Whether Tauri should bundle your application or just output the executable. + #[serde(default)] + pub active: bool, + /// The bundle targets, currently supports ["deb", "appimage", "nsis", "msi", "app", "dmg", "updater"] or "all". + #[serde(default)] + pub targets: BundleTarget, + /// The application identifier in reverse domain name notation (e.g. `com.tauri.example`). + /// This string must be unique across applications since it is used in system configurations like + /// the bundle ID and path to the webview data directory. + /// This string must contain only alphanumeric characters (A–Z, a–z, and 0–9), hyphens (-), + /// and periods (.). + pub identifier: String, + /// The application's publisher. Defaults to the second element in the identifier string. + /// Currently maps to the Manufacturer property of the Windows Installer. + pub publisher: Option, + /// The app's icons + #[serde(default)] + pub icon: Vec, + /// App resources to bundle. + /// Each resource is a path to a file or directory. + /// Glob patterns are supported. + pub resources: Option, + /// A copyright string associated with your application. + pub copyright: Option, + /// The application kind. + /// + /// Should be one of the following: + /// Business, DeveloperTool, Education, Entertainment, Finance, Game, ActionGame, AdventureGame, ArcadeGame, BoardGame, CardGame, CasinoGame, DiceGame, EducationalGame, FamilyGame, KidsGame, MusicGame, PuzzleGame, RacingGame, RolePlayingGame, SimulationGame, SportsGame, StrategyGame, TriviaGame, WordGame, GraphicsAndDesign, HealthcareAndFitness, Lifestyle, Medical, Music, News, Photography, Productivity, Reference, SocialNetworking, Sports, Travel, Utility, Video, Weather. + pub category: Option, + /// A short description of your application. + #[serde(alias = "short-description")] + pub short_description: Option, + /// A longer, multi-line description of the application. + #[serde(alias = "long-description")] + pub long_description: Option, + /// Configuration for the AppImage bundle. + #[serde(default)] + pub appimage: AppImageConfig, + /// Configuration for the Debian bundle. + #[serde(default)] + pub deb: DebConfig, + /// Configuration for the macOS bundles. + #[serde(rename = "macOS", default)] + pub macos: MacConfig, + /// A list of—either absolute or relative—paths to binaries to embed with your application. + /// + /// Note that Tauri will look for system-specific binaries following the pattern "binary-name{-target-triple}{.system-extension}". + /// + /// E.g. for the external binary "my-binary", Tauri looks for: + /// + /// - "my-binary-x86_64-pc-windows-msvc.exe" for Windows + /// - "my-binary-x86_64-apple-darwin" for macOS + /// - "my-binary-x86_64-unknown-linux-gnu" for Linux + /// + /// so don't forget to provide binaries for all targeted platforms. + #[serde(alias = "external-bin")] + pub external_bin: Option>, + /// Configuration for the Windows bundle. + #[serde(default)] + pub windows: WindowsConfig, +} + +/// A CLI argument definition. +#[skip_serializing_none] +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CliArg { + /// The short version of the argument, without the preceding -. + /// + /// NOTE: Any leading `-` characters will be stripped, and only the first non-character will be used as the short version. + pub short: Option, + /// The unique argument name + pub name: String, + /// The argument description which will be shown on the help information. + /// Typically, this is a short (one line) description of the arg. + pub description: Option, + /// The argument long description which will be shown on the help information. + /// Typically this a more detailed (multi-line) message that describes the argument. + #[serde(alias = "long-description")] + pub long_description: Option, + /// Specifies that the argument takes a value at run time. + /// + /// NOTE: values for arguments may be specified in any of the following methods + /// - Using a space such as -o value or --option value + /// - Using an equals and no space such as -o=value or --option=value + /// - Use a short and no space such as -ovalue + #[serde(default, alias = "takes-value")] + pub takes_value: bool, + /// Specifies that the argument may have an unknown number of multiple values. Without any other settings, this argument may appear only once. + /// + /// For example, --opt val1 val2 is allowed, but --opt val1 val2 --opt val3 is not. + /// + /// NOTE: Setting this requires `takes_value` to be set to true. + #[serde(default)] + pub multiple: bool, + /// Specifies that the argument may appear more than once. + /// For flags, this results in the number of occurrences of the flag being recorded. For example -ddd or -d -d -d would count as three occurrences. + /// For options or arguments that take a value, this does not affect how many values they can accept. (i.e. only one at a time is allowed) + /// + /// For example, --opt val1 --opt val2 is allowed, but --opt val1 val2 is not. + #[serde(default, alias = "multiple-occurrences")] + pub multiple_occurrences: bool, + /// Specifies how many values are required to satisfy this argument. For example, if you had a + /// `-f ` argument where you wanted exactly 3 'files' you would set + /// `number_of_values = 3`, and this argument wouldn't be satisfied unless the user provided + /// 3 and only 3 values. + /// + /// **NOTE:** Does *not* require `multiple_occurrences = true` to be set. Setting + /// `multiple_occurrences = true` would allow `-f -f ` where + /// as *not* setting it would only allow one occurrence of this argument. + /// + /// **NOTE:** implicitly sets `takes_value = true` and `multiple_values = true`. + #[serde(alias = "number-of-values")] + pub number_of_values: Option, + /// Specifies a list of possible values for this argument. + /// At runtime, the CLI verifies that only one of the specified values was used, or fails with an error message. + #[serde(alias = "possible-values")] + pub possible_values: Option>, + /// Specifies the minimum number of values for this argument. + /// For example, if you had a -f `` argument where you wanted at least 2 'files', + /// you would set `minValues: 2`, and this argument would be satisfied if the user provided, 2 or more values. + #[serde(alias = "min-values")] + pub min_values: Option, + /// Specifies the maximum number of values are for this argument. + /// For example, if you had a -f `` argument where you wanted up to 3 'files', + /// you would set .max_values(3), and this argument would be satisfied if the user provided, 1, 2, or 3 values. + #[serde(alias = "max-values")] + pub max_values: Option, + /// Sets whether or not the argument is required by default. + /// + /// - Required by default means it is required, when no other conflicting rules have been evaluated + /// - Conflicting rules take precedence over being required. + #[serde(default)] + pub required: bool, + /// Sets an arg that override this arg's required setting + /// i.e. this arg will be required unless this other argument is present. + #[serde(alias = "required-unless-present")] + pub required_unless_present: Option, + /// Sets args that override this arg's required setting + /// i.e. this arg will be required unless all these other arguments are present. + #[serde(alias = "required-unless-present-all")] + pub required_unless_present_all: Option>, + /// Sets args that override this arg's required setting + /// i.e. this arg will be required unless at least one of these other arguments are present. + #[serde(alias = "required-unless-present-any")] + pub required_unless_present_any: Option>, + /// Sets a conflicting argument by name + /// i.e. when using this argument, the following argument can't be present and vice versa. + #[serde(alias = "conflicts-with")] + pub conflicts_with: Option, + /// The same as conflictsWith but allows specifying multiple two-way conflicts per argument. + #[serde(alias = "conflicts-with-all")] + pub conflicts_with_all: Option>, + /// Tets an argument by name that is required when this one is present + /// i.e. when using this argument, the following argument must be present. + pub requires: Option, + /// Sts multiple arguments by names that are required when this one is present + /// i.e. when using this argument, the following arguments must be present. + #[serde(alias = "requires-all")] + pub requires_all: Option>, + /// Allows a conditional requirement with the signature [arg, value] + /// the requirement will only become valid if `arg`'s value equals `${value}`. + #[serde(alias = "requires-if")] + pub requires_if: Option>, + /// Allows specifying that an argument is required conditionally with the signature [arg, value] + /// the requirement will only become valid if the `arg`'s value equals `${value}`. + #[serde(alias = "requires-if-eq")] + pub required_if_eq: Option>, + /// Requires that options use the --option=val syntax + /// i.e. an equals between the option and associated value. + #[serde(alias = "requires-equals")] + pub require_equals: Option, + /// The positional argument index, starting at 1. + /// + /// The index refers to position according to other positional argument. + /// It does not define position in the argument list as a whole. When utilized with multiple=true, + /// only the last positional argument may be defined as multiple (i.e. the one with the highest index). + #[cfg_attr(feature = "schema", validate(range(min = 1)))] + pub index: Option, +} + +/// describes a CLI configuration +/// +/// See more: https://tauri.app/v1/api/config#cliconfig +#[skip_serializing_none] +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CliConfig { + /// Command description which will be shown on the help information. + pub description: Option, + /// Command long description which will be shown on the help information. + #[serde(alias = "long-description")] + pub long_description: Option, + /// Adds additional help information to be displayed in addition to auto-generated help. + /// This information is displayed before the auto-generated help information. + /// This is often used for header information. + #[serde(alias = "before-help")] + pub before_help: Option, + /// Adds additional help information to be displayed in addition to auto-generated help. + /// This information is displayed after the auto-generated help information. + /// This is often used to describe how to use the arguments, or caveats to be noted. + #[serde(alias = "after-help")] + pub after_help: Option, + /// List of arguments for the command + pub args: Option>, + /// List of subcommands of this command + pub subcommands: Option>, +} + +/// The window configuration object. +/// +/// See more: https://tauri.app/v1/api/config#windowconfig +#[skip_serializing_none] +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WindowConfig { + /// The window identifier. It must be alphanumeric. + #[serde(default = "default_window_label")] + pub label: String, + /// The window webview URL. + #[serde(default)] + pub url: WindowUrl, + /// The user agent for the webview + #[serde(alias = "user-agent")] + pub user_agent: Option, + /// 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_true", alias = "file-drop-enabled")] + pub file_drop_enabled: bool, + /// Whether or not the window starts centered or not. + #[serde(default)] + pub center: bool, + /// The horizontal position of the window's top left corner + pub x: Option, + /// The vertical position of the window's top left corner + pub y: Option, + /// The window width. + #[serde(default = "default_width")] + pub width: f64, + /// The window height. + #[serde(default = "default_height")] + pub height: f64, + /// The min window width. + #[serde(alias = "min-width")] + pub min_width: Option, + /// The min window height. + #[serde(alias = "min-height")] + pub min_height: Option, + /// The max window width. + #[serde(alias = "max-width")] + pub max_width: Option, + /// The max window height. + #[serde(alias = "max-height")] + pub max_height: Option, + /// 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, + /// Whether the window starts as fullscreen or not. + #[serde(default)] + pub fullscreen: bool, + /// Whether the window will be initially focused or not. + #[serde(default = "default_true")] + pub focus: bool, + /// Whether the window is transparent or not. + /// + /// Note that on `macOS` this requires the `macos-private-api` feature flag, enabled under `tauri > macOSPrivateApi`. + /// WARNING: Using private APIs on `macOS` prevents your application from being accepted to the `App Store`. + #[serde(default)] + pub transparent: bool, + /// Whether the window is maximized or not. + #[serde(default)] + pub maximized: bool, + /// Whether the window is visible or not. + #[serde(default = "default_true")] + pub visible: bool, + /// Whether the window should have borders and bars. + #[serde(default = "default_true")] + pub decorations: bool, + /// Whether the window should always be on top of other windows. + #[serde(default, alias = "always-on-top")] + pub always_on_top: bool, + /// Prevents the window contents from being captured by other apps. + #[serde(default, alias = "content-protected")] + pub content_protected: bool, + /// If `true`, hides the window icon from the taskbar on Windows and Linux. + #[serde(default, alias = "skip-taskbar")] + pub skip_taskbar: bool, + /// The initial window theme. Defaults to the system theme. Only implemented on Windows and macOS 10.14+. + pub theme: Option, + /// The style of the macOS title bar. + #[serde(default, alias = "title-bar-style")] + pub title_bar_style: TitleBarStyle, + /// If `true`, sets the window title to be hidden on macOS. + #[serde(default, alias = "hidden-title")] + pub hidden_title: bool, + /// Whether clicking an inactive window also clicks through to the webview on macOS. + #[serde(default, alias = "accept-first-mouse")] + pub accept_first_mouse: bool, + /// Defines the window [tabbing identifier] for macOS. + /// + /// Windows with matching tabbing identifiers will be grouped together. + /// If the tabbing identifier is not set, automatic tabbing will be disabled. + /// + /// [tabbing identifier]: + #[serde(default, alias = "tabbing-identifier")] + pub tabbing_identifier: Option, + /// Defines additional browser arguments on Windows. By default wry passes `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection` + /// so if you use this method, you also need to disable these components by yourself if you want. + #[serde(default, alias = "additional-browser-args")] + pub additional_browser_args: Option, +} + +impl Default for WindowConfig { + fn default() -> Self { + Self { + label: default_window_label(), + url: WindowUrl::default(), + user_agent: None, + file_drop_enabled: true, + center: false, + x: None, + y: None, + width: default_width(), + height: default_height(), + min_width: None, + min_height: None, + max_width: None, + max_height: None, + resizable: true, + maximizable: true, + minimizable: true, + closable: true, + title: default_title(), + fullscreen: false, + focus: false, + transparent: false, + maximized: false, + visible: true, + decorations: true, + always_on_top: false, + content_protected: false, + skip_taskbar: false, + theme: None, + title_bar_style: Default::default(), + hidden_title: false, + accept_first_mouse: false, + tabbing_identifier: None, + additional_browser_args: None, + } + } +} + +fn default_window_label() -> String { + "main".to_string() +} + +fn default_width() -> f64 { + 800f64 +} + +fn default_height() -> f64 { + 600f64 +} + +fn default_title() -> String { + "Tauri App".to_string() +} + +/// A Content-Security-Policy directive source list. +/// See . +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", untagged)] +pub enum CspDirectiveSources { + /// An inline list of CSP sources. Same as [`Self::List`], but concatenated with a space separator. + Inline(String), + /// A list of CSP sources. The collection will be concatenated with a space separator for the CSP string. + List(Vec), +} + +impl Default for CspDirectiveSources { + fn default() -> Self { + Self::List(Vec::new()) + } +} + +impl From for Vec { + fn from(sources: CspDirectiveSources) -> Self { + match sources { + CspDirectiveSources::Inline(source) => source.split(' ').map(|s| s.to_string()).collect(), + CspDirectiveSources::List(l) => l, + } + } +} + +impl CspDirectiveSources { + /// Whether the given source is configured on this directive or not. + pub fn contains(&self, source: &str) -> bool { + match self { + Self::Inline(s) => s.contains(&format!("{source} ")) || s.contains(&format!(" {source}")), + Self::List(l) => l.contains(&source.into()), + } + } + + /// Appends the given source to this directive. + pub fn push>(&mut self, source: S) { + match self { + Self::Inline(s) => { + s.push(' '); + s.push_str(source.as_ref()); + } + Self::List(l) => { + l.push(source.as_ref().to_string()); + } + } + } +} + +/// A Content-Security-Policy definition. +/// See . +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", untagged)] +pub enum Csp { + /// The entire CSP policy in a single text string. + Policy(String), + /// An object mapping a directive with its sources values as a list of strings. + DirectiveMap(HashMap), +} + +impl From> for Csp { + fn from(map: HashMap) -> Self { + Self::DirectiveMap(map) + } +} + +impl From for HashMap { + fn from(csp: Csp) -> Self { + match csp { + Csp::Policy(policy) => { + let mut map = HashMap::new(); + for directive in policy.split(';') { + let mut tokens = directive.trim().split(' '); + if let Some(directive) = tokens.next() { + let sources = tokens.map(|s| s.to_string()).collect::>(); + map.insert(directive.to_string(), CspDirectiveSources::List(sources)); + } + } + map + } + Csp::DirectiveMap(m) => m, + } + } +} + +impl Display for Csp { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Policy(s) => write!(f, "{s}"), + Self::DirectiveMap(m) => { + let len = m.len(); + let mut i = 0; + for (directive, sources) in m { + let sources: Vec = sources.clone().into(); + write!(f, "{} {}", directive, sources.join(" "))?; + i += 1; + if i != len { + write!(f, "; ")?; + } + } + Ok(()) + } + } + } +} + +/// The possible values for the `dangerous_disable_asset_csp_modification` config option. +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub enum DisabledCspModificationKind { + /// If `true`, disables all CSP modification. + /// `false` is the default value and it configures Tauri to control the CSP. + Flag(bool), + /// Disables the given list of CSP directives modifications. + List(Vec), +} + +impl Default for DisabledCspModificationKind { + fn default() -> Self { + Self::Flag(false) + } +} + +/// External command access definition. +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RemoteDomainAccessScope { + /// The URL scheme to allow. By default, all schemas are allowed. + pub scheme: Option, + /// The domain to allow. + pub domain: String, + /// The list of window labels this scope applies to. + pub windows: Vec, + /// 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, + /// Enables access to the Tauri API. + #[serde(default, rename = "enableTauriAPI", alias = "enable-tauri-api")] + pub enable_tauri_api: bool, +} + +/// Security configuration. +/// +/// See more: https://tauri.app/v1/api/config#securityconfig +#[skip_serializing_none] +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SecurityConfig { + /// The Content Security Policy that will be injected on all HTML files on the built application. + /// If [`dev_csp`](#SecurityConfig.devCsp) is not specified, this value is also injected on dev. + /// + /// This is a really important part of the configuration since it helps you ensure your WebView is secured. + /// See . + pub csp: Option, + /// The Content Security Policy that will be injected on all HTML files on development. + /// + /// This is a really important part of the configuration since it helps you ensure your WebView is secured. + /// See . + #[serde(alias = "dev-csp")] + pub dev_csp: Option, + /// Freeze the `Object.prototype` when using the custom protocol. + #[serde(default, alias = "freeze-prototype")] + pub freeze_prototype: bool, + /// Disables the Tauri-injected CSP sources. + /// + /// At compile time, Tauri parses all the frontend assets and changes the Content-Security-Policy + /// to only allow loading of your own scripts and styles by injecting nonce and hash sources. + /// This stricts your CSP, which may introduce issues when using along with other flexing sources. + /// + /// This configuration option allows both a boolean and a list of strings as value. + /// A boolean instructs Tauri to disable the injection for all CSP injections, + /// and a list of strings indicates the CSP directives that Tauri cannot inject. + /// + /// **WARNING:** Only disable this if you know what you are doing and have properly configured the CSP. + /// Your application might be vulnerable to XSS attacks without this Tauri protection. + #[serde(default, alias = "dangerous-disable-asset-csp-modification")] + pub dangerous_disable_asset_csp_modification: DisabledCspModificationKind, + /// Allow external domains to send command to Tauri. + /// + /// By default, external domains do not have access to `window.__TAURI__`, which means they cannot + /// communicate with the commands defined in Rust. This prevents attacks where an externally + /// loaded malicious or compromised sites could start executing commands on the user's device. + /// + /// This configuration allows a set of external domains to have access to the Tauri commands. + /// When you configure a domain to be allowed to access the IPC, all subpaths are allowed. Subdomains are not allowed. + /// + /// **WARNING:** Only use this option if you either have internal checks against malicious + /// external sites or you can trust the allowed external sites. You application might be + /// vulnerable to dangerous Tauri command related attacks otherwise. + #[serde(default, alias = "dangerous-remote-domain-ipc-access")] + pub dangerous_remote_domain_ipc_access: Vec, + /// Sets whether the custom protocols should use `http://.localhost` instead of the default `https://.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 `://localhost` protocols used on macOS and Linux. + #[serde(default, alias = "dangerous-use-http-scheme")] + pub dangerous_use_http_scheme: bool, +} + +/// Defines an allowlist type. +pub trait Allowlist { + /// Returns all features associated with the allowlist struct. + fn all_features() -> Vec<&'static str>; + /// Returns the tauri features enabled on this allowlist. + fn to_features(&self) -> Vec<&'static str>; +} + +macro_rules! check_feature { + ($self:ident, $features:ident, $flag:ident, $feature_name: expr) => { + if $self.$flag { + $features.push($feature_name) + } + }; +} + +/// Filesystem scope definition. +/// It is a list of glob patterns that restrict the API access from the webview. +/// +/// Each pattern can start with a variable that resolves to a system base directory. +/// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, +/// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, +/// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, +/// `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`. +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub enum FsAllowlistScope { + /// A list of paths that are allowed by this scope. + AllowedPaths(Vec), + /// A complete scope configuration. + #[serde(rename_all = "camelCase")] + Scope { + /// A list of paths that are allowed by this scope. + #[serde(default)] + allow: Vec, + /// A list of paths that are not allowed by this scope. + /// This gets precedence over the [`Self::Scope::allow`] list. + #[serde(default)] + deny: Vec, + /// 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, + }, +} + +impl Default for FsAllowlistScope { + fn default() -> Self { + Self::AllowedPaths(Vec::new()) + } +} + +/// Allowlist for the file system APIs. +/// +/// See more: https://tauri.app/v1/api/config#fsallowlistconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct FsAllowlistConfig { + /// The access scope for the filesystem APIs. + #[serde(default)] + pub scope: FsAllowlistScope, + /// Use this flag to enable all file system API features. + #[serde(default)] + pub all: bool, + /// Read file from local filesystem. + #[serde(default, alias = "read-file")] + pub read_file: bool, + /// Write file to local filesystem. + #[serde(default, alias = "write-file")] + pub write_file: bool, + /// Read directory from local filesystem. + #[serde(default, alias = "read-dir")] + pub read_dir: bool, + /// Copy file from local filesystem. + #[serde(default, alias = "copy-file")] + pub copy_file: bool, + /// Create directory from local filesystem. + #[serde(default, alias = "create-dir")] + pub create_dir: bool, + /// Remove directory from local filesystem. + #[serde(default, alias = "remove-dir")] + pub remove_dir: bool, + /// Remove file from local filesystem. + #[serde(default, alias = "remove-file")] + pub remove_file: bool, + /// Rename file from local filesystem. + #[serde(default, alias = "rename-file")] + pub rename_file: bool, + /// Check if path exists on the local filesystem. + #[serde(default)] + pub exists: bool, +} + +impl Allowlist for FsAllowlistConfig { + fn all_features() -> Vec<&'static str> { + let allowlist = Self { + scope: Default::default(), + all: false, + read_file: true, + write_file: true, + read_dir: true, + copy_file: true, + create_dir: true, + remove_dir: true, + remove_file: true, + rename_file: true, + exists: true, + }; + let mut features = allowlist.to_features(); + features.push("fs-all"); + features + } + + fn to_features(&self) -> Vec<&'static str> { + if self.all { + vec!["fs-all"] + } else { + let mut features = Vec::new(); + check_feature!(self, features, read_file, "fs-read-file"); + check_feature!(self, features, write_file, "fs-write-file"); + check_feature!(self, features, read_dir, "fs-read-dir"); + check_feature!(self, features, copy_file, "fs-copy-file"); + check_feature!(self, features, create_dir, "fs-create-dir"); + check_feature!(self, features, remove_dir, "fs-remove-dir"); + check_feature!(self, features, remove_file, "fs-remove-file"); + check_feature!(self, features, rename_file, "fs-rename-file"); + check_feature!(self, features, exists, "fs-exists"); + features + } + } +} + +/// Allowlist for the window APIs. +/// +/// See more: https://tauri.app/v1/api/config#windowallowlistconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WindowAllowlistConfig { + /// Use this flag to enable all window API features. + #[serde(default)] + pub all: bool, + /// Allows dynamic window creation. + #[serde(default)] + pub create: bool, + /// Allows centering the window. + #[serde(default)] + pub center: bool, + /// Allows requesting user attention on the window. + #[serde(default, alias = "request-user-attention")] + pub request_user_attention: bool, + /// 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, + /// Allows maximizing the window. + #[serde(default)] + pub maximize: bool, + /// Allows unmaximizing the window. + #[serde(default)] + pub unmaximize: bool, + /// Allows minimizing the window. + #[serde(default)] + pub minimize: bool, + /// Allows unminimizing the window. + #[serde(default)] + pub unminimize: bool, + /// Allows showing the window. + #[serde(default)] + pub show: bool, + /// Allows hiding the window. + #[serde(default)] + pub hide: bool, + /// Allows closing the window. + #[serde(default)] + pub close: bool, + /// Allows setting the decorations flag of the window. + #[serde(default, alias = "set-decorations")] + pub set_decorations: bool, + /// Allows setting the always_on_top flag of the window. + #[serde(default, alias = "set-always-on-top")] + pub set_always_on_top: bool, + /// Allows preventing the window contents from being captured by other apps. + #[serde(default, alias = "set-content-protected")] + pub set_content_protected: bool, + /// Allows setting the window size. + #[serde(default, alias = "set-size")] + pub set_size: bool, + /// Allows setting the window minimum size. + #[serde(default, alias = "set-min-size")] + pub set_min_size: bool, + /// Allows setting the window maximum size. + #[serde(default, alias = "set-max-size")] + pub set_max_size: bool, + /// Allows changing the position of the window. + #[serde(default, alias = "set-position")] + pub set_position: bool, + /// Allows setting the fullscreen flag of the window. + #[serde(default, alias = "set-fullscreen")] + pub set_fullscreen: bool, + /// Allows focusing the window. + #[serde(default, alias = "set-focus")] + pub set_focus: bool, + /// Allows changing the window icon. + #[serde(default, alias = "set-icon")] + pub set_icon: bool, + /// Allows setting the skip_taskbar flag of the window. + #[serde(default, alias = "set-skip-taskbar")] + pub set_skip_taskbar: bool, + /// Allows grabbing the cursor. + #[serde(default, alias = "set-cursor-grab")] + pub set_cursor_grab: bool, + /// Allows setting the cursor visibility. + #[serde(default, alias = "set-cursor-visible")] + pub set_cursor_visible: bool, + /// Allows changing the cursor icon. + #[serde(default, alias = "set-cursor-icon")] + pub set_cursor_icon: bool, + /// Allows setting the cursor position. + #[serde(default, alias = "set-cursor-position")] + pub set_cursor_position: bool, + /// Allows ignoring cursor events. + #[serde(default, alias = "set-ignore-cursor-events")] + pub set_ignore_cursor_events: bool, + /// Allows start dragging on the window. + #[serde(default, alias = "start-dragging")] + pub start_dragging: bool, + /// Allows opening the system dialog to print the window content. + #[serde(default)] + pub print: bool, +} + +impl Allowlist for WindowAllowlistConfig { + fn all_features() -> Vec<&'static str> { + let allowlist = Self { + all: false, + create: true, + 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, + minimize: true, + unminimize: true, + show: true, + hide: true, + close: true, + set_decorations: true, + set_always_on_top: true, + set_content_protected: false, + set_size: true, + set_min_size: true, + set_max_size: true, + set_position: true, + set_fullscreen: true, + set_focus: true, + set_icon: true, + set_skip_taskbar: true, + set_cursor_grab: true, + set_cursor_visible: true, + set_cursor_icon: true, + set_cursor_position: true, + set_ignore_cursor_events: true, + start_dragging: true, + print: true, + }; + let mut features = allowlist.to_features(); + features.push("window-all"); + features + } + + fn to_features(&self) -> Vec<&'static str> { + if self.all { + vec!["window-all"] + } else { + let mut features = Vec::new(); + check_feature!(self, features, create, "window-create"); + check_feature!(self, features, center, "window-center"); + check_feature!( + self, + features, + request_user_attention, + "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"); + check_feature!(self, features, minimize, "window-minimize"); + check_feature!(self, features, unminimize, "window-unminimize"); + check_feature!(self, features, show, "window-show"); + check_feature!(self, features, hide, "window-hide"); + check_feature!(self, features, close, "window-close"); + check_feature!(self, features, set_decorations, "window-set-decorations"); + check_feature!( + self, + features, + set_always_on_top, + "window-set-always-on-top" + ); + check_feature!( + self, + features, + set_content_protected, + "window-set-content-protected" + ); + check_feature!(self, features, set_size, "window-set-size"); + check_feature!(self, features, set_min_size, "window-set-min-size"); + check_feature!(self, features, set_max_size, "window-set-max-size"); + check_feature!(self, features, set_position, "window-set-position"); + check_feature!(self, features, set_fullscreen, "window-set-fullscreen"); + check_feature!(self, features, set_focus, "window-set-focus"); + check_feature!(self, features, set_icon, "window-set-icon"); + check_feature!(self, features, set_skip_taskbar, "window-set-skip-taskbar"); + check_feature!(self, features, set_cursor_grab, "window-set-cursor-grab"); + check_feature!( + self, + features, + set_cursor_visible, + "window-set-cursor-visible" + ); + check_feature!(self, features, set_cursor_icon, "window-set-cursor-icon"); + check_feature!( + self, + features, + set_cursor_position, + "window-set-cursor-position" + ); + check_feature!( + self, + features, + set_ignore_cursor_events, + "window-set-ignore-cursor-events" + ); + check_feature!(self, features, start_dragging, "window-start-dragging"); + check_feature!(self, features, print, "window-print"); + features + } + } +} + +/// A command allowed to be executed by the webview API. +#[derive(Debug, PartialEq, Eq, Clone, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub struct ShellAllowedCommand { + /// The name for this allowed shell command configuration. + /// + /// This name will be used inside of the webview API to call this command along with + /// any specified arguments. + pub name: String, + + /// The command name. + /// It can start with a variable that resolves to a system base directory. + /// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, + /// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, + /// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, + /// `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`. + #[serde(rename = "cmd", default)] // use default just so the schema doesn't flag it as required + pub command: PathBuf, + + /// The allowed arguments for the command execution. + #[serde(default)] + pub args: ShellAllowedArgs, + + /// If this command is a sidecar command. + #[serde(default)] + pub sidecar: bool, +} + +impl<'de> Deserialize<'de> for ShellAllowedCommand { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + #[derive(Deserialize)] + struct InnerShellAllowedCommand { + name: String, + #[serde(rename = "cmd")] + command: Option, + #[serde(default)] + args: ShellAllowedArgs, + #[serde(default)] + sidecar: bool, + } + + let config = InnerShellAllowedCommand::deserialize(deserializer)?; + + if !config.sidecar && config.command.is_none() { + return Err(DeError::custom( + "The shell scope `command` value is required.", + )); + } + + Ok(ShellAllowedCommand { + name: config.name, + command: config.command.unwrap_or_default(), + args: config.args, + sidecar: config.sidecar, + }) + } +} + +/// A set of command arguments allowed to be executed by the webview API. +/// +/// A value of `true` will allow any arguments to be passed to the command. `false` will disable all +/// arguments. A list of [`ShellAllowedArg`] will set those arguments as the only valid arguments to +/// be passed to the attached command configuration. +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(untagged, deny_unknown_fields)] +#[non_exhaustive] +pub enum ShellAllowedArgs { + /// Use a simple boolean to allow all or disable all arguments to this command configuration. + Flag(bool), + + /// A specific set of [`ShellAllowedArg`] that are valid to call for the command configuration. + List(Vec), +} + +impl Default for ShellAllowedArgs { + fn default() -> Self { + Self::Flag(false) + } +} + +/// A command argument allowed to be executed by the webview API. +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(untagged, deny_unknown_fields)] +#[non_exhaustive] +pub enum ShellAllowedArg { + /// A non-configurable argument that is passed to the command in the order it was specified. + Fixed(String), + + /// A variable that is set while calling the command from the webview API. + /// + Var { + /// [regex] validator to require passed values to conform to an expected input. + /// + /// This will require the argument value passed to this variable to match the `validator` regex + /// before it will be executed. + /// + /// [regex]: https://docs.rs/regex/latest/regex/#syntax + validator: String, + }, +} + +/// Shell scope definition. +/// It is a list of command names and associated CLI arguments that restrict the API access from the webview. +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub struct ShellAllowlistScope(pub Vec); + +/// Defines the `shell > open` api scope. +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(untagged, deny_unknown_fields)] +#[non_exhaustive] +pub enum ShellAllowlistOpen { + /// If the shell open API should be enabled. + /// + /// If enabled, the default validation regex (`^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+`) is used. + Flag(bool), + + /// Enable the shell open API, with a custom regex that the opened path must match against. + /// + /// If using a custom regex to support a non-http(s) schema, care should be used to prevent values + /// that allow flag-like strings to pass validation. e.g. `--enable-debugging`, `-i`, `/R`. + Validate(String), +} + +impl Default for ShellAllowlistOpen { + fn default() -> Self { + Self::Flag(false) + } +} + +/// Allowlist for the shell APIs. +/// +/// See more: https://tauri.app/v1/api/config#shellallowlistconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ShellAllowlistConfig { + /// Access scope for the binary execution APIs. + /// Sidecars are automatically enabled. + #[serde(default)] + pub scope: ShellAllowlistScope, + /// Use this flag to enable all shell API features. + #[serde(default)] + pub all: bool, + /// Enable binary execution. + #[serde(default)] + pub execute: bool, + /// Enable sidecar execution, allowing the JavaScript layer to spawn a sidecar command, + /// an executable that is shipped with the application. + /// For more information see . + #[serde(default)] + pub sidecar: bool, + /// Open URL with the user's default application. + #[serde(default)] + pub open: ShellAllowlistOpen, +} + +impl Allowlist for ShellAllowlistConfig { + fn all_features() -> Vec<&'static str> { + let allowlist = Self { + scope: Default::default(), + all: false, + execute: true, + sidecar: true, + open: ShellAllowlistOpen::Flag(true), + }; + let mut features = allowlist.to_features(); + features.push("shell-all"); + features + } + + fn to_features(&self) -> Vec<&'static str> { + if self.all { + vec!["shell-all"] + } else { + let mut features = Vec::new(); + check_feature!(self, features, execute, "shell-execute"); + check_feature!(self, features, sidecar, "shell-sidecar"); + + if !matches!(self.open, ShellAllowlistOpen::Flag(false)) { + features.push("shell-open") + } + + features + } + } +} + +/// Allowlist for the dialog APIs. +/// +/// See more: https://tauri.app/v1/api/config#dialogallowlistconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DialogAllowlistConfig { + /// Use this flag to enable all dialog API features. + #[serde(default)] + pub all: bool, + /// Allows the API to open a dialog window to pick files. + #[serde(default)] + pub open: bool, + /// Allows the API to open a dialog window to pick where to save files. + #[serde(default)] + pub save: bool, + /// Allows the API to show a message dialog window. + #[serde(default)] + pub message: bool, + /// Allows the API to show a dialog window with Yes/No buttons. + #[serde(default)] + pub ask: bool, + /// Allows the API to show a dialog window with Ok/Cancel buttons. + #[serde(default)] + pub confirm: bool, +} + +impl Allowlist for DialogAllowlistConfig { + fn all_features() -> Vec<&'static str> { + let allowlist = Self { + all: false, + open: true, + save: true, + message: true, + ask: true, + confirm: true, + }; + let mut features = allowlist.to_features(); + features.push("dialog-all"); + features + } + + fn to_features(&self) -> Vec<&'static str> { + if self.all { + vec!["dialog-all"] + } else { + let mut features = Vec::new(); + check_feature!(self, features, open, "dialog-open"); + check_feature!(self, features, save, "dialog-save"); + check_feature!(self, features, message, "dialog-message"); + check_feature!(self, features, ask, "dialog-ask"); + check_feature!(self, features, confirm, "dialog-confirm"); + features + } + } +} + +/// 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. +/// +/// Examples: +/// - "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(schemars::JsonSchema))] +pub struct HttpAllowlistScope(pub Vec); + +/// Allowlist for the HTTP APIs. +/// +/// See more: https://tauri.app/v1/api/config#httpallowlistconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct HttpAllowlistConfig { + /// The access scope for the HTTP APIs. + #[serde(default)] + pub scope: HttpAllowlistScope, + /// Use this flag to enable all HTTP API features. + #[serde(default)] + pub all: bool, + /// Allows making HTTP requests. + #[serde(default)] + pub request: bool, +} + +impl Allowlist for HttpAllowlistConfig { + fn all_features() -> Vec<&'static str> { + let allowlist = Self { + scope: Default::default(), + all: false, + request: true, + }; + let mut features = allowlist.to_features(); + features.push("http-all"); + features + } + + fn to_features(&self) -> Vec<&'static str> { + if self.all { + vec!["http-all"] + } else { + let mut features = Vec::new(); + check_feature!(self, features, request, "http-request"); + features + } + } +} + +/// Allowlist for the notification APIs. +/// +/// See more: https://tauri.app/v1/api/config#notificationallowlistconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct NotificationAllowlistConfig { + /// Use this flag to enable all notification API features. + #[serde(default)] + pub all: bool, +} + +impl Allowlist for NotificationAllowlistConfig { + fn all_features() -> Vec<&'static str> { + let allowlist = Self { all: false }; + let mut features = allowlist.to_features(); + features.push("notification-all"); + features + } + + fn to_features(&self) -> Vec<&'static str> { + if self.all { + vec!["notification-all"] + } else { + vec![] + } + } +} + +/// Allowlist for the global shortcut APIs. +/// +/// See more: https://tauri.app/v1/api/config#globalshortcutallowlistconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct GlobalShortcutAllowlistConfig { + /// Use this flag to enable all global shortcut API features. + #[serde(default)] + pub all: bool, +} + +impl Allowlist for GlobalShortcutAllowlistConfig { + fn all_features() -> Vec<&'static str> { + let allowlist = Self { all: false }; + let mut features = allowlist.to_features(); + features.push("global-shortcut-all"); + features + } + + fn to_features(&self) -> Vec<&'static str> { + if self.all { + vec!["global-shortcut-all"] + } else { + vec![] + } + } +} + +/// Allowlist for the OS APIs. +/// +/// See more: https://tauri.app/v1/api/config#osallowlistconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct OsAllowlistConfig { + /// Use this flag to enable all OS API features. + #[serde(default)] + pub all: bool, +} + +impl Allowlist for OsAllowlistConfig { + fn all_features() -> Vec<&'static str> { + let allowlist = Self { all: false }; + let mut features = allowlist.to_features(); + features.push("os-all"); + features + } + + fn to_features(&self) -> Vec<&'static str> { + if self.all { + vec!["os-all"] + } else { + vec![] + } + } +} + +/// Allowlist for the path APIs. +/// +/// See more: https://tauri.app/v1/api/config#pathallowlistconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PathAllowlistConfig { + /// Use this flag to enable all path API features. + #[serde(default)] + pub all: bool, +} + +impl Allowlist for PathAllowlistConfig { + fn all_features() -> Vec<&'static str> { + let allowlist = Self { all: false }; + let mut features = allowlist.to_features(); + features.push("path-all"); + features + } + + fn to_features(&self) -> Vec<&'static str> { + if self.all { + vec!["path-all"] + } else { + vec![] + } + } +} + +/// Allowlist for the custom protocols. +/// +/// See more: https://tauri.app/v1/api/config#protocolallowlistconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProtocolAllowlistConfig { + /// The access scope for the asset protocol. + #[serde(default, alias = "asset-scope")] + pub asset_scope: FsAllowlistScope, + /// Use this flag to enable all custom protocols. + #[serde(default)] + pub all: bool, + /// Enables the asset protocol. + #[serde(default)] + pub asset: bool, +} + +impl Allowlist for ProtocolAllowlistConfig { + fn all_features() -> Vec<&'static str> { + let allowlist = Self { + asset_scope: Default::default(), + all: false, + asset: true, + }; + let mut features = allowlist.to_features(); + features.push("protocol-all"); + features + } + + fn to_features(&self) -> Vec<&'static str> { + if self.all { + vec!["protocol-all"] + } else { + let mut features = Vec::new(); + check_feature!(self, features, asset, "protocol-asset"); + features + } + } +} + +/// Allowlist for the process APIs. +/// +/// See more: https://tauri.app/v1/api/config#processallowlistconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProcessAllowlistConfig { + /// Use this flag to enable all process APIs. + #[serde(default)] + pub all: bool, + /// Enables the relaunch API. + #[serde(default)] + pub relaunch: bool, + /// Dangerous option that allows macOS to relaunch even if the binary contains a symlink. + /// + /// This is due to macOS having less symlink protection. Highly recommended to not set this flag + /// unless you have a very specific reason too, and understand the implications of it. + #[serde( + default, + alias = "relaunchDangerousAllowSymlinkMacOS", + alias = "relaunch-dangerous-allow-symlink-macos" + )] + pub relaunch_dangerous_allow_symlink_macos: bool, + /// Enables the exit API. + #[serde(default)] + pub exit: bool, +} + +impl Allowlist for ProcessAllowlistConfig { + fn all_features() -> Vec<&'static str> { + let allowlist = Self { + all: false, + relaunch: true, + relaunch_dangerous_allow_symlink_macos: false, + exit: true, + }; + let mut features = allowlist.to_features(); + features.push("process-all"); + features + } + + fn to_features(&self) -> Vec<&'static str> { + if self.all { + vec!["process-all"] + } else { + let mut features = Vec::new(); + check_feature!(self, features, relaunch, "process-relaunch"); + check_feature!( + self, + features, + relaunch_dangerous_allow_symlink_macos, + "process-relaunch-dangerous-allow-symlink-macos" + ); + check_feature!(self, features, exit, "process-exit"); + features + } + } +} + +/// Allowlist for the clipboard APIs. +/// +/// See more: https://tauri.app/v1/api/config#clipboardallowlistconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ClipboardAllowlistConfig { + /// Use this flag to enable all clipboard APIs. + #[serde(default)] + pub all: bool, + /// Enables the clipboard's `writeText` API. + #[serde(default, alias = "writeText")] + pub write_text: bool, + /// Enables the clipboard's `readText` API. + #[serde(default, alias = "readText")] + pub read_text: bool, +} + +impl Allowlist for ClipboardAllowlistConfig { + fn all_features() -> Vec<&'static str> { + let allowlist = Self { + all: false, + write_text: true, + read_text: true, + }; + let mut features = allowlist.to_features(); + features.push("clipboard-all"); + features + } + + fn to_features(&self) -> Vec<&'static str> { + if self.all { + vec!["clipboard-all"] + } else { + let mut features = Vec::new(); + check_feature!(self, features, write_text, "clipboard-write-text"); + check_feature!(self, features, read_text, "clipboard-read-text"); + features + } + } +} + +/// Allowlist for the app APIs. +/// +/// See more: https://tauri.app/v1/api/config#appallowlistconfig +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct AppAllowlistConfig { + /// Use this flag to enable all app APIs. + #[serde(default)] + pub all: bool, + /// Enables the app's `show` API. + #[serde(default)] + pub show: bool, + /// Enables the app's `hide` API. + #[serde(default)] + pub hide: bool, +} + +impl Allowlist for AppAllowlistConfig { + fn all_features() -> Vec<&'static str> { + let allowlist = Self { + all: false, + show: true, + hide: true, + }; + let mut features = allowlist.to_features(); + features.push("app-all"); + features + } + + fn to_features(&self) -> Vec<&'static str> { + if self.all { + vec!["app-all"] + } else { + let mut features = Vec::new(); + check_feature!(self, features, show, "app-show"); + check_feature!(self, features, hide, "app-hide"); + features + } + } +} + +/// Allowlist configuration. The allowlist is a translation of the [Cargo allowlist features](https://docs.rs/tauri/latest/tauri/#cargo-allowlist-features). +/// +/// # Notes +/// +/// - 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. +/// +/// # Examples +/// +/// - * [`"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. +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct AllowlistConfig { + /// Use this flag to enable all API features. + #[serde(default)] + pub all: bool, + /// File system API allowlist. + #[serde(default)] + pub fs: FsAllowlistConfig, + /// Window API allowlist. + #[serde(default)] + pub window: WindowAllowlistConfig, + /// Shell API allowlist. + #[serde(default)] + pub shell: ShellAllowlistConfig, + /// Dialog API allowlist. + #[serde(default)] + pub dialog: DialogAllowlistConfig, + /// HTTP API allowlist. + #[serde(default)] + pub http: HttpAllowlistConfig, + /// Notification API allowlist. + #[serde(default)] + pub notification: NotificationAllowlistConfig, + /// Global shortcut API allowlist. + #[serde(default, alias = "global-shortcut")] + pub global_shortcut: GlobalShortcutAllowlistConfig, + /// OS allowlist. + #[serde(default)] + pub os: OsAllowlistConfig, + /// Path API allowlist. + #[serde(default)] + pub path: PathAllowlistConfig, + /// Custom protocol allowlist. + #[serde(default)] + pub protocol: ProtocolAllowlistConfig, + /// Process API allowlist. + #[serde(default)] + pub process: ProcessAllowlistConfig, + /// Clipboard APIs allowlist. + #[serde(default)] + pub clipboard: ClipboardAllowlistConfig, + /// App APIs allowlist. + #[serde(default)] + pub app: AppAllowlistConfig, +} + +impl Allowlist for AllowlistConfig { + fn all_features() -> Vec<&'static str> { + let mut features = vec!["api-all"]; + features.extend(FsAllowlistConfig::all_features()); + features.extend(WindowAllowlistConfig::all_features()); + features.extend(ShellAllowlistConfig::all_features()); + features.extend(DialogAllowlistConfig::all_features()); + features.extend(HttpAllowlistConfig::all_features()); + features.extend(NotificationAllowlistConfig::all_features()); + features.extend(GlobalShortcutAllowlistConfig::all_features()); + features.extend(OsAllowlistConfig::all_features()); + features.extend(PathAllowlistConfig::all_features()); + features.extend(ProtocolAllowlistConfig::all_features()); + features.extend(ProcessAllowlistConfig::all_features()); + features.extend(ClipboardAllowlistConfig::all_features()); + features.extend(AppAllowlistConfig::all_features()); + features + } + + fn to_features(&self) -> Vec<&'static str> { + if self.all { + vec!["api-all"] + } else { + let mut features = Vec::new(); + features.extend(self.fs.to_features()); + features.extend(self.window.to_features()); + features.extend(self.shell.to_features()); + features.extend(self.dialog.to_features()); + features.extend(self.http.to_features()); + features.extend(self.notification.to_features()); + features.extend(self.global_shortcut.to_features()); + features.extend(self.os.to_features()); + features.extend(self.path.to_features()); + features.extend(self.protocol.to_features()); + features.extend(self.process.to_features()); + features.extend(self.clipboard.to_features()); + features.extend(self.app.to_features()); + features + } + } +} + +/// The application pattern. +#[skip_serializing_none] +#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] +#[serde(rename_all = "lowercase", tag = "use", content = "options")] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub enum PatternKind { + /// Brownfield pattern. + Brownfield, + /// Isolation pattern. Recommended for security purposes. + Isolation { + /// The dir containing the index.html file that contains the secure isolation application. + dir: PathBuf, + }, +} + +impl Default for PatternKind { + fn default() -> Self { + Self::Brownfield + } +} + +/// The Tauri configuration object. +/// +/// See more: https://tauri.app/v1/api/config#tauriconfig +#[skip_serializing_none] +#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct TauriConfig { + /// The pattern to use. + #[serde(default)] + pub pattern: PatternKind, + /// The windows configuration. + #[serde(default)] + pub windows: Vec, + /// The CLI configuration. + pub cli: Option, + /// The bundler configuration. + #[serde(default)] + pub bundle: BundleConfig, + /// The allowlist configuration. + #[serde(default)] + pub allowlist: AllowlistConfig, + /// Security configuration. + #[serde(default)] + pub security: SecurityConfig, + /// The updater configuration. + #[serde(default)] + pub updater: UpdaterConfig, + /// Configuration for app system tray. + #[serde(alias = "system-tray")] + pub system_tray: Option, + /// MacOS private API configuration. Enables the transparent background API and sets the `fullScreenEnabled` preference to `true`. + #[serde(rename = "macOSPrivateApi", alias = "macos-private-api", default)] + pub macos_private_api: bool, +} + +/// A URL to an updater server. +/// +/// The URL must use the `https` scheme on production. +#[skip_serializing_none] +#[derive(Debug, PartialEq, Eq, Clone, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub struct UpdaterEndpoint(pub Url); + +impl std::fmt::Display for UpdaterEndpoint { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +impl<'de> Deserialize<'de> for UpdaterEndpoint { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let url = Url::deserialize(deserializer)?; + #[cfg(all(not(debug_assertions), not(feature = "schema")))] + { + if url.scheme() != "https" { + return Err(serde::de::Error::custom( + "The configured updater endpoint must use the `https` protocol.", + )); + } + } + Ok(Self(url)) + } +} + +/// Install modes for the Windows update. +#[derive(Debug, PartialEq, Eq, Clone)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "schema", schemars(rename_all = "camelCase"))] +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. + Quiet, + /// Specifies unattended mode, which means the installation only shows a progress bar. + Passive, + // to add more modes, we need to check if the updater relaunch makes sense + // i.e. for a full UI mode, the user can also mark the installer to start the app +} + +impl Display for WindowsUpdateInstallMode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + match self { + Self::BasicUi => "basicUI", + Self::Quiet => "quiet", + Self::Passive => "passive", + } + ) + } +} + +impl Default for WindowsUpdateInstallMode { + fn default() -> Self { + Self::Passive + } +} + +impl Serialize for WindowsUpdateInstallMode { + fn serialize(&self, serializer: S) -> std::result::Result + where + S: Serializer, + { + serializer.serialize_str(self.to_string().as_ref()) + } +} + +impl<'de> Deserialize<'de> for WindowsUpdateInstallMode { + fn deserialize(deserializer: D) -> std::result::Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + match s.to_lowercase().as_str() { + "basicui" => Ok(Self::BasicUi), + "quiet" => Ok(Self::Quiet), + "passive" => Ok(Self::Passive), + _ => Err(DeError::custom(format!( + "unknown update install mode '{s}'" + ))), + } + } +} + +/// The updater configuration for Windows. +/// +/// See more: https://tauri.app/v1/api/config#updaterwindowsconfig +#[skip_serializing_none] +#[derive(Debug, Default, PartialEq, Eq, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct UpdaterWindowsConfig { + /// Additional arguments given to the NSIS or WiX installer. + #[serde(default, alias = "installer-args")] + pub installer_args: Vec, + /// The installation mode for the update on Windows. Defaults to `passive`. + #[serde(default, alias = "install-mode")] + pub install_mode: WindowsUpdateInstallMode, +} + +/// The Updater configuration object. +/// +/// See more: https://tauri.app/v1/api/config#updaterconfig +#[skip_serializing_none] +#[derive(Debug, PartialEq, Eq, Clone, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct UpdaterConfig { + /// Whether the updater is active or not. + #[serde(default)] + pub active: bool, + /// Display built-in dialog or use event system if disabled. + #[serde(default = "default_true")] + pub dialog: bool, + /// The updater endpoints. TLS is enforced on production. + /// + /// The updater URL can contain the following variables: + /// - {{current_version}}: The version of the app that is requesting the update + /// - {{target}}: The operating system name (one of `linux`, `windows` or `darwin`). + /// - {{arch}}: The architecture of the machine (one of `x86_64`, `i686`, `aarch64` or `armv7`). + /// + /// # Examples + /// - "https://my.cdn.com/latest.json": a raw JSON endpoint that returns the latest version and download links for each platform. + /// - "https://updates.app.dev/{{target}}?version={{current_version}}&arch={{arch}}": a dedicated API with positional and query string arguments. + #[allow(rustdoc::bare_urls)] + pub endpoints: Option>, + /// Signature public key. + #[serde(default)] // use default just so the schema doesn't flag it as required + pub pubkey: String, + /// The Windows configuration for the updater. + #[serde(default)] + pub windows: UpdaterWindowsConfig, +} + +impl<'de> Deserialize<'de> for UpdaterConfig { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + #[derive(Deserialize)] + struct InnerUpdaterConfig { + #[serde(default)] + active: bool, + #[serde(default = "default_true")] + dialog: bool, + endpoints: Option>, + pubkey: Option, + #[serde(default)] + windows: UpdaterWindowsConfig, + } + + let config = InnerUpdaterConfig::deserialize(deserializer)?; + + if config.active && config.pubkey.is_none() { + return Err(DeError::custom( + "The updater `pubkey` configuration is required.", + )); + } + + Ok(UpdaterConfig { + active: config.active, + dialog: config.dialog, + endpoints: config.endpoints, + pubkey: config.pubkey.unwrap_or_default(), + windows: config.windows, + }) + } +} + +impl Default for UpdaterConfig { + fn default() -> Self { + Self { + active: false, + dialog: true, + endpoints: None, + pubkey: "".into(), + windows: Default::default(), + } + } +} + +/// Configuration for application system tray icon. +/// +/// See more: https://tauri.app/v1/api/config#systemtrayconfig +#[skip_serializing_none] +#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SystemTrayConfig { + /// Path to the default icon to use on the system tray. + #[serde(alias = "icon-path")] + pub icon_path: PathBuf, + /// A Boolean value that determines whether the image represents a [template](https://developer.apple.com/documentation/appkit/nsimage/1520017-template?language=objc) image on macOS. + #[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_true", alias = "menu-on-left-click")] + pub menu_on_left_click: bool, + /// Title for MacOS tray + pub title: Option, +} + +/// Defines the URL or assets to embed in the application. +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(untagged, deny_unknown_fields)] +#[non_exhaustive] +pub enum AppUrl { + /// The app's external URL, or the path to the directory containing the app assets. + Url(WindowUrl), + /// An array of files to embed on the app. + Files(Vec), +} + +impl std::fmt::Display for AppUrl { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Url(url) => write!(f, "{url}"), + Self::Files(files) => write!(f, "{}", serde_json::to_string(files).unwrap()), + } + } +} + +/// Describes the shell command to run before `tauri dev`. +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", untagged)] +pub enum BeforeDevCommand { + /// Run the given script with the default options. + Script(String), + /// Run the given script with custom options. + ScriptWithOptions { + /// The script to execute. + script: String, + /// The current working directory. + cwd: Option, + /// Whether `tauri dev` should wait for the command to finish or not. Defaults to `false`. + #[serde(default)] + wait: bool, + }, +} + +/// Describes a shell command to be executed when a CLI hook is triggered. +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", untagged)] +pub enum HookCommand { + /// Run the given script with the default options. + Script(String), + /// Run the given script with custom options. + ScriptWithOptions { + /// The script to execute. + script: String, + /// The current working directory. + cwd: Option, + }, +} + +/// The Build configuration object. +/// +/// See more: https://tauri.app/v1/api/config#buildconfig +#[skip_serializing_none] +#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BuildConfig { + /// The binary used to build and run the application. + pub runner: Option, + /// The path to the application assets or URL to load in development. + /// + /// This is usually an URL to a dev server, which serves your application assets + /// with live reloading. Most modern JavaScript bundlers provides a way to start a dev server by default. + /// + /// See [vite](https://vitejs.dev/guide/), [Webpack DevServer](https://webpack.js.org/configuration/dev-server/) and [sirv](https://github.com/lukeed/sirv) + /// for examples on how to set up a dev server. + #[serde(default = "default_dev_path", alias = "dev-path")] + pub dev_path: AppUrl, + /// The path to the application assets or URL to load in production. + /// + /// When a path relative to the configuration file is provided, + /// it is read recursively and all files are embedded in the application binary. + /// Tauri then looks for an `index.html` file unless you provide a custom window URL. + /// + /// You can also provide a list of paths to be embedded, which allows granular control over what files are added to the binary. + /// In this case, all files are added to the root and you must reference it that way in your HTML files. + /// + /// When an URL is provided, the application won't have bundled assets + /// and the application will load that URL by default. + #[serde(default = "default_dist_dir", alias = "dist-dir")] + pub dist_dir: AppUrl, + /// A shell command to run before `tauri dev` kicks in. + /// + /// The TAURI_PLATFORM, TAURI_ARCH, TAURI_FAMILY, TAURI_PLATFORM_VERSION, TAURI_PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation. + #[serde(alias = "before-dev-command")] + pub before_dev_command: Option, + /// A shell command to run before `tauri build` kicks in. + /// + /// The TAURI_PLATFORM, TAURI_ARCH, TAURI_FAMILY, TAURI_PLATFORM_VERSION, TAURI_PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation. + #[serde(alias = "before-build-command")] + pub before_build_command: Option, + /// A shell command to run before the bundling phase in `tauri build` kicks in. + /// + /// The TAURI_PLATFORM, TAURI_ARCH, TAURI_FAMILY, TAURI_PLATFORM_VERSION, TAURI_PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation. + #[serde(alias = "before-bundle-command")] + pub before_bundle_command: Option, + /// Features passed to `cargo` commands. + pub features: Option>, + /// Whether we should inject the Tauri API on `window.__TAURI__` or not. + #[serde(default, alias = "with-global-tauri")] + pub with_global_tauri: bool, +} + +impl Default for BuildConfig { + fn default() -> Self { + Self { + runner: None, + dev_path: default_dev_path(), + dist_dir: default_dist_dir(), + before_dev_command: None, + before_build_command: None, + before_bundle_command: None, + features: None, + with_global_tauri: false, + } + } +} + +fn default_dev_path() -> AppUrl { + AppUrl::Url(WindowUrl::External( + Url::parse("http://localhost:8080").unwrap(), + )) +} + +fn default_dist_dir() -> AppUrl { + AppUrl::Url(WindowUrl::App("../dist".into())) +} + +#[derive(Debug, PartialEq, Eq)] +struct PackageVersion(String); + +impl<'d> serde::Deserialize<'d> for PackageVersion { + fn deserialize>(deserializer: D) -> Result { + struct PackageVersionVisitor; + + impl<'d> Visitor<'d> for PackageVersionVisitor { + type Value = PackageVersion; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + formatter, + "a semver string or a path to a package.json file" + ) + } + + fn visit_str(self, value: &str) -> Result { + let path = PathBuf::from(value); + if path.exists() { + let json_str = read_to_string(&path) + .map_err(|e| DeError::custom(format!("failed to read version JSON file: {e}")))?; + let package_json: serde_json::Value = serde_json::from_str(&json_str) + .map_err(|e| DeError::custom(format!("failed to read version JSON file: {e}")))?; + if let Some(obj) = package_json.as_object() { + let version = obj + .get("version") + .ok_or_else(|| DeError::custom("JSON must contain a `version` field"))? + .as_str() + .ok_or_else(|| { + DeError::custom(format!("`{} > version` must be a string", path.display())) + })?; + Ok(PackageVersion( + Version::from_str(version) + .map_err(|_| DeError::custom("`package > version` must be a semver string"))? + .to_string(), + )) + } else { + Err(DeError::custom( + "`package > version` value is not a path to a JSON object", + )) + } + } else { + Ok(PackageVersion( + Version::from_str(value) + .map_err(|_| DeError::custom("`package > version` must be a semver string"))? + .to_string(), + )) + } + } + } + + deserializer.deserialize_string(PackageVersionVisitor {}) + } +} + +/// The package configuration. +/// +/// See more: https://tauri.app/v1/api/config#packageconfig +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PackageConfig { + /// App name. + #[serde(alias = "product-name")] + #[cfg_attr(feature = "schema", validate(regex(pattern = "^[^/\\:*?\"<>|]+$")))] + pub product_name: Option, + /// 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, +} + +fn version_deserializer<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + Option::::deserialize(deserializer).map(|v| v.map(|v| v.0)) +} + +/// The Tauri configuration object. +/// It is read from a file where you can define your frontend assets, +/// configure the bundler, enable the app updater, define a system tray, +/// enable APIs via the allowlist and more. +/// +/// The configuration file is generated by the +/// [`tauri init`](https://tauri.app/v1/api/cli#init) command that lives in +/// your Tauri application source directory (src-tauri). +/// +/// Once generated, you may modify it at will to customize your Tauri application. +/// +/// ## File Formats +/// +/// By default, the configuration is defined as a JSON file named `tauri.conf.json`. +/// +/// Tauri also supports JSON5 and TOML files via the `config-json5` and `config-toml` Cargo features, respectively. +/// The JSON5 file name must be either `tauri.conf.json` or `tauri.conf.json5`. +/// The TOML file name is `Tauri.toml`. +/// +/// ## Platform-Specific Configuration +/// +/// In addition to the default configuration file, Tauri can +/// read a platform-specific configuration from `tauri.linux.conf.json`, +/// `tauri.windows.conf.json`, and `tauri.macos.conf.json` +/// (or `Tauri.linux.toml`, `Tauri.windows.toml` and `Tauri.macos.toml` if the `Tauri.toml` format is used), +/// which gets merged with the main configuration object. +/// +/// ## Configuration Structure +/// +/// The configuration is composed of the following objects: +/// +/// - [`package`](#packageconfig): Package settings +/// - [`tauri`](#tauriconfig): The Tauri config +/// - [`build`](#buildconfig): The build configuration +/// - [`plugins`](#pluginconfig): The plugins config +/// +/// ```json title="Example tauri.config.json file" +/// { +/// "build": { +/// "beforeBuildCommand": "", +/// "beforeDevCommand": "", +/// "devPath": "../dist", +/// "distDir": "../dist" +/// }, +/// "package": { +/// "productName": "tauri-app", +/// "version": "0.1.0" +/// }, +/// "tauri": { +/// "allowlist": { +/// "all": true +/// }, +/// "bundle": {}, +/// "security": { +/// "csp": null +/// }, +/// "updater": { +/// "active": false +/// }, +/// "windows": [ +/// { +/// "fullscreen": false, +/// "height": 600, +/// "resizable": true, +/// "title": "Tauri App", +/// "width": 800 +/// } +/// ] +/// } +/// } +/// ``` +#[skip_serializing_none] +#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Config { + /// The JSON schema for the Tauri config. + #[serde(rename = "$schema")] + pub schema: Option, + /// Package settings. + #[serde(default)] + pub package: PackageConfig, + /// The Tauri configuration. + #[serde(default)] + pub tauri: TauriConfig, + /// The build configuration. + #[serde(default = "default_build")] + pub build: BuildConfig, + /// The plugins config. + #[serde(default)] + pub plugins: PluginConfig, +} + +/// The plugin configs holds a HashMap mapping a plugin name to its configuration object. +/// +/// See more: https://tauri.app/v1/api/config#pluginconfig +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub struct PluginConfig(pub HashMap); + +fn default_build() -> BuildConfig { + BuildConfig { + runner: None, + dev_path: default_dev_path(), + dist_dir: default_dist_dir(), + before_dev_command: None, + before_build_command: None, + before_bundle_command: None, + features: None, + with_global_tauri: false, + } +} + +/// How the window title bar should be displayed on macOS. +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub enum TitleBarStyle { + /// A normal title bar. + Visible, + /// Makes the title bar transparent, so the window background color is shown instead. + /// + /// Useful if you don't need to have actual HTML under the title bar. This lets you avoid the caveats of using `TitleBarStyle::Overlay`. Will be more useful when Tauri lets you set a custom window background color. + Transparent, + /// Shows the title bar as a transparent overlay over the window's content. + /// + /// Keep in mind: + /// - The height of the title bar is different on different OS versions, which can lead to window the controls and title not being where you don't expect. + /// - You need to define a custom drag region to make your window draggable, however due to a limitation you can't drag the window when it's not in focus . + /// - The color of the window title depends on the system theme. + Overlay, +} + +impl Default for TitleBarStyle { + fn default() -> Self { + Self::Visible + } +} + +impl Serialize for TitleBarStyle { + fn serialize(&self, serializer: S) -> std::result::Result + where + S: Serializer, + { + serializer.serialize_str(self.to_string().as_ref()) + } +} + +impl<'de> Deserialize<'de> for TitleBarStyle { + fn deserialize(deserializer: D) -> std::result::Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + Ok(match s.to_lowercase().as_str() { + "transparent" => Self::Transparent, + "overlay" => Self::Overlay, + _ => Self::Visible, + }) + } +} + +impl Display for TitleBarStyle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + match self { + Self::Visible => "Visible", + Self::Transparent => "Transparent", + Self::Overlay => "Overlay", + } + ) + } +} + +/// System theme. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[non_exhaustive] +pub enum Theme { + /// Light theme. + Light, + /// Dark theme. + Dark, +} + +impl Serialize for Theme { + fn serialize(&self, serializer: S) -> std::result::Result + where + S: Serializer, + { + serializer.serialize_str(self.to_string().as_ref()) + } +} + +impl<'de> Deserialize<'de> for Theme { + fn deserialize(deserializer: D) -> std::result::Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + Ok(match s.to_lowercase().as_str() { + "dark" => Self::Dark, + _ => Self::Light, + }) + } +} + +impl Display for Theme { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + match self { + Self::Light => "light", + Self::Dark => "dark", + } + ) + } +} + +#[cfg(test)] +mod test { + use super::*; + + // TODO: create a test that compares a config to a json config + + #[test] + // test all of the default functions + fn test_defaults() { + // get default tauri config + let t_config = TauriConfig::default(); + // get default build config + let b_config = BuildConfig::default(); + // get default dev path + let d_path = default_dev_path(); + // get default window + let d_windows: Vec = vec![]; + // get default bundle + let d_bundle = BundleConfig::default(); + // get default updater + let d_updater = UpdaterConfig::default(); + + // create a tauri config. + let tauri = TauriConfig { + pattern: Default::default(), + windows: vec![], + bundle: BundleConfig { + active: false, + targets: Default::default(), + identifier: String::from(""), + publisher: None, + icon: Vec::new(), + resources: None, + copyright: None, + category: None, + short_description: None, + long_description: None, + appimage: Default::default(), + deb: Default::default(), + macos: Default::default(), + external_bin: None, + windows: Default::default(), + }, + cli: None, + updater: UpdaterConfig { + active: false, + dialog: true, + pubkey: "".into(), + endpoints: None, + windows: Default::default(), + }, + security: SecurityConfig { + csp: None, + dev_csp: None, + 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, + macos_private_api: false, + }; + + // create a build config + let build = BuildConfig { + runner: None, + dev_path: AppUrl::Url(WindowUrl::External( + Url::parse("http://localhost:8080").unwrap(), + )), + dist_dir: AppUrl::Url(WindowUrl::App("../dist".into())), + before_dev_command: None, + before_build_command: None, + before_bundle_command: None, + features: None, + with_global_tauri: false, + }; + + // test the configs + assert_eq!(t_config, tauri); + assert_eq!(b_config, build); + assert_eq!(d_bundle, tauri.bundle); + assert_eq!(d_updater, tauri.updater); + assert_eq!( + d_path, + AppUrl::Url(WindowUrl::External( + Url::parse("http://localhost:8080").unwrap() + )) + ); + assert_eq!(d_windows, tauri.windows); + } +} diff --git a/crates/tauri-utils/src/config_v1/parse.rs b/crates/tauri-utils/src/config_v1/parse.rs new file mode 100644 index 000000000000..0e1c7b94dd9a --- /dev/null +++ b/crates/tauri-utils/src/config_v1/parse.rs @@ -0,0 +1,253 @@ +// Copyright 2019-2024 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT + +use serde::de::DeserializeOwned; +use serde_json::Value; +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; +use thiserror::Error; + +/// All extensions that are possibly supported, but perhaps not enabled. +const EXTENSIONS_SUPPORTED: &[&str] = &["json", "json5", "toml"]; + +/// All configuration formats that are currently enabled. +const ENABLED_FORMATS: &[ConfigFormat] = &[ + ConfigFormat::Json, + #[cfg(feature = "config-json5")] + ConfigFormat::Json5, + #[cfg(feature = "config-toml")] + ConfigFormat::Toml, +]; + +/// The available configuration formats. +#[derive(Debug, Copy, Clone)] +enum ConfigFormat { + /// The default JSON (tauri.conf.json) format. + Json, + /// The JSON5 (tauri.conf.json5) format. + Json5, + /// The TOML (Tauri.toml file) format. + Toml, +} + +impl ConfigFormat { + /// Maps the config format to its file name. + fn into_file_name(self) -> &'static str { + match self { + Self::Json => "tauri.conf.json", + Self::Json5 => "tauri.conf.json5", + Self::Toml => "Tauri.toml", + } + } + + fn into_platform_file_name(self) -> &'static str { + match self { + Self::Json => { + if cfg!(target_os = "macos") { + "tauri.macos.conf.json" + } else if cfg!(windows) { + "tauri.windows.conf.json" + } else { + "tauri.linux.conf.json" + } + } + Self::Json5 => { + if cfg!(target_os = "macos") { + "tauri.macos.conf.json5" + } else if cfg!(windows) { + "tauri.windows.conf.json5" + } else { + "tauri.linux.conf.json5" + } + } + Self::Toml => { + if cfg!(target_os = "macos") { + "Tauri.macos.toml" + } else if cfg!(windows) { + "Tauri.windows.toml" + } else { + "Tauri.linux.toml" + } + } + } + } +} + +/// Represents all the errors that can happen while reading the config. +#[derive(Debug, Error)] +#[non_exhaustive] +pub enum ConfigError { + /// Failed to parse from JSON. + #[error("unable to parse JSON Tauri config file at {path} because {error}")] + FormatJson { + /// The path that failed to parse into JSON. + path: PathBuf, + + /// The parsing [`serde_json::Error`]. + error: serde_json::Error, + }, + + /// Failed to parse from JSON5. + #[cfg(feature = "config-json5")] + #[error("unable to parse JSON5 Tauri config file at {path} because {error}")] + FormatJson5 { + /// The path that failed to parse into JSON5. + path: PathBuf, + + /// The parsing [`json5::Error`]. + error: ::json5::Error, + }, + + /// Failed to parse from TOML. + #[cfg(feature = "config-toml")] + #[error("unable to parse toml Tauri config file at {path} because {error}")] + FormatToml { + /// The path that failed to parse into TOML. + path: PathBuf, + + /// The parsing [`toml::Error`]. + error: ::toml::de::Error, + }, + + /// Unknown config file name encountered. + #[error("unsupported format encountered {0}")] + UnsupportedFormat(String), + + /// Known file extension encountered, but corresponding parser is not enabled (cargo features). + #[error("supported (but disabled) format encountered {extension} - try enabling `{feature}` ")] + DisabledFormat { + /// The extension encountered. + extension: String, + + /// The cargo feature to enable it. + feature: String, + }, + + /// A generic IO error with context of what caused it. + #[error("unable to read Tauri config file at {path} because {error}")] + Io { + /// The path the IO error occurred on. + path: PathBuf, + + /// The [`std::io::Error`]. + error: std::io::Error, + }, +} + +/// See [`parse`] for specifics, returns a JSON [`Value`] instead of [`Config`]. +pub fn parse_value(path: impl Into) -> Result<(Value, PathBuf), ConfigError> { + do_parse(path.into()) +} + +fn do_parse(path: PathBuf) -> Result<(D, PathBuf), ConfigError> { + let file_name = path + .file_name() + .map(OsStr::to_string_lossy) + .unwrap_or_default(); + let lookup_platform_config = ENABLED_FORMATS + .iter() + .any(|format| file_name == format.into_platform_file_name()); + + let json5 = path.with_file_name(if lookup_platform_config { + ConfigFormat::Json5.into_platform_file_name() + } else { + ConfigFormat::Json5.into_file_name() + }); + let toml = path.with_file_name(if lookup_platform_config { + ConfigFormat::Toml.into_platform_file_name() + } else { + ConfigFormat::Toml.into_file_name() + }); + + let path_ext = path + .extension() + .map(OsStr::to_string_lossy) + .unwrap_or_default(); + + if path.exists() { + let raw = read_to_string(&path)?; + + // to allow us to easily use the compile-time #[cfg], we always bind + #[allow(clippy::let_and_return)] + let json = do_parse_json(&raw, &path); + + // we also want to support **valid** json5 in the .json extension if the feature is enabled. + // if the json5 is not valid the serde_json error for regular json will be returned. + // this could be a bit confusing, so we may want to encourage users using json5 to use the + // .json5 extension instead of .json + #[cfg(feature = "config-json5")] + let json = { + match do_parse_json5(&raw, &path) { + json5 @ Ok(_) => json5, + + // assume any errors from json5 in a .json file is because it's not json5 + Err(_) => json, + } + }; + + json.map(|j| (j, path)) + } else if json5.exists() { + #[cfg(feature = "config-json5")] + { + let raw = read_to_string(&json5)?; + do_parse_json5(&raw, &path).map(|config| (config, json5)) + } + + #[cfg(not(feature = "config-json5"))] + Err(ConfigError::DisabledFormat { + extension: ".json5".into(), + feature: "config-json5".into(), + }) + } else if toml.exists() { + #[cfg(feature = "config-toml")] + { + let raw = read_to_string(&toml)?; + do_parse_toml(&raw, &path).map(|config| (config, toml)) + } + + #[cfg(not(feature = "config-toml"))] + Err(ConfigError::DisabledFormat { + extension: ".toml".into(), + feature: "config-toml".into(), + }) + } else if !EXTENSIONS_SUPPORTED.contains(&path_ext.as_ref()) { + Err(ConfigError::UnsupportedFormat(path_ext.to_string())) + } else { + Err(ConfigError::Io { + path, + error: std::io::ErrorKind::NotFound.into(), + }) + } +} + +fn do_parse_json(raw: &str, path: &Path) -> Result { + serde_json::from_str(raw).map_err(|error| ConfigError::FormatJson { + path: path.into(), + error, + }) +} + +#[cfg(feature = "config-json5")] +fn do_parse_json5(raw: &str, path: &Path) -> Result { + ::json5::from_str(raw).map_err(|error| ConfigError::FormatJson5 { + path: path.into(), + error, + }) +} + +#[cfg(feature = "config-toml")] +fn do_parse_toml(raw: &str, path: &Path) -> Result { + ::toml::from_str(raw).map_err(|error| ConfigError::FormatToml { + path: path.into(), + error, + }) +} + +/// Helper function to wrap IO errors from [`std::fs::read_to_string`] into a [`ConfigError`]. +fn read_to_string(path: &Path) -> Result { + std::fs::read_to_string(path).map_err(|error| ConfigError::Io { + path: path.into(), + error, + }) +} diff --git a/crates/tauri-utils/src/html.rs b/crates/tauri-utils/src/html.rs index 1ff9657b7df1..bfa203f00401 100644 --- a/crates/tauri-utils/src/html.rs +++ b/crates/tauri-utils/src/html.rs @@ -112,7 +112,7 @@ pub fn serialize_node(node: &NodeRef) -> Vec { /// Parses the given HTML string. pub fn parse(html: String) -> NodeRef { - kuchiki::parse_html().one(html) + kuchiki::parse_html().one(html).document_node } fn with_head(document: &NodeRef, f: F) { @@ -288,7 +288,6 @@ pub fn inline_isolation(document: &NodeRef, dir: &Path) { #[cfg(test)] mod tests { - use kuchiki::traits::*; #[test] fn csp() { @@ -297,7 +296,7 @@ mod tests { "".to_string(), ]; for html in htmls { - let document = kuchiki::parse_html().one(html); + let document = super::parse(html); let csp = "csp-string"; super::inject_csp(&document, csp); assert_eq!( diff --git a/crates/tauri-utils/src/lib.rs b/crates/tauri-utils/src/lib.rs index 04c327042dd2..b8c41bca9364 100644 --- a/crates/tauri-utils/src/lib.rs +++ b/crates/tauri-utils/src/lib.rs @@ -23,6 +23,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; pub mod acl; pub mod assets; pub mod config; +pub mod config_v1; #[cfg(feature = "html-manipulation")] pub mod html; pub mod io; diff --git a/crates/tauri/Cargo.toml b/crates/tauri/Cargo.toml index c2b712d5259e..5e8177b3819a 100644 --- a/crates/tauri/Cargo.toml +++ b/crates/tauri/Cargo.toml @@ -61,7 +61,7 @@ tauri-macros = { version = "2.2.0", path = "../tauri-macros" } tauri-utils = { version = "2.4.0", features = [ "resources", ], path = "../tauri-utils" } -tauri-runtime-wry = { version = "2.6.0", path = "../tauri-runtime-wry", optional = true } +tauri-runtime-wry = { version = "2.6.0", path = "../tauri-runtime-wry", default-features = false, optional = true } getrandom = "0.2" serde_repr = "0.1" http = "1" @@ -122,7 +122,7 @@ window-vibrancy = "0.6" # windows [target."cfg(windows)".dependencies] -webview2-com = { version = "0.37", optional = true } +webview2-com = { version = "0.38", optional = true } window-vibrancy = "0.6" windows = { version = "0.61", features = [ "Win32_Foundation", @@ -179,8 +179,9 @@ objc2-web-kit = { version = "0.3", features = [ ] } [features] -default = ["wry", "compression", "common-controls-v6", "dynamic-acl"] +default = ["wry", "compression", "common-controls-v6", "dynamic-acl", "x11"] unstable = ["tauri-runtime-wry?/unstable"] +x11 = ["tauri-runtime-wry?/x11"] common-controls-v6 = [ "tray-icon?/common-controls-v6", "muda/common-controls-v6", diff --git a/crates/tauri/src/lib.rs b/crates/tauri/src/lib.rs index 2a8a0fea616f..48fe2b4b709b 100644 --- a/crates/tauri/src/lib.rs +++ b/crates/tauri/src/lib.rs @@ -12,6 +12,7 @@ //! //! - **wry** *(enabled by default)*: Enables the [wry](https://github.com/tauri-apps/wry) runtime. Only disable it if you want a custom runtime. //! - **common-controls-v6** *(enabled by default)*: Enables [Common Controls v6](https://learn.microsoft.com/en-us/windows/win32/controls/common-control-versions) support on Windows, mainly for the predefined `about` menu item. +//! - **x11** *(enabled by default)*: Enables X11 support. Disable this if you only target Wayland. //! - **unstable**: Enables unstable features. Be careful, it might introduce breaking changes in future minor releases. //! - **tracing**: Enables [`tracing`](https://docs.rs/tracing/latest/tracing) for window startup, plugins, `Window::eval`, events, IPC, updater and custom protocol request handlers. //! - **test**: Enables the [`mod@test`] module exposing unit test helpers. diff --git a/crates/tauri/src/manager/webview.rs b/crates/tauri/src/manager/webview.rs index f9c0436b2570..1df052f59db0 100644 --- a/crates/tauri/src/manager/webview.rs +++ b/crates/tauri/src/manager/webview.rs @@ -461,7 +461,7 @@ impl WebviewManager { if html.contains('<') && html.contains('>') { let document = tauri_utils::html::parse(html); tauri_utils::html::inject_csp(&document, &csp.to_string()); - url.set_path(&format!("{},{}", mime::TEXT_HTML, document.to_string())); + url.set_path(&format!("{},{document}", mime::TEXT_HTML)); } } }