Compare commits

...

10 commits

Author SHA1 Message Date
Bianca Fürstenau
1cf83b65df Make it build 2025-03-04 15:45:51 +01:00
bicarlsen
6c75037edd
Add Menu functionality (#65)
* Added core::Channel and menu functionality. core::Channel may leak memory.

* Added leptos example.

* Updated Channel to stream over message. Added Menu::with_items.

* Updated examples to v2 using Leptos.

* Added Menu::with_id_and_items.

* Derived Clone for drag drop events.
2024-11-15 03:49:07 +01:00
bicarlsen
ae49310ee1
Add menu functionality (#59)
* Added core::Channel and menu functionality. core::Channel may leak memory.

* Updated examples to v2 using Leptos.
2024-08-06 18:20:50 +02:00
bicarlsen
115009d4bf
Added menu functionality. (#58)
* Added core::Channel and menu functionality. core::Channel may leak memory.

* Added leptos example.
2024-08-02 15:31:56 +02:00
Brian Carlsen
aa3a64af11
Updated drag drop paths to be PathBuf instead of String. 2024-07-23 16:31:07 +02:00
Brian Carlsen
4698574b7d
Update drag drop events to match new Tauri updates. 2024-07-23 13:43:37 +02:00
Brian Carlsen
eae62c1e5c
Removed mut requirement for window.on_drag_drop_event. 2024-07-23 11:53:33 +02:00
Brian Carlsen
694a3f6f87
Added Debug to DragDropEvent. 2024-07-23 11:45:32 +02:00
bicarlsen
9c3cd94275
Added initial window module functionality. (#57) 2024-07-23 09:35:07 +02:00
Brian Carlsen
125136ae79
Updated readme with new Cargo.toml info. 2024-07-13 22:06:27 +02:00
76 changed files with 8264 additions and 4240 deletions

4543
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -6,6 +6,7 @@ version = "0.2.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
derive_more = "0.99.18"
futures = { version = "0.3.30", optional = true }
js-sys = "0.3.69"
log = "0.4.21"
@ -24,9 +25,13 @@ wasm-bindgen-test = "0.3.42"
all-features = true
[features]
all = ["core", "event"]
core = []
all = ["core", "dpi", "event", "menu", "window"]
core = ["dep:futures"]
dpi = []
event = ["dep:futures"]
menu = ["core", "window"]
window = ["dpi", "event"]
fs = []
[workspace]
members = ["examples/test", "examples/test/src-tauri"]

View file

@ -23,7 +23,7 @@ This crate is not yet published to crates.io, so you need to use it from git. Yo
```toml
tauri-sys = { git = "https://github.com/JonasKruckenberg/tauri-sys" } // tauri v1 api, main repo
// OR
tauri-sys = { git = "https://github.com/bicarlsen/tauri-sys", branch = "v2" } // tauri v2 api
tauri-sys = { git = "https://github.com/JonasKruckenberg/tauri-sys", branch = "v2" } // tauri v2 api
```
## Usage
@ -51,8 +51,10 @@ fn main() {
All modules are gated by accordingly named Cargo features. It is recommended you keep this synced with the features enabled in your [Tauri Allowlist] but no automated tool for this exists (yet).
- **all**: Enables all modules.
- **core**: Enables the `core` module. (Only `invoke` and `convertFileSrc` currently implemented.)
- **core**: Enables the `core` module. (~70% implmented)
- **event**: Enables the `event` module.
- **menu**: Enables the `menu` module. (~20% implemented)
- **window**: Enables the `windows` module. (~20% implemented)
## Are we Tauri yet?
@ -60,19 +62,22 @@ These API bindings are not completely on-par with `@tauri-apps/api` yet, but her
- [ ] `app`
- [x] `core` (partial implementation)
- [ ] `dpi`
- [x] `dpi`
- [x] `event`
- [ ] `image`
- [ ] `menu`
- [x] `menu` (partial implementation)
- [ ] `mocks`
- [ ] `path`
- [ ] `tray`
- [ ] `webview`
- [ ] `webviewWindow`
- [ ] `window`
- [x] `window` (partial implementation)
The current API also very closely mirrors the JS API even though that might not be the most ergonomic choice, ideas for improving the API with quality-of-life features beyond the regular JS API interface are very welcome.
## Examples
The [`examples/leptos`] crate provides examples of how to use most of the implemented functionality.
[wasm-bindgen]: https://github.com/rustwasm/wasm-bindgen
[tauri allowlist]: https://tauri.app/v1/api/config#allowlistconfig
[`esbuild`]: https://esbuild.github.io/getting-started/#install-esbuild

3
examples/leptos/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
/dist/
/target/
/Cargo.lock

View file

@ -0,0 +1,3 @@
/src
/public
/Cargo.toml

View file

@ -0,0 +1,3 @@
{
"recommendations": ["tauri-apps.tauri-vscode", "rust-lang.rust-analyzer"]
}

5
examples/leptos/.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,5 @@
{
"emmet.includeLanguages": {
"rust": "html"
}
}

View file

@ -0,0 +1,22 @@
[package]
name = "test-tauri-events-ui"
version = "0.0.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
leptos = { version = "0.6", features = ["csr", "nightly"] }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
serde = { version = "1", features = ["derive"] }
serde-wasm-bindgen = "0.6"
console_error_panic_hook = "0.1.7"
tauri-sys = { path = "../tauri-sys", features = ["all"] }
futures = "0.3"
tracing = "0.1.40"
tracing-subscriber = "0.3.18"
tracing-web = "0.1.3"
[workspace]
members = ["src-tauri"]

View file

@ -0,0 +1,7 @@
# Tauri + Leptos
This template should help get you started developing with Tauri and Leptos.
## Recommended IDE Setup
[VS Code](https://code.visualstudio.com/) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer).

View file

@ -0,0 +1,10 @@
[build]
target = "./index.html"
[watch]
ignore = ["./src-tauri"]
[serve]
address = "127.0.0.1"
port = 1420
open = false

View file

@ -0,0 +1,11 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Tauri + Leptos App</title>
<link data-trunk rel="css" href="styles.css" />
<link data-trunk rel="copy-dir" href="public" />
<link data-trunk rel="rust" data-wasm-opt="z" />
</head>
<body></body>
</html>

View file

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 27.1.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 437.4294 209.6185" style="enable-background:new 0 0 437.4294 209.6185;" xml:space="preserve">
<path style="fill:none;" d="M130.0327,79.3931c-11.4854-0.23-22.52,9.3486-24.5034,21.0117l49.1157,0.0293
c-2.1729-10.418-11.1821-21.0449-24.1987-21.0449C130.3081,79.3892,130.1714,79.3907,130.0327,79.3931z"/>
<path style="fill:#181139;" d="M95.1109,128.1089H58.6797V65.6861c0-1.5234-0.8169-2.4331-2.1855-2.4331h-3.1187
c-1.3159,0-2.2349,1.0005-2.2349,2.4331v67.4297c0,1.4521,0.8145,2.2852,2.2349,2.2852h41.7353c1.4844,0,2.4819-0.9375,2.4819-2.333
v-2.7744C97.5928,128.9253,96.6651,128.1089,95.1109,128.1089z"/>
<path style="fill:#181139;" d="M146.4561,77.1739c-4.8252-3.001-10.3037-4.5249-16.2837-4.5288c-0.0068,0-0.0137,0-0.0205,0
c-5.7349,0-11.1377,1.4639-16.0566,4.3511c-4.916,2.8853-8.8721,6.8364-11.7593,11.7456
c-2.8975,4.9248-4.3687,10.332-4.3721,16.0713c-0.0034,5.7188,1.4966,11.0654,4.4565,15.8887
c2.9893,4.9209,6.8789,8.7334,11.8887,11.6514c4.8657,2.8633,10.2397,4.3174,15.9717,4.3203c0.0073,0,0.0146,0,0.022,0
c8.123,0,14.7441-2.5869,21.4683-8.3906c0.5493-0.4805,0.8516-1.1201,0.8516-1.8008c0.001-0.6074-0.1743-1.1035-0.5205-1.4756
l-1.3569-1.8428l-0.0732-0.0859c-0.2637-0.2637-0.6929-0.6152-1.3716-0.6152c-0.6421,0-1.2549,0.2217-1.7124,0.6143
c-1.9346,1.585-3.5459,2.8008-4.7969,3.6182c-1.7979,1.208-5.8218,3.2314-12.5986,3.2314c-0.0073,0-0.0142,0-0.021,0
c-0.1357,0.0029-0.269,0.0039-0.4043,0.0039c-12.2642,0-23.4736-10.3262-24.5088-22.4814l53.0127,0.0322c0.0015,0,0.0024,0,0.0034,0
c2.2373,0,3.4697-1.1621,3.4712-3.2715c0.0034-5.2588-1.3574-10.3945-4.0464-15.2705
C155.0015,84.0953,151.2188,80.1363,146.4561,77.1739z M154.6451,100.4341l-49.1157-0.0293
c1.9834-11.6631,13.0181-21.2417,24.5034-21.0117c0.1387-0.0024,0.2754-0.0039,0.4136-0.0039
C143.4629,79.3892,152.4722,90.0162,154.6451,100.4341z"/>
<path style="fill:#181139;" d="M204.0386,136.6382c5.7319,0,11.1069-1.4502,15.9746-4.3115
c4.938-2.9014,8.75-6.7129,11.6533-11.6533c2.8608-4.8672,4.311-10.2578,4.311-16.0244c0-5.7324-1.4502-11.1064-4.311-15.9746
c-2.9019-4.9385-6.7134-8.75-11.6533-11.6533c-4.8687-2.8618-10.2437-4.3125-15.9746-4.3125
c-9.938,0-19.2021,4.7583-24.3516,12.3174v-9.438c0-0.5946-0.1465-1.0788-0.411-1.4511c-0.3815-0.5369-1.0157-0.834-1.8727-0.834
h-2.6738c-1.4521,0-2.2852,0.833-2.2852,2.2852v5.6964v46.4791v23.9676c0,1.2568,0.7808,2.0371,2.0371,2.0371h3.3667
c0.9209,0,1.6421-0.6992,1.6421-1.5908v-17.098v-10.984C185.0884,131.8892,194.2749,136.6382,204.0386,136.6382z M186.6358,122.5591
c-4.9346-4.9346-7.6831-11.4932-7.542-18.0254c-0.1367-6.3506,2.5439-12.751,7.3545-17.5605
c4.8521-4.8521,11.3037-7.5547,17.7383-7.417c4.3691,0,8.4863,1.1465,12.2314,3.4043c3.7344,2.2979,6.7456,5.4053,8.9492,9.2354
c2.1699,3.9072,3.2695,8.0967,3.2695,12.4697c0.1396,6.4619-2.5967,12.9844-7.5083,17.8955
c-4.7617,4.7617-11.0469,7.3857-17.2544,7.2803C197.6856,129.9712,191.396,127.3208,186.6358,122.5591z"/>
<path style="fill:#181139;" d="M241.8955,80.3975h7.5669v42.0259c0,6.8174,4.5674,12.1309,11.0825,12.9189
c0.6836,0.1055,1.8379,0.1572,3.5303,0.1572c2.0078,0,3.0273-0.3535,3.0273-2.2842v-2.377c0-1.7891-1.334-2.0371-2.7568-2.0371
c0,0-0.001,0-0.002,0l-1.7871-0.0488c-2.0117-0.0439-3.4883-0.7627-4.3896-2.1367c-0.9697-1.4805-1.4619-3.1738-1.4619-5.0352
V80.3975h10.0928c1.3076,0,2.2852-1.3628,2.2852-2.5815v-1.9312c0-1.3999-0.8359-2.2354-2.2354-2.2354h-10.1426V60.6861
c0-1.4619-0.7969-2.4829-1.9375-2.4829c-0.1865,0-0.4121,0-0.6392,0.0884l-2.6489,0.6865
c-1.2109,0.3682-2.0171,0.9263-2.0171,2.4507v12.2207h-7.5669c-1.4185,0-2.335,0.897-2.335,2.2852v1.8813
C239.5606,79.2393,240.6079,80.3975,241.8955,80.3975z"/>
<path style="fill:#181139;" d="M379.1182,106.2691c-4.0488-2.9219-8.8545-5.0293-14.291-6.2646
c-6.5049-1.3975-13.4473-5.2129-13.3203-10.3066c0-7.5225,6.6367-10.1914,12.3203-10.1914c5.3574,0,10.2207,3.002,13.001,8.0146
c0.6729,1.2861,1.4785,1.9375,2.3955,1.9375c0.3311,0,0.7061-0.1113,0.9922-0.2832l2.2021-1.1523
c0.5947-0.3408,0.9229-0.9414,0.9229-1.6924c0-0.5205-0.0908-0.9541-0.2617-1.292c-3.6367-8.2466-10.0967-12.4282-19.2021-12.4282
c-11.7305,0-19.6123,6.9263-19.6123,17.2349c0,4.3125,1.8438,7.9746,5.4756,10.8809c3.4482,2.7979,7.9121,4.8623,13.2705,6.1377
c4.5859,1.085,8.3193,2.5654,11.0977,4.4023c1.4159,0.9354,2.4412,2.0535,3.106,3.3672c0.6053,1.1962,0.9135,2.5535,0.9135,4.1005
c0.0742,2.3857-0.79,4.5176-2.5684,6.3389c-3.1445,3.2178-8.4053,4.6689-12.0205,4.6689c-0.0361,0-0.0723,0-0.1074,0
c-3.4268,0-6.4893-0.8438-9.1035-2.5068c-2.5918-1.6484-4.2363-3.8076-5.0293-6.6064c-0.3203-1.0996-0.751-2.1738-2.1553-2.1738
c-0.0742,0-0.2109,0.0146-0.4062,0.0449c-0.1133,0.0166-0.2559,0.0381-0.5088,0.0742l-1.8818,0.4463l-0.1045,0.0332
c-1.0244,0.4082-1.6113,1.1846-1.6113,2.1309c0,0.2285,0.0625,0.6592,0.2178,1.1094c1.9707,8.5801,10.2432,14.3447,20.5732,14.3447
c0.125,0.002,0.249,0.002,0.374,0.002c6.5947,0,12.6748-2.3193,16.7275-6.3945c3.1895-3.208,4.8311-7.2363,4.748-11.6357
c0-2.8187-0.6185-5.3109-1.8062-7.481C382.4437,109.2624,381.0062,107.631,379.1182,106.2691z"/>
<path style="fill:#EF3939;" d="M348.9043,45.7325c0-6.3157-3.2826-11.8699-8.2238-15.0756
c-2.811-1.8237-6.1537-2.8947-9.7469-2.8947c-9.9092,0-17.9707,8.0615-17.9707,17.9702c0,4.7659,1.8775,9.0925,4.9157,12.3123
c-3.6619,4.3709-6.6334,9.3336-8.7663,14.7186c-1.5873-0.2422-3.2123-0.3683-4.8662-0.3683
c-17.7158,0-32.1289,14.4131-32.1289,32.1289c0,14.6854,9.9077,27.0922,23.3869,30.9101
c-6.7762,17.3461-23.6572,29.6719-43.3742,29.6719c-16.8195,0-31.583-8.9662-39.7656-22.369
c-2.4778,0.5446-5.0429,0.8519-7.6721,0.9023c9.0226,16.99,26.8969,28.5917,47.4377,28.5917
c23.2646,0,43.1121-14.8788,50.5461-35.6179c0.5204,0.0251,1.0435,0.0398,1.5701,0.0398c17.7158,0,32.1289-14.4131,32.1289-32.1289
c0-13.557-8.4446-25.1712-20.3465-29.8811c1.9001-4.5678,4.5115-8.7646,7.6888-12.4641c0.9996,0.4404,2.0479,0.785,3.1324,1.0384
c1.3144,0.3071,2.6773,0.486,4.0839,0.486C340.8428,63.7032,348.9043,55.6416,348.9043,45.7325z M304.2461,129.5279
c-13.7871,0-25.0039-11.2168-25.0039-25.0039s11.2168-25.0039,25.0039-25.0039S329.25,90.7369,329.25,104.524
S318.0332,129.5279,304.2461,129.5279z M330.9336,34.8872c0.645,0,1.2737,0.0671,1.8881,0.1755
c5.0818,0.8974,8.9576,5.3347,8.9576,10.6697c0,5.9805-4.8652,10.8457-10.8457,10.8457s-10.8457-4.8652-10.8457-10.8457
c0-1.3967,0.2746-2.7282,0.7576-3.9555C322.4306,37.7496,326.35,34.8872,330.9336,34.8872z"/>
</svg>

After

Width:  |  Height:  |  Size: 6.5 KiB

View file

@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

7
examples/leptos/src-tauri/.gitignore vendored Normal file
View file

@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas

View file

@ -0,0 +1,20 @@
[package]
name = "test-tauri-events"
version = "0.0.0"
description = "A Tauri App"
authors = ["you"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
# tauri-build = { version = "2.0.0-beta", features = [] }
tauri-build = { path = "../../tauri/core/tauri-build", features = [] }
[dependencies]
tauri = { path = "../../tauri/core/tauri", features = [] }
tauri-plugin-shell = { path = "../../plugins-workspace/plugins/shell" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tracing = "0.1.40"
tracing-subscriber = "0.3.18"

View file

@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

View file

@ -0,0 +1,17 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:path:default",
"core:event:default",
"core:window:default",
"core:app:default",
"core:image:default",
"core:resources:default",
"core:menu:default",
"core:tray:default",
"shell:allow-open"
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 974 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 903 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View file

@ -0,0 +1,41 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use tauri::{Emitter, Manager};
fn main() {
logging::enable();
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![trigger_listen_events,])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
#[tauri::command]
fn trigger_listen_events(app: tauri::AppHandle) {
tracing::debug!("trigger_listen_event");
std::thread::spawn({
move || {
for i in 1..=100 {
app.emit("event::listen", i).unwrap();
std::thread::sleep(std::time::Duration::from_millis(500));
}
}
});
}
mod logging {
use tracing_subscriber::{filter::LevelFilter, fmt, prelude::*, Layer, Registry};
const MAX_LOG_LEVEL: LevelFilter = LevelFilter::DEBUG;
pub fn enable() {
let console_logger = fmt::layer()
.with_writer(std::io::stdout)
.pretty()
.with_filter(MAX_LOG_LEVEL);
let subscriber = Registry::default().with(console_logger);
tracing::subscriber::set_global_default(subscriber).unwrap();
}
}

View file

@ -0,0 +1,35 @@
{
"productName": "test-tauri-events",
"version": "0.0.0",
"identifier": "com.tauri.dev",
"build": {
"beforeDevCommand": "trunk serve",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "trunk build",
"frontendDist": "../dist"
},
"app": {
"withGlobalTauri": true,
"windows": [
{
"title": "test-tauri-events",
"width": 800,
"height": 600
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}

517
examples/leptos/src/app.rs Normal file
View file

@ -0,0 +1,517 @@
use futures::stream::StreamExt;
use leptos::{ev::MouseEvent, *};
use std::rc::Rc;
#[component]
pub fn App() -> impl IntoView {
view! {
<main class="container">
<div>
<h2>"core"</h2>
<Core/>
</div>
<div>
<h2>"events"</h2>
<Events/>
</div>
<div>
<h2>"window"</h2>
<Window/>
</div>
<div>
<h2>"menu"</h2>
<Menu/>
</div>
</main>
}
}
#[component]
fn Core() -> impl IntoView {
let (convert_path, set_convert_path) = create_signal("".to_string());
let (converted_path, set_converted_path) = create_signal("".to_string());
let do_convert_path = move |_| {
let converted = tauri_sys::core::convert_file_src(convert_path());
set_converted_path(converted);
};
view! {
<div>
<div>
<label>
"Convert path"
<input
prop:value=convert_path
on:input=move |e| set_convert_path(event_target_value(&e))
/>
</label>
<button on:click=do_convert_path>"Convert"</button>
</div>
<div>{converted_path}</div>
</div>
}
}
#[component]
fn Events() -> impl IntoView {
let (listen_event, set_listen_event) = create_signal(None);
let (emit_count, set_emit_count) = create_signal(0);
spawn_local(async move {
let mut listener = tauri_sys::event::listen::<i32>("event::listen")
.await
.unwrap();
while let Some(event) = listener.next().await {
tracing::debug!(?event);
let tauri_sys::event::Event {
event: _,
id: _,
payload,
} = event;
set_listen_event.set(Some(payload));
}
});
spawn_local(async move {
let mut listener = tauri_sys::event::listen::<i32>("event::emit")
.await
.unwrap();
while let Some(event) = listener.next().await {
tracing::debug!(?event);
let tauri_sys::event::Event {
event: _,
id: _,
payload,
} = event;
set_emit_count.set(payload);
}
});
let trigger_listen_events = move |_| {
spawn_local(async move {
tauri_sys::core::invoke::<()>("trigger_listen_events", &()).await;
});
};
let trigger_emit_event = move |_| {
spawn_local(async move {
tauri_sys::event::emit("event::emit", &emit_count.with_untracked(|n| n + 1))
.await
.unwrap();
});
};
view! {
<div>
<div>
<button on:click=trigger_listen_events>"Trigger listen events"</button>
<div>
<strong>"Last listen event: "</strong>
{move || listen_event()}
</div>
</div>
<div>
<button on:click=trigger_emit_event>"Trigger emit event"</button>
<div>
<strong>"Events emitted: "</strong>
{move || emit_count()}
</div>
</div>
</div>
}
}
#[component]
fn Window() -> impl IntoView {
view! {
<div>
<div>
<h3>"Windows"</h3>
<WindowWindows/>
</div>
<div>
<h3>"Monitors"</h3>
<WindowMonitors/>
</div>
<div>
<h3>"Events"</h3>
<WindowEvents/>
</div>
</div>
}
}
#[component]
fn WindowWindows() -> impl IntoView {
let current_window = create_action(|_| async move { tauri_sys::window::get_current() });
let all_windows = create_action(|_| async move { tauri_sys::window::get_all() });
let refresh = move |_| {
current_window.dispatch(());
all_windows.dispatch(());
};
current_window.dispatch(());
all_windows.dispatch(());
view! {
<div>
<div style="display: flex; justify-content: center; gap: 10px;">
<div>"Current window:"</div>
{move || {
current_window
.value()
.with(|window| match window {
None => "Loading".to_string(),
Some(window) => window.label().clone(),
})
}}
</div>
<div style="display: flex; justify-content: center; gap: 10px;">
<div>"All windows:"</div>
{move || {
all_windows
.value()
.with(|windows| match windows {
None => "Loading".to_string(),
Some(windows) => {
let out = windows
.iter()
.map(|window| { window.label().clone() })
.collect::<Vec<_>>()
.join(", ");
format!("[{out}]")
}
})
}}
</div>
<button on:click=refresh>"Refresh"</button>
</div>
}
}
#[component]
fn WindowMonitors() -> impl IntoView {
let current_monitor =
create_action(|_| async move { tauri_sys::window::current_monitor().await });
let primary_monitor =
create_action(|_| async move { tauri_sys::window::primary_monitor().await });
let available_monitors =
create_action(|_| async move { tauri_sys::window::available_monitors().await });
let monitor_from_point = create_action(|(x, y): &(isize, isize)| {
let x = x.clone();
let y = y.clone();
async move { tauri_sys::window::monitor_from_point(x, y).await }
});
// let cursor_position =
// create_action(|_| async move { tauri_sys::window::cursor_position().await });
let refresh = move |_| {
current_monitor.dispatch(());
primary_monitor.dispatch(());
available_monitors.dispatch(());
};
let oninput_monitor_from_point = move |e| {
let value = event_target_value(&e);
let Some((x, y)) = value.split_once(',') else {
return;
};
let Ok(x) = x.parse::<isize>() else {
return;
};
let Ok(y) = y.parse::<isize>() else {
return;
};
monitor_from_point.dispatch((x, y));
};
current_monitor.dispatch(());
primary_monitor.dispatch(());
available_monitors.dispatch(());
view! {
<div>
<div>
<div style="display: flex; justify-content: center; gap: 10px;">
<div>"Current monitor:"</div>
{move || {
current_monitor
.value()
.with(|monitor| match monitor {
None => "Loading".into_view(),
Some(Some(monitor)) => view! { <Monitor monitor/> }.into_view(),
Some(None) => "Could not detect monitor.".into_view(),
})
}}
</div>
<div style="display: flex; justify-content: center; gap: 10px;">
<div>"Primary monitor:"</div>
{move || {
primary_monitor
.value()
.with(|monitor| match monitor {
None => "Loading".into_view(),
Some(Some(monitor)) => view! { <Monitor monitor/> }.into_view(),
Some(None) => "Could not detect monitor.".into_view(),
})
}}
</div>
<div style="display: flex; justify-content: center; gap: 10px;">
<div>"Available monitors:"</div>
{move || {
available_monitors
.value()
.with(|monitors| match monitors {
None => "Loading".into_view(),
Some(monitors) => {
view! {
{monitors
.iter()
.map(|monitor| view! { <Monitor monitor/> })
.collect::<Vec<_>>()}
}
.into_view()
}
})
}}
</div>
<button on:click=refresh>"Refresh"</button>
</div>
<div>
<label>"Monitor from point" <input on:input=oninput_monitor_from_point/></label>
<div style="margin: 0 auto;">
{move || {
monitor_from_point
.value()
.with(|monitor| match monitor {
None => "Enter an `x, y` coordinate.".into_view(),
Some(Some(monitor)) => view! { <Monitor monitor/> }.into_view(),
Some(None) => "Could not detect monitor.".into_view(),
})
}}
</div>
</div>
<div>
// {move || {
// cursor_position
// .value()
// .with(|position| {
// position
// .as_ref()
// .map(|position| {
// view! {
// {position.x()}
// ", "
// {position.y()}
// }
// })
// })
// }}
<div>"Cursor position: "</div>
<div style="width: 50vw; height: 30vh; margin: 0 auto; border: 2px solid black; border-radius: 5px;">
// on:mousemove=move |_| cursor_position.dispatch(())
"TODO (See https://github.com/tauri-apps/tauri/issues/10340)"
</div>
</div>
</div>
}
}
#[component]
fn WindowEvents() -> impl IntoView {
use tauri_sys::window::{DragDropEvent, DragDropPayload, DragOverPayload};
let (count, set_count) = create_signal(0);
let increment_count = create_action(|count: &usize| {
let count = count.clone();
let window = tauri_sys::window::get_current();
async move {
web_sys::console::debug_1(&"0".into());
window.emit("count", count).await.unwrap();
}
});
let (drag_drop, set_drag_drop) = create_signal(().into_view());
spawn_local(async move {
let mut window = tauri_sys::window::get_current();
let mut listener = window.listen::<usize>("count").await.unwrap();
while let Some(event) = listener.next().await {
set_count(event.payload);
}
});
spawn_local(async move {
let window = tauri_sys::window::get_current();
let mut listener = window.on_drag_drop_event().await.unwrap();
while let Some(event) = listener.next().await {
match event.payload {
DragDropEvent::Enter(payload) => {
let out = view! {
<div>
<strong>"Enter"</strong>
<div>
"Paths: ["
{payload
.paths()
.iter()
.map(|path| path.to_string_lossy().to_string())
.collect::<Vec<_>>()
.join(", ")} "]"
</div>
<div>
"Position: " {payload.position().x()} ", " {payload.position().y()}
</div>
</div>
};
set_drag_drop(out.into_view());
}
DragDropEvent::Over(payload) => {
let out = view! {
<div>
<strong>"Over"</strong>
<div>
"Position: " {payload.position().x()} ", " {payload.position().y()}
</div>
</div>
};
set_drag_drop(out.into_view());
}
DragDropEvent::Drop(payload) => {
let out = view! {
<div>
<strong>"Drop"</strong>
<div>
"Paths: ["
{payload
.paths()
.iter()
.map(|path| path.to_string_lossy().to_string())
.collect::<Vec<_>>()
.join(", ")} "]"
</div>
<div>
"Position: " {payload.position().x()} ", " {payload.position().y()}
</div>
</div>
};
set_drag_drop(out.into_view());
}
DragDropEvent::Leave => {
let out = view! { <strong>"Leave"</strong> };
set_drag_drop(out.into_view());
}
}
}
});
view! {
<div>
<div>
"Count: " {count}
<button on:click=move |_| increment_count.dispatch(count() + 1)>"+"</button>
</div>
<div>
<h3>"Drag drop event"</h3>
<div>{drag_drop}</div>
</div>
</div>
}
}
#[component]
fn Monitor<'a>(monitor: &'a tauri_sys::window::Monitor) -> impl IntoView {
view! {
<div style="display: inline-block; text-align: left;">
<div>"Name: " {monitor.name().clone()}</div>
<div>"Size: " {monitor.size().width()} " x " {monitor.size().height()}</div>
<div>"Position: " {monitor.position().x()} ", " {monitor.position().y()}</div>
<div>"Scale: " {monitor.scale_factor()}</div>
</div>
}
}
#[component]
fn Menu() -> impl IntoView {
let (event, set_event) = create_signal::<Option<String>>(None);
let menu = create_local_resource(
|| (),
move |_| async move {
let menu = tauri_sys::menu::Menu::with_id("tauri-sys-menu").await;
let mut item_open = tauri_sys::menu::item::MenuItem::with_id("Open", "open").await;
let mut item_close = tauri_sys::menu::item::MenuItem::with_id("Close", "close").await;
menu.append_item(&item_open).await.unwrap();
menu.append_item(&item_close).await.unwrap();
spawn_local(async move {
let mut listener_item_open = item_open.listen().fuse();
let mut listener_item_close = item_close.listen().fuse();
loop {
futures::select! {
event = listener_item_open.next() => match event{
None => continue,
Some(event) => set_event(Some((*event).clone())),
},
event = listener_item_close.next() => match event{
None => continue,
Some(event) => set_event(Some((*event).clone())),
},
}
}
});
Rc::new(menu)
},
);
let default_menu = move |e: MouseEvent| {
spawn_local(async move {
let menu = tauri_sys::menu::Menu::default().await;
});
};
let open_menu = move |e: MouseEvent| {
let menu = menu.get().unwrap();
spawn_local(async move {
menu.popup().await.unwrap();
});
};
view! {
<div
on:mousedown=open_menu
style="margin: auto; width: 50vw; height: 10em; border: 1px black solid; border-radius: 5px;"
>
{event}
</div>
}
}

View file

@ -0,0 +1,33 @@
mod app;
use app::*;
use leptos::*;
fn main() {
#[cfg(debug_assertions)]
tracing::enable();
console_error_panic_hook::set_once();
mount_to_body(|| {
view! { <App/> }
})
}
#[cfg(debug_assertions)]
mod tracing {
use tracing::level_filters::LevelFilter;
use tracing_subscriber::prelude::*;
use tracing_web::MakeConsoleWriter;
const MAX_LOG_LEVEL: LevelFilter = LevelFilter::DEBUG;
pub fn enable() {
let fmt_layer = tracing_subscriber::fmt::layer()
.with_ansi(false) // Only partially supported across browsers
.pretty()
.without_time()
.with_writer(MakeConsoleWriter) // write events to the console
.with_filter(MAX_LOG_LEVEL);
tracing_subscriber::registry().with(fmt_layer).init();
}
}

112
examples/leptos/styles.css Normal file
View file

@ -0,0 +1,112 @@
.logo.leptos:hover {
filter: drop-shadow(0 0 2em #a82e20);
}
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
color: #0f0f0f;
background-color: #f6f6f6;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
.container {
margin: 0;
padding-top: 10vh;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: 0.75s;
}
.logo.tauri:hover {
filter: drop-shadow(0 0 2em #24c8db);
}
.row {
display: flex;
justify-content: center;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
h1 {
text-align: center;
}
input,
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
color: #0f0f0f;
background-color: #ffffff;
transition: border-color 0.25s;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
}
button {
cursor: pointer;
}
button:hover {
border-color: #396cd8;
}
button:active {
border-color: #396cd8;
background-color: #e8e8e8;
}
input,
button {
outline: none;
}
#greet-input {
margin-right: 5px;
}
@media (prefers-color-scheme: dark) {
:root {
color: #f6f6f6;
background-color: #2f2f2f;
}
a:hover {
color: #24c8db;
}
input,
button {
color: #ffffff;
background-color: #0f0f0f98;
}
button:active {
background-color: #0f0f0f69;
}
}

View file

@ -1,2 +1,3 @@
target
dist
/dist/
/target/
/Cargo.lock

3
examples/test/.vscode/extensions.json vendored Normal file
View file

@ -0,0 +1,3 @@
{
"recommendations": ["tauri-apps.tauri-vscode", "rust-lang.rust-analyzer"]
}

5
examples/test/.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,5 @@
{
"emmet.includeLanguages": {
"rust": "html"
}
}

4000
examples/test/Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,19 +1,19 @@
[package]
name = "tauri-sys-test-ui"
name = "test-tauri-events-ui"
version = "0.0.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tauri-sys = { path = "../../", features = ["all"] }
sycamore = { git = "https://github.com/sycamore-rs/sycamore", rev = "abd556cbc02047042dad2ebd04405e455a9b11b2", features = ["suspense"] }
anyhow = "1.0.75"
leptos = { version = "0.6", features = ["csr", "nightly"] }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
serde = { version = "1", features = ["derive"] }
serde-wasm-bindgen = "0.6"
console_error_panic_hook = "0.1.7"
wasm-bindgen-futures = "0.4.39"
serde = { version = "1.0.193", features = ["derive"] }
log = { version = "0.4.20", features = ["serde"] }
futures = "0.3.29"
gloo-timers = { version = "0.3", features = ["futures"] }
[features]
ci = []
tauri-sys = { path = "../../", features = ["all"] }
futures = "0.3"
tracing = "0.1.40"
tracing-subscriber = "0.3.18"
tracing-web = "0.1.3"

7
examples/test/README.md Normal file
View file

@ -0,0 +1,7 @@
# Tauri + Leptos
This template should help get you started developing with Tauri and Leptos.
## Recommended IDE Setup
[VS Code](https://code.visualstudio.com/) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer).

View file

@ -8,7 +8,3 @@ ignore = ["./src-tauri"]
address = "127.0.0.1"
port = 1420
open = false
[tools]
# Default wasm-bindgen version to download.
wasm_bindgen = "0.2.89"

View file

@ -1,8 +1,11 @@
<!DOCTYPE html>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Tauri + Yew App</title>
<link data-trunk rel="css" href="./styles.css">
<title>Tauri + Leptos App</title>
<link data-trunk rel="css" href="styles.css" />
<link data-trunk rel="copy-dir" href="public" />
<link data-trunk rel="rust" data-wasm-opt="z" />
</head>
<body></body>
</html>

View file

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 27.1.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 437.4294 209.6185" style="enable-background:new 0 0 437.4294 209.6185;" xml:space="preserve">
<path style="fill:none;" d="M130.0327,79.3931c-11.4854-0.23-22.52,9.3486-24.5034,21.0117l49.1157,0.0293
c-2.1729-10.418-11.1821-21.0449-24.1987-21.0449C130.3081,79.3892,130.1714,79.3907,130.0327,79.3931z"/>
<path style="fill:#181139;" d="M95.1109,128.1089H58.6797V65.6861c0-1.5234-0.8169-2.4331-2.1855-2.4331h-3.1187
c-1.3159,0-2.2349,1.0005-2.2349,2.4331v67.4297c0,1.4521,0.8145,2.2852,2.2349,2.2852h41.7353c1.4844,0,2.4819-0.9375,2.4819-2.333
v-2.7744C97.5928,128.9253,96.6651,128.1089,95.1109,128.1089z"/>
<path style="fill:#181139;" d="M146.4561,77.1739c-4.8252-3.001-10.3037-4.5249-16.2837-4.5288c-0.0068,0-0.0137,0-0.0205,0
c-5.7349,0-11.1377,1.4639-16.0566,4.3511c-4.916,2.8853-8.8721,6.8364-11.7593,11.7456
c-2.8975,4.9248-4.3687,10.332-4.3721,16.0713c-0.0034,5.7188,1.4966,11.0654,4.4565,15.8887
c2.9893,4.9209,6.8789,8.7334,11.8887,11.6514c4.8657,2.8633,10.2397,4.3174,15.9717,4.3203c0.0073,0,0.0146,0,0.022,0
c8.123,0,14.7441-2.5869,21.4683-8.3906c0.5493-0.4805,0.8516-1.1201,0.8516-1.8008c0.001-0.6074-0.1743-1.1035-0.5205-1.4756
l-1.3569-1.8428l-0.0732-0.0859c-0.2637-0.2637-0.6929-0.6152-1.3716-0.6152c-0.6421,0-1.2549,0.2217-1.7124,0.6143
c-1.9346,1.585-3.5459,2.8008-4.7969,3.6182c-1.7979,1.208-5.8218,3.2314-12.5986,3.2314c-0.0073,0-0.0142,0-0.021,0
c-0.1357,0.0029-0.269,0.0039-0.4043,0.0039c-12.2642,0-23.4736-10.3262-24.5088-22.4814l53.0127,0.0322c0.0015,0,0.0024,0,0.0034,0
c2.2373,0,3.4697-1.1621,3.4712-3.2715c0.0034-5.2588-1.3574-10.3945-4.0464-15.2705
C155.0015,84.0953,151.2188,80.1363,146.4561,77.1739z M154.6451,100.4341l-49.1157-0.0293
c1.9834-11.6631,13.0181-21.2417,24.5034-21.0117c0.1387-0.0024,0.2754-0.0039,0.4136-0.0039
C143.4629,79.3892,152.4722,90.0162,154.6451,100.4341z"/>
<path style="fill:#181139;" d="M204.0386,136.6382c5.7319,0,11.1069-1.4502,15.9746-4.3115
c4.938-2.9014,8.75-6.7129,11.6533-11.6533c2.8608-4.8672,4.311-10.2578,4.311-16.0244c0-5.7324-1.4502-11.1064-4.311-15.9746
c-2.9019-4.9385-6.7134-8.75-11.6533-11.6533c-4.8687-2.8618-10.2437-4.3125-15.9746-4.3125
c-9.938,0-19.2021,4.7583-24.3516,12.3174v-9.438c0-0.5946-0.1465-1.0788-0.411-1.4511c-0.3815-0.5369-1.0157-0.834-1.8727-0.834
h-2.6738c-1.4521,0-2.2852,0.833-2.2852,2.2852v5.6964v46.4791v23.9676c0,1.2568,0.7808,2.0371,2.0371,2.0371h3.3667
c0.9209,0,1.6421-0.6992,1.6421-1.5908v-17.098v-10.984C185.0884,131.8892,194.2749,136.6382,204.0386,136.6382z M186.6358,122.5591
c-4.9346-4.9346-7.6831-11.4932-7.542-18.0254c-0.1367-6.3506,2.5439-12.751,7.3545-17.5605
c4.8521-4.8521,11.3037-7.5547,17.7383-7.417c4.3691,0,8.4863,1.1465,12.2314,3.4043c3.7344,2.2979,6.7456,5.4053,8.9492,9.2354
c2.1699,3.9072,3.2695,8.0967,3.2695,12.4697c0.1396,6.4619-2.5967,12.9844-7.5083,17.8955
c-4.7617,4.7617-11.0469,7.3857-17.2544,7.2803C197.6856,129.9712,191.396,127.3208,186.6358,122.5591z"/>
<path style="fill:#181139;" d="M241.8955,80.3975h7.5669v42.0259c0,6.8174,4.5674,12.1309,11.0825,12.9189
c0.6836,0.1055,1.8379,0.1572,3.5303,0.1572c2.0078,0,3.0273-0.3535,3.0273-2.2842v-2.377c0-1.7891-1.334-2.0371-2.7568-2.0371
c0,0-0.001,0-0.002,0l-1.7871-0.0488c-2.0117-0.0439-3.4883-0.7627-4.3896-2.1367c-0.9697-1.4805-1.4619-3.1738-1.4619-5.0352
V80.3975h10.0928c1.3076,0,2.2852-1.3628,2.2852-2.5815v-1.9312c0-1.3999-0.8359-2.2354-2.2354-2.2354h-10.1426V60.6861
c0-1.4619-0.7969-2.4829-1.9375-2.4829c-0.1865,0-0.4121,0-0.6392,0.0884l-2.6489,0.6865
c-1.2109,0.3682-2.0171,0.9263-2.0171,2.4507v12.2207h-7.5669c-1.4185,0-2.335,0.897-2.335,2.2852v1.8813
C239.5606,79.2393,240.6079,80.3975,241.8955,80.3975z"/>
<path style="fill:#181139;" d="M379.1182,106.2691c-4.0488-2.9219-8.8545-5.0293-14.291-6.2646
c-6.5049-1.3975-13.4473-5.2129-13.3203-10.3066c0-7.5225,6.6367-10.1914,12.3203-10.1914c5.3574,0,10.2207,3.002,13.001,8.0146
c0.6729,1.2861,1.4785,1.9375,2.3955,1.9375c0.3311,0,0.7061-0.1113,0.9922-0.2832l2.2021-1.1523
c0.5947-0.3408,0.9229-0.9414,0.9229-1.6924c0-0.5205-0.0908-0.9541-0.2617-1.292c-3.6367-8.2466-10.0967-12.4282-19.2021-12.4282
c-11.7305,0-19.6123,6.9263-19.6123,17.2349c0,4.3125,1.8438,7.9746,5.4756,10.8809c3.4482,2.7979,7.9121,4.8623,13.2705,6.1377
c4.5859,1.085,8.3193,2.5654,11.0977,4.4023c1.4159,0.9354,2.4412,2.0535,3.106,3.3672c0.6053,1.1962,0.9135,2.5535,0.9135,4.1005
c0.0742,2.3857-0.79,4.5176-2.5684,6.3389c-3.1445,3.2178-8.4053,4.6689-12.0205,4.6689c-0.0361,0-0.0723,0-0.1074,0
c-3.4268,0-6.4893-0.8438-9.1035-2.5068c-2.5918-1.6484-4.2363-3.8076-5.0293-6.6064c-0.3203-1.0996-0.751-2.1738-2.1553-2.1738
c-0.0742,0-0.2109,0.0146-0.4062,0.0449c-0.1133,0.0166-0.2559,0.0381-0.5088,0.0742l-1.8818,0.4463l-0.1045,0.0332
c-1.0244,0.4082-1.6113,1.1846-1.6113,2.1309c0,0.2285,0.0625,0.6592,0.2178,1.1094c1.9707,8.5801,10.2432,14.3447,20.5732,14.3447
c0.125,0.002,0.249,0.002,0.374,0.002c6.5947,0,12.6748-2.3193,16.7275-6.3945c3.1895-3.208,4.8311-7.2363,4.748-11.6357
c0-2.8187-0.6185-5.3109-1.8062-7.481C382.4437,109.2624,381.0062,107.631,379.1182,106.2691z"/>
<path style="fill:#EF3939;" d="M348.9043,45.7325c0-6.3157-3.2826-11.8699-8.2238-15.0756
c-2.811-1.8237-6.1537-2.8947-9.7469-2.8947c-9.9092,0-17.9707,8.0615-17.9707,17.9702c0,4.7659,1.8775,9.0925,4.9157,12.3123
c-3.6619,4.3709-6.6334,9.3336-8.7663,14.7186c-1.5873-0.2422-3.2123-0.3683-4.8662-0.3683
c-17.7158,0-32.1289,14.4131-32.1289,32.1289c0,14.6854,9.9077,27.0922,23.3869,30.9101
c-6.7762,17.3461-23.6572,29.6719-43.3742,29.6719c-16.8195,0-31.583-8.9662-39.7656-22.369
c-2.4778,0.5446-5.0429,0.8519-7.6721,0.9023c9.0226,16.99,26.8969,28.5917,47.4377,28.5917
c23.2646,0,43.1121-14.8788,50.5461-35.6179c0.5204,0.0251,1.0435,0.0398,1.5701,0.0398c17.7158,0,32.1289-14.4131,32.1289-32.1289
c0-13.557-8.4446-25.1712-20.3465-29.8811c1.9001-4.5678,4.5115-8.7646,7.6888-12.4641c0.9996,0.4404,2.0479,0.785,3.1324,1.0384
c1.3144,0.3071,2.6773,0.486,4.0839,0.486C340.8428,63.7032,348.9043,55.6416,348.9043,45.7325z M304.2461,129.5279
c-13.7871,0-25.0039-11.2168-25.0039-25.0039s11.2168-25.0039,25.0039-25.0039S329.25,90.7369,329.25,104.524
S318.0332,129.5279,304.2461,129.5279z M330.9336,34.8872c0.645,0,1.2737,0.0671,1.8881,0.1755
c5.0818,0.8974,8.9576,5.3347,8.9576,10.6697c0,5.9805-4.8652,10.8457-10.8457,10.8457s-10.8457-4.8652-10.8457-10.8457
c0-1.3967,0.2746-2.7282,0.7576-3.9555C322.4306,37.7496,326.35,34.8872,330.9336,34.8872z"/>
</svg>

After

Width:  |  Height:  |  Size: 6.5 KiB

View file

@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

View file

@ -2,3 +2,6 @@
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas

View file

@ -1,28 +1,17 @@
[package]
name = "tauri-sys-test"
name = "test-tauri-events"
version = "0.0.0"
description = "A Tauri App"
authors = ["you"]
license = ""
repository = ""
edition = "2021"
rust-version = "1.57"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
tauri-build = { version = "1.5.0", features = [] }
tauri-build = { version = "2", features = [] }
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
tauri-plugin-log = {git = "https://github.com/tauri-apps/tauri-plugin-log", features = ["colored"] }
tauri = { version = "1.5.3", features = ["api-all", "updater"] }
[features]
# by default Tauri runs in production mode
# when `tauri dev` runs it is executed with `cargo run --no-default-features` if `devPath` is an URL
default = [ "custom-protocol" ]
# this feature is used for production builds where `devPath` points to the filesystem
# DO NOT remove this
custom-protocol = [ "tauri/custom-protocol" ]
tauri = { version = "2", features = [] }
tauri-plugin-shell = { version = "2" }
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1" }
tracing = { version = "0.1.40" }
tracing-subscriber = { version = "0.3.18" }

View file

@ -0,0 +1,17 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:path:default",
"core:event:default",
"core:window:default",
"core:app:default",
"core:image:default",
"core:resources:default",
"core:menu:default",
"core:tray:default",
"shell:allow-open"
]
}

View file

@ -1,6 +0,0 @@
{
"build": {
"beforeDevCommand": "trunk serve --features ci",
"beforeBuildCommand": "trunk build --release --features ci"
}
}

View file

@ -1,70 +1,41 @@
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::sync::atomic::{AtomicBool, Ordering};
use tauri::{Manager, Runtime, State, Window};
use tauri_plugin_log::{LogTarget, LoggerBuilder};
struct Received(AtomicBool);
// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn verify_receive(emitted: State<Received>) -> bool {
emitted.0.load(Ordering::Relaxed)
}
#[tauri::command]
async fn emit_event<R: Runtime>(win: Window<R>) -> Result<(), ()> {
let _ = win.emit("rust-event-once", "Hello World from Rust!");
Ok(())
}
#[tauri::command]
async fn emit_event_5_times<R: Runtime>(win: Window<R>) -> Result<(), ()> {
for i in 0..5 {
let _ = win.emit("rust-event-listen", i);
}
Ok(())
}
#[tauri::command]
fn exit_with_error(e: &str) -> bool {
eprintln!("{}", e);
std::process::exit(1);
}
use tauri::{Emitter, Manager};
fn main() {
let log_plugin = {
let targets = [
LogTarget::LogDir,
#[cfg(debug_assertions)]
LogTarget::Stdout,
#[cfg(debug_assertions)]
LogTarget::Webview,
];
LoggerBuilder::new().targets(targets).build()
};
logging::enable();
tauri::Builder::default()
.plugin(log_plugin)
.invoke_handler(tauri::generate_handler![verify_receive, emit_event, emit_event_5_times, exit_with_error])
.setup(|app| {
app.manage(Received(AtomicBool::new(false)));
let app_handle = app.handle();
app.listen_global("javascript-event", move |_| {
app_handle
.state::<Received>()
.0
.store(true, Ordering::Relaxed);
});
Ok(())
})
.invoke_handler(tauri::generate_handler![trigger_listen_events,])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
#[tauri::command]
fn trigger_listen_events(app: tauri::AppHandle) {
tracing::debug!("trigger_listen_event");
std::thread::spawn({
move || {
for i in 1..=100 {
app.emit("event::listen", i).unwrap();
std::thread::sleep(std::time::Duration::from_millis(500));
}
}
});
}
mod logging {
use tracing_subscriber::{filter::LevelFilter, fmt, prelude::*, Layer, Registry};
const MAX_LOG_LEVEL: LevelFilter = LevelFilter::DEBUG;
pub fn enable() {
let console_logger = fmt::layer()
.with_writer(std::io::stdout)
.pretty()
.with_filter(MAX_LOG_LEVEL);
let subscriber = Registry::default().with(console_logger);
tracing::subscriber::set_global_default(subscriber).unwrap();
}
}

View file

@ -1,71 +1,35 @@
{
"productName": "test-tauri-events",
"version": "0.0.0",
"identifier": "com.tauri.dev",
"build": {
"beforeDevCommand": "trunk serve",
"beforeBuildCommand": "trunk build --release",
"devPath": "http://localhost:1420",
"distDir": "../dist",
"withGlobalTauri": true
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "trunk build",
"frontendDist": "../dist"
},
"package": {
"productName": "tauri-sys-test",
"version": "0.0.0"
},
"tauri": {
"allowlist": {
"all": true
},
"bundle": {
"active": true,
"category": "DeveloperTool",
"copyright": "",
"deb": {
"depends": []
},
"externalBin": [],
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"identifier": "com.tauri.dev",
"longDescription": "",
"macOS": {
"entitlements": null,
"exceptionDomain": "",
"frameworks": [],
"providerShortName": null,
"signingIdentity": null
},
"resources": [],
"shortDescription": "",
"targets": "all",
"windows": {
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
"timestampUrl": ""
}
},
"security": {
"csp": null
},
"updater": {
"active": true,
"endpoints": [
"https://releases.myapp.com/{{target}}/{{current_version}}"
],
"dialog": true,
"pubkey": "YOUR_UPDATER_SIGNATURE_PUBKEY_HERE"
},
"app": {
"withGlobalTauri": true,
"windows": [
{
"fullscreen": false,
"height": 600,
"resizable": true,
"title": "tauri-sys testing suite",
"width": 800
"title": "test-tauri-events",
"width": 800,
"height": 600
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}

View file

@ -1,34 +1,569 @@
use anyhow::ensure;
use tauri_sys::app;
use futures::stream::StreamExt;
use leptos::{ev::MouseEvent, *};
use std::rc::Rc;
pub async fn get_name() -> anyhow::Result<()> {
let name = app::get_name().await?;
#[component]
pub fn App() -> impl IntoView {
view! {
<main class="container">
<div>
<h2>"core"</h2>
<Core/>
</div>
ensure!(name == "tauri-sys-test");
<div>
<h2>"events"</h2>
<Events/>
</div>
Ok(())
<div>
<h2>"window"</h2>
<Window/>
</div>
<div>
<h2>"menu"</h2>
<Menu/>
</div>
</main>
}
}
pub async fn get_version() -> anyhow::Result<()> {
let version = app::get_version().await?;
#[component]
fn Core() -> impl IntoView {
let (convert_path, set_convert_path) = create_signal("".to_string());
let (converted_path, set_converted_path) = create_signal("".to_string());
ensure!(version.major == 0);
ensure!(version.minor == 0);
ensure!(version.patch == 0);
ensure!(version.build.is_empty());
ensure!(version.pre.is_empty());
let do_convert_path = move |_| {
let converted = tauri_sys::core::convert_file_src(convert_path());
set_converted_path(converted);
};
Ok(())
view! {
<div>
<div>
<label>
"Convert path"
<input
prop:value=convert_path
on:input=move |e| set_convert_path(event_target_value(&e))
/>
</label>
<button on:click=do_convert_path>"Convert"</button>
</div>
<div>{converted_path}</div>
</div>
}
}
pub async fn get_tauri_version() -> anyhow::Result<()> {
let version = app::get_tauri_version().await?;
#[component]
fn Events() -> impl IntoView {
let (listen_event, set_listen_event) = create_signal(None);
let (emit_count, set_emit_count) = create_signal(0);
ensure!(version.major == 1);
ensure!(version.minor == 5);
ensure!(version.patch == 3);
ensure!(version.build.is_empty());
ensure!(version.pre.is_empty());
spawn_local(async move {
let mut listener = tauri_sys::event::listen::<i32>("event::listen")
.await
.unwrap();
Ok(())
while let Some(event) = listener.next().await {
tracing::debug!(?event);
let tauri_sys::event::Event {
event: _,
id: _,
payload,
} = event;
set_listen_event.set(Some(payload));
}
});
spawn_local(async move {
let mut listener = tauri_sys::event::listen::<i32>("event::emit")
.await
.unwrap();
while let Some(event) = listener.next().await {
tracing::debug!(?event);
let tauri_sys::event::Event {
event: _,
id: _,
payload,
} = event;
set_emit_count.set(payload);
}
});
let trigger_listen_events = move |_| {
spawn_local(async move {
tauri_sys::core::invoke::<()>("trigger_listen_events", &()).await;
});
};
let trigger_emit_event = move |_| {
spawn_local(async move {
tauri_sys::event::emit("event::emit", &emit_count.with_untracked(|n| n + 1))
.await
.unwrap();
});
};
view! {
<div>
<div>
<button on:click=trigger_listen_events>"Trigger listen events"</button>
<div>
<strong>"Last listen event: "</strong>
{move || listen_event()}
</div>
</div>
<div>
<button on:click=trigger_emit_event>"Trigger emit event"</button>
<div>
<strong>"Events emitted: "</strong>
{move || emit_count()}
</div>
</div>
</div>
}
}
#[component]
fn Window() -> impl IntoView {
view! {
<div>
<div>
<h3>"Windows"</h3>
<WindowWindows/>
</div>
<div>
<h3>"Monitors"</h3>
<WindowMonitors/>
</div>
<div>
<h3>"Events"</h3>
<WindowEvents/>
</div>
</div>
}
}
#[component]
fn WindowWindows() -> impl IntoView {
let current_window = create_action(|_| async move { tauri_sys::window::get_current() });
let all_windows = create_action(|_| async move { tauri_sys::window::get_all() });
let refresh = move |_| {
current_window.dispatch(());
all_windows.dispatch(());
};
current_window.dispatch(());
all_windows.dispatch(());
view! {
<div>
<div style="display: flex; justify-content: center; gap: 10px;">
<div>"Current window:"</div>
{move || {
current_window
.value()
.with(|window| match window {
None => "Loading".to_string(),
Some(window) => window.label().clone(),
})
}}
</div>
<div style="display: flex; justify-content: center; gap: 10px;">
<div>"All windows:"</div>
{move || {
all_windows
.value()
.with(|windows| match windows {
None => "Loading".to_string(),
Some(windows) => {
let out = windows
.iter()
.map(|window| { window.label().clone() })
.collect::<Vec<_>>()
.join(", ");
format!("[{out}]")
}
})
}}
</div>
<button on:click=refresh>"Refresh"</button>
</div>
}
}
#[component]
fn WindowMonitors() -> impl IntoView {
let current_monitor =
create_action(|_| async move { tauri_sys::window::current_monitor().await });
let primary_monitor =
create_action(|_| async move { tauri_sys::window::primary_monitor().await });
let available_monitors =
create_action(|_| async move { tauri_sys::window::available_monitors().await });
let monitor_from_point = create_action(|(x, y): &(isize, isize)| {
let x = x.clone();
let y = y.clone();
async move { tauri_sys::window::monitor_from_point(x, y).await }
});
// let cursor_position =
// create_action(|_| async move { tauri_sys::window::cursor_position().await });
let refresh = move |_| {
current_monitor.dispatch(());
primary_monitor.dispatch(());
available_monitors.dispatch(());
};
let oninput_monitor_from_point = move |e| {
let value = event_target_value(&e);
let Some((x, y)) = value.split_once(',') else {
return;
};
let Ok(x) = x.parse::<isize>() else {
return;
};
let Ok(y) = y.parse::<isize>() else {
return;
};
monitor_from_point.dispatch((x, y));
};
current_monitor.dispatch(());
primary_monitor.dispatch(());
available_monitors.dispatch(());
view! {
<div>
<div>
<div style="display: flex; justify-content: center; gap: 10px;">
<div>"Current monitor:"</div>
{move || {
current_monitor
.value()
.with(|monitor| match monitor {
None => "Loading".into_view(),
Some(Some(monitor)) => view! { <Monitor monitor/> }.into_view(),
Some(None) => "Could not detect monitor.".into_view(),
})
}}
</div>
<div style="display: flex; justify-content: center; gap: 10px;">
<div>"Primary monitor:"</div>
{move || {
primary_monitor
.value()
.with(|monitor| match monitor {
None => "Loading".into_view(),
Some(Some(monitor)) => view! { <Monitor monitor/> }.into_view(),
Some(None) => "Could not detect monitor.".into_view(),
})
}}
</div>
<div style="display: flex; justify-content: center; gap: 10px;">
<div>"Available monitors:"</div>
{move || {
available_monitors
.value()
.with(|monitors| match monitors {
None => "Loading".into_view(),
Some(monitors) => {
view! {
{monitors
.iter()
.map(|monitor| view! { <Monitor monitor/> })
.collect::<Vec<_>>()}
}
.into_view()
}
})
}}
</div>
<button on:click=refresh>"Refresh"</button>
</div>
<div>
<label>"Monitor from point" <input on:input=oninput_monitor_from_point/></label>
<div style="margin: 0 auto;">
{move || {
monitor_from_point
.value()
.with(|monitor| match monitor {
None => "Enter an `x, y` coordinate.".into_view(),
Some(Some(monitor)) => view! { <Monitor monitor/> }.into_view(),
Some(None) => "Could not detect monitor.".into_view(),
})
}}
</div>
</div>
<div>
// {move || {
// cursor_position
// .value()
// .with(|position| {
// position
// .as_ref()
// .map(|position| {
// view! {
// {position.x()}
// ", "
// {position.y()}
// }
// })
// })
// }}
<div>"Cursor position: "</div>
<div style="width: 50vw; height: 30vh; margin: 0 auto; border: 2px solid black; border-radius: 5px;">
// on:mousemove=move |_| cursor_position.dispatch(())
"TODO (See https://github.com/tauri-apps/tauri/issues/10340)"
</div>
</div>
</div>
}
}
#[component]
fn WindowEvents() -> impl IntoView {
use tauri_sys::window::{DragDropEvent, DragDropPayload, DragOverPayload};
let (count, set_count) = create_signal(0);
let increment_count = create_action(|count: &usize| {
let count = count.clone();
let window = tauri_sys::window::get_current();
async move {
web_sys::console::debug_1(&"0".into());
window.emit("count", count).await.unwrap();
}
});
let (drag_drop, set_drag_drop) = create_signal(().into_view());
spawn_local(async move {
let mut window = tauri_sys::window::get_current();
let mut listener = window.listen::<usize>("count").await.unwrap();
while let Some(event) = listener.next().await {
set_count(event.payload);
}
});
spawn_local(async move {
let window = tauri_sys::window::get_current();
let mut listener = window.on_drag_drop_event().await.unwrap();
while let Some(event) = listener.next().await {
match event.payload {
DragDropEvent::Enter(payload) => {
let out = view! {
<div>
<strong>"Enter"</strong>
<div>
"Paths: ["
{payload
.paths()
.iter()
.map(|path| path.to_string_lossy().to_string())
.collect::<Vec<_>>()
.join(", ")} "]"
</div>
<div>
"Position: " {payload.position().x()} ", " {payload.position().y()}
</div>
</div>
};
set_drag_drop(out.into_view());
}
DragDropEvent::Over(payload) => {
let out = view! {
<div>
<strong>"Over"</strong>
<div>
"Position: " {payload.position().x()} ", " {payload.position().y()}
</div>
</div>
};
set_drag_drop(out.into_view());
}
DragDropEvent::Drop(payload) => {
let out = view! {
<div>
<strong>"Drop"</strong>
<div>
"Paths: ["
{payload
.paths()
.iter()
.map(|path| path.to_string_lossy().to_string())
.collect::<Vec<_>>()
.join(", ")} "]"
</div>
<div>
"Position: " {payload.position().x()} ", " {payload.position().y()}
</div>
</div>
};
set_drag_drop(out.into_view());
}
DragDropEvent::Leave => {
let out = view! { <strong>"Leave"</strong> };
set_drag_drop(out.into_view());
}
}
}
});
view! {
<div>
<div>
"Count: " {count}
<button on:click=move |_| increment_count.dispatch(count() + 1)>"+"</button>
</div>
<div>
<h3>"Drag drop event"</h3>
<div>{drag_drop}</div>
</div>
</div>
}
}
#[component]
fn Monitor<'a>(monitor: &'a tauri_sys::window::Monitor) -> impl IntoView {
view! {
<div style="display: inline-block; text-align: left;">
<div>"Name: " {monitor.name().clone()}</div>
<div>"Size: " {monitor.size().width()} " x " {monitor.size().height()}</div>
<div>"Position: " {monitor.position().x()} ", " {monitor.position().y()}</div>
<div>"Scale: " {monitor.scale_factor()}</div>
</div>
}
}
#[component]
fn Menu() -> impl IntoView {
let (event_manual, set_event_manual) = create_signal::<Option<String>>(None);
let (event_with_items, set_event_with_items) = create_signal::<Option<String>>(None);
let default_menu = move |e: MouseEvent| {
spawn_local(async move {
let menu = tauri_sys::menu::Menu::default().await;
});
};
let menu_manual = create_local_resource(
|| (),
move |_| async move {
let menu = tauri_sys::menu::Menu::with_id("tauri-sys-menu").await;
let mut item_open =
tauri_sys::menu::item::MenuItem::with_id("Item 1 - Manual", "manual-item_1").await;
let mut item_close =
tauri_sys::menu::item::MenuItem::with_id("Item 2 - Manual", "manual-item_2").await;
menu.append_item(&item_open).await.unwrap();
menu.append_item(&item_close).await.unwrap();
spawn_local(async move {
let mut listener_item_open = item_open.listen().fuse();
let mut listener_item_close = item_close.listen().fuse();
loop {
futures::select! {
event = listener_item_open.next() => match event{
None => continue,
Some(event) => set_event_manual(Some(event.clone())),
},
event = listener_item_close.next() => match event{
None => continue,
Some(event) => set_event_manual(Some(event.clone())),
},
}
}
});
Rc::new(menu)
},
);
let menu_with_items = create_local_resource(
|| (),
move |_| async move {
let mut item_open = tauri_sys::menu::item::MenuItemOptions::new("Item 1 - w/ items");
item_open.set_id("w_items-item_1");
let mut item_close = tauri_sys::menu::item::MenuItemOptions::new("Item 2 - w/ items");
item_close.set_id("w_items-item_2");
let items = vec![item_open.into(), item_close.into()];
let (menu, mut listeners) =
tauri_sys::menu::Menu::with_id_and_items("tauri-sys_menu_w_items", items).await;
let mut listener_item_open = listeners.remove(0).unwrap().fuse();
let mut listener_item_close = listeners.remove(0).unwrap().fuse();
spawn_local(async move {
loop {
futures::select! {
event = listener_item_open.next() => match event{
None => continue,
Some(event) => {
set_event_with_items(Some(event.clone()))
},
},
event = listener_item_close.next() => match event{
None => continue,
Some(event) => set_event_with_items(Some(event.clone())),
},
}
}
});
Rc::new(menu)
},
);
let open_menu_manual = move |_e: MouseEvent| {
let menu = menu_manual.get().unwrap();
spawn_local(async move {
menu.popup().await.unwrap();
});
};
let open_menu_with_items = move |_e: MouseEvent| {
let menu = menu_with_items.get().unwrap();
spawn_local(async move {
menu.popup().await.unwrap();
});
};
view! {
<div
on:mousedown=open_menu_manual
style="margin: 0 auto 2em; width: 50vw; height: 10em; border: 1px black solid; border-radius: 5px;"
>
{event_manual}
</div>
<div
on:mousedown=open_menu_with_items
style="margin: auto; width: 50vw; height: 10em; border: 1px black solid; border-radius: 5px;"
>
{event_with_items}
</div>
}
}

View file

@ -1,12 +0,0 @@
use anyhow::ensure;
use tauri_sys::clipboard;
pub async fn test() -> anyhow::Result<()> {
clipboard::write_text("foobar").await?;
let text = clipboard::read_text().await?;
ensure!(text == "foobar".to_string());
Ok(())
}

View file

@ -1,93 +0,0 @@
use anyhow::ensure;
use tauri_sys::dialog::{FileDialogBuilder, MessageDialogBuilder, MessageDialogKind};
pub async fn ask() -> anyhow::Result<()> {
let works = MessageDialogBuilder::new()
.set_title("Tauri")
.set_kind(MessageDialogKind::Warning)
.ask("Does this work? \n Click Yes to mark this test as passing")
.await?;
ensure!(works);
Ok(())
}
pub async fn confirm() -> anyhow::Result<()> {
let works = MessageDialogBuilder::new()
.set_title("Tauri")
.set_kind(MessageDialogKind::Warning)
.confirm("Does this work? \n Click Ok to mark this test as passing")
.await?;
ensure!(works);
Ok(())
}
pub async fn message() -> anyhow::Result<()> {
MessageDialogBuilder::new()
.set_title("Tauri")
.set_kind(MessageDialogKind::Warning)
.message("This is a message just for you!")
.await?;
Ok(())
}
pub async fn pick_file() -> anyhow::Result<()> {
let file = FileDialogBuilder::new()
.set_title("Select a file to mark this test as passing")
.pick_file()
.await?;
ensure!(file.is_some());
Ok(())
}
pub async fn pick_files() -> anyhow::Result<()> {
let file = FileDialogBuilder::new()
.set_title("Select a multiple files to mark this test as passing")
.pick_files()
.await?;
ensure!(file.is_some());
ensure!(file.unwrap().count() > 1);
Ok(())
}
pub async fn pick_folder() -> anyhow::Result<()> {
let file = FileDialogBuilder::new()
.set_title("Select a folder to mark this test as passing")
.pick_folder()
.await?;
ensure!(file.is_some());
Ok(())
}
pub async fn pick_folders() -> anyhow::Result<()> {
let file = FileDialogBuilder::new()
.set_title("Select a multiple folders to mark this test as passing")
.pick_folders()
.await?;
ensure!(file.is_some());
ensure!(file.unwrap().count() > 1);
Ok(())
}
pub async fn save() -> anyhow::Result<()> {
let file = FileDialogBuilder::new()
.set_title("Select a file to mark this test as passing")
.save()
.await?;
ensure!(file.is_some());
Ok(())
}

View file

@ -1,38 +0,0 @@
use anyhow::ensure;
use futures::StreamExt;
use tauri_sys::{event, tauri};
pub async fn emit() -> anyhow::Result<()> {
event::emit("javascript-event", &"bar").await?;
ensure!(tauri::invoke::<_, bool>("verify_receive", &()).await?);
Ok(())
}
pub async fn listen() -> anyhow::Result<()> {
let events = event::listen::<u32>("rust-event-listen").await?;
tauri::invoke::<_, ()>("emit_event_5_times", &()).await?;
let events: Vec<u32> = events
.take(5)
.map(|e| e.payload)
.collect()
.await;
ensure!(events == vec![0, 1, 2, 3, 4]);
Ok(())
}
pub async fn once() -> anyhow::Result<()> {
// this causes enough delay for `once` to register it's event listener before the event gets triggered
wasm_bindgen_futures::spawn_local(async {
tauri::invoke::<_, ()>("emit_event", &()).await.unwrap();
});
let event = event::once::<String>("rust-event-once").await?;
ensure!(event.payload == "Hello World from Rust!");
Ok(())
}

View file

@ -1,31 +0,0 @@
use std::time::Duration;
use futures::StreamExt;
use tauri_sys::global_shortcut;
pub async fn register_all() -> anyhow::Result<()> {
let task = async {
let shortcuts = ["CommandOrControl+Shift+C", "Ctrl+Alt+F12"];
let streams = futures::future::try_join_all(shortcuts.map(|s| async move {
let stream = global_shortcut::register(s).await?;
anyhow::Ok(stream.map(move |_| s))
}))
.await?;
let mut events = futures::stream::select_all(streams);
while let Some(shortcut) = events.next().await {
log::debug!("Shortcut {} triggered", shortcut)
}
anyhow::Ok(())
};
let timeout = gloo_timers::future::sleep(Duration::from_secs(20));
futures::future::select(Box::pin(task), timeout).await;
Ok(())
}

View file

@ -1,196 +1,33 @@
mod app;
mod clipboard;
mod dialog;
mod event;
mod notification;
mod os;
mod tauri_log;
mod window;
mod global_shortcut;
extern crate console_error_panic_hook;
use log::LevelFilter;
use std::future::Future;
use std::panic;
use sycamore::prelude::*;
use sycamore::suspense::Suspense;
use tauri_log::TauriLogger;
#[cfg(feature = "ci")]
async fn exit_with_error(e: String) {
use serde::Serialize;
#[derive(Serialize)]
struct Args {
e: String,
}
tauri_sys::tauri::invoke::<_, ()>("exit_with_error", &Args { e })
.await
.unwrap();
}
#[derive(Props)]
pub struct TestProps<'a, F>
where
F: Future<Output = anyhow::Result<()>> + 'a,
{
name: &'a str,
test: F,
}
#[component]
pub async fn TestInner<'a, G: Html, F>(cx: Scope<'a>, props: TestProps<'a, F>) -> View<G>
where
F: Future<Output = anyhow::Result<()>> + 'a,
{
let res = props.test.await;
view! { cx,
tr {
td { code { (props.name.to_string()) } }
td { (if let Err(e) = &res {
#[cfg(feature = "ci")]
{
wasm_bindgen_futures::spawn_local(exit_with_error(e.to_string()));
unreachable!()
}
#[cfg(not(feature = "ci"))]
format!("{:?}", e)
} else {
format!("")
})
}
}
}
}
#[component]
pub fn Test<'a, G: Html, F>(cx: Scope<'a>, props: TestProps<'a, F>) -> View<G>
where
F: Future<Output = anyhow::Result<()>> + 'a,
{
let fallback = view! { cx,
tr {
td { code { (props.name.to_string()) } }
td {
span(class="loader") { "" }
}
}
};
view! { cx,
Suspense(fallback=fallback) {
TestInner(name=props.name, test=props.test)
}
}
}
#[cfg(not(feature = "ci"))]
#[component]
pub fn InteractiveTest<'a, G: Html, F>(cx: Scope<'a>, props: TestProps<'a, F>) -> View<G>
where
F: Future<Output = anyhow::Result<()>> + 'a,
{
let mut test = Some(props.test);
let render_test = create_signal(cx, false);
let run_test = |_| {
render_test.set(true);
};
view! { cx,
(if *render_test.get() {
let test = test.take().unwrap();
view! { cx,
Test(name=props.name, test=test)
}
} else {
view! { cx,
tr {
td { code { (props.name.to_string()) } }
td {
button(on:click=run_test) { "Run Interactive Test"}
}
}
}
})
}
}
#[cfg(feature = "ci")]
#[component]
pub async fn InteractiveTest<'a, G: Html, F>(cx: Scope<'a>, _props: TestProps<'a, F>) -> View<G>
where
F: Future<Output = anyhow::Result<()>> + 'a,
{
view! { cx, "Interactive tests are not run in CI mode" }
}
#[component]
pub async fn Terminate<'a, G: Html>(cx: Scope<'a>) -> View<G> {
#[cfg(feature = "ci")]
sycamore::suspense::await_suspense(cx, async {
tauri_sys::process::exit(0).await;
})
.await;
view! {
cx,
}
}
static LOGGER: TauriLogger = TauriLogger;
use app::*;
use leptos::*;
fn main() {
log::set_logger(&LOGGER)
.map(|()| log::set_max_level(LevelFilter::Trace))
.unwrap();
panic::set_hook(Box::new(|info| {
console_error_panic_hook::hook(info);
#[cfg(feature = "ci")]
wasm_bindgen_futures::spawn_local(exit_with_error(format!("{}", info)));
}));
sycamore::render(|cx| {
view! { cx,
table {
tbody {
// Suspense(fallback=view!{ cx, "Running Tests..." }) {
Test(name="app::get_name",test=app::get_name())
Test(name="app::get_version",test=app::get_version())
Test(name="app::get_tauri_version",test=app::get_tauri_version())
Test(name="clipboard::read_text | clipboard::write_text",test=clipboard::test())
Test(name="event::emit",test=event::emit())
Test(name="event::listen",test=event::listen())
Test(name="event::once",test=event::once())
InteractiveTest(name="dialog::message",test=dialog::message())
InteractiveTest(name="dialog::ask",test=dialog::ask())
InteractiveTest(name="dialog::confirm",test=dialog::confirm())
InteractiveTest(name="dialog::pick_file",test=dialog::pick_file())
InteractiveTest(name="dialog::pick_files",test=dialog::pick_files())
InteractiveTest(name="dialog::pick_folder",test=dialog::pick_folder())
InteractiveTest(name="dialog::pick_folders",test=dialog::pick_folders())
InteractiveTest(name="dialog::save",test=dialog::save())
Test(name="os::arch",test=os::arch())
Test(name="os::platform",test=os::platform())
Test(name="os::tempdir",test=os::tempdir())
Test(name="os::kind",test=os::kind())
Test(name="os::version",test=os::version())
Test(name="notification::is_permission_granted",test=notification::is_permission_granted())
Test(name="notification::request_permission",test=notification::request_permission())
InteractiveTest(name="notification::show_notification",test=notification::show_notification())
InteractiveTest(name="global_shortcut::register_all",test=global_shortcut::register_all())
Test(name="window::WebviewWindow::new",test=window::create_window())
Terminate
// }
}
}
}
});
#[cfg(debug_assertions)]
tracing::enable();
console_error_panic_hook::set_once();
mount_to_body(|| {
view! { <App/> }
})
}
#[cfg(debug_assertions)]
mod tracing {
use tracing::level_filters::LevelFilter;
use tracing_subscriber::prelude::*;
use tracing_web::MakeConsoleWriter;
const MAX_LOG_LEVEL: LevelFilter = LevelFilter::DEBUG;
pub fn enable() {
let fmt_layer = tracing_subscriber::fmt::layer()
.with_ansi(false) // Only partially supported across browsers
.pretty()
.without_time()
.with_writer(MakeConsoleWriter) // write events to the console
.with_filter(MAX_LOG_LEVEL);
tracing_subscriber::registry().with(fmt_layer).init();
}
}

View file

@ -1,28 +0,0 @@
use anyhow::ensure;
use tauri_sys::notification::{self, Permission};
pub async fn is_permission_granted() -> anyhow::Result<()> {
let granted = notification::is_permission_granted().await?;
ensure!(granted);
Ok(())
}
pub async fn request_permission() -> anyhow::Result<()> {
let permission = notification::request_permission().await?;
ensure!(permission == Permission::Granted);
Ok(())
}
pub async fn show_notification() -> anyhow::Result<()> {
let mut n = notification::Notification::default();
n.set_title("TAURI");
n.set_body("Tauri is awesome!");
n.show()?;
Ok(())
}

View file

@ -1,41 +0,0 @@
use tauri_sys::os;
pub async fn arch() -> anyhow::Result<()> {
let arch = os::arch().await?;
log::debug!("{:?}", arch);
Ok(())
}
pub async fn platform() -> anyhow::Result<()> {
let platform = os::platform().await?;
log::debug!("{:?}", platform);
Ok(())
}
pub async fn tempdir() -> anyhow::Result<()> {
let tempdir = os::tempdir().await?;
log::info!("{:?}", tempdir);
Ok(())
}
pub async fn kind() -> anyhow::Result<()> {
let kind = os::kind().await?;
log::debug!("{:?}", kind);
Ok(())
}
pub async fn version() -> anyhow::Result<()> {
let version = os::version().await?;
log::debug!("{:?}", version);
Ok(())
}

View file

@ -1,75 +0,0 @@
use log::{Metadata, Record};
use serde::Serialize;
use tauri_sys::tauri;
#[derive(Debug, Serialize)]
struct LogArgs {
level: Level,
message: String,
location: String,
file: Option<String>,
line: Option<u32>,
}
#[derive(Debug)]
enum Level {
Trace,
Debug,
Info,
Warn,
Error,
}
impl From<log::Level> for Level {
fn from(l: log::Level) -> Self {
match l {
log::Level::Error => Level::Error,
log::Level::Warn => Level::Warn,
log::Level::Info => Level::Info,
log::Level::Debug => Level::Debug,
log::Level::Trace => Level::Trace,
}
}
}
impl Serialize for Level {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_u8(match self {
Level::Trace => 1,
Level::Debug => 2,
Level::Info => 3,
Level::Warn => 4,
Level::Error => 5,
})
}
}
pub struct TauriLogger;
impl log::Log for TauriLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= log::Level::Trace
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
let args = LogArgs {
level: record.level().into(),
location: record.target().to_string(),
message: format!("{}", record.args()),
file: record.file().map(ToString::to_string),
line: record.line(),
};
wasm_bindgen_futures::spawn_local(async move {
tauri::invoke::<_, ()>("plugin:log|log", &args)
.await
.unwrap();
});
}
}
fn flush(&self) {}
}

View file

@ -1,15 +0,0 @@
use anyhow::ensure;
use tauri_sys::window;
pub async fn create_window() -> anyhow::Result<()> {
let win = window::WebviewWindowBuilder::new("foo-win")
.set_url("/")
.build()
.await?;
ensure!(win.is_visible().await?);
win.close().await?;
Ok(())
}

View file

@ -1,15 +1,112 @@
.loader {
transform-origin: baseline;
display: inline-block;
box-sizing: border-box;
animation: rotation 1.3s linear infinite;
.logo.leptos:hover {
filter: drop-shadow(0 0 2em #a82e20);
}
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
color: #0f0f0f;
background-color: #f6f6f6;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
@keyframes rotation {
0% {
transform: rotate(0deg);
.container {
margin: 0;
padding-top: 10vh;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: 0.75s;
}
.logo.tauri:hover {
filter: drop-shadow(0 0 2em #24c8db);
}
.row {
display: flex;
justify-content: center;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
h1 {
text-align: center;
}
input,
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
color: #0f0f0f;
background-color: #ffffff;
transition: border-color 0.25s;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
}
button {
cursor: pointer;
}
button:hover {
border-color: #396cd8;
}
button:active {
border-color: #396cd8;
background-color: #e8e8e8;
}
input,
button {
outline: none;
}
#greet-input {
margin-right: 5px;
}
@media (prefers-color-scheme: dark) {
:root {
color: #f6f6f6;
background-color: #2f2f2f;
}
100% {
transform: rotate(360deg);
a:hover {
color: #24c8db;
}
input,
button {
color: #ffffff;
background-color: #0f0f0f98;
}
button:active {
background-color: #0f0f0f69;
}
}

View file

@ -1,4 +1,7 @@
// tauri/tooling/api/src/core.ts
function transformCallback(callback, once = false) {
return window.__TAURI_INTERNALS__.transformCallback(callback, once)
}
async function invoke(cmd, args = {}) {
// NB: `options` ignored as not used here.
return window.__TAURI_INTERNALS__.invoke(cmd, args)
@ -8,5 +11,6 @@ function convertFileSrc(filePath, protocol = 'asset') {
}
export {
invoke,
convertFileSrc
convertFileSrc,
transformCallback,
}

View file

@ -1,8 +1,9 @@
//! Common functionality
use std::path::PathBuf;
use serde::{de::DeserializeOwned, Serialize};
use serde_wasm_bindgen as swb;
use wasm_bindgen::{prelude::Closure, JsValue};
pub use channel::{Channel, Message};
pub async fn invoke<T>(command: &str, args: impl Serialize) -> T
where
@ -38,16 +39,94 @@ pub fn convert_file_src_with_protocol(
.unwrap()
}
mod channel {
use super::inner;
use futures::{channel::mpsc, Stream, StreamExt};
use serde::{de::DeserializeOwned, ser::SerializeStruct, Deserialize, Serialize};
use wasm_bindgen::{prelude::Closure, JsValue};
#[derive(derive_more::Deref, Deserialize, Debug)]
pub struct Message<T> {
id: usize,
#[deref]
message: T,
}
impl<T> Message<T> {
pub fn id(&self) -> usize {
self.id
}
}
// TODO: Could cause memory leak because handler is never released.
#[derive(Debug)]
pub struct Channel<T> {
id: usize,
rx: mpsc::UnboundedReceiver<Message<T>>,
}
impl<T> Channel<T> {
pub fn new() -> Self
where
T: DeserializeOwned + 'static,
{
let (tx, rx) = mpsc::unbounded::<Message<T>>();
let closure = Closure::<dyn FnMut(JsValue)>::new(move |raw| {
let _ = tx.unbounded_send(serde_wasm_bindgen::from_value(raw).unwrap());
});
let id = inner::transform_callback(&closure, false);
closure.forget();
Channel { id, rx }
}
pub fn id(&self) -> usize {
self.id
}
}
impl<T> Serialize for Channel<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut map = serializer.serialize_struct("Channel", 2)?;
map.serialize_field("__TAURI_CHANNEL_MARKER__", &true)?;
map.serialize_field("id", &self.id)?;
map.end()
}
}
impl<T> Stream for Channel<T> {
type Item = T;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
self.rx
.poll_next_unpin(cx)
.map(|item| item.map(|value| value.message))
}
}
}
mod inner {
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
use wasm_bindgen::{
prelude::{wasm_bindgen, Closure},
JsValue,
};
#[wasm_bindgen(module = "/src/core.js")]
extern "C" {
#[wasm_bindgen]
pub async fn invoke(cmd: &str, args: JsValue) -> JsValue;
#[wasm_bindgen(js_name = "invoke", catch)]
pub async fn invoke_result(cmd: &str, args: JsValue) -> Result<JsValue, JsValue>;
#[wasm_bindgen(js_name = "convertFileSrc")]
pub fn convert_file_src(filePath: &str, protocol: &str) -> JsValue;
#[wasm_bindgen(js_name = "transformCallback")]
pub fn transform_callback(callback: &Closure<dyn FnMut(JsValue)>, once: bool) -> usize;
}
}

110
src/dpi.rs Normal file
View file

@ -0,0 +1,110 @@
use serde::Deserialize;
pub type ScaleFactor = f64;
pub type PixelCount = isize;
#[derive(Debug)]
pub enum Kind {
Logical,
Physical,
}
/// A size represented in logical pixels.
#[derive(Deserialize, Clone, Debug)]
pub struct LogicalSize {
width: PixelCount,
height: PixelCount,
}
impl LogicalSize {
pub fn kind() -> Kind {
Kind::Logical
}
pub fn width(&self) -> PixelCount {
self.width
}
pub fn height(&self) -> PixelCount {
self.height
}
}
/// A size represented in physical pixels.
#[derive(Deserialize, Clone, Debug)]
pub struct PhysicalSize {
width: PixelCount,
height: PixelCount,
}
impl PhysicalSize {
pub fn kind() -> Kind {
Kind::Physical
}
pub fn width(&self) -> PixelCount {
self.width
}
pub fn height(&self) -> PixelCount {
self.height
}
/// Converts the physical size to a logical one.
pub fn as_logical(&self, scale_factor: ScaleFactor) -> LogicalSize {
LogicalSize {
width: (self.width as f64 / scale_factor) as PixelCount,
height: (self.height as f64 / scale_factor) as PixelCount,
}
}
}
/// A position represented in logical pixels.
#[derive(Deserialize, Clone, Debug)]
pub struct LogicalPosition {
x: PixelCount,
y: PixelCount,
}
impl LogicalPosition {
pub fn kind() -> Kind {
Kind::Logical
}
pub fn x(&self) -> PixelCount {
self.x
}
pub fn y(&self) -> PixelCount {
self.y
}
}
/// A position represented in physical pixels.
#[derive(Deserialize, Clone, Debug)]
pub struct PhysicalPosition {
x: PixelCount,
y: PixelCount,
}
impl PhysicalPosition {
pub fn kind() -> Kind {
Kind::Physical
}
pub fn x(&self) -> PixelCount {
self.x
}
pub fn y(&self) -> PixelCount {
self.y
}
/// Converts the physical position to a logical one.
pub fn as_logical(&self, scale_factor: ScaleFactor) -> LogicalPosition {
LogicalPosition {
x: (self.x as f64 / scale_factor) as PixelCount,
y: (self.y as f64 / scale_factor) as PixelCount,
}
}
}

View file

@ -1,7 +1,7 @@
use std::path::PathBuf;
use wasm_bindgen::JsValue;
#[derive(Clone, Eq, PartialEq, Debug, thiserror::Error)]
#[derive(Clone, Eq, PartialEq, Debug, thiserror::Error, serde::Deserialize)]
pub enum Error {
#[error("Command returned Error: {0}")]
Command(String),

View file

@ -55,28 +55,9 @@ async function once(event, handler, options) {
)
}
// tauri/tooling/api/src/event.ts
var TauriEvent = /* @__PURE__ */ ((TauriEvent2) => {
TauriEvent2["WINDOW_RESIZED"] = 'tauri://resize';
TauriEvent2["WINDOW_MOVED"] = 'tauri://move';
TauriEvent2["WINDOW_CLOSE_REQUESTED"] = 'tauri://close-requested';
TauriEvent2["WINDOW_DESTROYED"] = 'tauri://destroyed';
TauriEvent2["WINDOW_FOCUS"] = 'tauri://focus';
TauriEvent2["WINDOW_BLUR"] = 'tauri://blur';
TauriEvent2["WINDOW_SCALE_FACTOR_CHANGED"] = 'tauri://scale-change';
TauriEvent2["WINDOW_THEME_CHANGED"] = 'tauri://theme-changed';
TauriEvent2["WINDOW_CREATED"] = 'tauri://window-created';
TauriEvent2["WEBVIEW_CREATED"] = 'tauri://webview-created';
TauriEvent2["DRAG"] = 'tauri://drag';
TauriEvent2["DROP"] = 'tauri://drop';
TauriEvent2["DROP_OVER"] = 'tauri://drop-over';
TauriEvent2["DROP_CANCELLED"] = 'tauri://drag-cancelled';
return TauriEvent2;
})(TauriEvent || {});
export {
TauriEvent,
emit,
emitTo,
listen,
once
once,
};

View file

@ -1,5 +1,4 @@
//! The event system allows you to emit events to the backend and listen to events from it.
use futures::{
channel::{mpsc, oneshot},
Future, FutureExt, Stream, StreamExt,
@ -8,13 +7,28 @@ use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::fmt::Debug;
use wasm_bindgen::{prelude::Closure, JsValue};
pub const WINDOW_RESIZED: &str = "tauri://resize";
pub const WINDOW_MOVED: &str = "tauri://move";
pub const WINDOW_CLOSE_REQUESTED: &str = "tauri://close-requested";
pub const WINDOW_DESTROYED: &str = "tauri://destroyed";
pub const WINDOW_FOCUS: &str = "tauri://focus";
pub const WINDOW_BLUR: &str = "tauri://blur";
pub const WINDOW_SCALE_FACTOR_CHANGED: &str = "tauri://scale-change";
pub const WINDOW_THEME_CHANGED: &str = "tauri://theme-changed";
pub const WINDOW_CREATED: &str = "tauri://window-created";
pub const WEBVIEW_CREATED: &str = "tauri://webview-created";
pub const DRAG_ENTER: &str = "tauri://drag-enter";
pub const DRAG_OVER: &str = "tauri://drag-over";
pub const DRAG_DROP: &str = "tauri://drag-drop";
pub const DRAG_LEAVE: &str = "tauri://drag-leave";
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Event<T> {
/// Event name
pub event: String,
/// Event identifier used to unlisten
pub id: f32,
pub id: isize,
/// Event payload
pub payload: T,
}
@ -31,8 +45,8 @@ pub enum EventTarget {
}
#[derive(Debug, Clone, PartialEq, Serialize)]
struct Options {
target: EventTarget,
pub(crate) struct Options {
pub target: EventTarget,
}
/// Emits an event to the backend.
@ -334,7 +348,7 @@ impl<T> Future for Once<T> {
}
}
mod inner {
pub(crate) mod inner {
use wasm_bindgen::{
prelude::{wasm_bindgen, Closure},
JsValue,

View file

@ -92,6 +92,15 @@ pub mod event;
#[cfg(feature = "core")]
pub mod core;
#[cfg(feature = "dpi")]
pub mod dpi;
#[cfg(feature = "menu")]
pub mod menu;
#[cfg(feature = "window")]
pub mod window;
pub use error::Error;
pub(crate) type Result<T> = std::result::Result<T, Error>;

0
src/menu.js Normal file
View file

362
src/menu.rs Normal file
View file

@ -0,0 +1,362 @@
//! # See also
//! + `tauri::menu`
use crate::{core, window};
use serde::{ser::SerializeStruct, Deserialize, Serialize};
use std::collections::HashMap;
type Rid = usize;
#[derive(Debug)]
pub struct Menu {
rid: Rid,
id: MenuId,
channel: Option<core::Channel<String>>,
}
impl Menu {
pub async fn with_id(id: impl Into<MenuId>) -> Self {
let (this, _) = Self::new(Some(id.into()), vec![]).await;
this
}
pub async fn with_items(items: Vec<NewMenuItem>) -> (Self, Vec<Option<core::Channel<String>>>) {
Self::new(None, items).await
}
pub async fn with_id_and_items(
id: impl Into<MenuId>,
items: Vec<NewMenuItem>,
) -> (Self, Vec<Option<core::Channel<String>>>) {
Self::new(Some(id.into()), items).await
}
async fn new(
id: Option<MenuId>,
items: Vec<NewMenuItem>,
) -> (Self, Vec<Option<core::Channel<String>>>) {
#[derive(Serialize)]
struct Args {
kind: String,
options: NewMenuOptions,
handler: ChannelId,
}
let channel = core::Channel::new();
let (items, item_channels) = items
.into_iter()
.map(|mut item| match item {
NewMenuItem::MenuItemsOptions(ref mut value) => {
let channel = core::Channel::new();
value.set_handler_channel_id(channel.id());
(item, Some(channel))
}
})
.unzip();
let options = NewMenuOptions { id, items };
let (rid, id) = core::invoke::<(Rid, String)>(
"plugin:menu|new",
Args {
kind: ItemId::Menu.as_str().to_string(),
options,
handler: ChannelId::from(&channel),
},
)
.await;
(
Self {
rid,
id: id.into(),
channel: Some(channel),
},
item_channels,
)
}
pub async fn default() -> Self {
let (rid, id) = core::invoke::<(Rid, String)>("plugin:menu|create_default", ()).await;
Self {
rid,
id: id.into(),
channel: None,
}
}
}
impl Menu {
pub fn rid(&self) -> Rid {
self.rid
}
pub fn kind() -> &'static str {
ItemId::Menu.as_str()
}
}
impl Menu {
pub async fn append_item(&self, item: &item::MenuItem) -> Result<(), ()> {
core::invoke_result(
"plugin:menu|append",
AppendItemArgs {
rid: self.rid,
kind: Self::kind().to_string(),
items: vec![(item.rid(), item::MenuItem::kind().to_string())],
},
)
.await
}
/// Popup this menu as a context menu on the specified window.
/// If the position, is provided, it is relative to the window's top-left corner.
pub async fn popup(&self) -> Result<(), ()> {
#[derive(Serialize)]
struct Position {
x: isize,
y: isize,
}
#[derive(Serialize)]
struct Args {
rid: Rid,
kind: String,
window: Option<window::WindowLabel>,
at: Option<HashMap<String, Position>>,
}
core::invoke_result(
"plugin:menu|popup",
Args {
rid: self.rid,
kind: Self::kind().to_string(),
window: None,
at: None,
},
)
.await
}
}
impl Menu {
pub fn listen(&mut self) -> Option<&mut core::Channel<String>> {
self.channel.as_mut()
}
}
#[derive(Serialize)]
struct AppendItemArgs {
rid: Rid,
kind: String,
items: Vec<(Rid, String)>,
}
#[derive(Serialize, Clone, derive_more::From, Debug)]
#[serde(transparent)]
pub struct MenuId(pub String);
impl From<&'static str> for MenuId {
fn from(value: &'static str) -> Self {
Self(value.to_string())
}
}
#[derive(Serialize)]
struct NewMenuOptions {
id: Option<MenuId>,
items: Vec<NewMenuItem>,
}
#[derive(Serialize, derive_more::From)]
#[serde(untagged)]
pub enum NewMenuItem {
MenuItemsOptions(item::MenuItemOptions),
}
#[derive(Serialize)]
enum OptionsKind {
MenuItem(item::MenuItemOptions),
}
enum ItemId {
MenuItem,
Predefined,
Check,
Icon,
Submenu,
Menu,
}
impl ItemId {
pub fn as_str(&self) -> &'static str {
match self {
Self::MenuItem => "MenuItem",
Self::Predefined => "Predefined",
Self::Check => "Check",
Self::Icon => "Icon",
Self::Submenu => "Submenu",
Self::Menu => "Menu",
}
}
}
struct ChannelId {
id: usize,
}
impl ChannelId {
pub fn from<T>(channel: &core::Channel<T>) -> Self {
Self { id: channel.id() }
}
}
impl Serialize for ChannelId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut map = serializer.serialize_struct("ChannelId", 2)?;
map.serialize_field("__TAURI_CHANNEL_MARKER__", &true)?;
map.serialize_field("id", &self.id)?;
map.end()
}
}
pub mod item {
use super::{ChannelId, ItemId, MenuId, Rid};
use crate::core;
use serde::{ser::SerializeStruct, Serialize};
pub struct MenuItem {
rid: Rid,
id: MenuId,
channel: core::Channel<String>,
}
impl MenuItem {
pub async fn with_id(text: impl Into<String>, id: impl Into<MenuId>) -> Self {
let mut options = MenuItemOptions::new(text);
options.set_id(id);
Self::with_options(options).await
}
pub async fn with_options(options: MenuItemOptions) -> Self {
#[derive(Serialize)]
struct Args {
kind: String,
options: MenuItemOptions,
handler: ChannelId,
}
let channel = core::Channel::new();
let (rid, id) = core::invoke::<(Rid, String)>(
"plugin:menu|new",
Args {
kind: ItemId::MenuItem.as_str().to_string(),
options,
handler: ChannelId::from(&channel),
},
)
.await;
Self {
rid,
id: id.into(),
channel,
}
}
}
impl MenuItem {
pub fn rid(&self) -> Rid {
self.rid
}
pub fn kind() -> &'static str {
ItemId::MenuItem.as_str()
}
}
impl MenuItem {
pub fn listen(&mut self) -> &mut core::Channel<String> {
&mut self.channel
}
}
#[derive(Serialize)]
pub struct MenuItemOptions {
/// Specify an id to use for the new menu item.
id: Option<MenuId>,
/// The text of the new menu item.
text: String,
/// Whether the new menu item is enabled or not.
enabled: Option<bool>,
/// Specify an accelerator for the new menu item.
accelerator: Option<String>,
/// Id to the channel handler.
#[serde(rename = "handler")]
handler_channel_id: Option<HandlerChannelId>,
}
impl MenuItemOptions {
pub fn new(text: impl Into<String>) -> Self {
Self {
id: None,
text: text.into(),
enabled: None,
accelerator: None,
handler_channel_id: None,
}
}
pub fn set_id(&mut self, id: impl Into<MenuId>) -> &mut Self {
let _ = self.id.insert(id.into());
self
}
pub fn set_enabled(&mut self, enabled: bool) -> &mut Self {
let _ = self.enabled.insert(enabled);
self
}
pub fn set_accelerator(&mut self, accelerator: impl Into<String>) -> &mut Self {
let _ = self.accelerator.insert(accelerator.into());
self
}
/// Set the handler channel id directly.
pub(crate) fn set_handler_channel_id(&mut self, id: usize) -> &mut Self {
let _ = self.handler_channel_id.insert(id.into());
self
}
}
#[derive(derive_more::From)]
struct HandlerChannelId(usize);
impl Serialize for HandlerChannelId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut map = serializer.serialize_struct("Channel", 2)?;
map.serialize_field("__TAURI_CHANNEL_MARKER__", &true)?;
map.serialize_field("id", &self.0)?;
map.end()
}
}
}
mod inner {
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
#[wasm_bindgen(module = "/src/menu.js")]
extern "C" {
#[wasm_bindgen(js_name = "getCurrent")]
pub fn get_current() -> JsValue;
}
}

38
src/window.js Normal file
View file

@ -0,0 +1,38 @@
// tauri/tooling/api/src/core.ts
async function invoke(cmd, args = {}) {
// NB: `options` ignored as not used here.
return window.__TAURI_INTERNALS__.invoke(cmd, args)
}
// tauri/tooling/api/src/window.ts
function getCurrent() {
return window.__TAURI_INTERNALS__.metadata.currentWindow
}
function getAll() {
return window.__TAURI_INTERNALS__.metadata.windows
}
async function currentMonitor() {
return invoke('plugin:window|current_monitor')
}
async function primaryMonitor() {
return invoke('plugin:window|primary_monitor')
}
async function monitorFromPoint(x, y) {
return invoke('plugin:window|monitor_from_point', { x, y })
}
async function availableMonitors() {
return invoke('plugin:window|available_monitors')
}
async function cursorPosition() {
return invoke('plugin:window|cursor_position')
}
export {
getCurrent,
getAll,
currentMonitor,
primaryMonitor,
monitorFromPoint,
availableMonitors,
cursorPosition,
}

748
src/window.rs Normal file
View file

@ -0,0 +1,748 @@
//! Provides APIs to create windows, communicate with other windows, and manipulate the current window.
//!
//! ## Window events
//! Events can be listened to using [`Window::listen`].
use crate::{
dpi,
event::{self, Event},
};
use futures::{
channel::{
mpsc::{self, UnboundedSender},
oneshot,
},
Future, FutureExt, Stream, StreamExt,
};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::{any::Any, collections::HashMap, path::PathBuf};
use wasm_bindgen::{prelude::Closure, JsValue};
/// Events that are emitted right here instead of by the created window.
const LOCAL_TAURI_EVENTS: &'static [&'static str; 2] = &["tauri://created", "tauri://error"];
trait SenderVec: Any {
fn as_any(&self) -> &dyn std::any::Any;
fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
}
impl<T> SenderVec for Vec<mpsc::UnboundedSender<T>>
where
T: DeserializeOwned + 'static,
{
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self as &mut dyn Any
}
}
pub(crate) struct Listen<T> {
pub rx: mpsc::UnboundedReceiver<T>,
}
impl<T> Stream for Listen<T> {
type Item = T;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
self.rx.poll_next_unpin(cx)
}
}
pub(crate) struct DragDropListen {
pub rx: mpsc::UnboundedReceiver<Event<DragDropEvent>>,
pub unlisten_enter: js_sys::Function,
pub unlisten_drop: js_sys::Function,
pub unlisten_over: js_sys::Function,
pub unlisten_leave: js_sys::Function,
}
impl Drop for DragDropListen {
fn drop(&mut self) {
log::debug!("Calling unlisten for listen callback");
self.unlisten_enter
.call0(&wasm_bindgen::JsValue::NULL)
.unwrap();
self.unlisten_drop
.call0(&wasm_bindgen::JsValue::NULL)
.unwrap();
self.unlisten_over
.call0(&wasm_bindgen::JsValue::NULL)
.unwrap();
self.unlisten_leave
.call0(&wasm_bindgen::JsValue::NULL)
.unwrap();
}
}
impl Stream for DragDropListen {
type Item = Event<DragDropEvent>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
self.rx.poll_next_unpin(cx)
}
}
#[derive(Serialize, Deserialize)]
pub(crate) struct WindowLabel {
label: String,
}
#[derive(Deserialize, Clone, Debug)]
pub enum DragDropEvent {
Enter(DragDropPayload),
Over(DragOverPayload),
Drop(DragDropPayload),
Leave,
}
#[derive(Deserialize, Clone, Debug)]
pub struct DragDropPayload {
paths: Vec<PathBuf>,
position: dpi::PhysicalPosition,
}
impl DragDropPayload {
pub fn paths(&self) -> &Vec<PathBuf> {
&self.paths
}
pub fn position(&self) -> &dpi::PhysicalPosition {
&self.position
}
}
#[derive(Deserialize, Clone, Debug)]
pub struct DragOverPayload {
position: dpi::PhysicalPosition,
}
impl DragOverPayload {
pub fn position(&self) -> &dpi::PhysicalPosition {
&self.position
}
}
pub struct Window {
label: String,
listeners: HashMap<String, Box<dyn SenderVec>>,
}
impl Window {
/// Create a new Window.
///
/// # Arguments
/// + `label`: Unique window label. Must be alphanumberic: `a-zA-Z-/:_`.
pub fn new(label: impl Into<String>) -> Self {
Self {
label: label.into(),
listeners: HashMap::new(),
}
}
/// Gets the Window associated with the given label.
pub fn get_by_label(label: impl AsRef<str>) -> Option<Self> {
js_sys::try_iter(&inner::get_all())
.unwrap()
.unwrap()
.into_iter()
.find_map(|value| {
let window_label = value.unwrap().as_string().unwrap();
if window_label == label.as_ref() {
Some(Window::new(window_label))
} else {
None
}
})
}
/// Get an instance of `Window` for the current window.
pub fn get_current() -> Self {
get_current()
}
/// Gets a list of instances of `Window` for all available windows.
pub fn get_all() -> Vec<Self> {
get_all()
}
}
impl Window {
pub fn label(&self) -> &String {
&self.label
}
fn handle_tauri_event<T>(&mut self, event: String) -> Option<impl Stream<Item = Event<T>>>
where
T: DeserializeOwned + 'static,
{
if LOCAL_TAURI_EVENTS.contains(&event.as_str()) {
let (tx, rx) = mpsc::unbounded::<Event<T>>();
let entry = self
.listeners
.entry(event)
.or_insert(Box::new(Vec::<mpsc::UnboundedSender<Event<T>>>::new()));
let senders = entry
.as_any_mut()
.downcast_mut::<Vec<mpsc::UnboundedSender<Event<T>>>>()
.unwrap();
senders.push(tx);
Some(Listen { rx })
} else {
None
}
}
}
impl Window {
/// Listen to an emitted event on this window.
///
/// # Arguments
/// + `event`: Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
/// + `handler`: Event handler.
///
/// # Returns
/// A function to unlisten to the event.
/// Note that removing the listener is required if your listener goes out of scope e.g. the component is unmounted.
pub async fn listen<T>(
&mut self,
event: impl Into<String>,
) -> crate::Result<impl Stream<Item = Event<T>>>
where
T: DeserializeOwned + 'static,
{
use futures::future::Either;
let event = event.into();
if let Some(listener) = self.handle_tauri_event(event.clone()) {
Ok(Either::Left(listener))
} else {
let listener =
event::listen_to(&event, event::EventTarget::Window(self.label.clone())).await?;
Ok(Either::Right(listener))
}
}
/// Listen to an emitted event on this window only once.
///
/// # Arguments
/// + `event`: Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
/// + `handler`: Event handler.
///
/// # Returns
/// A promise resolving to a function to unlisten to the event.
/// Note that removing the listener is required if your listener goes out of scope e.g. the component is unmounted.
pub async fn once(&self, event: impl Into<String>, handler: Closure<dyn FnMut(JsValue)>) {
todo!();
}
/// Emits an event to all {@link EventTarget|targets}.
///
/// # Arguments
/// + `event`: Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
/// + `payload`: Event payload.
pub async fn emit<T: Serialize + Clone + 'static>(
&self,
event: impl Into<String>,
payload: T,
) -> crate::Result<()> {
let event: String = event.into();
if LOCAL_TAURI_EVENTS.contains(&event.as_str()) {
if let Some(listeners) = self.listeners.get(&event) {
let listeners = listeners
.as_any()
.downcast_ref::<Vec<UnboundedSender<Event<T>>>>()
.unwrap();
for listener in listeners {
listener
.unbounded_send(event::Event {
event: event.clone(),
id: -1,
payload: payload.clone(),
})
.unwrap();
}
}
Ok(())
} else {
event::emit(event.as_str(), &payload).await
}
}
/// Emits an event to all {@link EventTarget|targets} matching the given target.
///
/// # Arguments
/// + `target`: Label of the target Window/Webview/WebviewWindow or raw {@link EventTarget} object.
/// + `event`: Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
/// + `payload`: Event payload.
pub async fn emit_to<T: Serialize + Clone + 'static>(
&self,
target: &event::EventTarget,
event: impl Into<String>,
payload: T,
) -> crate::Result<()> {
let event: String = event.into();
if LOCAL_TAURI_EVENTS.contains(&event.as_str()) {
if let Some(listeners) = self.listeners.get(&event) {
let listeners = listeners
.as_any()
.downcast_ref::<Vec<UnboundedSender<Event<T>>>>()
.unwrap();
for listener in listeners {
listener
.unbounded_send(event::Event {
event: event.clone(),
id: -1,
payload: payload.clone(),
})
.unwrap();
}
}
Ok(())
} else {
event::emit_to(target, event.as_str(), &payload).await
}
}
}
impl Window {
/// Listen to a file drop event.
/// The listener is triggered when the user hovers the selected files on the webview,
/// drops the files or cancels the operation.
///
/// # Returns
/// Function to unlisten to the event.
/// Note that removing the listener is required if your listener goes out of scope e.g. the component is unmounted.
pub async fn on_drag_drop_event(
&self,
) -> crate::Result<impl Stream<Item = Event<DragDropEvent>>> {
let (tx, rx) = mpsc::unbounded::<Event<DragDropEvent>>();
let closure = {
let tx = tx.clone();
Closure::<dyn FnMut(JsValue)>::new(move |raw| {
let Event { event, id, payload } =
serde_wasm_bindgen::from_value::<Event<DragDropPayload>>(raw).unwrap();
let _ = tx.unbounded_send(Event {
event,
id,
payload: DragDropEvent::Enter(payload),
});
})
};
let unlisten = event::inner::listen(
event::DRAG_ENTER,
&closure,
serde_wasm_bindgen::to_value(&event::Options {
target: event::EventTarget::Window(self.label.clone()),
})?,
)
.await?;
closure.forget();
let unlisten_enter = js_sys::Function::from(unlisten);
let closure = {
let tx = tx.clone();
Closure::<dyn FnMut(JsValue)>::new(move |raw| {
let Event { event, id, payload } =
serde_wasm_bindgen::from_value::<Event<DragDropPayload>>(raw).unwrap();
let _ = tx.unbounded_send(Event {
event,
id,
payload: DragDropEvent::Drop(payload),
});
})
};
let unlisten = event::inner::listen(
event::DRAG_DROP,
&closure,
serde_wasm_bindgen::to_value(&event::Options {
target: event::EventTarget::Window(self.label.clone()),
})?,
)
.await?;
closure.forget();
let unlisten_drop = js_sys::Function::from(unlisten);
let closure = {
let tx = tx.clone();
Closure::<dyn FnMut(JsValue)>::new(move |raw| {
let Event { event, id, payload } =
serde_wasm_bindgen::from_value::<Event<DragOverPayload>>(raw).unwrap();
let _ = tx.unbounded_send(Event {
event,
id,
payload: DragDropEvent::Over(payload),
});
})
};
let unlisten = event::inner::listen(
event::DRAG_OVER,
&closure,
serde_wasm_bindgen::to_value(&event::Options {
target: event::EventTarget::Window(self.label.clone()),
})?,
)
.await?;
closure.forget();
let unlisten_over = js_sys::Function::from(unlisten);
let closure = {
let tx = tx.clone();
Closure::<dyn FnMut(JsValue)>::new(move |raw| {
let Event { event, id, .. } =
serde_wasm_bindgen::from_value::<Event<()>>(raw).unwrap();
let _ = tx.unbounded_send(Event {
event,
id,
payload: DragDropEvent::Leave,
});
})
};
let unlisten = event::inner::listen(
event::DRAG_LEAVE,
&closure,
serde_wasm_bindgen::to_value(&event::Options {
target: event::EventTarget::Window(self.label.clone()),
})?,
)
.await?;
closure.forget();
let unlisten_leave = js_sys::Function::from(unlisten);
Ok(DragDropListen {
rx,
unlisten_enter,
unlisten_drop,
unlisten_over,
unlisten_leave,
})
}
}
#[derive(Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Monitor {
/// Human-readable name of the monitor.
name: Option<String>,
/// The monitor's resolution.
size: dpi::PhysicalSize,
/// the Top-left corner position of the monitor relative to the larger full screen area.
position: dpi::PhysicalPosition,
/// The scale factor that can be used to map physical pixels to logical pixels.
scale_factor: f64,
}
impl Monitor {
pub fn name(&self) -> &Option<String> {
&self.name
}
pub fn size(&self) -> &dpi::PhysicalSize {
&self.size
}
pub fn position(&self) -> &dpi::PhysicalPosition {
&self.position
}
pub fn scale_factor(&self) -> f64 {
self.scale_factor
}
}
pub fn get_current() -> Window {
let WindowLabel { label } = serde_wasm_bindgen::from_value(inner::get_current()).unwrap();
Window::new(label)
}
pub fn get_all() -> Vec<Window> {
js_sys::try_iter(&inner::get_all())
.unwrap()
.unwrap()
.into_iter()
.map(|value| {
let WindowLabel { label } = serde_wasm_bindgen::from_value(value.unwrap()).unwrap();
Window::new(label)
})
.collect()
}
/// # Returns
/// Monitor on which the window currently resides.
pub async fn current_monitor() -> Option<Monitor> {
let value = inner::current_monitor().await;
if value.is_null() {
None
} else {
Some(serde_wasm_bindgen::from_value(value).unwrap())
}
}
/// # Returns
/// Primary monitor of the system.
pub async fn primary_monitor() -> Option<Monitor> {
let value = inner::primary_monitor().await;
if value.is_null() {
None
} else {
Some(serde_wasm_bindgen::from_value(value).unwrap())
}
}
/// # Returns
/// Monitor that contains the given point.
pub async fn monitor_from_point(x: isize, y: isize) -> Option<Monitor> {
let value = inner::monitor_from_point(x, y).await;
if value.is_null() {
None
} else {
Some(serde_wasm_bindgen::from_value(value).unwrap())
}
}
/// # Returns
/// All the monitors available on the system.
pub async fn available_monitors() -> Vec<Monitor> {
let value = inner::available_monitors().await;
js_sys::try_iter(&value)
.unwrap()
.unwrap()
.into_iter()
.map(|value| serde_wasm_bindgen::from_value(value.unwrap()).unwrap())
.collect()
}
// TODO: Issue with cursorPosition in Tauri.
// See: https://github.com/tauri-apps/tauri/issues/10340
///// Get the cursor position relative to the top-left hand corner of the desktop.
/////
///// Note that the top-left hand corner of the desktop is not necessarily the same as the screen.
///// If the user uses a desktop with multiple monitors,
///// the top-left hand corner of the desktop is the top-left hand corner of the main monitor on Windows and macOS
///// or the top-left of the leftmost monitor on X11.
/////
///// The coordinates can be negative if the top-left hand corner of the window is outside of the visible screen region.
//pub async fn cursor_position() -> PhysicalPosition {
// serde_wasm_bindgen::from_value(inner::cursor_position().await).unwrap()
//}
mod inner {
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
#[wasm_bindgen(module = "/src/window.js")]
extern "C" {
#[wasm_bindgen(js_name = "getCurrent")]
pub fn get_current() -> JsValue;
#[wasm_bindgen(js_name = "getAll")]
pub fn get_all() -> JsValue;
#[wasm_bindgen(js_name = "currentMonitor")]
pub async fn current_monitor() -> JsValue;
#[wasm_bindgen(js_name = "primaryMonitor")]
pub async fn primary_monitor() -> JsValue;
#[wasm_bindgen(js_name = "monitorFromPoint")]
pub async fn monitor_from_point(x: isize, y: isize) -> JsValue;
#[wasm_bindgen(js_name = "availableMonitors")]
pub async fn available_monitors() -> JsValue;
#[wasm_bindgen(js_name = "cursorPosition")]
pub async fn cursor_position() -> JsValue;
}
}
// partial mocks
/*
pub enum Theme {
Light,
Dark,
}
/// Attention type to request on a window.
pub enum UserAttentionType {
/// # Platform-specific
/// - **macOS:** Bounces the dock icon until the application is in focus.
/// - **Windows:** Flashes both the window and the taskbar button until the application is in focus.
Critical = 1,
/// # Platform-specific
/// - **macOS:** Bounces the dock icon once.
/// - **Windows:** Flashes the taskbar button until the application is in focus.
Informational,
}
impl Window {
/// The scale factor that can be used to map physical pixels to logical pixels.
pub async fn scale_factor(&self) -> dpi::ScaleFactor {
todo!();
}
/// The position of the top-left hand corner of the window's client area relative to the top-left hand corner of the desktop.
pub async fn inner_position(&self) -> dpi::PhysicalPosition {
todo!();
}
/// The position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.
pub async fn outer_position(&self) -> dpi::PhysicalPosition {
todo!();
}
/// The physical size of the window's client area.
/// The client area is the content of the window, excluding the title bar and borders.
pub async fn inner_size(&self) -> dpi::PhysicalSize {
todo!();
}
/// The physical size of the entire window.
/// These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
pub async fn outer_size(&self) -> dpi::PhysicalSize {
todo!();
}
/// Gets the window's current fullscreen state.
pub async fn is_fullscreen(&self) -> bool {
todo!();
}
/// Gets the window's current minimized state.
pub async fn is_minimized(&self) -> bool {
todo!();
}
/// Gets the window's current maximized state.
pub async fn is_maximized(&self) -> bool {
todo!();
}
/// Gets the window's current focused state.
pub async fn is_focused(&self) -> bool {
todo!();
}
/// Gets the window's current decorated state.
pub async fn is_decorated(&self) -> bool {
todo!();
}
/// Gets the window's current resizable state.
pub async fn is_resizable(&self) -> bool {
todo!();
}
/// Gets the window's current visible state.
pub async fn is_visible(&self) -> bool {
todo!();
}
/// Gets the window's current title.
pub async fn title(&self) -> String {
todo!();
}
/// Gets the window's current theme.
pub async fn theme(&self) -> Option<Theme> {
todo!();
}
}
/// # Platform-specific
/// - **Linux / iOS / Android:** Unsupported.
impl Window {
/// Gets the window's native maximize button state.
///
/// # Platform-specific
/// - **Linux / iOS / Android:** Unsupported.
pub async fn is_maximizable(&self) -> bool {
todo!();
}
/// Gets the window's native minimize button state.
///
/// # Platform-specific
/// - **Linux / iOS / Android:** Unsupported.
pub async fn is_minimizable(&self) -> bool {
todo!();
}
/// Gets the window's native close button state.
///
/// # Platform-specific
/// - **Linux / iOS / Android:** Unsupported.
pub async fn is_closable(&self) -> bool {
todo!();
}
}
impl Window {
/// Centers the window.
///
/// # Returns
/// The success or failure of the operation.
pub async fn center(&self) -> Result<(), ()> {
todo!();
}
/// Requests user attention to the window, this has no effect if the application
/// is already focused. How requesting for user attention manifests is platform dependent,
/// see `UserAttentionType` for details.
///
/// Providing `null` will unset the request for user attention. Unsetting the request for
/// user attention might not be done automatically by the WM when the window receives input.
///
/// # Platform-specific
/// - **macOS:** `null` has no effect.
/// - **Linux:** Urgency levels have the same effect.
///
/// # Returns
/// The success or failure of the operation.
pub async fn request_user_attention() -> Result<(), ()> {
todo!();
}
/// Requests user attention to the window, this has no effect if the application
/// is already focused. How requesting for user attention manifests is platform dependent,
/// see `UserAttentionType` for details.
///
/// Providing `null` will unset the request for user attention. Unsetting the request for
/// user attention might not be done automatically by the WM when the window receives input.
///
/// # Platform-specific
/// - **macOS:** `null` has no effect.
/// - **Linux:** Urgency levels have the same effect.
///
/// # Returns
/// The success or failure of the operation.
pub async fn request_user_attention_with_type(
request_type: UserAttentionType,
) -> Result<(), ()> {
todo!();
}
/// Updates the window resizable flag.
///
/// # Returns
/// The success or failure of the operation.
pub async fn set_resizable(&self, resizable: bool) -> Result<(), ()> {
todo!();
}
}
*/