Merged
Upstream-sync 30 november (upstream 6f153287)
hephaestus bot
wants to merge
21 commits
from
kvt/upstream-sync-1130
into
master
Overview Commits 21 Pipelines 3 Changes 124
Zes nieuwe upstream-commits (Google OAuth-client in Instellingen, Windows MSAL-sleutel, Defender-aanmelding, berichttijd, Opnieuw/Verzenden, URL-hosts via parser). Conflicten opgelost in links.rs, app-base/Cargo.toml, release_feed.rs, app.yml (nl-vertalingen erbij) en docs/decisions (onze ADR 0024 is 0025). Lokaal groen: kvt-sleutels, app-state, app-base, chatsvc, app (456 tests), layout_guard, packaging/kvt/tests.sh. Details in KVT-FORK.md.
Activity
- hephaestus Pipeline #561 is Passed 30 November 2026
- hephaestus opened this merge request 30 November 2026
- hephaestus Pipeline #562 is Failed 30 November 2026
-
hephaestus
pushed
30 November 2026
ci(kvt): toelichting app_test en KVT-FORK.md
- hephaestus Pipeline #563 is Passed 30 November 2026
-
hephaestus
pushed
30 November 2026
ci(kvt): libpulse-dev in ci-setup.sh en libpulse in de AUR-PKGBUILD's (upstream linkt Pulse)
- hephaestus merged this merge request 30 November 2026
Commits
- ci(kvt): libpulse-dev in ci-setup.sh en libpulse in de AUR-PKGBUILD's (upstream linkt Pulse)
397b685a5ehephaestus - ci(kvt): toelichting app_test en KVT-FORK.md
b97c85cc2dhephaestus - KVT-FORK.md: upstream-sync van 30 november
bd06e07a2bhephaestus - Merge remote-tracking branch 'kvt/master' into kvt/upstream-sync-1130
b8bc0d3d83hephaestus - Upstream-merge: KVT-links via open_link::open_url, sleutels-sessiehosts toegestaan
49774714d6hephaestus - Merge upstream main (6f153287) into master
71f649e521hephaestus - fix(security): check URL hosts with a parser and route opened links through one gate
6f1532871fmetis - fix(chat): the message time no longer covers the end of the last line (#157)
d5f922eb93metis - fix(sign-in): Teams behind Defender for Cloud Apps no longer hangs on the sign-in screen (#154)
c47a197474metis - feat(calendar): enter your own Google OAuth client in Settings (#151)
6dd18f36e0metis - fix(auth): Windows keeps the MSAL cache key across restarts (#152)
e248a41ca5metis - fix(chat): Retry and Send now under a failed message work again (#160)
907b0380c0metis - fix(chat): message times keep the chosen 12- or 24-hour format (#158)
3b60e2c107metis - fix(calling): end a Wayland portal share quietly after frames (#147)
08cf519ed7metis - fix(calling): a gone incoming call ends as cancelled (#142)
dcc3e9b84ametis - fix(audio): play Linux call tones on the saved Pulse sink (#141)
06ae9ed51dmetis - fix(diagnostics): drop Linux audio-device enumeration lines (#140)
f8f077fe69metis - fix(calling): an early send limit still applies when the camera starts (#139)
e9c3659921metis - fix(chat): code block composer test expects the header mark
bf6052cf9ametis - refactor(session): one MSAL cache unseal helper for token fetch and sign-in check
024e3bbed2metis - feat(chat): code blocks open on ```, show Copy in Teams, confirm Copy (#145)
c5f9d2596dmetis
Pipelines
Changes
@@ -14,13 +14,14 @@ runs:
14
14
run: |
15
15
# README: "Linux build needs clang + mold (set in .cargo/config.toml)".
16
16
# The rest are headers the calling stack probes at build time: glib for webrtc-sys,
17
# alsa for cpal, v4l2 for nokhwa (bindgen wants libclang), xkbcommon and fontconfig
18
# for GPUI (font lookup via yeslogic-fontconfig-sys),
17
# alsa for cpal, Pulse for call tones (libpulse-simple), v4l2 for nokhwa
18
# (bindgen wants libclang), xkbcommon and fontconfig for GPUI
19
# (font lookup via yeslogic-fontconfig-sys),
19
20
# libva enables the hardware video codecs of webrtc-sys.
20
21
sudo apt-get update
21
22
sudo apt-get install --no-install-recommends -y \
22
23
clang mold pkg-config libclang-dev \
23
libglib2.0-dev libfontconfig-dev libasound2-dev libva-dev \
24
libglib2.0-dev libfontconfig-dev libasound2-dev libpulse-dev libva-dev \
24
25
libxkbcommon-dev libxkbcommon-x11-dev \
25
26
libx11-dev libxcb1-dev libxext-dev libxfixes-dev libxdamage-dev \
26
27
libxrandr-dev libxcomposite-dev libwayland-dev libpipewire-0.3-dev
@@ -14,13 +14,14 @@ runs:14
run: |14
run: |15
# README: "Linux build needs clang + mold (set in .cargo/config.toml)".15
# README: "Linux build needs clang + mold (set in .cargo/config.toml)".16
# The rest are headers the calling stack probes at build time: glib for webrtc-sys,16
# The rest are headers the calling stack probes at build time: glib for webrtc-sys,17
# alsa for cpal, v4l2 for nokhwa (bindgen wants libclang), xkbcommon and fontconfig17
# alsa for cpal, Pulse for call tones (libpulse-simple), v4l2 for nokhwa18
# for GPUI (font lookup via yeslogic-fontconfig-sys),18
# (bindgen wants libclang), xkbcommon and fontconfig for GPUI19
# (font lookup via yeslogic-fontconfig-sys),19
# libva enables the hardware video codecs of webrtc-sys.20
# libva enables the hardware video codecs of webrtc-sys.20
sudo apt-get update21
sudo apt-get update21
sudo apt-get install --no-install-recommends -y \22
sudo apt-get install --no-install-recommends -y \22
clang mold pkg-config libclang-dev \23
clang mold pkg-config libclang-dev \23
libglib2.0-dev libfontconfig-dev libasound2-dev libva-dev \24
libglib2.0-dev libfontconfig-dev libasound2-dev libpulse-dev libva-dev \24
libxkbcommon-dev libxkbcommon-x11-dev \25
libxkbcommon-dev libxkbcommon-x11-dev \25
libx11-dev libxcb1-dev libxext-dev libxfixes-dev libxdamage-dev \26
libx11-dev libxcb1-dev libxext-dev libxfixes-dev libxdamage-dev \26
libxrandr-dev libxcomposite-dev libwayland-dev libpipewire-0.3-dev27
libxrandr-dev libxcomposite-dev libwayland-dev libpipewire-0.3-dev@@ -324,6 +324,8 @@ dependencies = [
324
324
"ksni",
325
325
"kvt-update",
326
326
"libc",
327
"libpulse-binding",
328
"libpulse-simple-binding",
327
329
"log",
328
330
"mcp",
329
331
"raw-window-handle",
@@ -340,6 +342,7 @@ dependencies = [
340
342
"tempfile",
341
343
"tokio",
342
344
"tray-icon",
345
"url",
343
346
"wayland-client",
344
347
"wayland-protocols",
345
348
"windows 0.62.2",
@@ -1226,6 +1229,8 @@ dependencies = [
1226
1229
"libwebrtc",
1227
1230
"ndarray",
1228
1231
"nokhwa",
1232
"objc2 0.6.5",
1233
"objc2-foundation 0.3.2",
1229
1234
"ort",
1230
1235
"serde",
1231
1236
"serde_json",
@@ -1234,6 +1239,7 @@ dependencies = [
1234
1239
"thiserror 2.0.21",
1235
1240
"tokio",
1236
1241
"tract-onnx",
1242
"url",
1237
1243
"uuid",
1238
1244
"webrtc-sys",
1239
1245
"webview",
@@ -5294,6 +5300,54 @@ version = "0.2.16"
5294
5300
source = "registry+https://github.com/rust-lang/crates.io-index"
5295
5301
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
5296
5302
5303
[[package]]
5304
name = "libpulse-binding"
5305
version = "2.30.1"
5306
source = "registry+https://github.com/rust-lang/crates.io-index"
5307
checksum = "909eb3049e16e373680fe65afe6e2a722ace06b671250cc4849557bc57d6a397"
5308
dependencies = [
5309
"bitflags 2.13.2",
5310
"libc",
5311
"libpulse-sys",
5312
"num-derive",
5313
"num-traits",
5314
"winapi",
5315
]
5316
5317
[[package]]
5318
name = "libpulse-simple-binding"
5319
version = "2.29.0"
5320
source = "registry+https://github.com/rust-lang/crates.io-index"
5321
checksum = "b7bebef0381c8e3e4b23cc24aaf36fab37472bece128de96f6a111efa464cfef"
5322
dependencies = [
5323
"libpulse-binding",
5324
"libpulse-simple-sys",
5325
"libpulse-sys",
5326
]
5327
5328
[[package]]
5329
name = "libpulse-simple-sys"
5330
version = "1.22.0"
5331
source = "registry+https://github.com/rust-lang/crates.io-index"
5332
checksum = "3bd96888fe37ad270d16abf5e82cccca1424871cf6afa2861824d2a52758eebc"
5333
dependencies = [
5334
"libpulse-sys",
5335
"pkg-config",
5336
]
5337
5338
[[package]]
5339
name = "libpulse-sys"
5340
version = "1.23.0"
5341
source = "registry+https://github.com/rust-lang/crates.io-index"
5342
checksum = "d74371848b22e989f829cc1621d2ebd74960711557d8b45cfe740f60d0a05e61"
5343
dependencies = [
5344
"libc",
5345
"num-derive",
5346
"num-traits",
5347
"pkg-config",
5348
"winapi",
5349
]
5350
5297
5351
[[package]]
5298
5352
name = "libredox"
5299
5353
version = "0.1.25"
@@ -6226,7 +6280,7 @@ version = "0.7.6"
6226
6280
source = "registry+https://github.com/rust-lang/crates.io-index"
6227
6281
checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
6228
6282
dependencies = [
6229
"proc-macro-crate 1.3.1",
6283
"proc-macro-crate 3.5.0",
6230
6284
"proc-macro2",
6231
6285
"quote",
6232
6286
"syn 2.0.119",
@@ -9434,7 +9488,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
9434
9488
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
9435
9489
dependencies = [
9436
9490
"fastrand",
9437
"getrandom 0.3.4",
9491
"getrandom 0.4.3",
9438
9492
"once_cell",
9439
9493
"rustix 1.1.5",
9440
9494
"windows-sys 0.61.2",
@@ -11073,7 +11127,7 @@ version = "0.1.11"
11073
11127
source = "registry+https://github.com/rust-lang/crates.io-index"
11074
11128
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
11075
11129
dependencies = [
11076
"windows-sys 0.48.0",
11130
"windows-sys 0.61.2",
11077
11131
]
11078
11132
11079
11133
[[package]]
@@ -324,6 +324,8 @@ dependencies = [324
"ksni",324
"ksni",325
"kvt-update",325
"kvt-update",326
"libc",326
"libc",327
"libpulse-binding",328
"libpulse-simple-binding",327
"log",329
"log",328
"mcp",330
"mcp",329
"raw-window-handle",331
"raw-window-handle",@@ -340,6 +342,7 @@ dependencies = [340
"tempfile",342
"tempfile",341
"tokio",343
"tokio",342
"tray-icon",344
"tray-icon",345
"url",343
"wayland-client",346
"wayland-client",344
"wayland-protocols",347
"wayland-protocols",345
"windows 0.62.2",348
"windows 0.62.2",@@ -1226,6 +1229,8 @@ dependencies = [1226
"libwebrtc",1229
"libwebrtc",1227
"ndarray",1230
"ndarray",1228
"nokhwa",1231
"nokhwa",1232
"objc2 0.6.5",1233
"objc2-foundation 0.3.2",1229
"ort",1234
"ort",1230
"serde",1235
"serde",1231
"serde_json",1236
"serde_json",@@ -1234,6 +1239,7 @@ dependencies = [1234
"thiserror 2.0.21",1239
"thiserror 2.0.21",1235
"tokio",1240
"tokio",1236
"tract-onnx",1241
"tract-onnx",1242
"url",1237
"uuid",1243
"uuid",1238
"webrtc-sys",1244
"webrtc-sys",1239
"webview",1245
"webview",@@ -5294,6 +5300,54 @@ version = "0.2.16"5294
source = "registry+https://github.com/rust-lang/crates.io-index"5300
source = "registry+https://github.com/rust-lang/crates.io-index"5295
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"5301
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"5296
5302
5303
[[package]]5304
name = "libpulse-binding"5305
version = "2.30.1"5306
source = "registry+https://github.com/rust-lang/crates.io-index"5307
checksum = "909eb3049e16e373680fe65afe6e2a722ace06b671250cc4849557bc57d6a397"5308
dependencies = [5309
"bitflags 2.13.2",5310
"libc",5311
"libpulse-sys",5312
"num-derive",5313
"num-traits",5314
"winapi",5315
]5316
5317
[[package]]5318
name = "libpulse-simple-binding"5319
version = "2.29.0"5320
source = "registry+https://github.com/rust-lang/crates.io-index"5321
checksum = "b7bebef0381c8e3e4b23cc24aaf36fab37472bece128de96f6a111efa464cfef"5322
dependencies = [5323
"libpulse-binding",5324
"libpulse-simple-sys",5325
"libpulse-sys",5326
]5327
5328
[[package]]5329
name = "libpulse-simple-sys"5330
version = "1.22.0"5331
source = "registry+https://github.com/rust-lang/crates.io-index"5332
checksum = "3bd96888fe37ad270d16abf5e82cccca1424871cf6afa2861824d2a52758eebc"5333
dependencies = [5334
"libpulse-sys",5335
"pkg-config",5336
]5337
5338
[[package]]5339
name = "libpulse-sys"5340
version = "1.23.0"5341
source = "registry+https://github.com/rust-lang/crates.io-index"5342
checksum = "d74371848b22e989f829cc1621d2ebd74960711557d8b45cfe740f60d0a05e61"5343
dependencies = [5344
"libc",5345
"num-derive",5346
"num-traits",5347
"pkg-config",5348
"winapi",5349
]5350
5297
[[package]]5351
[[package]]5298
name = "libredox"5352
name = "libredox"5299
version = "0.1.25"5353
version = "0.1.25"@@ -6226,7 +6280,7 @@ version = "0.7.6"6226
source = "registry+https://github.com/rust-lang/crates.io-index"6280
source = "registry+https://github.com/rust-lang/crates.io-index"6227
checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"6281
checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"6228
dependencies = [6282
dependencies = [6229
"proc-macro-crate 1.3.1",6283
"proc-macro-crate 3.5.0",6230
"proc-macro2",6284
"proc-macro2",6231
"quote",6285
"quote",6232
"syn 2.0.119",6286
"syn 2.0.119",@@ -9434,7 +9488,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"9434
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"9488
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"9435
dependencies = [9489
dependencies = [9436
"fastrand",9490
"fastrand",9437
"getrandom 0.3.4",9491
"getrandom 0.4.3",9438
"once_cell",9492
"once_cell",9439
"rustix 1.1.5",9493
"rustix 1.1.5",9440
"windows-sys 0.61.2",9494
"windows-sys 0.61.2",@@ -11073,7 +11127,7 @@ version = "0.1.11"11073
source = "registry+https://github.com/rust-lang/crates.io-index"11127
source = "registry+https://github.com/rust-lang/crates.io-index"11074
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"11128
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"11075
dependencies = [11129
dependencies = [11076
"windows-sys 0.48.0",11130
"windows-sys 0.61.2",11077
]11131
]11078
11132
11079
[[package]]11133
[[package]]@@ -111,15 +111,36 @@ teruggedraaid, de rest blijft:
111
111
(`kvt-rusty-teams-bin`) en `publish_aur_source` (`kvt-rusty-teams`, zonder `needs`). Geen
112
112
`when: manual` meer.
113
113
- **Blijft:** de `CARGO_HOME`/`RUSTUP_HOME`-exports in `linux_release`, `windows_release` en
114
`app_test` (anders zoekt `. "$CARGO_HOME/env"` in `$HOME/.cargo`, eerste echte run, pipeline 542)
115
`ci-setup.sh` maakt `cargo-home/env` zelf aan als de cache die niet bevat (de cache bewaart alleen
116
`cargo-home/bin`; zonder dat bestand stopte `app_test` in pipeline 556), en de lichtere `ci-setup.sh`: `clang-21` via het apt.llvm.org-repo zelf en niet via `llvm.sh`
117
(dat ook lldb, lld en clangd bijzet), zonder `software-properties-common`.
114
`app_test` (anders zoekt `. "$CARGO_HOME/env"` in `$HOME/.cargo`, eerste echte run, pipeline 542).
115
- **`ci-setup.sh`:** maakt `cargo-home/env` zelf aan als de cache dat bestand niet bevat (de cache
116
bewaart alleen `cargo-home/bin`; zonder dat bestand stopte `app_test` in pipeline 556). Installeert
117
`clang-21` via het apt.llvm.org-repo zelf en niet via `llvm.sh` (dat ook lldb, lld en clangd bijzet),
118
zonder `software-properties-common`.
118
119
119
120
Merge-tip: conflict in `blue-ci-cd.yml` of `Cargo.toml` alleen de KVT-jobs en
120
121
`[profile.ci]` terugzetten; de release-, AUR- en checksum-scripts zelf zijn
121
122
ongewijzigd.
122
123
124
### Upstream-sync van 30 november 2026 (upstream `6f153287`)
125
126
Zes upstream-commits erbij (Google OAuth-client in Instellingen, Windows-MSAL-sleutel, Defender-aanmelding,
127
berichttijd, Opnieuw/Verzenden-knoppen, URL-hosts via een parser). Conflicten en keuzes:
128
129
- `crates/chatsvc/src/links.rs`: onze `hosted_content_fields`/`hosted_content_object_id` (custom emoji) blijven;
130
upstreams `Url::parse`-normalisatie zit nu in `hosted_content_image_url`.
131
- `crates/app-base/Cargo.toml`: `kvt-update` en `url` staan allebei.
132
- `crates/app-base/src/release_feed.rs`: de aanroep van `kvt_feed::releases` blijft.
133
- `app.yml`: upstreams teksten (Zwitserse ss) plus onze `nl`-regels; de nieuwe `google_client_*`-sleutels
134
kregen een Nederlandse vertaling.
135
- ADR: onze `0024` is `0025` geworden (upstream gebruikt `0024` voor de Google-client).
136
- Upstream linkt de belltonen nu tegen Pulse (`libpulse-simple`): `libpulse-dev` staat in `ci-setup.sh`
137
(zonder bleef de linkstap van `app_test` hangen op `libpulse-simple.so.0`), en `libpulse` in `depends`
138
van beide AUR-PKGBUILD's (`.SRCINFO` van `aur-source` bijgewerkt). `app_test` start nu ook bij een
139
wijziging van `packaging/kvt/ci-setup.sh`.
140
- Nieuwe upstream-regels: links openen via `app_base::open_link::open_url` (ook in `kvt/tickets.rs` en
141
`kvt/mod.rs`), en `kvt-sleutels/src/session.rs` staat in `ALLOWED_PATHS` van
142
`crates/chatsvc/tests/internal_endpoints.rs` (inlogdomeinen van het sleuteltabblad).
143
123
144
### AUR-pakket dat van de broncode bouwt — `packaging/aur-source/`
124
145
125
146
Op verzoek van Tim (t2295u) naast `kvt-rusty-teams-bin`: `kvt-rusty-teams` bouwt een release-tag
@@ -240,7 +261,7 @@ trekt hem in bij de Login en wist hem. `KVT_SLEUTELS_URL` (alleen `https://`) wi
240
261
Login/Mímir aan, bijvoorbeeld .test.
241
262
242
263
Taal: knoppen volgen de app-taal (standaard Nederlands, zie «Nederlandse UI»), veldnamen en waarden in het Nederlands uit Mímir. `--demo` toont een verzonnen bericht in de
243
chat met Jonas Ortega en verzonnen kaarten. Besluit: ADR 0024.
264
chat met Jonas Ortega en verzonnen kaarten. Besluit: ADR 0025.
244
265
245
266
| | |
246
267
|---|---|
@@ -251,7 +272,7 @@ chat met Jonas Ortega en verzonnen kaarten. Besluit: ADR 0024.
251
272
252
273
### Asclepius, Ponos en Daedalus vanuit Rusty Teams
253
274
254
Zelfde koppeling (app-token, scopes `asclepius ponos daedalus`), geen nieuwe inlog. Besluit: ADR 0024.
275
Zelfde koppeling (app-token, scopes `asclepius ponos daedalus`), geen nieuwe inlog. Besluit: ADR 0025.
255
276
256
277
- **Ticket maken in Asclepius** (berichtmenu, «Create Asclepius ticket»): opent het formulier
257
278
«Nieuw ticket maken» in de app (zie «Asclepius-tegel»), vooraf ingevuld: titel = eerste regel (max.
@@ -111,15 +111,36 @@ teruggedraaid, de rest blijft:111
(`kvt-rusty-teams-bin`) en `publish_aur_source` (`kvt-rusty-teams`, zonder `needs`). Geen111
(`kvt-rusty-teams-bin`) en `publish_aur_source` (`kvt-rusty-teams`, zonder `needs`). Geen112
`when: manual` meer.112
`when: manual` meer.113
- **Blijft:** de `CARGO_HOME`/`RUSTUP_HOME`-exports in `linux_release`, `windows_release` en113
- **Blijft:** de `CARGO_HOME`/`RUSTUP_HOME`-exports in `linux_release`, `windows_release` en114
`app_test` (anders zoekt `. "$CARGO_HOME/env"` in `$HOME/.cargo`, eerste echte run, pipeline 542)114
`app_test` (anders zoekt `. "$CARGO_HOME/env"` in `$HOME/.cargo`, eerste echte run, pipeline 542).115
`ci-setup.sh` maakt `cargo-home/env` zelf aan als de cache die niet bevat (de cache bewaart alleen115
- **`ci-setup.sh`:** maakt `cargo-home/env` zelf aan als de cache dat bestand niet bevat (de cache116
`cargo-home/bin`; zonder dat bestand stopte `app_test` in pipeline 556), en de lichtere `ci-setup.sh`: `clang-21` via het apt.llvm.org-repo zelf en niet via `llvm.sh`116
bewaart alleen `cargo-home/bin`; zonder dat bestand stopte `app_test` in pipeline 556). Installeert117
(dat ook lldb, lld en clangd bijzet), zonder `software-properties-common`.117
`clang-21` via het apt.llvm.org-repo zelf en niet via `llvm.sh` (dat ook lldb, lld en clangd bijzet),118
zonder `software-properties-common`.118
119
119
Merge-tip: conflict in `blue-ci-cd.yml` of `Cargo.toml` alleen de KVT-jobs en120
Merge-tip: conflict in `blue-ci-cd.yml` of `Cargo.toml` alleen de KVT-jobs en120
`[profile.ci]` terugzetten; de release-, AUR- en checksum-scripts zelf zijn121
`[profile.ci]` terugzetten; de release-, AUR- en checksum-scripts zelf zijn121
ongewijzigd.122
ongewijzigd.122
123
124
### Upstream-sync van 30 november 2026 (upstream `6f153287`)125
126
Zes upstream-commits erbij (Google OAuth-client in Instellingen, Windows-MSAL-sleutel, Defender-aanmelding,127
berichttijd, Opnieuw/Verzenden-knoppen, URL-hosts via een parser). Conflicten en keuzes:128
129
- `crates/chatsvc/src/links.rs`: onze `hosted_content_fields`/`hosted_content_object_id` (custom emoji) blijven;130
upstreams `Url::parse`-normalisatie zit nu in `hosted_content_image_url`.131
- `crates/app-base/Cargo.toml`: `kvt-update` en `url` staan allebei.132
- `crates/app-base/src/release_feed.rs`: de aanroep van `kvt_feed::releases` blijft.133
- `app.yml`: upstreams teksten (Zwitserse ss) plus onze `nl`-regels; de nieuwe `google_client_*`-sleutels134
kregen een Nederlandse vertaling.135
- ADR: onze `0024` is `0025` geworden (upstream gebruikt `0024` voor de Google-client).136
- Upstream linkt de belltonen nu tegen Pulse (`libpulse-simple`): `libpulse-dev` staat in `ci-setup.sh`137
(zonder bleef de linkstap van `app_test` hangen op `libpulse-simple.so.0`), en `libpulse` in `depends`138
van beide AUR-PKGBUILD's (`.SRCINFO` van `aur-source` bijgewerkt). `app_test` start nu ook bij een139
wijziging van `packaging/kvt/ci-setup.sh`.140
- Nieuwe upstream-regels: links openen via `app_base::open_link::open_url` (ook in `kvt/tickets.rs` en141
`kvt/mod.rs`), en `kvt-sleutels/src/session.rs` staat in `ALLOWED_PATHS` van142
`crates/chatsvc/tests/internal_endpoints.rs` (inlogdomeinen van het sleuteltabblad).143
123
### AUR-pakket dat van de broncode bouwt — `packaging/aur-source/`144
### AUR-pakket dat van de broncode bouwt — `packaging/aur-source/`124
145
125
Op verzoek van Tim (t2295u) naast `kvt-rusty-teams-bin`: `kvt-rusty-teams` bouwt een release-tag146
Op verzoek van Tim (t2295u) naast `kvt-rusty-teams-bin`: `kvt-rusty-teams` bouwt een release-tag@@ -240,7 +261,7 @@ trekt hem in bij de Login en wist hem. `KVT_SLEUTELS_URL` (alleen `https://`) wi240
Login/Mímir aan, bijvoorbeeld .test.261
Login/Mímir aan, bijvoorbeeld .test.241
262
242
Taal: knoppen volgen de app-taal (standaard Nederlands, zie «Nederlandse UI»), veldnamen en waarden in het Nederlands uit Mímir. `--demo` toont een verzonnen bericht in de263
Taal: knoppen volgen de app-taal (standaard Nederlands, zie «Nederlandse UI»), veldnamen en waarden in het Nederlands uit Mímir. `--demo` toont een verzonnen bericht in de243
chat met Jonas Ortega en verzonnen kaarten. Besluit: ADR 0024.264
chat met Jonas Ortega en verzonnen kaarten. Besluit: ADR 0025.244
265
245
| | |266
| | |246
|---|---|267
|---|---|@@ -251,7 +272,7 @@ chat met Jonas Ortega en verzonnen kaarten. Besluit: ADR 0024.251
272
252
### Asclepius, Ponos en Daedalus vanuit Rusty Teams273
### Asclepius, Ponos en Daedalus vanuit Rusty Teams253
274
254
Zelfde koppeling (app-token, scopes `asclepius ponos daedalus`), geen nieuwe inlog. Besluit: ADR 0024.275
Zelfde koppeling (app-token, scopes `asclepius ponos daedalus`), geen nieuwe inlog. Besluit: ADR 0025.255
276
256
- **Ticket maken in Asclepius** (berichtmenu, «Create Asclepius ticket»): opent het formulier277
- **Ticket maken in Asclepius** (berichtmenu, «Create Asclepius ticket»): opent het formulier257
«Nieuw ticket maken» in de app (zie «Asclepius-tegel»), vooraf ingevuld: titel = eerste regel (max.278
«Nieuw ticket maken» in de app (zie «Asclepius-tegel»), vooraf ingevuld: titel = eerste regel (max.@@ -143,19 +143,17 @@ cargo run --release -p app
143
143
144
144
### Google Calendar (optional)
145
145
146
1. Create an OAuth Desktop client in Google Cloud Console with redirect `http://127.0.0.1:<port>/` (loopback; the app picks a free port).
147
2. Export before starting the app:
146
1. Settings > Calendar accounts > Connect Google.
147
2. Finish sign-in in the browser (if Google says the app is not verified, choose Advanced, then continue).
148
3. Choose the home calendar and optional dual-write targets.
149
150
Release builds bake in the project OAuth Desktop client, so those steps are enough when the client fields are empty. To use your own Desktop client, paste the client ID and client secret on that same page (the page has the short Google Cloud Console guide) and save. A saved pair is used instead of the built-in client and instead of `TEAMS_GOOGLE_CLIENT_ID` / `TEAMS_GOOGLE_CLIENT_SECRET`. Local builds without a built-in client stay Outlook-only until you save a pair or export those variables before `cargo run`:
148
151
149
152
```bash
150
153
export TEAMS_GOOGLE_CLIENT_ID="….apps.googleusercontent.com"
151
# only if the client has a secret:
152
154
export TEAMS_GOOGLE_CLIENT_SECRET="…"
153
155
```
154
156
155
3. Settings > Calendar > Connect Google, then choose home calendar and optional dual-write targets.
156
157
Without these env vars the calendar stays Outlook-only.
158
159
157
| Task | Command |
160
158
|---|---|
161
159
| Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |
@@ -143,19 +143,17 @@ cargo run --release -p app143
143
144
### Google Calendar (optional)144
### Google Calendar (optional)145
145
146
1. Create an OAuth Desktop client in Google Cloud Console with redirect `http://127.0.0.1:<port>/` (loopback; the app picks a free port).146
1. Settings > Calendar accounts > Connect Google.147
2. Export before starting the app:147
2. Finish sign-in in the browser (if Google says the app is not verified, choose Advanced, then continue).148
3. Choose the home calendar and optional dual-write targets.149
150
Release builds bake in the project OAuth Desktop client, so those steps are enough when the client fields are empty. To use your own Desktop client, paste the client ID and client secret on that same page (the page has the short Google Cloud Console guide) and save. A saved pair is used instead of the built-in client and instead of `TEAMS_GOOGLE_CLIENT_ID` / `TEAMS_GOOGLE_CLIENT_SECRET`. Local builds without a built-in client stay Outlook-only until you save a pair or export those variables before `cargo run`:148
151
149
```bash152
```bash150
export TEAMS_GOOGLE_CLIENT_ID="….apps.googleusercontent.com"153
export TEAMS_GOOGLE_CLIENT_ID="….apps.googleusercontent.com"151
# only if the client has a secret:152
export TEAMS_GOOGLE_CLIENT_SECRET="…"154
export TEAMS_GOOGLE_CLIENT_SECRET="…"153
```155
```154
156
155
3. Settings > Calendar > Connect Google, then choose home calendar and optional dual-write targets.156
157
Without these env vars the calendar stays Outlook-only.158
159
| Task | Command |157
| Task | Command |160
|---|---|158
|---|---|161
| Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |159
| Linux build needs clang 21+ (libwebrtc's hermetic libc++) + mold (set in `.cargo/config.toml`); sccache shares compiled deps across worktrees | `sudo apt install clang mold sccache`, clang from [apt.llvm.org](https://apt.llvm.org) if the distro one is older than 21 |@@ -162,7 +162,7 @@ aur_check:
162
162
# Bouwt één keer (cargo test --no-run) en draait daarna dezelfde tests als
163
163
# voorheen: kvt-update, de updatertests (release_feed, kvt_feed) en de tests
164
164
# van crates/kvt-sleutels (BC-links, kaarten, Ponos, planning, koppelen), plus
165
# cargo check -p app. Alleen als Rust-code of Cargo-bestanden veranderen.
165
# cargo check -p app. Alleen als Rust-code, Cargo-bestanden of deze CI-config veranderen.
166
166
app_test:
167
167
stage: test
168
168
image: ubuntu:22.04
@@ -171,9 +171,9 @@ app_test:
171
171
timeout: 120m
172
172
rules:
173
173
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
174
changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml]
174
changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml, packaging/kvt/ci-setup.sh]
175
175
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null
176
changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml]
176
changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml, packaging/kvt/ci-setup.sh]
177
177
variables:
178
178
CC: clang-21
179
179
CXX: clang++-21
@@ -162,7 +162,7 @@ aur_check:162
# Bouwt één keer (cargo test --no-run) en draait daarna dezelfde tests als162
# Bouwt één keer (cargo test --no-run) en draait daarna dezelfde tests als163
# voorheen: kvt-update, de updatertests (release_feed, kvt_feed) en de tests163
# voorheen: kvt-update, de updatertests (release_feed, kvt_feed) en de tests164
# van crates/kvt-sleutels (BC-links, kaarten, Ponos, planning, koppelen), plus164
# van crates/kvt-sleutels (BC-links, kaarten, Ponos, planning, koppelen), plus165
# cargo check -p app. Alleen als Rust-code of Cargo-bestanden veranderen.165
# cargo check -p app. Alleen als Rust-code, Cargo-bestanden of deze CI-config veranderen.166
app_test:166
app_test:167
stage: test167
stage: test168
image: ubuntu:22.04168
image: ubuntu:22.04@@ -171,9 +171,9 @@ app_test:171
timeout: 120m171
timeout: 120m172
rules:172
rules:173
- if: $CI_PIPELINE_SOURCE == "merge_request_event"173
- if: $CI_PIPELINE_SOURCE == "merge_request_event"174
changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml]174
changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml, packaging/kvt/ci-setup.sh]175
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null175
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null176
changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml]176
changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml, packaging/kvt/ci-setup.sh]177
variables:177
variables:178
CC: clang-21178
CC: clang-21179
CXX: clang++-21179
CXX: clang++-21@@ -27,6 +27,7 @@ store.workspace = true
27
27
teams-core.workspace = true
28
28
tokio.workspace = true
29
29
kvt-update = { path = "../kvt-update" }
30
url.workspace = true
30
31
image = { version = "0.25", default-features = false, features = ["bmp", "gif", "ico", "jpeg", "png", "webp"] }
31
32
raw-window-handle = "0.6"
32
33
sha2 = "0.10"
@@ -47,6 +48,8 @@ wayland-protocols = { version = "0.32", features = ["client", "staging"] }
47
48
x11rb = { version = "0.13", features = ["shape"] }
48
49
ksni = { version = "0.3", features = ["blocking"] }
49
50
zbus = { version = "5", default-features = false, features = ["tokio"] }
51
libpulse-binding = "2.30.1"
52
libpulse-simple-binding = "2.29.0"
50
53
51
54
[target.'cfg(any(windows, target_os = "macos"))'.dependencies]
52
55
tray-icon = { version = "0.21", default-features = false }
@@ -27,6 +27,7 @@ store.workspace = true27
teams-core.workspace = true27
teams-core.workspace = true28
tokio.workspace = true28
tokio.workspace = true29
kvt-update = { path = "../kvt-update" }29
kvt-update = { path = "../kvt-update" }30
url.workspace = true30
image = { version = "0.25", default-features = false, features = ["bmp", "gif", "ico", "jpeg", "png", "webp"] }31
image = { version = "0.25", default-features = false, features = ["bmp", "gif", "ico", "jpeg", "png", "webp"] }31
raw-window-handle = "0.6"32
raw-window-handle = "0.6"32
sha2 = "0.10"33
sha2 = "0.10"@@ -47,6 +48,8 @@ wayland-protocols = { version = "0.32", features = ["client", "staging"] }47
x11rb = { version = "0.13", features = ["shape"] }48
x11rb = { version = "0.13", features = ["shape"] }48
ksni = { version = "0.3", features = ["blocking"] }49
ksni = { version = "0.3", features = ["blocking"] }49
zbus = { version = "5", default-features = false, features = ["tokio"] }50
zbus = { version = "5", default-features = false, features = ["tokio"] }51
libpulse-binding = "2.30.1"52
libpulse-simple-binding = "2.29.0"50
53
51
[target.'cfg(any(windows, target_os = "macos"))'.dependencies]54
[target.'cfg(any(windows, target_os = "macos"))'.dependencies]52
tray-icon = { version = "0.21", default-features = false }55
tray-icon = { version = "0.21", default-features = false }@@ -319,7 +319,7 @@ settings:
319
319
nl: Schrijft uitgebreide logs naar diagnostics.log - zet uit als je klaar bent
320
320
debug_logging_off_detail:
321
321
en: Off by default - enable before reproducing a bug
322
de: Standardmäßig aus - vor der Fehlerreproduktion einschalten
322
de: Standardmässig aus - vor der Fehlerreproduktion einschalten
323
323
nl: Standaard uit - zet aan voordat je een fout naspeelt
324
324
clear_logs:
325
325
en: Clear logs
@@ -455,6 +455,86 @@ settings:
455
455
en: Google Calendar
456
456
de: Google Kalender
457
457
nl: Google Agenda
458
google_client_status_title:
459
en: OAuth client
460
de: OAuth-Client
461
nl: OAuth-client
462
google_client_status_own:
463
en: Your client
464
de: Eigener Client
465
nl: Je eigen client
466
google_client_status_builtin:
467
en: Built-in client, or TEAMS_GOOGLE_CLIENT_ID when set
468
de: Eingebauter Client, oder TEAMS_GOOGLE_CLIENT_ID, wenn gesetzt
469
nl: Ingebouwde client, of TEAMS_GOOGLE_CLIENT_ID als die is ingesteld
470
google_client_status_missing:
471
en: No client yet. Save one here, or use a build that includes one.
472
de: Noch kein Client. Hier einen speichern, oder einen Build mit eingebautem Client verwenden.
473
nl: Nog geen client. Sla hier een client op, of gebruik een build met een ingebouwde client.
474
google_client_id:
475
en: Client ID
476
de: Client-ID
477
nl: Client-ID
478
google_client_secret:
479
en: Client secret
480
de: Clientschlüssel
481
nl: Clientgeheim
482
google_client_secret_kept:
483
en: A secret is saved. Leave this empty to keep it.
484
de: Ein Schlüssel ist gespeichert. Leer lassen behält ihn.
485
nl: Er is een geheim opgeslagen. Laat dit leeg om het te behouden.
486
google_client_save:
487
en: Save
488
de: Speichern
489
nl: Opslaan
490
google_client_reset:
491
en: Use built-in client
492
de: Eingebauten Client verwenden
493
nl: Ingebouwde client gebruiken
494
google_client_saved:
495
en: Saved. Connect Google uses this client.
496
de: Gespeichert. «Google verbinden» nutzt diesen Client.
497
nl: "Opgeslagen. \"Google verbinden\" gebruikt deze client."
498
google_client_saved_reconnect:
499
en: Saved. Connect Google again. Existing tokens belong to the previous client.
500
de: Gespeichert. Google erneut verbinden. Bestehende Tokens gehören zum vorherigen Client.
501
nl: Opgeslagen. Verbind Google opnieuw. Bestaande tokens horen bij de vorige client.
502
google_client_cleared:
503
en: Cleared. Connect uses the built-in client again.
504
de: Zurückgesetzt. Verbinden nutzt wieder den eingebauten Client.
505
nl: Gewist. Verbinden gebruikt weer de ingebouwde client.
506
google_client_cleared_reconnect:
507
en: Cleared. Connect Google again. Existing tokens belong to the previous client.
508
de: Zurückgesetzt. Google erneut verbinden. Bestehende Tokens gehören zum vorherigen Client.
509
nl: Gewist. Verbind Google opnieuw. Bestaande tokens horen bij de vorige client.
510
google_client_secret_required:
511
en: Enter the client secret. A saved secret can be left blank.
512
de: Clientschlüssel eintragen. Ein gespeicherter Schlüssel darf leer bleiben.
513
nl: Vul het clientgeheim in. Een opgeslagen geheim mag leeg blijven.
514
google_client_save_failed:
515
en: The Google client could not be saved.
516
de: Der Google-Client konnte nicht gespeichert werden.
517
nl: De Google-client kon niet worden opgeslagen.
518
google_client_guide_1:
519
en: "1. Open https://console.cloud.google.com/ and choose a project."
520
de: "1. https://console.cloud.google.com/ öffnen und ein Projekt wählen."
521
nl: "1. Open https://console.cloud.google.com/ en kies een project."
522
google_client_guide_2:
523
en: "2. Enable the Google Calendar API."
524
de: "2. Google Calendar API aktivieren."
525
nl: "2. Schakel de Google Calendar API in."
526
google_client_guide_3:
527
en: "3. Google Auth Platform (OAuth consent screen): External. Add the calendar and userinfo.email scopes. Under Audience, add your Google account as a test user, or publish the app."
528
de: "3. Google Auth Platform (OAuth-Zustimmungsbildschirm): Extern. Bereiche calendar und userinfo.email hinzufügen. Unter «Zielgruppe» das eigene Google-Konto als Testnutzer eintragen oder die App veröffentlichen."
529
nl: "3. Google Auth Platform (OAuth-toestemmingsscherm): Extern. Voeg de scopes calendar en userinfo.email toe. Voeg onder Doelgroep je Google-account toe als testgebruiker, of publiceer de app."
530
google_client_guide_4:
531
en: "4. Clients, then Create client (older consoles: Credentials, OAuth client ID), application type Desktop. Do not set a redirect URI. The app uses http://127.0.0.1 on a free port."
532
de: "4. Clients, dann Client erstellen (ältere Konsolen: Anmeldedaten, OAuth-Client-ID), Anwendungstyp Desktop. Keine Redirect-URI setzen. Die App nutzt http://127.0.0.1 mit einem freien Port."
533
nl: "4. Clients, dan Client maken (oudere consoles: Inloggegevens, OAuth-client-ID), toepassingstype Desktop. Stel geen redirect-URI in. De app gebruikt http://127.0.0.1 op een vrije poort."
534
google_client_guide_5:
535
en: "5. Paste the client ID and client secret here, save, then choose Connect Google."
536
de: "5. Client-ID und Clientschlüssel hier eintragen, speichern, dann «Google verbinden»."
537
nl: "5. Plak de client-ID en het clientgeheim hier, sla op en kies Google verbinden."
458
538
caldav_title:
459
539
en: CalDAV calendar
460
540
de: CalDAV-Kalender
@@ -2604,7 +2684,7 @@ sidebar:
2604
2684
nl: Sectie verwijderen
2605
2685
delete_section_title:
2606
2686
en: 'Delete section "%{name}"?'
2607
de: 'Abschnitt „%{name}" löschen?'
2687
de: 'Abschnitt «%{name}» löschen?'
2608
2688
nl: Sectie "%{name}" verwijderen?
2609
2689
delete_section_detail:
2610
2690
en: Chats in it move back to Chats.
@@ -319,7 +319,7 @@ settings:319
nl: Schrijft uitgebreide logs naar diagnostics.log - zet uit als je klaar bent319
nl: Schrijft uitgebreide logs naar diagnostics.log - zet uit als je klaar bent320
debug_logging_off_detail:320
debug_logging_off_detail:321
en: Off by default - enable before reproducing a bug321
en: Off by default - enable before reproducing a bug322
de: Standardmäßig aus - vor der Fehlerreproduktion einschalten322
de: Standardmässig aus - vor der Fehlerreproduktion einschalten323
nl: Standaard uit - zet aan voordat je een fout naspeelt323
nl: Standaard uit - zet aan voordat je een fout naspeelt324
clear_logs:324
clear_logs:325
en: Clear logs325
en: Clear logs@@ -455,6 +455,86 @@ settings:455
en: Google Calendar455
en: Google Calendar456
de: Google Kalender456
de: Google Kalender457
nl: Google Agenda457
nl: Google Agenda458
google_client_status_title:459
en: OAuth client460
de: OAuth-Client461
nl: OAuth-client462
google_client_status_own:463
en: Your client464
de: Eigener Client465
nl: Je eigen client466
google_client_status_builtin:467
en: Built-in client, or TEAMS_GOOGLE_CLIENT_ID when set468
de: Eingebauter Client, oder TEAMS_GOOGLE_CLIENT_ID, wenn gesetzt469
nl: Ingebouwde client, of TEAMS_GOOGLE_CLIENT_ID als die is ingesteld470
google_client_status_missing:471
en: No client yet. Save one here, or use a build that includes one.472
de: Noch kein Client. Hier einen speichern, oder einen Build mit eingebautem Client verwenden.473
nl: Nog geen client. Sla hier een client op, of gebruik een build met een ingebouwde client.474
google_client_id:475
en: Client ID476
de: Client-ID477
nl: Client-ID478
google_client_secret:479
en: Client secret480
de: Clientschlüssel481
nl: Clientgeheim482
google_client_secret_kept:483
en: A secret is saved. Leave this empty to keep it.484
de: Ein Schlüssel ist gespeichert. Leer lassen behält ihn.485
nl: Er is een geheim opgeslagen. Laat dit leeg om het te behouden.486
google_client_save:487
en: Save488
de: Speichern489
nl: Opslaan490
google_client_reset:491
en: Use built-in client492
de: Eingebauten Client verwenden493
nl: Ingebouwde client gebruiken494
google_client_saved:495
en: Saved. Connect Google uses this client.496
de: Gespeichert. «Google verbinden» nutzt diesen Client.497
nl: "Opgeslagen. \"Google verbinden\" gebruikt deze client."498
google_client_saved_reconnect:499
en: Saved. Connect Google again. Existing tokens belong to the previous client.500
de: Gespeichert. Google erneut verbinden. Bestehende Tokens gehören zum vorherigen Client.501
nl: Opgeslagen. Verbind Google opnieuw. Bestaande tokens horen bij de vorige client.502
google_client_cleared:503
en: Cleared. Connect uses the built-in client again.504
de: Zurückgesetzt. Verbinden nutzt wieder den eingebauten Client.505
nl: Gewist. Verbinden gebruikt weer de ingebouwde client.506
google_client_cleared_reconnect:507
en: Cleared. Connect Google again. Existing tokens belong to the previous client.508
de: Zurückgesetzt. Google erneut verbinden. Bestehende Tokens gehören zum vorherigen Client.509
nl: Gewist. Verbind Google opnieuw. Bestaande tokens horen bij de vorige client.510
google_client_secret_required:511
en: Enter the client secret. A saved secret can be left blank.512
de: Clientschlüssel eintragen. Ein gespeicherter Schlüssel darf leer bleiben.513
nl: Vul het clientgeheim in. Een opgeslagen geheim mag leeg blijven.514
google_client_save_failed:515
en: The Google client could not be saved.516
de: Der Google-Client konnte nicht gespeichert werden.517
nl: De Google-client kon niet worden opgeslagen.518
google_client_guide_1:519
en: "1. Open https://console.cloud.google.com/ and choose a project."520
de: "1. https://console.cloud.google.com/ öffnen und ein Projekt wählen."521
nl: "1. Open https://console.cloud.google.com/ en kies een project."522
google_client_guide_2:523
en: "2. Enable the Google Calendar API."524
de: "2. Google Calendar API aktivieren."525
nl: "2. Schakel de Google Calendar API in."526
google_client_guide_3:527
en: "3. Google Auth Platform (OAuth consent screen): External. Add the calendar and userinfo.email scopes. Under Audience, add your Google account as a test user, or publish the app."528
de: "3. Google Auth Platform (OAuth-Zustimmungsbildschirm): Extern. Bereiche calendar und userinfo.email hinzufügen. Unter «Zielgruppe» das eigene Google-Konto als Testnutzer eintragen oder die App veröffentlichen."529
nl: "3. Google Auth Platform (OAuth-toestemmingsscherm): Extern. Voeg de scopes calendar en userinfo.email toe. Voeg onder Doelgroep je Google-account toe als testgebruiker, of publiceer de app."530
google_client_guide_4:531
en: "4. Clients, then Create client (older consoles: Credentials, OAuth client ID), application type Desktop. Do not set a redirect URI. The app uses http://127.0.0.1 on a free port."532
de: "4. Clients, dann Client erstellen (ältere Konsolen: Anmeldedaten, OAuth-Client-ID), Anwendungstyp Desktop. Keine Redirect-URI setzen. Die App nutzt http://127.0.0.1 mit einem freien Port."533
nl: "4. Clients, dan Client maken (oudere consoles: Inloggegevens, OAuth-client-ID), toepassingstype Desktop. Stel geen redirect-URI in. De app gebruikt http://127.0.0.1 op een vrije poort."534
google_client_guide_5:535
en: "5. Paste the client ID and client secret here, save, then choose Connect Google."536
de: "5. Client-ID und Clientschlüssel hier eintragen, speichern, dann «Google verbinden»."537
nl: "5. Plak de client-ID en het clientgeheim hier, sla op en kies Google verbinden."458
caldav_title:538
caldav_title:459
en: CalDAV calendar539
en: CalDAV calendar460
de: CalDAV-Kalender540
de: CalDAV-Kalender@@ -2604,7 +2684,7 @@ sidebar:2604
nl: Sectie verwijderen2684
nl: Sectie verwijderen2605
delete_section_title:2685
delete_section_title:2606
en: 'Delete section "%{name}"?'2686
en: 'Delete section "%{name}"?'2607
de: 'Abschnitt „%{name}" löschen?'2687
de: 'Abschnitt «%{name}» löschen?'2608
nl: Sectie "%{name}" verwijderen?2688
nl: Sectie "%{name}" verwijderen?2609
delete_section_detail:2689
delete_section_detail:2610
en: Chats in it move back to Chats.2690
en: Chats in it move back to Chats.@@ -271,6 +271,38 @@ fn keeps_webrtc_line(level: log::Level, text: &str) -> bool {
271
271
.any(|marker| text.contains(marker))
272
272
&& !WEBRTC_SKIPPED.iter().any(|skipped| text.contains(skipped))
273
273
&& !is_endpoint_dump(text)
274
&& !is_adm_enumeration_dump(text)
275
}
276
277
/// Device-name lines from each `list_devices` poll. Linux prints the function
278
/// name; MSVC prefixes it with `virtual webrtc::AudioDeviceModuleImpl::`.
279
/// Numeric `output:` / `input:` lines are return values (`Recording`, `Playing`)
280
/// and stay. `Initialized:` is the per-poll flag, not that return value.
281
fn is_adm_enumeration_dump(text: &str) -> bool {
282
let Some(message) = text
283
.split_once("audio_device_impl.cc:")
284
.and_then(|(_, rest)| rest.split_once("): ").map(|(_, message)| message))
285
else {
286
return false;
287
};
288
let head = adm_function_name(message);
289
const CALLS: [&str; 4] = [
290
"PlayoutDeviceName",
291
"RecordingDeviceName",
292
"PlayoutDevices",
293
"RecordingDevices",
294
];
295
const DUMPS: [&str; 4] = ["output: name", "output: guid", "input: name", "input: guid"];
296
CALLS.iter().any(|prefix| head.starts_with(prefix))
297
|| DUMPS.iter().any(|prefix| head.starts_with(prefix))
298
|| head.starts_with("Initialized")
299
}
300
301
/// Drops an optional MSVC `__FUNCTION__` prefix so Linux and Windows share one check.
302
fn adm_function_name(message: &str) -> &str {
303
let rest = message.strip_prefix("virtual ").unwrap_or(message);
304
rest.strip_prefix("webrtc::AudioDeviceModuleImpl::")
305
.unwrap_or(rest)
274
306
}
275
307
276
308
fn is_endpoint_dump(text: &str) -> bool {
@@ -299,6 +331,74 @@ mod tests {
299
331
log::Level::Debug,
300
332
"(audio_device_impl.cc:123): Init"
301
333
));
334
assert!(!keeps_webrtc_line(
335
log::Level::Debug,
336
"(audio_device_impl.cc:655): PlayoutDeviceName(0, ...)"
337
));
338
assert!(!keeps_webrtc_line(
339
log::Level::Debug,
340
"(audio_device_impl.cc:632): PlayoutDevices"
341
));
342
assert!(!keeps_webrtc_line(
343
log::Level::Debug,
344
"(audio_device_impl.cc:640): RecordingDevices"
345
));
346
assert!(!keeps_webrtc_line(
347
log::Level::Debug,
348
"(audio_device_impl.cc:648): RecordingDeviceName(1, ...)"
349
));
350
assert!(!keeps_webrtc_line(
351
log::Level::Debug,
352
"(audio_device_impl.cc:664): output: name = Headset Game"
353
));
354
assert!(!keeps_webrtc_line(
355
log::Level::Debug,
356
"(audio_device_impl.cc:667): output: guid = "
357
));
358
assert!(!keeps_webrtc_line(
359
log::Level::Debug,
360
"(audio_device_impl.cc:680): input: name = Headset Chat"
361
));
362
assert!(!keeps_webrtc_line(
363
log::Level::Debug,
364
"(audio_device_impl.cc:683): input: guid = "
365
));
366
assert!(!keeps_webrtc_line(
367
log::Level::Debug,
368
"(audio_device_impl.cc:620): Initialized: 1"
369
));
370
assert!(keeps_webrtc_line(
371
log::Level::Debug,
372
"(audio_device_impl.cc:700): output: 1"
373
));
374
assert!(keeps_webrtc_line(
375
log::Level::Debug,
376
"(audio_device_impl.cc:710): input: 0"
377
));
378
assert!(!keeps_webrtc_line(
379
log::Level::Debug,
380
"(audio_device_impl.cc:655): virtual webrtc::AudioDeviceModuleImpl::PlayoutDeviceName(0, ...)"
381
));
382
assert!(!keeps_webrtc_line(
383
log::Level::Debug,
384
"(audio_device_impl.cc:632): virtual webrtc::AudioDeviceModuleImpl::PlayoutDevices"
385
));
386
assert!(keeps_webrtc_line(
387
log::Level::Debug,
388
"(audio_device_impl.cc:635): output: 4"
389
));
390
assert!(keeps_webrtc_line(
391
log::Level::Debug,
392
"(audio_device_pulse_linux.cc:1161): disconnected recording"
393
));
394
assert!(keeps_webrtc_line(
395
log::Level::Debug,
396
"(audio_device_pulse_linux.cc:1366): failed"
397
));
398
assert!(keeps_webrtc_line(
399
log::Level::Debug,
400
"(audio_device_pulse_linux.cc:1735): PulseAudio terminated"
401
));
302
402
assert!(keeps_webrtc_line(
303
403
log::Level::Debug,
304
404
"(webrtc_voice_engine.cc:10): WebRtcVoiceEngine::Init"
@@ -271,6 +271,38 @@ fn keeps_webrtc_line(level: log::Level, text: &str) -> bool {271
.any(|marker| text.contains(marker))271
.any(|marker| text.contains(marker))272
&& !WEBRTC_SKIPPED.iter().any(|skipped| text.contains(skipped))272
&& !WEBRTC_SKIPPED.iter().any(|skipped| text.contains(skipped))273
&& !is_endpoint_dump(text)273
&& !is_endpoint_dump(text)274
&& !is_adm_enumeration_dump(text)275
}276
277
/// Device-name lines from each `list_devices` poll. Linux prints the function278
/// name; MSVC prefixes it with `virtual webrtc::AudioDeviceModuleImpl::`.279
/// Numeric `output:` / `input:` lines are return values (`Recording`, `Playing`)280
/// and stay. `Initialized:` is the per-poll flag, not that return value.281
fn is_adm_enumeration_dump(text: &str) -> bool {282
let Some(message) = text283
.split_once("audio_device_impl.cc:")284
.and_then(|(_, rest)| rest.split_once("): ").map(|(_, message)| message))285
else {286
return false;287
};288
let head = adm_function_name(message);289
const CALLS: [&str; 4] = [290
"PlayoutDeviceName",291
"RecordingDeviceName",292
"PlayoutDevices",293
"RecordingDevices",294
];295
const DUMPS: [&str; 4] = ["output: name", "output: guid", "input: name", "input: guid"];296
CALLS.iter().any(|prefix| head.starts_with(prefix))297
|| DUMPS.iter().any(|prefix| head.starts_with(prefix))298
|| head.starts_with("Initialized")299
}300
301
/// Drops an optional MSVC `__FUNCTION__` prefix so Linux and Windows share one check.302
fn adm_function_name(message: &str) -> &str {303
let rest = message.strip_prefix("virtual ").unwrap_or(message);304
rest.strip_prefix("webrtc::AudioDeviceModuleImpl::")305
.unwrap_or(rest)274
}306
}275
307
276
fn is_endpoint_dump(text: &str) -> bool {308
fn is_endpoint_dump(text: &str) -> bool {@@ -299,6 +331,74 @@ mod tests {299
log::Level::Debug,331
log::Level::Debug,300
"(audio_device_impl.cc:123): Init"332
"(audio_device_impl.cc:123): Init"301
));333
));334
assert!(!keeps_webrtc_line(335
log::Level::Debug,336
"(audio_device_impl.cc:655): PlayoutDeviceName(0, ...)"337
));338
assert!(!keeps_webrtc_line(339
log::Level::Debug,340
"(audio_device_impl.cc:632): PlayoutDevices"341
));342
assert!(!keeps_webrtc_line(343
log::Level::Debug,344
"(audio_device_impl.cc:640): RecordingDevices"345
));346
assert!(!keeps_webrtc_line(347
log::Level::Debug,348
"(audio_device_impl.cc:648): RecordingDeviceName(1, ...)"349
));350
assert!(!keeps_webrtc_line(351
log::Level::Debug,352
"(audio_device_impl.cc:664): output: name = Headset Game"353
));354
assert!(!keeps_webrtc_line(355
log::Level::Debug,356
"(audio_device_impl.cc:667): output: guid = "357
));358
assert!(!keeps_webrtc_line(359
log::Level::Debug,360
"(audio_device_impl.cc:680): input: name = Headset Chat"361
));362
assert!(!keeps_webrtc_line(363
log::Level::Debug,364
"(audio_device_impl.cc:683): input: guid = "365
));366
assert!(!keeps_webrtc_line(367
log::Level::Debug,368
"(audio_device_impl.cc:620): Initialized: 1"369
));370
assert!(keeps_webrtc_line(371
log::Level::Debug,372
"(audio_device_impl.cc:700): output: 1"373
));374
assert!(keeps_webrtc_line(375
log::Level::Debug,376
"(audio_device_impl.cc:710): input: 0"377
));378
assert!(!keeps_webrtc_line(379
log::Level::Debug,380
"(audio_device_impl.cc:655): virtual webrtc::AudioDeviceModuleImpl::PlayoutDeviceName(0, ...)"381
));382
assert!(!keeps_webrtc_line(383
log::Level::Debug,384
"(audio_device_impl.cc:632): virtual webrtc::AudioDeviceModuleImpl::PlayoutDevices"385
));386
assert!(keeps_webrtc_line(387
log::Level::Debug,388
"(audio_device_impl.cc:635): output: 4"389
));390
assert!(keeps_webrtc_line(391
log::Level::Debug,392
"(audio_device_pulse_linux.cc:1161): disconnected recording"393
));394
assert!(keeps_webrtc_line(395
log::Level::Debug,396
"(audio_device_pulse_linux.cc:1366): failed"397
));398
assert!(keeps_webrtc_line(399
log::Level::Debug,400
"(audio_device_pulse_linux.cc:1735): PulseAudio terminated"401
));302
assert!(keeps_webrtc_line(402
assert!(keeps_webrtc_line(303
log::Level::Debug,403
log::Level::Debug,304
"(webrtc_voice_engine.cc:10): WebRtcVoiceEngine::Init"404
"(webrtc_voice_engine.cc:10): WebRtcVoiceEngine::Init"@@ -69,7 +69,8 @@ pub fn set_date_locale(locale: Option<&str>) {
69
69
set_date_style(locale.map(date_style));
70
70
}
71
71
72
fn current_date_style() -> Option<DateStyle> {
72
/// The style set on this thread; work moved to another thread sets it there with [`set_date_style`].
73
pub fn current_date_style() -> Option<DateStyle> {
73
74
DATE_STYLE.with(Cell::get)
74
75
}
75
76
@@ -69,7 +69,8 @@ pub fn set_date_locale(locale: Option<&str>) {69
set_date_style(locale.map(date_style));69
set_date_style(locale.map(date_style));70
}70
}71
71
72
fn current_date_style() -> Option<DateStyle> {72
/// The style set on this thread; work moved to another thread sets it there with [`set_date_style`].73
pub fn current_date_style() -> Option<DateStyle> {73
DATE_STYLE.with(Cell::get)74
DATE_STYLE.with(Cell::get)74
}75
}75
76
@@ -33,6 +33,7 @@ pub mod linux_fonts;
33
33
mod linux_idle;
34
34
pub mod native_dumps;
35
35
pub mod notify;
36
pub mod open_link;
36
37
pub mod orgs;
37
38
pub mod presence_link;
38
39
pub mod read_state;
@@ -33,6 +33,7 @@ pub mod linux_fonts;33
mod linux_idle;33
mod linux_idle;34
pub mod native_dumps;34
pub mod native_dumps;35
pub mod notify;35
pub mod notify;36
pub mod open_link;36
pub mod orgs;37
pub mod orgs;37
pub mod presence_link;38
pub mod presence_link;38
pub mod read_state;39
pub mod read_state;@@ -1,20 +1,77 @@
1
//! Linux and macOS notification and ringtone playback through the system audio output.
1
//! Linux and macOS notification and ringtone playback.
2
//!
3
//! On Linux the saved call output is a Pulse sink description or name. Tones go to that
4
//! sink. When the Pulse daemon is not running, Linux uses the same cpal lookup as macOS.
5
//! A sink that disappears while a tone is playing falls back to the system default.
6
7
use std::collections::HashSet;
2
8
use std::io::Cursor;
3
9
use std::sync::atomic::{AtomicBool, Ordering};
4
use std::sync::{Arc, Mutex};
10
use std::sync::{Arc, LazyLock, Mutex};
5
11
use std::time::Duration;
6
12
13
use rodio::Source;
7
14
use rodio::cpal::traits::{DeviceTrait, HostTrait};
8
15
9
16
const SOUND_BYTES: &[u8] = include_bytes!("../../../../app/assets/sounds/notification.mp3");
10
17
const POLL: Duration = Duration::from_millis(20);
11
18
static SOUND_OUTPUT: Mutex<Option<String>> = Mutex::new(None);
19
static LOGGED_MISSES: LazyLock<Mutex<HashSet<String>>> =
20
LazyLock::new(|| Mutex::new(HashSet::new()));
12
21
13
22
pub fn set_sound_output(device_key: Option<String>) {
14
23
*SOUND_OUTPUT.lock().unwrap_or_else(|p| p.into_inner()) = device_key;
15
24
}
16
25
17
/// True when a call-output key names this cpal device (id, friendly name, or Pulse-style id).
26
/// One Pulse sink, as listed by the daemon.
27
#[derive(Clone)]
28
pub(crate) struct PulseSink {
29
pub name: String,
30
pub description: String,
31
}
32
33
/// Trim, drop one leading `default:` prefix, then ASCII-lowercase.
34
pub(crate) fn normalized_audio_key(value: &str) -> String {
35
let trimmed = value.trim();
36
let rest = strip_default_prefix(trimmed).trim();
37
rest.to_ascii_lowercase()
38
}
39
40
fn strip_default_prefix(value: &str) -> &str {
41
const PREFIX: &str = "default:";
42
if value.len() >= PREFIX.len() && value[..PREFIX.len()].eq_ignore_ascii_case(PREFIX) {
43
&value[PREFIX.len()..]
44
} else {
45
value
46
}
47
}
48
49
/// Exact name or description match. A Game sink does not satisfy a Chat key.
50
pub(crate) fn matching_sink<'a>(sinks: &'a [PulseSink], key: &str) -> Option<&'a PulseSink> {
51
let key = normalized_audio_key(key);
52
if key.is_empty() {
53
return None;
54
}
55
sinks.iter().find(|sink| {
56
normalized_audio_key(&sink.name) == key || normalized_audio_key(&sink.description) == key
57
})
58
}
59
60
/// True the first time this key is reported missing.
61
fn claim_miss(key: &str) -> bool {
62
LOGGED_MISSES
63
.lock()
64
.unwrap_or_else(|p| p.into_inner())
65
.insert(key.to_owned())
66
}
67
68
fn note_missing_once(key: &str, message: String) {
69
if claim_miss(key) {
70
crate::diagnostics::record(message);
71
}
72
}
73
74
/// True when a call-output key names this cpal device (id or friendly name).
18
75
pub(crate) fn device_matches_key(device_id: &str, device_name: &str, key: &str) -> bool {
19
76
let key = key.trim();
20
77
if key.is_empty() {
@@ -32,10 +89,61 @@ pub(crate) fn device_matches_key(device_id: &str, device_name: &str, key: &str)
32
89
|| (key_lower.len() >= 4 && name_lower.contains(&key_lower))
33
90
}
34
91
92
struct Decoded {
93
rate: u32,
94
channels: u16,
95
samples: Vec<f32>,
96
}
97
98
fn decode(bytes: &[u8]) -> Result<Decoded, String> {
99
let decoder = rodio::Decoder::try_from(Cursor::new(bytes.to_vec()))
100
.map_err(|error| format!("cannot decode notification sound: {error}"))?;
101
let rate = decoder.sample_rate().get();
102
let channels = decoder.channels().get();
103
let samples = decoder.collect();
104
Ok(Decoded {
105
rate,
106
channels,
107
samples,
108
})
109
}
110
111
fn play_on_rodio(
112
sink: &mut rodio::MixerDeviceSink,
113
bytes: Vec<u8>,
114
looped: bool,
115
stop: &AtomicBool,
116
) -> Result<(), String> {
117
sink.log_on_drop(false);
118
loop {
119
if stop.load(Ordering::SeqCst) {
120
return Ok(());
121
}
122
let player = rodio::play(sink.mixer(), Cursor::new(bytes.clone()))
123
.map_err(|error| format!("cannot decode notification sound: {error}"))?;
124
while !player.empty() {
125
if stop.load(Ordering::SeqCst) {
126
player.stop();
127
return Ok(());
128
}
129
std::thread::sleep(POLL);
130
}
131
if !looped {
132
return Ok(());
133
}
134
}
135
}
136
137
fn open_default_and_play(bytes: Vec<u8>, looped: bool, stop: &AtomicBool) -> Result<(), String> {
138
let mut sink = rodio::DeviceSinkBuilder::open_default_sink()
139
.map_err(|error| format!("cannot open audio output: {error}"))?;
140
play_on_rodio(&mut sink, bytes, looped, stop)
141
}
142
35
143
fn open_sink() -> Result<rodio::MixerDeviceSink, String> {
36
144
let chosen = SOUND_OUTPUT
37
145
.lock()
38
.unwrap_or_else(|p| p.into_inner())
146
.unwrap_or_else(|poisoned| poisoned.into_inner())
39
147
.clone();
40
148
if let Some(key) = chosen.as_ref() {
41
149
if let Some(device) = rodio::cpal::default_host()
@@ -68,34 +176,184 @@ fn open_sink() -> Result<rodio::MixerDeviceSink, String> {
68
176
}
69
177
}
70
178
rodio::DeviceSinkBuilder::open_default_sink()
71
.map_err(|e| format!("cannot open audio output: {e}"))
179
.map_err(|error| format!("cannot open audio output: {error}"))
72
180
}
73
181
74
fn play(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) -> Result<(), String> {
75
if stop.load(Ordering::SeqCst) {
76
return Ok(());
77
}
78
let mut sink = open_sink()?;
79
sink.log_on_drop(false);
182
#[cfg(target_os = "linux")]
183
fn pulse_sinks() -> Option<Vec<PulseSink>> {
184
use libpulse_binding::callbacks::ListResult;
185
use libpulse_binding::context::{Context, FlagSet, State};
186
use libpulse_binding::mainloop::standard::Mainloop;
187
188
let mut mainloop = Mainloop::new()?;
189
let mut context = Context::new(&mainloop, "rusty-teams")?;
190
context.connect(None, FlagSet::NOAUTOSPAWN, None).ok()?;
191
let deadline = std::time::Instant::now() + Duration::from_millis(400);
80
192
loop {
81
if stop.load(Ordering::SeqCst) {
82
return Ok(());
193
if std::time::Instant::now() > deadline {
194
return None;
83
195
}
84
let player = rodio::play(sink.mixer(), Cursor::new(bytes.clone()))
85
.map_err(|e| format!("cannot decode notification sound: {e}"))?;
86
while !player.empty() {
196
let _ = mainloop.iterate(false);
197
match context.get_state() {
198
State::Ready => break,
199
State::Failed | State::Terminated => return None,
200
_ => std::thread::sleep(Duration::from_millis(5)),
201
}
202
}
203
let found = Arc::new(Mutex::new(Vec::new()));
204
let done = Arc::new(AtomicBool::new(false));
205
let found_cb = Arc::clone(&found);
206
let done_cb = Arc::clone(&done);
207
let operation = context
208
.introspect()
209
.get_sink_info_list(move |item| match item {
210
ListResult::Item(info) => found_cb
211
.lock()
212
.unwrap_or_else(|poisoned| poisoned.into_inner())
213
.push(PulseSink {
214
name: info.name.as_deref().unwrap_or("").to_owned(),
215
description: info.description.as_deref().unwrap_or("").to_owned(),
216
}),
217
ListResult::End | ListResult::Error => done_cb.store(true, Ordering::SeqCst),
218
});
219
while !done.load(Ordering::SeqCst) {
220
if std::time::Instant::now() > deadline {
221
return None;
222
}
223
let _ = mainloop.iterate(false);
224
std::thread::sleep(Duration::from_millis(5));
225
}
226
drop(operation);
227
Some(
228
found
229
.lock()
230
.unwrap_or_else(|poisoned| poisoned.into_inner())
231
.clone(),
232
)
233
}
234
235
#[cfg(target_os = "linux")]
236
fn play_on_pulse(
237
sink_name: &str,
238
decoded: &Decoded,
239
looped: bool,
240
stop: &AtomicBool,
241
) -> Result<(), String> {
242
use libpulse_binding::sample::{Format, Spec};
243
use libpulse_binding::stream::Direction;
244
use libpulse_simple_binding::Simple;
245
246
let channels =
247
u8::try_from(decoded.channels).map_err(|_| "too many audio channels".to_owned())?;
248
let spec = Spec {
249
format: Format::FLOAT32NE,
250
channels,
251
rate: decoded.rate,
252
};
253
if !spec.is_valid() {
254
return Err(format!(
255
"pulse cannot play {} Hz {} ch",
256
decoded.rate, decoded.channels
257
));
258
}
259
let simple = Simple::new(
260
None,
261
"rusty-teams",
262
Direction::Playback,
263
Some(sink_name),
264
"call tone",
265
&spec,
266
None,
267
None,
268
)
269
.map_err(|error| format!("pulse open {sink_name}: {error}"))?;
270
let frame = decoded.channels as usize;
271
let chunk = (decoded.rate as usize / 10).max(1) * frame.max(1);
272
loop {
273
for piece in decoded.samples.chunks(chunk.max(1)) {
87
274
if stop.load(Ordering::SeqCst) {
88
player.stop();
89
275
return Ok(());
90
276
}
91
std::thread::sleep(POLL);
277
let mut bytes = Vec::with_capacity(piece.len() * 4);
278
for sample in piece {
279
bytes.extend_from_slice(&sample.to_ne_bytes());
280
}
281
simple
282
.write(&bytes)
283
.map_err(|error| format!("pulse write: {error}"))?;
92
284
}
93
285
if !looped {
286
simple
287
.drain()
288
.map_err(|error| format!("pulse drain: {error}"))?;
94
289
return Ok(());
95
290
}
96
291
}
97
292
}
98
293
294
#[cfg(target_os = "linux")]
295
fn play_linux(bytes: Vec<u8>, looped: bool, stop: &AtomicBool) -> Result<(), String> {
296
let key = SOUND_OUTPUT
297
.lock()
298
.unwrap_or_else(|poisoned| poisoned.into_inner())
299
.clone();
300
if let Some(key) = key.filter(|key| !normalized_audio_key(key).is_empty()) {
301
match pulse_sinks() {
302
Some(sinks) => {
303
if let Some(sink) = matching_sink(&sinks, &key) {
304
let decoded = decode(&bytes)?;
305
match play_on_pulse(&sink.name, &decoded, looped, stop) {
306
Ok(()) => return Ok(()),
307
Err(error)
308
if error.starts_with("pulse open ")
309
|| error.starts_with("pulse cannot play")
310
|| error.starts_with("pulse write")
311
|| error.starts_with("pulse drain") =>
312
{
313
note_missing_once(
314
&key,
315
format!(
316
"sound: selected output {key:?} failed ({error}), using system default"
317
),
318
);
319
}
320
Err(error) => return Err(error),
321
}
322
} else {
323
note_missing_once(
324
&key,
325
format!("sound: selected output {key:?} not found, using system default"),
326
);
327
}
328
}
329
None => {
330
note_missing_once(
331
&format!("pulse:{key}"),
332
format!("sound: pulse unavailable for {key:?}, trying the device list"),
333
);
334
let mut sink = open_sink()?;
335
return play_on_rodio(&mut sink, bytes, looped, stop);
336
}
337
}
338
}
339
open_default_and_play(bytes, looped, stop)
340
}
341
342
fn play(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) -> Result<(), String> {
343
if stop.load(Ordering::SeqCst) {
344
return Ok(());
345
}
346
#[cfg(target_os = "linux")]
347
{
348
return play_linux(bytes, looped, &stop);
349
}
350
#[cfg(not(target_os = "linux"))]
351
{
352
let mut sink = open_sink()?;
353
play_on_rodio(&mut sink, bytes, looped, &stop)
354
}
355
}
356
99
357
pub fn play_mp3_until(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) {
100
358
std::thread::spawn(move || {
101
359
if let Err(error) = play(bytes, looped, stop) {
@@ -116,6 +374,20 @@ pub fn play_sound() {
116
374
mod tests {
117
375
use super::*;
118
376
377
fn sink(name: &str, description: &str) -> PulseSink {
378
PulseSink {
379
name: name.to_owned(),
380
description: description.to_owned(),
381
}
382
}
383
384
fn headset_sinks() -> Vec<PulseSink> {
385
vec![
386
sink("alsa_output.headset.mono-chat", "Headset Chat"),
387
sink("alsa_output.headset.stereo-game", "Headset Game"),
388
]
389
}
390
119
391
#[test]
120
392
fn bundled_notification_decodes_to_audible_samples() {
121
393
let decoded = rodio::Decoder::try_from(Cursor::new(SOUND_BYTES)).unwrap();
@@ -153,6 +425,28 @@ mod tests {
153
425
assert!(!device_matches_key("id", "Speaker", ""));
154
426
}
155
427
428
#[test]
429
fn a_pulse_description_selects_that_sink_and_not_the_other_output() {
430
let sinks = headset_sinks();
431
let game = matching_sink(&sinks, "Headset Game").unwrap();
432
assert_eq!(game.name, "alsa_output.headset.stereo-game");
433
let prefixed = matching_sink(&sinks, "default: Headset Game").unwrap();
434
assert_eq!(prefixed.name, "alsa_output.headset.stereo-game");
435
let chat = matching_sink(&sinks, "Headset Chat").unwrap();
436
assert_eq!(chat.name, "alsa_output.headset.mono-chat");
437
assert!(matching_sink(&sinks, "Headset Game").unwrap().name != chat.name);
438
assert!(matching_sink(&sinks, "missing output").is_none());
439
assert!(matching_sink(&sinks, "Game").is_none());
440
}
441
442
#[test]
443
fn a_missing_key_is_noted_once() {
444
let key = format!("missing-output-{}", std::process::id());
445
assert!(claim_miss(&key));
446
assert!(!claim_miss(&key));
447
assert!(claim_miss(&format!("{key}-other")));
448
}
449
156
450
#[test]
157
451
#[ignore = "plays a short notification on the real default audio output"]
158
452
fn notification_plays_on_default_output() {
@@ -163,4 +457,30 @@ mod tests {
163
457
)
164
458
.unwrap();
165
459
}
460
461
#[cfg(target_os = "linux")]
462
#[test]
463
#[ignore = "plays a short tone on the Pulse sink named by CALL_OUTPUT_KEY"]
464
fn selected_pulse_sink_plays_the_tone() {
465
let key = std::env::var("CALL_OUTPUT_KEY").expect("CALL_OUTPUT_KEY");
466
let sinks = pulse_sinks().expect("pulse");
467
let sink = matching_sink(&sinks, &key).unwrap_or_else(|| {
468
panic!(
469
"no sink for {key:?}; have {}",
470
sinks
471
.iter()
472
.map(|sink| format!("{} ({})", sink.description, sink.name))
473
.collect::<Vec<_>>()
474
.join(", ")
475
)
476
});
477
eprintln!("pulse sink {} ({})", sink.name, sink.description);
478
set_sound_output(Some(key));
479
play(
480
SOUND_BYTES.to_vec(),
481
false,
482
Arc::new(AtomicBool::new(false)),
483
)
484
.unwrap();
485
}
166
486
}
@@ -1,20 +1,77 @@1
//! Linux and macOS notification and ringtone playback through the system audio output.1
//! Linux and macOS notification and ringtone playback.2
//!3
//! On Linux the saved call output is a Pulse sink description or name. Tones go to that4
//! sink. When the Pulse daemon is not running, Linux uses the same cpal lookup as macOS.5
//! A sink that disappears while a tone is playing falls back to the system default.6
7
use std::collections::HashSet;2
use std::io::Cursor;8
use std::io::Cursor;3
use std::sync::atomic::{AtomicBool, Ordering};9
use std::sync::atomic::{AtomicBool, Ordering};4
use std::sync::{Arc, Mutex};10
use std::sync::{Arc, LazyLock, Mutex};5
use std::time::Duration;11
use std::time::Duration;6
12
13
use rodio::Source;7
use rodio::cpal::traits::{DeviceTrait, HostTrait};14
use rodio::cpal::traits::{DeviceTrait, HostTrait};8
15
9
const SOUND_BYTES: &[u8] = include_bytes!("../../../../app/assets/sounds/notification.mp3");16
const SOUND_BYTES: &[u8] = include_bytes!("../../../../app/assets/sounds/notification.mp3");10
const POLL: Duration = Duration::from_millis(20);17
const POLL: Duration = Duration::from_millis(20);11
static SOUND_OUTPUT: Mutex<Option<String>> = Mutex::new(None);18
static SOUND_OUTPUT: Mutex<Option<String>> = Mutex::new(None);19
static LOGGED_MISSES: LazyLock<Mutex<HashSet<String>>> =20
LazyLock::new(|| Mutex::new(HashSet::new()));12
21
13
pub fn set_sound_output(device_key: Option<String>) {22
pub fn set_sound_output(device_key: Option<String>) {14
*SOUND_OUTPUT.lock().unwrap_or_else(|p| p.into_inner()) = device_key;23
*SOUND_OUTPUT.lock().unwrap_or_else(|p| p.into_inner()) = device_key;15
}24
}16
25
17
/// True when a call-output key names this cpal device (id, friendly name, or Pulse-style id).26
/// One Pulse sink, as listed by the daemon.27
#[derive(Clone)]28
pub(crate) struct PulseSink {29
pub name: String,30
pub description: String,31
}32
33
/// Trim, drop one leading `default:` prefix, then ASCII-lowercase.34
pub(crate) fn normalized_audio_key(value: &str) -> String {35
let trimmed = value.trim();36
let rest = strip_default_prefix(trimmed).trim();37
rest.to_ascii_lowercase()38
}39
40
fn strip_default_prefix(value: &str) -> &str {41
const PREFIX: &str = "default:";42
if value.len() >= PREFIX.len() && value[..PREFIX.len()].eq_ignore_ascii_case(PREFIX) {43
&value[PREFIX.len()..]44
} else {45
value46
}47
}48
49
/// Exact name or description match. A Game sink does not satisfy a Chat key.50
pub(crate) fn matching_sink<'a>(sinks: &'a [PulseSink], key: &str) -> Option<&'a PulseSink> {51
let key = normalized_audio_key(key);52
if key.is_empty() {53
return None;54
}55
sinks.iter().find(|sink| {56
normalized_audio_key(&sink.name) == key || normalized_audio_key(&sink.description) == key57
})58
}59
60
/// True the first time this key is reported missing.61
fn claim_miss(key: &str) -> bool {62
LOGGED_MISSES63
.lock()64
.unwrap_or_else(|p| p.into_inner())65
.insert(key.to_owned())66
}67
68
fn note_missing_once(key: &str, message: String) {69
if claim_miss(key) {70
crate::diagnostics::record(message);71
}72
}73
74
/// True when a call-output key names this cpal device (id or friendly name).18
pub(crate) fn device_matches_key(device_id: &str, device_name: &str, key: &str) -> bool {75
pub(crate) fn device_matches_key(device_id: &str, device_name: &str, key: &str) -> bool {19
let key = key.trim();76
let key = key.trim();20
if key.is_empty() {77
if key.is_empty() {@@ -32,10 +89,61 @@ pub(crate) fn device_matches_key(device_id: &str, device_name: &str, key: &str)32
|| (key_lower.len() >= 4 && name_lower.contains(&key_lower))89
|| (key_lower.len() >= 4 && name_lower.contains(&key_lower))33
}90
}34
91
92
struct Decoded {93
rate: u32,94
channels: u16,95
samples: Vec<f32>,96
}97
98
fn decode(bytes: &[u8]) -> Result<Decoded, String> {99
let decoder = rodio::Decoder::try_from(Cursor::new(bytes.to_vec()))100
.map_err(|error| format!("cannot decode notification sound: {error}"))?;101
let rate = decoder.sample_rate().get();102
let channels = decoder.channels().get();103
let samples = decoder.collect();104
Ok(Decoded {105
rate,106
channels,107
samples,108
})109
}110
111
fn play_on_rodio(112
sink: &mut rodio::MixerDeviceSink,113
bytes: Vec<u8>,114
looped: bool,115
stop: &AtomicBool,116
) -> Result<(), String> {117
sink.log_on_drop(false);118
loop {119
if stop.load(Ordering::SeqCst) {120
return Ok(());121
}122
let player = rodio::play(sink.mixer(), Cursor::new(bytes.clone()))123
.map_err(|error| format!("cannot decode notification sound: {error}"))?;124
while !player.empty() {125
if stop.load(Ordering::SeqCst) {126
player.stop();127
return Ok(());128
}129
std::thread::sleep(POLL);130
}131
if !looped {132
return Ok(());133
}134
}135
}136
137
fn open_default_and_play(bytes: Vec<u8>, looped: bool, stop: &AtomicBool) -> Result<(), String> {138
let mut sink = rodio::DeviceSinkBuilder::open_default_sink()139
.map_err(|error| format!("cannot open audio output: {error}"))?;140
play_on_rodio(&mut sink, bytes, looped, stop)141
}142
35
fn open_sink() -> Result<rodio::MixerDeviceSink, String> {143
fn open_sink() -> Result<rodio::MixerDeviceSink, String> {36
let chosen = SOUND_OUTPUT144
let chosen = SOUND_OUTPUT37
.lock()145
.lock()38
.unwrap_or_else(|p| p.into_inner())146
.unwrap_or_else(|poisoned| poisoned.into_inner())39
.clone();147
.clone();40
if let Some(key) = chosen.as_ref() {148
if let Some(key) = chosen.as_ref() {41
if let Some(device) = rodio::cpal::default_host()149
if let Some(device) = rodio::cpal::default_host()@@ -68,34 +176,184 @@ fn open_sink() -> Result<rodio::MixerDeviceSink, String> {68
}176
}69
}177
}70
rodio::DeviceSinkBuilder::open_default_sink()178
rodio::DeviceSinkBuilder::open_default_sink()71
.map_err(|e| format!("cannot open audio output: {e}"))179
.map_err(|error| format!("cannot open audio output: {error}"))72
}180
}73
181
74
fn play(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) -> Result<(), String> {182
#[cfg(target_os = "linux")]75
if stop.load(Ordering::SeqCst) {183
fn pulse_sinks() -> Option<Vec<PulseSink>> {76
return Ok(());184
use libpulse_binding::callbacks::ListResult;77
}185
use libpulse_binding::context::{Context, FlagSet, State};78
let mut sink = open_sink()?;186
use libpulse_binding::mainloop::standard::Mainloop;79
sink.log_on_drop(false);187
188
let mut mainloop = Mainloop::new()?;189
let mut context = Context::new(&mainloop, "rusty-teams")?;190
context.connect(None, FlagSet::NOAUTOSPAWN, None).ok()?;191
let deadline = std::time::Instant::now() + Duration::from_millis(400);80
loop {192
loop {81
if stop.load(Ordering::SeqCst) {193
if std::time::Instant::now() > deadline {82
return Ok(());194
return None;83
}195
}84
let player = rodio::play(sink.mixer(), Cursor::new(bytes.clone()))196
let _ = mainloop.iterate(false);85
.map_err(|e| format!("cannot decode notification sound: {e}"))?;197
match context.get_state() {86
while !player.empty() {198
State::Ready => break,199
State::Failed | State::Terminated => return None,200
_ => std::thread::sleep(Duration::from_millis(5)),201
}202
}203
let found = Arc::new(Mutex::new(Vec::new()));204
let done = Arc::new(AtomicBool::new(false));205
let found_cb = Arc::clone(&found);206
let done_cb = Arc::clone(&done);207
let operation = context208
.introspect()209
.get_sink_info_list(move |item| match item {210
ListResult::Item(info) => found_cb211
.lock()212
.unwrap_or_else(|poisoned| poisoned.into_inner())213
.push(PulseSink {214
name: info.name.as_deref().unwrap_or("").to_owned(),215
description: info.description.as_deref().unwrap_or("").to_owned(),216
}),217
ListResult::End | ListResult::Error => done_cb.store(true, Ordering::SeqCst),218
});219
while !done.load(Ordering::SeqCst) {220
if std::time::Instant::now() > deadline {221
return None;222
}223
let _ = mainloop.iterate(false);224
std::thread::sleep(Duration::from_millis(5));225
}226
drop(operation);227
Some(228
found229
.lock()230
.unwrap_or_else(|poisoned| poisoned.into_inner())231
.clone(),232
)233
}234
235
#[cfg(target_os = "linux")]236
fn play_on_pulse(237
sink_name: &str,238
decoded: &Decoded,239
looped: bool,240
stop: &AtomicBool,241
) -> Result<(), String> {242
use libpulse_binding::sample::{Format, Spec};243
use libpulse_binding::stream::Direction;244
use libpulse_simple_binding::Simple;245
246
let channels =247
u8::try_from(decoded.channels).map_err(|_| "too many audio channels".to_owned())?;248
let spec = Spec {249
format: Format::FLOAT32NE,250
channels,251
rate: decoded.rate,252
};253
if !spec.is_valid() {254
return Err(format!(255
"pulse cannot play {} Hz {} ch",256
decoded.rate, decoded.channels257
));258
}259
let simple = Simple::new(260
None,261
"rusty-teams",262
Direction::Playback,263
Some(sink_name),264
"call tone",265
&spec,266
None,267
None,268
)269
.map_err(|error| format!("pulse open {sink_name}: {error}"))?;270
let frame = decoded.channels as usize;271
let chunk = (decoded.rate as usize / 10).max(1) * frame.max(1);272
loop {273
for piece in decoded.samples.chunks(chunk.max(1)) {87
if stop.load(Ordering::SeqCst) {274
if stop.load(Ordering::SeqCst) {88
player.stop();89
return Ok(());275
return Ok(());90
}276
}91
std::thread::sleep(POLL);277
let mut bytes = Vec::with_capacity(piece.len() * 4);278
for sample in piece {279
bytes.extend_from_slice(&sample.to_ne_bytes());280
}281
simple282
.write(&bytes)283
.map_err(|error| format!("pulse write: {error}"))?;92
}284
}93
if !looped {285
if !looped {286
simple287
.drain()288
.map_err(|error| format!("pulse drain: {error}"))?;94
return Ok(());289
return Ok(());95
}290
}96
}291
}97
}292
}98
293
294
#[cfg(target_os = "linux")]295
fn play_linux(bytes: Vec<u8>, looped: bool, stop: &AtomicBool) -> Result<(), String> {296
let key = SOUND_OUTPUT297
.lock()298
.unwrap_or_else(|poisoned| poisoned.into_inner())299
.clone();300
if let Some(key) = key.filter(|key| !normalized_audio_key(key).is_empty()) {301
match pulse_sinks() {302
Some(sinks) => {303
if let Some(sink) = matching_sink(&sinks, &key) {304
let decoded = decode(&bytes)?;305
match play_on_pulse(&sink.name, &decoded, looped, stop) {306
Ok(()) => return Ok(()),307
Err(error)308
if error.starts_with("pulse open ")309
|| error.starts_with("pulse cannot play")310
|| error.starts_with("pulse write")311
|| error.starts_with("pulse drain") =>312
{313
note_missing_once(314
&key,315
format!(316
"sound: selected output {key:?} failed ({error}), using system default"317
),318
);319
}320
Err(error) => return Err(error),321
}322
} else {323
note_missing_once(324
&key,325
format!("sound: selected output {key:?} not found, using system default"),326
);327
}328
}329
None => {330
note_missing_once(331
&format!("pulse:{key}"),332
format!("sound: pulse unavailable for {key:?}, trying the device list"),333
);334
let mut sink = open_sink()?;335
return play_on_rodio(&mut sink, bytes, looped, stop);336
}337
}338
}339
open_default_and_play(bytes, looped, stop)340
}341
342
fn play(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) -> Result<(), String> {343
if stop.load(Ordering::SeqCst) {344
return Ok(());345
}346
#[cfg(target_os = "linux")]347
{348
return play_linux(bytes, looped, &stop);349
}350
#[cfg(not(target_os = "linux"))]351
{352
let mut sink = open_sink()?;353
play_on_rodio(&mut sink, bytes, looped, &stop)354
}355
}356
99
pub fn play_mp3_until(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) {357
pub fn play_mp3_until(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) {100
std::thread::spawn(move || {358
std::thread::spawn(move || {101
if let Err(error) = play(bytes, looped, stop) {359
if let Err(error) = play(bytes, looped, stop) {@@ -116,6 +374,20 @@ pub fn play_sound() {116
mod tests {374
mod tests {117
use super::*;375
use super::*;118
376
377
fn sink(name: &str, description: &str) -> PulseSink {378
PulseSink {379
name: name.to_owned(),380
description: description.to_owned(),381
}382
}383
384
fn headset_sinks() -> Vec<PulseSink> {385
vec![386
sink("alsa_output.headset.mono-chat", "Headset Chat"),387
sink("alsa_output.headset.stereo-game", "Headset Game"),388
]389
}390
119
#[test]391
#[test]120
fn bundled_notification_decodes_to_audible_samples() {392
fn bundled_notification_decodes_to_audible_samples() {121
let decoded = rodio::Decoder::try_from(Cursor::new(SOUND_BYTES)).unwrap();393
let decoded = rodio::Decoder::try_from(Cursor::new(SOUND_BYTES)).unwrap();@@ -153,6 +425,28 @@ mod tests {153
assert!(!device_matches_key("id", "Speaker", ""));425
assert!(!device_matches_key("id", "Speaker", ""));154
}426
}155
427
428
#[test]429
fn a_pulse_description_selects_that_sink_and_not_the_other_output() {430
let sinks = headset_sinks();431
let game = matching_sink(&sinks, "Headset Game").unwrap();432
assert_eq!(game.name, "alsa_output.headset.stereo-game");433
let prefixed = matching_sink(&sinks, "default: Headset Game").unwrap();434
assert_eq!(prefixed.name, "alsa_output.headset.stereo-game");435
let chat = matching_sink(&sinks, "Headset Chat").unwrap();436
assert_eq!(chat.name, "alsa_output.headset.mono-chat");437
assert!(matching_sink(&sinks, "Headset Game").unwrap().name != chat.name);438
assert!(matching_sink(&sinks, "missing output").is_none());439
assert!(matching_sink(&sinks, "Game").is_none());440
}441
442
#[test]443
fn a_missing_key_is_noted_once() {444
let key = format!("missing-output-{}", std::process::id());445
assert!(claim_miss(&key));446
assert!(!claim_miss(&key));447
assert!(claim_miss(&format!("{key}-other")));448
}449
156
#[test]450
#[test]157
#[ignore = "plays a short notification on the real default audio output"]451
#[ignore = "plays a short notification on the real default audio output"]158
fn notification_plays_on_default_output() {452
fn notification_plays_on_default_output() {@@ -163,4 +457,30 @@ mod tests {163
)457
)164
.unwrap();458
.unwrap();165
}459
}460
461
#[cfg(target_os = "linux")]462
#[test]463
#[ignore = "plays a short tone on the Pulse sink named by CALL_OUTPUT_KEY"]464
fn selected_pulse_sink_plays_the_tone() {465
let key = std::env::var("CALL_OUTPUT_KEY").expect("CALL_OUTPUT_KEY");466
let sinks = pulse_sinks().expect("pulse");467
let sink = matching_sink(&sinks, &key).unwrap_or_else(|| {468
panic!(469
"no sink for {key:?}; have {}",470
sinks471
.iter()472
.map(|sink| format!("{} ({})", sink.description, sink.name))473
.collect::<Vec<_>>()474
.join(", ")475
)476
});477
eprintln!("pulse sink {} ({})", sink.name, sink.description);478
set_sound_output(Some(key));479
play(480
SOUND_BYTES.to_vec(),481
false,482
Arc::new(AtomicBool::new(false)),483
)484
.unwrap();485
}166
}486
}@@ -0,0 +1,138 @@
1
use gpui_kit::App;
2
use url::Url;
3
4
const WEB_SCHEMES: [&str; 2] = ["https", "http"];
5
const PLAIN_SCHEMES: [&str; 5] = ["mailto", "tel", "sip", "callto", "msteams"];
6
const OFFICE_SCHEMES: [&str; 8] = [
7
"ms-word",
8
"ms-excel",
9
"ms-powerpoint",
10
"ms-visio",
11
"ms-access",
12
"ms-project",
13
"ms-publisher",
14
"ms-infopath",
15
];
16
17
pub fn openable_url(raw: &str) -> Option<String> {
18
let url = Url::parse(raw.trim()).ok()?;
19
let scheme = url.scheme();
20
let allowed = if WEB_SCHEMES.contains(&scheme) {
21
url.host_str().is_some_and(|host| !host.is_empty())
22
} else if PLAIN_SCHEMES.contains(&scheme) {
23
url.host().is_none() && !url.path().contains('\\')
24
} else if scheme == "onenote" {
25
web_document(url.path()).is_some()
26
} else if OFFICE_SCHEMES.contains(&scheme) {
27
url.path()
28
.rsplit('|')
29
.next()
30
.and_then(web_document)
31
.is_some()
32
} else {
33
false
34
};
35
allowed.then(|| url.into())
36
}
37
38
fn web_document(document: &str) -> Option<Url> {
39
let document = Url::parse(document).ok()?;
40
(document.scheme() == "https" && document.host_str().is_some()).then_some(document)
41
}
42
43
pub fn is_openable_url(raw: &str) -> bool {
44
openable_url(raw).is_some()
45
}
46
47
pub fn open_url(cx: &mut App, raw: &str) {
48
match openable_url(raw) {
49
Some(url) => cx.open_url(&url),
50
None => crate::diagnostics::record(format!("refused to open a link: {}", scheme_of(raw))),
51
}
52
}
53
54
fn scheme_of(raw: &str) -> &str {
55
raw.trim()
56
.split_once(':')
57
.map_or("no scheme", |(scheme, _)| scheme)
58
}
59
60
#[cfg(test)]
61
mod tests {
62
use super::*;
63
64
#[test]
65
fn web_mail_and_teams_links_open() {
66
for url in [
67
"https://contoso.sharepoint.com/x.pdf",
68
"http://intranet.example/x",
69
"mailto:someone@example.com",
70
"tel:+491234",
71
"msteams:/l/chat/0/0",
72
"onenote:https://contoso.sharepoint.com/n.one",
73
"ms-word:ofe|u|https://contoso.sharepoint.com/a.docx",
74
] {
75
assert!(is_openable_url(url), "{url}");
76
}
77
}
78
79
#[test]
80
fn files_shares_and_local_handlers_do_not_open() {
81
for url in [
82
"\\\\203.0.113.5\\s\\x.lnk",
83
"file:///C:/Windows/System32/calc.exe",
84
"file://203.0.113.5/s/x.lnk",
85
"search-ms:query=x&crumb=location:\\\\203.0.113.5\\s",
86
"javascript:alert(1)",
87
"ms-msdt:/id x",
88
"ms-word:ofe|u|\\\\203.0.113.5\\s\\a.docx",
89
"ms-word:ofe|u|file:///C:/a.docx",
90
"ms-word:ofe|u|http://203.0.113.5/a.docx",
91
"mailto:\\\\203.0.113.5\\s",
92
"onenote:\\\\203.0.113.5\\s\\n.one",
93
"onenote://203.0.113.5/s/n.one",
94
"onenote:file:///C:/n.one",
95
"C:\\Windows\\System32\\calc.exe",
96
"",
97
] {
98
assert!(!is_openable_url(url), "{url}");
99
}
100
}
101
102
#[test]
103
fn every_url_the_app_opens_goes_through_this_module() {
104
let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
105
let mut offenders = Vec::new();
106
visit(&crates, &mut offenders);
107
assert!(
108
offenders.is_empty(),
109
"use app_base::open_link::open_url instead of cx.open_url: {offenders:#?}"
110
);
111
}
112
113
fn visit(directory: &std::path::Path, offenders: &mut Vec<String>) {
114
let Ok(entries) = std::fs::read_dir(directory) else {
115
return;
116
};
117
for entry in entries.flatten() {
118
let path = entry.path();
119
if path.is_dir() {
120
if path.file_name().is_some_and(|name| name != "target") {
121
visit(&path, offenders);
122
}
123
continue;
124
}
125
if path.extension().is_none_or(|extension| extension != "rs")
126
|| path.ends_with("app-base/src/open_link.rs")
127
{
128
continue;
129
}
130
let text = std::fs::read_to_string(&path).unwrap_or_default();
131
for (number, line) in text.lines().enumerate() {
132
if line.contains("cx.open_url(") {
133
offenders.push(format!("{}:{}", path.display(), number + 1));
134
}
135
}
136
}
137
}
138
}
@@ -0,0 +1,138 @@1
use gpui_kit::App;2
use url::Url;3
4
const WEB_SCHEMES: [&str; 2] = ["https", "http"];5
const PLAIN_SCHEMES: [&str; 5] = ["mailto", "tel", "sip", "callto", "msteams"];6
const OFFICE_SCHEMES: [&str; 8] = [7
"ms-word",8
"ms-excel",9
"ms-powerpoint",10
"ms-visio",11
"ms-access",12
"ms-project",13
"ms-publisher",14
"ms-infopath",15
];16
17
pub fn openable_url(raw: &str) -> Option<String> {18
let url = Url::parse(raw.trim()).ok()?;19
let scheme = url.scheme();20
let allowed = if WEB_SCHEMES.contains(&scheme) {21
url.host_str().is_some_and(|host| !host.is_empty())22
} else if PLAIN_SCHEMES.contains(&scheme) {23
url.host().is_none() && !url.path().contains('\\')24
} else if scheme == "onenote" {25
web_document(url.path()).is_some()26
} else if OFFICE_SCHEMES.contains(&scheme) {27
url.path()28
.rsplit('|')29
.next()30
.and_then(web_document)31
.is_some()32
} else {33
false34
};35
allowed.then(|| url.into())36
}37
38
fn web_document(document: &str) -> Option<Url> {39
let document = Url::parse(document).ok()?;40
(document.scheme() == "https" && document.host_str().is_some()).then_some(document)41
}42
43
pub fn is_openable_url(raw: &str) -> bool {44
openable_url(raw).is_some()45
}46
47
pub fn open_url(cx: &mut App, raw: &str) {48
match openable_url(raw) {49
Some(url) => cx.open_url(&url),50
None => crate::diagnostics::record(format!("refused to open a link: {}", scheme_of(raw))),51
}52
}53
54
fn scheme_of(raw: &str) -> &str {55
raw.trim()56
.split_once(':')57
.map_or("no scheme", |(scheme, _)| scheme)58
}59
60
#[cfg(test)]61
mod tests {62
use super::*;63
64
#[test]65
fn web_mail_and_teams_links_open() {66
for url in [67
"https://contoso.sharepoint.com/x.pdf",68
"http://intranet.example/x",69
"mailto:someone@example.com",70
"tel:+491234",71
"msteams:/l/chat/0/0",72
"onenote:https://contoso.sharepoint.com/n.one",73
"ms-word:ofe|u|https://contoso.sharepoint.com/a.docx",74
] {75
assert!(is_openable_url(url), "{url}");76
}77
}78
79
#[test]80
fn files_shares_and_local_handlers_do_not_open() {81
for url in [82
"\\\\203.0.113.5\\s\\x.lnk",83
"file:///C:/Windows/System32/calc.exe",84
"file://203.0.113.5/s/x.lnk",85
"search-ms:query=x&crumb=location:\\\\203.0.113.5\\s",86
"javascript:alert(1)",87
"ms-msdt:/id x",88
"ms-word:ofe|u|\\\\203.0.113.5\\s\\a.docx",89
"ms-word:ofe|u|file:///C:/a.docx",90
"ms-word:ofe|u|http://203.0.113.5/a.docx",91
"mailto:\\\\203.0.113.5\\s",92
"onenote:\\\\203.0.113.5\\s\\n.one",93
"onenote://203.0.113.5/s/n.one",94
"onenote:file:///C:/n.one",95
"C:\\Windows\\System32\\calc.exe",96
"",97
] {98
assert!(!is_openable_url(url), "{url}");99
}100
}101
102
#[test]103
fn every_url_the_app_opens_goes_through_this_module() {104
let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");105
let mut offenders = Vec::new();106
visit(&crates, &mut offenders);107
assert!(108
offenders.is_empty(),109
"use app_base::open_link::open_url instead of cx.open_url: {offenders:#?}"110
);111
}112
113
fn visit(directory: &std::path::Path, offenders: &mut Vec<String>) {114
let Ok(entries) = std::fs::read_dir(directory) else {115
return;116
};117
for entry in entries.flatten() {118
let path = entry.path();119
if path.is_dir() {120
if path.file_name().is_some_and(|name| name != "target") {121
visit(&path, offenders);122
}123
continue;124
}125
if path.extension().is_none_or(|extension| extension != "rs")126
|| path.ends_with("app-base/src/open_link.rs")127
{128
continue;129
}130
let text = std::fs::read_to_string(&path).unwrap_or_default();131
for (number, line) in text.lines().enumerate() {132
if line.contains("cx.open_url(") {133
offenders.push(format!("{}:{}", path.display(), number + 1));134
}135
}136
}137
}138
}@@ -188,6 +188,7 @@ async fn supervise(
188
188
}
189
189
};
190
190
tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone()));
191
tokio::spawn(msal_key_loop(home.clone()));
191
192
// Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.
192
193
// Chat files of a guest org go to the home OneDrive: the guest tenant has none.
193
194
let (session, home_drive) = match &guest_tenant {
@@ -240,6 +241,39 @@ async fn supervise(
240
241
refresh_loop(engine, events, nudges).await;
241
242
}
242
243
244
/// Gives the MSAL cache key an expiry once the page is signed in, so the next start can read the
245
/// token cache. WebView2 drops session cookies with the process just like Chromium does. One
246
/// success is enough: the expiry is renewed on the next start, and repeated CDP calls would wake a
247
/// parked WebView2.
248
async fn msal_key_loop(session: Session) {
249
if !session.can_persist_msal_key() {
250
return;
251
}
252
let mut wait = Duration::from_secs(5);
253
loop {
254
tokio::time::sleep(wait).await;
255
let outcome =
256
tokio::time::timeout(Duration::from_secs(10), session.persist_msal_key()).await;
257
match outcome {
258
Ok(Ok(true)) => {
259
crate::diagnostics::record("msal: key cookie persisted");
260
return;
261
}
262
Ok(Ok(false)) => {
263
wait = (wait * 2).min(Duration::from_secs(300));
264
}
265
Ok(Err(error)) => {
266
crate::diagnostics::record(format!("msal: key cookie not persisted: {error}"));
267
wait = (wait * 2).min(Duration::from_secs(300));
268
}
269
Err(_) => {
270
crate::diagnostics::record("msal: key cookie persistence timed out");
271
wait = (wait * 2).min(Duration::from_secs(300));
272
}
273
}
274
}
275
}
276
243
277
/// Fetches the account's organizations once per start, retried a few times while sign-in settles,
244
278
/// and keeps every org that is not open live for notifications.
245
279
async fn org_list(home: Session, open_guest: Option<String>, events: EventSender) {
@@ -352,6 +386,7 @@ async fn realtime_loop(
352
386
let _ = events.send(BackendEvent::Live(LiveState::Connecting));
353
387
let config = RealtimeConfig {
354
388
initially_active: *activity.borrow(),
389
retry: Some(live_retry.clone()),
355
390
..RealtimeConfig::default()
356
391
};
357
392
match Realtime::start_with(&session, config).await {
@@ -398,6 +433,12 @@ async fn realtime_loop(
398
433
let _ = events.send(BackendEvent::Typing(typing));
399
434
}
400
435
RealtimeEvent::Status(status) => {
436
if status.kind != StatusKind::Connected {
437
crate::diagnostics::record(format!(
438
"live: {:?} {}",
439
status.kind, status.detail
440
));
441
}
401
442
let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
402
443
if let Some(signal) = link_signal_for(status.kind) {
403
444
let _ = link.send(signal);
@@ -425,7 +466,8 @@ async fn realtime_loop(
425
466
let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));
426
467
let _ = link.send(LinkSignal::Disconnected);
427
468
}
428
Err(_) => {
469
Err(error) => {
470
crate::diagnostics::record(format!("live: start failed: {error}"));
429
471
let _ = events.send(BackendEvent::Live(LiveState::Failed));
430
472
let _ = link.send(LinkSignal::Disconnected);
431
473
}
@@ -572,8 +614,13 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)
572
614
}
573
615
}
574
616
}
575
match crate::google_calendar_sync::fetch_google_events(&mut fetched_accounts, start, end)
576
.await
617
match crate::google_calendar_sync::fetch_google_events(
618
&store,
619
&mut fetched_accounts,
620
start,
621
end,
622
)
623
.await
577
624
{
578
625
Ok((google_events, account_errors)) => {
579
626
// Only refreshed tokens: a calendar toggle made during the fetch stays.
@@ -188,6 +188,7 @@ async fn supervise(188
}188
}189
};189
};190
tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone()));190
tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone()));191
tokio::spawn(msal_key_loop(home.clone()));191
// Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.192
// Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.192
// Chat files of a guest org go to the home OneDrive: the guest tenant has none.193
// Chat files of a guest org go to the home OneDrive: the guest tenant has none.193
let (session, home_drive) = match &guest_tenant {194
let (session, home_drive) = match &guest_tenant {@@ -240,6 +241,39 @@ async fn supervise(240
refresh_loop(engine, events, nudges).await;241
refresh_loop(engine, events, nudges).await;241
}242
}242
243
244
/// Gives the MSAL cache key an expiry once the page is signed in, so the next start can read the245
/// token cache. WebView2 drops session cookies with the process just like Chromium does. One246
/// success is enough: the expiry is renewed on the next start, and repeated CDP calls would wake a247
/// parked WebView2.248
async fn msal_key_loop(session: Session) {249
if !session.can_persist_msal_key() {250
return;251
}252
let mut wait = Duration::from_secs(5);253
loop {254
tokio::time::sleep(wait).await;255
let outcome =256
tokio::time::timeout(Duration::from_secs(10), session.persist_msal_key()).await;257
match outcome {258
Ok(Ok(true)) => {259
crate::diagnostics::record("msal: key cookie persisted");260
return;261
}262
Ok(Ok(false)) => {263
wait = (wait * 2).min(Duration::from_secs(300));264
}265
Ok(Err(error)) => {266
crate::diagnostics::record(format!("msal: key cookie not persisted: {error}"));267
wait = (wait * 2).min(Duration::from_secs(300));268
}269
Err(_) => {270
crate::diagnostics::record("msal: key cookie persistence timed out");271
wait = (wait * 2).min(Duration::from_secs(300));272
}273
}274
}275
}276
243
/// Fetches the account's organizations once per start, retried a few times while sign-in settles,277
/// Fetches the account's organizations once per start, retried a few times while sign-in settles,244
/// and keeps every org that is not open live for notifications.278
/// and keeps every org that is not open live for notifications.245
async fn org_list(home: Session, open_guest: Option<String>, events: EventSender) {279
async fn org_list(home: Session, open_guest: Option<String>, events: EventSender) {@@ -352,6 +386,7 @@ async fn realtime_loop(352
let _ = events.send(BackendEvent::Live(LiveState::Connecting));386
let _ = events.send(BackendEvent::Live(LiveState::Connecting));353
let config = RealtimeConfig {387
let config = RealtimeConfig {354
initially_active: *activity.borrow(),388
initially_active: *activity.borrow(),389
retry: Some(live_retry.clone()),355
..RealtimeConfig::default()390
..RealtimeConfig::default()356
};391
};357
match Realtime::start_with(&session, config).await {392
match Realtime::start_with(&session, config).await {@@ -398,6 +433,12 @@ async fn realtime_loop(398
let _ = events.send(BackendEvent::Typing(typing));433
let _ = events.send(BackendEvent::Typing(typing));399
}434
}400
RealtimeEvent::Status(status) => {435
RealtimeEvent::Status(status) => {436
if status.kind != StatusKind::Connected {437
crate::diagnostics::record(format!(438
"live: {:?} {}",439
status.kind, status.detail440
));441
}401
let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));442
let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));402
if let Some(signal) = link_signal_for(status.kind) {443
if let Some(signal) = link_signal_for(status.kind) {403
let _ = link.send(signal);444
let _ = link.send(signal);@@ -425,7 +466,8 @@ async fn realtime_loop(425
let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));466
let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));426
let _ = link.send(LinkSignal::Disconnected);467
let _ = link.send(LinkSignal::Disconnected);427
}468
}428
Err(_) => {469
Err(error) => {470
crate::diagnostics::record(format!("live: start failed: {error}"));429
let _ = events.send(BackendEvent::Live(LiveState::Failed));471
let _ = events.send(BackendEvent::Live(LiveState::Failed));430
let _ = link.send(LinkSignal::Disconnected);472
let _ = link.send(LinkSignal::Disconnected);431
}473
}@@ -572,8 +614,13 @@ async fn calendar_loop(session: Session, store: Arc<Store>, events: EventSender)572
}614
}573
}615
}574
}616
}575
match crate::google_calendar_sync::fetch_google_events(&mut fetched_accounts, start, end)617
match crate::google_calendar_sync::fetch_google_events(576
.await618
&store,619
&mut fetched_accounts,620
start,621
end,622
)623
.await577
{624
{578
Ok((google_events, account_errors)) => {625
Ok((google_events, account_errors)) => {579
// Only refreshed tokens: a calendar toggle made during the fetch stays.626
// Only refreshed tokens: a calendar toggle made during the fetch stays.@@ -8,8 +8,8 @@ use store::{
8
8
use uuid::Uuid;
9
9
10
10
use chatsvc::{
11
GoogleCalendar, GoogleOAuth, allocate_redirect_uri, client_id_from_env, exchange_code,
12
parse_calendar_list, wait_for_code,
11
GoogleCalendar, GoogleOAuth, allocate_redirect_uri, exchange_code, parse_calendar_list,
12
wait_for_code,
13
13
};
14
14
15
15
use crate::app_state::AppState;
@@ -264,17 +264,16 @@ impl AppState {
264
264
self.reopen_google_connect(cx);
265
265
return;
266
266
}
267
let Some(oauth) = client_id_from_env() else {
268
self.raise_notice(tr("settings.calendar.not_in_build"), None, cx);
269
return;
270
};
271
267
let store = self.store.clone();
272
268
self.google_connect_generation = self.google_connect_generation.wrapping_add(1);
273
269
let generation = self.google_connect_generation;
274
270
cx.spawn(async move |this, cx| {
275
271
let prepared = runtime::spawn({
276
let oauth = oauth.clone();
272
let store = store.clone();
277
273
async move {
274
let oauth = crate::google_oauth_client::resolve(&store)
275
.await
276
.ok_or_else(|| tr("settings.calendar.not_in_build"))?;
278
277
let (redirect_uri, listener) = allocate_redirect_uri()
279
278
.await
280
279
.map_err(|error| error.to_string())?;
@@ -8,8 +8,8 @@ use store::{8
use uuid::Uuid;8
use uuid::Uuid;9
9
10
use chatsvc::{10
use chatsvc::{11
GoogleCalendar, GoogleOAuth, allocate_redirect_uri, client_id_from_env, exchange_code,11
GoogleCalendar, GoogleOAuth, allocate_redirect_uri, exchange_code, parse_calendar_list,12
parse_calendar_list, wait_for_code,12
wait_for_code,13
};13
};14
14
15
use crate::app_state::AppState;15
use crate::app_state::AppState;@@ -264,17 +264,16 @@ impl AppState {264
self.reopen_google_connect(cx);264
self.reopen_google_connect(cx);265
return;265
return;266
}266
}267
let Some(oauth) = client_id_from_env() else {268
self.raise_notice(tr("settings.calendar.not_in_build"), None, cx);269
return;270
};271
let store = self.store.clone();267
let store = self.store.clone();272
self.google_connect_generation = self.google_connect_generation.wrapping_add(1);268
self.google_connect_generation = self.google_connect_generation.wrapping_add(1);273
let generation = self.google_connect_generation;269
let generation = self.google_connect_generation;274
cx.spawn(async move |this, cx| {270
cx.spawn(async move |this, cx| {275
let prepared = runtime::spawn({271
let prepared = runtime::spawn({276
let oauth = oauth.clone();272
let store = store.clone();277
async move {273
async move {274
let oauth = crate::google_oauth_client::resolve(&store)275
.await276
.ok_or_else(|| tr("settings.calendar.not_in_build"))?;278
let (redirect_uri, listener) = allocate_redirect_uri()277
let (redirect_uri, listener) = allocate_redirect_uri()279
.await278
.await280
.map_err(|error| error.to_string())?;279
.map_err(|error| error.to_string())?;@@ -549,7 +549,7 @@ impl AppState {
549
549
return;
550
550
}
551
551
CallUpdate::WhiteboardUrl(url) => {
552
cx.open_url(&url);
552
app_base::open_link::open_url(cx, &url);
553
553
return;
554
554
}
555
555
CallUpdate::BreakoutMove(moved) => {
@@ -549,7 +549,7 @@ impl AppState {549
return;549
return;550
}550
}551
CallUpdate::WhiteboardUrl(url) => {551
CallUpdate::WhiteboardUrl(url) => {552
cx.open_url(&url);552
app_base::open_link::open_url(cx, &url);553
return;553
return;554
}554
}555
CallUpdate::BreakoutMove(moved) => {555
CallUpdate::BreakoutMove(moved) => {@@ -169,7 +169,7 @@ impl AppState {
169
169
return;
170
170
};
171
171
if let Some(url) = call.model.whiteboard_url() {
172
cx.open_url(url);
172
app_base::open_link::open_url(cx, url);
173
173
return;
174
174
}
175
175
let title = call.model.title.clone();
@@ -169,7 +169,7 @@ impl AppState {169
return;169
return;170
};170
};171
if let Some(url) = call.model.whiteboard_url() {171
if let Some(url) = call.model.whiteboard_url() {172
cx.open_url(url);172
app_base::open_link::open_url(cx, url);173
return;173
return;174
}174
}175
let title = call.model.title.clone();175
let title = call.model.title.clone();@@ -47,6 +47,7 @@ pub async fn create_across_targets(
47
47
for target in targets {
48
48
match write_target(
49
49
launcher.as_ref(),
50
store.as_ref(),
50
51
&mut accounts,
51
52
&target,
52
53
&event,
@@ -82,6 +83,7 @@ pub async fn create_across_targets(
82
83
83
84
async fn write_target(
84
85
launcher: &CallLauncher,
86
store: &Store,
85
87
accounts: &mut CalendarAccounts,
86
88
target: &CalendarRef,
87
89
event: &NewEvent,
@@ -102,6 +104,7 @@ async fn write_target(
102
104
let mut draft = GoogleEventDraft::from(event);
103
105
draft.join_url = Some(join_url.to_owned());
104
106
crate::google_calendar_sync::insert_google_event(
107
store,
105
108
accounts,
106
109
&target.account_id,
107
110
calendar_id,
@@ -47,6 +47,7 @@ pub async fn create_across_targets(47
for target in targets {47
for target in targets {48
match write_target(48
match write_target(49
launcher.as_ref(),49
launcher.as_ref(),50
store.as_ref(),50
&mut accounts,51
&mut accounts,51
&target,52
&target,52
&event,53
&event,@@ -82,6 +83,7 @@ pub async fn create_across_targets(82
83
83
async fn write_target(84
async fn write_target(84
launcher: &CallLauncher,85
launcher: &CallLauncher,86
store: &Store,85
accounts: &mut CalendarAccounts,87
accounts: &mut CalendarAccounts,86
target: &CalendarRef,88
target: &CalendarRef,87
event: &NewEvent,89
event: &NewEvent,@@ -102,6 +104,7 @@ async fn write_target(102
let mut draft = GoogleEventDraft::from(event);104
let mut draft = GoogleEventDraft::from(event);103
draft.join_url = Some(join_url.to_owned());105
draft.join_url = Some(join_url.to_owned());104
crate::google_calendar_sync::insert_google_event(106
crate::google_calendar_sync::insert_google_event(107
store,105
accounts,108
accounts,106
&target.account_id,109
&target.account_id,107
calendar_id,110
calendar_id,@@ -309,6 +309,7 @@ impl AppState {
309
309
account_id.ok_or_else(|| "Google account missing".to_owned())?;
310
310
let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());
311
311
let result = crate::google_calendar_sync::delete_google_event(
312
&store,
312
313
&mut accounts,
313
314
&account,
314
315
&calendar,
@@ -554,6 +555,7 @@ impl AppState {
554
555
account_id.ok_or_else(|| "Google account missing".to_owned())?;
555
556
let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());
556
557
let result = crate::google_calendar_sync::respond_google_event(
558
&store,
557
559
&mut accounts,
558
560
&account,
559
561
&calendar,
@@ -309,6 +309,7 @@ impl AppState {309
account_id.ok_or_else(|| "Google account missing".to_owned())?;309
account_id.ok_or_else(|| "Google account missing".to_owned())?;310
let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());310
let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());311
let result = crate::google_calendar_sync::delete_google_event(311
let result = crate::google_calendar_sync::delete_google_event(312
&store,312
&mut accounts,313
&mut accounts,313
&account,314
&account,314
&calendar,315
&calendar,@@ -554,6 +555,7 @@ impl AppState {554
account_id.ok_or_else(|| "Google account missing".to_owned())?;555
account_id.ok_or_else(|| "Google account missing".to_owned())?;555
let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());556
let calendar = calendar_id.unwrap_or_else(|| "primary".to_owned());556
let result = crate::google_calendar_sync::respond_google_event(557
let result = crate::google_calendar_sync::respond_google_event(558
&store,557
&mut accounts,559
&mut accounts,558
&account,560
&account,559
&calendar,561
&calendar,@@ -266,6 +266,7 @@ impl AppState {
266
266
let mut google_count = None;
267
267
if accounts.has_google() {
268
268
match crate::google_calendar_sync::fetch_google_events(
269
&store,
269
270
&mut fetched_accounts,
270
271
from,
271
272
to,
@@ -266,6 +266,7 @@ impl AppState {266
let mut google_count = None;266
let mut google_count = None;267
if accounts.has_google() {267
if accounts.has_google() {268
match crate::google_calendar_sync::fetch_google_events(268
match crate::google_calendar_sync::fetch_google_events(269
&store,269
&mut fetched_accounts,270
&mut fetched_accounts,270
from,271
from,271
to,272
to,@@ -429,7 +429,7 @@ impl AppState {
429
429
cx: &mut Context<Self>,
430
430
) {
431
431
match &action.kind {
432
CardActionKind::OpenUrl(url) => cx.open_url(url),
432
CardActionKind::OpenUrl(url) => app_base::open_link::open_url(cx, url),
433
433
_ => self.run_card_action(
434
434
scope.clone(),
435
435
action_key,
@@ -429,7 +429,7 @@ impl AppState {429
cx: &mut Context<Self>,429
cx: &mut Context<Self>,430
) {430
) {431
match &action.kind {431
match &action.kind {432
CardActionKind::OpenUrl(url) => cx.open_url(url),432
CardActionKind::OpenUrl(url) => app_base::open_link::open_url(cx, url),433
_ => self.run_card_action(433
_ => self.run_card_action(434
scope.clone(),434
scope.clone(),435
action_key,435
action_key,@@ -67,7 +67,10 @@ pub fn banner_text(kind: BannerKind, last_sync: Option<DateTime<Utc>>) -> Banner
67
67
};
68
68
match kind {
69
69
BannerKind::Connecting => text("auth.banner.connecting"),
70
BannerKind::Reconnecting => text("auth.banner.reconnecting"),
70
BannerKind::Reconnecting => BannerText {
71
action: Some(app_base::ui_locale::tr("common.retry")),
72
..text("auth.banner.reconnecting")
73
},
71
74
BannerKind::Offline => BannerText {
72
75
detail: last_sync.map(|time| {
73
76
app_base::ui_locale::tr("auth.banner.last_synced").replace(
@@ -81,6 +84,7 @@ pub fn banner_text(kind: BannerKind, last_sync: Option<DateTime<Utc>>) -> Banner
81
84
..text("auth.banner.offline")
82
85
},
83
86
BannerKind::SignIn => {
87
#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(unused_mut))]
84
88
let mut banner = text("auth.banner.sign_in");
85
89
// Windows signs in through the embedded view. The managed window exists
86
90
// only on Linux and macOS, so other platforms get no button.
@@ -311,6 +315,7 @@ mod tests {
311
315
.action
312
316
.is_some()
313
317
);
318
assert!(banner_text(BannerKind::Reconnecting, None).action.is_some());
314
319
#[cfg(any(target_os = "linux", target_os = "macos"))]
315
320
assert!(banner_text(BannerKind::SignIn, None).action.is_some());
316
321
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
@@ -67,7 +67,10 @@ pub fn banner_text(kind: BannerKind, last_sync: Option<DateTime<Utc>>) -> Banner67
};67
};68
match kind {68
match kind {69
BannerKind::Connecting => text("auth.banner.connecting"),69
BannerKind::Connecting => text("auth.banner.connecting"),70
BannerKind::Reconnecting => text("auth.banner.reconnecting"),70
BannerKind::Reconnecting => BannerText {71
action: Some(app_base::ui_locale::tr("common.retry")),72
..text("auth.banner.reconnecting")73
},71
BannerKind::Offline => BannerText {74
BannerKind::Offline => BannerText {72
detail: last_sync.map(|time| {75
detail: last_sync.map(|time| {73
app_base::ui_locale::tr("auth.banner.last_synced").replace(76
app_base::ui_locale::tr("auth.banner.last_synced").replace(@@ -81,6 +84,7 @@ pub fn banner_text(kind: BannerKind, last_sync: Option<DateTime<Utc>>) -> Banner81
..text("auth.banner.offline")84
..text("auth.banner.offline")82
},85
},83
BannerKind::SignIn => {86
BannerKind::SignIn => {87
#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(unused_mut))]84
let mut banner = text("auth.banner.sign_in");88
let mut banner = text("auth.banner.sign_in");85
// Windows signs in through the embedded view. The managed window exists89
// Windows signs in through the embedded view. The managed window exists86
// only on Linux and macOS, so other platforms get no button.90
// only on Linux and macOS, so other platforms get no button.@@ -311,6 +315,7 @@ mod tests {311
.action315
.action312
.is_some()316
.is_some()313
);317
);318
assert!(banner_text(BannerKind::Reconnecting, None).action.is_some());314
#[cfg(any(target_os = "linux", target_os = "macos"))]319
#[cfg(any(target_os = "linux", target_os = "macos"))]315
assert!(banner_text(BannerKind::SignIn, None).action.is_some());320
assert!(banner_text(BannerKind::SignIn, None).action.is_some());316
#[cfg(not(any(target_os = "linux", target_os = "macos")))]321
#[cfg(not(any(target_os = "linux", target_os = "macos")))]@@ -49,14 +49,19 @@ pub fn save(store: &Store, browser: &ExternalBrowser) {
49
49
}
50
50
51
51
pub fn open_url(cx: &mut App, store: &Store, url: &str) {
52
let Some(url) = app_base::open_link::openable_url(url) else {
53
app_base::open_link::open_url(cx, url);
54
return;
55
};
56
let url = url.as_str();
52
57
match load(store) {
53
ExternalBrowser::System => cx.open_url(url),
58
ExternalBrowser::System => app_base::open_link::open_url(cx, url),
54
59
ExternalBrowser::Program(program) => {
55
60
let known = available_choices()
56
61
.iter()
57
62
.any(|choice| choice.id == program);
58
63
if !known || launch_program(&program, url).is_err() {
59
cx.open_url(url);
64
app_base::open_link::open_url(cx, url);
60
65
}
61
66
}
62
67
}
@@ -49,14 +49,19 @@ pub fn save(store: &Store, browser: &ExternalBrowser) {49
}49
}50
50
51
pub fn open_url(cx: &mut App, store: &Store, url: &str) {51
pub fn open_url(cx: &mut App, store: &Store, url: &str) {52
let Some(url) = app_base::open_link::openable_url(url) else {53
app_base::open_link::open_url(cx, url);54
return;55
};56
let url = url.as_str();52
match load(store) {57
match load(store) {53
ExternalBrowser::System => cx.open_url(url),58
ExternalBrowser::System => app_base::open_link::open_url(cx, url),54
ExternalBrowser::Program(program) => {59
ExternalBrowser::Program(program) => {55
let known = available_choices()60
let known = available_choices()56
.iter()61
.iter()57
.any(|choice| choice.id == program);62
.any(|choice| choice.id == program);58
if !known || launch_program(&program, url).is_err() {63
if !known || launch_program(&program, url).is_err() {59
cx.open_url(url);64
app_base::open_link::open_url(cx, url);60
}65
}61
}66
}62
}67
}@@ -1,18 +1,19 @@
1
1
use chrono::{DateTime, Utc};
2
use store::{CalendarAccounts, GoogleTokenSet};
2
use store::{CalendarAccounts, GoogleTokenSet, Store};
3
3
4
4
use chatsvc::{
5
CalendarEvent, GoogleCalendar, GoogleEventDraft, GoogleOAuth, Reply, client_id_from_env,
6
google_rsvp_status, refresh_access_token,
5
CalendarEvent, GoogleCalendar, GoogleEventDraft, GoogleOAuth, Reply, google_rsvp_status,
6
refresh_access_token,
7
7
};
8
8
9
9
/// Refresh tokens when needed and load events from every selected Google calendar.
10
10
pub async fn fetch_google_events(
11
store: &Store,
11
12
accounts: &mut CalendarAccounts,
12
13
start: DateTime<Utc>,
13
14
end: DateTime<Utc>,
14
15
) -> Result<(Vec<CalendarEvent>, Vec<String>), String> {
15
let Some(oauth) = client_id_from_env() else {
16
let Some(oauth) = crate::google_oauth_client::resolve(store).await else {
16
17
// Connected accounts but no client id compiled in: say so instead of an empty week.
17
18
if accounts.has_google() {
18
19
return Err(missing_client_id());
@@ -86,12 +87,15 @@ fn remember_account_error(errors: &mut Vec<String>, error: String) {
86
87
}
87
88
88
89
pub async fn insert_google_event(
90
store: &Store,
89
91
accounts: &mut CalendarAccounts,
90
92
account_id: &str,
91
93
calendar_id: &str,
92
94
draft: &GoogleEventDraft,
93
95
) -> Result<(), String> {
94
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
96
let oauth = crate::google_oauth_client::resolve(store)
97
.await
98
.ok_or_else(|| missing_client_id())?;
95
99
let index = accounts
96
100
.google_accounts
97
101
.iter()
@@ -109,6 +113,7 @@ pub async fn insert_google_event(
109
113
}
110
114
111
115
pub async fn respond_google_event(
116
store: &Store,
112
117
accounts: &mut CalendarAccounts,
113
118
account_id: &str,
114
119
calendar_id: &str,
@@ -116,7 +121,9 @@ pub async fn respond_google_event(
116
121
reply: Reply,
117
122
send_updates: bool,
118
123
) -> Result<(), String> {
119
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
124
let oauth = crate::google_oauth_client::resolve(store)
125
.await
126
.ok_or_else(|| missing_client_id())?;
120
127
let index = accounts
121
128
.google_accounts
122
129
.iter()
@@ -138,13 +145,16 @@ pub async fn respond_google_event(
138
145
}
139
146
140
147
pub async fn delete_google_event(
148
store: &Store,
141
149
accounts: &mut CalendarAccounts,
142
150
account_id: &str,
143
151
calendar_id: &str,
144
152
event_id: &str,
145
153
send_updates: bool,
146
154
) -> Result<(), String> {
147
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;
155
let oauth = crate::google_oauth_client::resolve(store)
156
.await
157
.ok_or_else(|| missing_client_id())?;
148
158
let index = accounts
149
159
.google_accounts
150
160
.iter()
@@ -1,18 +1,19 @@1
use chrono::{DateTime, Utc};1
use chrono::{DateTime, Utc};2
use store::{CalendarAccounts, GoogleTokenSet};2
use store::{CalendarAccounts, GoogleTokenSet, Store};3
3
4
use chatsvc::{4
use chatsvc::{5
CalendarEvent, GoogleCalendar, GoogleEventDraft, GoogleOAuth, Reply, client_id_from_env,5
CalendarEvent, GoogleCalendar, GoogleEventDraft, GoogleOAuth, Reply, google_rsvp_status,6
google_rsvp_status, refresh_access_token,6
refresh_access_token,7
};7
};8
8
9
/// Refresh tokens when needed and load events from every selected Google calendar.9
/// Refresh tokens when needed and load events from every selected Google calendar.10
pub async fn fetch_google_events(10
pub async fn fetch_google_events(11
store: &Store,11
accounts: &mut CalendarAccounts,12
accounts: &mut CalendarAccounts,12
start: DateTime<Utc>,13
start: DateTime<Utc>,13
end: DateTime<Utc>,14
end: DateTime<Utc>,14
) -> Result<(Vec<CalendarEvent>, Vec<String>), String> {15
) -> Result<(Vec<CalendarEvent>, Vec<String>), String> {15
let Some(oauth) = client_id_from_env() else {16
let Some(oauth) = crate::google_oauth_client::resolve(store).await else {16
// Connected accounts but no client id compiled in: say so instead of an empty week.17
// Connected accounts but no client id compiled in: say so instead of an empty week.17
if accounts.has_google() {18
if accounts.has_google() {18
return Err(missing_client_id());19
return Err(missing_client_id());@@ -86,12 +87,15 @@ fn remember_account_error(errors: &mut Vec<String>, error: String) {86
}87
}87
88
88
pub async fn insert_google_event(89
pub async fn insert_google_event(90
store: &Store,89
accounts: &mut CalendarAccounts,91
accounts: &mut CalendarAccounts,90
account_id: &str,92
account_id: &str,91
calendar_id: &str,93
calendar_id: &str,92
draft: &GoogleEventDraft,94
draft: &GoogleEventDraft,93
) -> Result<(), String> {95
) -> Result<(), String> {94
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;96
let oauth = crate::google_oauth_client::resolve(store)97
.await98
.ok_or_else(|| missing_client_id())?;95
let index = accounts99
let index = accounts96
.google_accounts100
.google_accounts97
.iter()101
.iter()@@ -109,6 +113,7 @@ pub async fn insert_google_event(109
}113
}110
114
111
pub async fn respond_google_event(115
pub async fn respond_google_event(116
store: &Store,112
accounts: &mut CalendarAccounts,117
accounts: &mut CalendarAccounts,113
account_id: &str,118
account_id: &str,114
calendar_id: &str,119
calendar_id: &str,@@ -116,7 +121,9 @@ pub async fn respond_google_event(116
reply: Reply,121
reply: Reply,117
send_updates: bool,122
send_updates: bool,118
) -> Result<(), String> {123
) -> Result<(), String> {119
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;124
let oauth = crate::google_oauth_client::resolve(store)125
.await126
.ok_or_else(|| missing_client_id())?;120
let index = accounts127
let index = accounts121
.google_accounts128
.google_accounts122
.iter()129
.iter()@@ -138,13 +145,16 @@ pub async fn respond_google_event(138
}145
}139
146
140
pub async fn delete_google_event(147
pub async fn delete_google_event(148
store: &Store,141
accounts: &mut CalendarAccounts,149
accounts: &mut CalendarAccounts,142
account_id: &str,150
account_id: &str,143
calendar_id: &str,151
calendar_id: &str,144
event_id: &str,152
event_id: &str,145
send_updates: bool,153
send_updates: bool,146
) -> Result<(), String> {154
) -> Result<(), String> {147
let oauth = client_id_from_env().ok_or_else(|| missing_client_id())?;155
let oauth = crate::google_oauth_client::resolve(store)156
.await157
.ok_or_else(|| missing_client_id())?;148
let index = accounts158
let index = accounts149
.google_accounts159
.google_accounts150
.iter()160
.iter()@@ -0,0 +1,135 @@
1
//! Saved Google OAuth Desktop client (ADR 0024).
2
//!
3
//! The client id lives in store meta. The secret lives in the OS keyring and is
4
//! never written to the calendar account document or to logs.
5
6
use store::Store;
7
8
use chatsvc::GoogleOAuth;
9
10
pub const CLIENT_ID_KEY: &str = "calendar.google_client_id";
11
const SERVICE: &str = "rusty-teams.google-oauth";
12
const ACCOUNT: &str = "desktop";
13
14
pub enum GoogleClientSave {
15
Saved,
16
Cleared,
17
}
18
19
pub enum GoogleClientSaveError {
20
/// An id was given without a secret, and no secret is stored for that id.
21
SecretRequired,
22
Failed,
23
}
24
25
pub fn load_client_id(store: &Store) -> String {
26
store
27
.meta(CLIENT_ID_KEY)
28
.ok()
29
.flatten()
30
.map(|value| value.trim().to_owned())
31
.filter(|value| !value.is_empty())
32
.unwrap_or_default()
33
}
34
35
pub async fn secret_is_stored() -> bool {
36
load_secret()
37
.await
38
.map(|value| !value.trim().is_empty())
39
.unwrap_or(false)
40
}
41
42
/// Saved pair, then the environment, then the client compiled into the build.
43
pub async fn resolve(store: &Store) -> Option<GoogleOAuth> {
44
let stored_id = load_client_id(store);
45
// Without a saved id the keyring is never asked, so Secret Service stays out of every fetch.
46
let stored_secret = if stored_id.is_empty() {
47
String::new()
48
} else {
49
match load_secret().await {
50
Ok(secret) => secret,
51
Err(_) => {
52
log::warn!("saved Google client secret not read from the keyring");
53
String::new()
54
}
55
}
56
};
57
chatsvc::client_from_stored(Some(stored_id.as_str()), Some(stored_secret.as_str()))
58
}
59
60
pub async fn save(
61
store: &Store,
62
client_id: &str,
63
secret: &str,
64
) -> Result<GoogleClientSave, GoogleClientSaveError> {
65
let id = client_id.trim();
66
let secret = secret.trim();
67
if id.is_empty() {
68
store
69
.set_meta(CLIENT_ID_KEY, "")
70
.map_err(|_| GoogleClientSaveError::Failed)?;
71
delete_secret().await?;
72
return Ok(GoogleClientSave::Cleared);
73
}
74
if secret.is_empty() {
75
// The kept secret belongs to the saved id; a new id needs its own secret.
76
if load_client_id(store) != id {
77
return Err(GoogleClientSaveError::SecretRequired);
78
}
79
return match load_secret().await {
80
Ok(existing) if !existing.trim().is_empty() => Ok(GoogleClientSave::Saved),
81
_ => Err(GoogleClientSaveError::SecretRequired),
82
};
83
}
84
// Secret before id: a failed keyring write must not leave a new id beside the old secret.
85
store_secret(secret).await?;
86
store
87
.set_meta(CLIENT_ID_KEY, id)
88
.map_err(|_| GoogleClientSaveError::Failed)?;
89
Ok(GoogleClientSave::Saved)
90
}
91
92
async fn load_secret() -> Result<String, GoogleClientSaveError> {
93
spawn_blocking(move || {
94
let entry =
95
keyring::Entry::new(SERVICE, ACCOUNT).map_err(|_| GoogleClientSaveError::Failed)?;
96
entry
97
.get_password()
98
.map_err(|_| GoogleClientSaveError::Failed)
99
})
100
.await
101
}
102
103
async fn store_secret(secret: &str) -> Result<(), GoogleClientSaveError> {
104
let secret = secret.to_owned();
105
spawn_blocking(move || {
106
let entry =
107
keyring::Entry::new(SERVICE, ACCOUNT).map_err(|_| GoogleClientSaveError::Failed)?;
108
entry
109
.set_password(&secret)
110
.map_err(|_| GoogleClientSaveError::Failed)
111
})
112
.await
113
}
114
115
async fn delete_secret() -> Result<(), GoogleClientSaveError> {
116
spawn_blocking(move || {
117
let entry =
118
keyring::Entry::new(SERVICE, ACCOUNT).map_err(|_| GoogleClientSaveError::Failed)?;
119
match entry.delete_credential() {
120
Ok(()) => Ok(()),
121
Err(keyring::Error::NoEntry) => Ok(()),
122
Err(_) => Err(GoogleClientSaveError::Failed),
123
}
124
})
125
.await
126
}
127
128
async fn spawn_blocking<T: Send + 'static>(
129
work: impl FnOnce() -> Result<T, GoogleClientSaveError> + Send + 'static,
130
) -> Result<T, GoogleClientSaveError> {
131
match tokio::task::spawn_blocking(work).await {
132
Ok(result) => result,
133
Err(_) => Err(GoogleClientSaveError::Failed),
134
}
135
}
@@ -0,0 +1,135 @@1
//! Saved Google OAuth Desktop client (ADR 0024).2
//!3
//! The client id lives in store meta. The secret lives in the OS keyring and is4
//! never written to the calendar account document or to logs.5
6
use store::Store;7
8
use chatsvc::GoogleOAuth;9
10
pub const CLIENT_ID_KEY: &str = "calendar.google_client_id";11
const SERVICE: &str = "rusty-teams.google-oauth";12
const ACCOUNT: &str = "desktop";13
14
pub enum GoogleClientSave {15
Saved,16
Cleared,17
}18
19
pub enum GoogleClientSaveError {20
/// An id was given without a secret, and no secret is stored for that id.21
SecretRequired,22
Failed,23
}24
25
pub fn load_client_id(store: &Store) -> String {26
store27
.meta(CLIENT_ID_KEY)28
.ok()29
.flatten()30
.map(|value| value.trim().to_owned())31
.filter(|value| !value.is_empty())32
.unwrap_or_default()33
}34
35
pub async fn secret_is_stored() -> bool {36
load_secret()37
.await38
.map(|value| !value.trim().is_empty())39
.unwrap_or(false)40
}41
42
/// Saved pair, then the environment, then the client compiled into the build.43
pub async fn resolve(store: &Store) -> Option<GoogleOAuth> {44
let stored_id = load_client_id(store);45
// Without a saved id the keyring is never asked, so Secret Service stays out of every fetch.46
let stored_secret = if stored_id.is_empty() {47
String::new()48
} else {49
match load_secret().await {50
Ok(secret) => secret,51
Err(_) => {52
log::warn!("saved Google client secret not read from the keyring");53
String::new()54
}55
}56
};57
chatsvc::client_from_stored(Some(stored_id.as_str()), Some(stored_secret.as_str()))58
}59
60
pub async fn save(61
store: &Store,62
client_id: &str,63
secret: &str,64
) -> Result<GoogleClientSave, GoogleClientSaveError> {65
let id = client_id.trim();66
let secret = secret.trim();67
if id.is_empty() {68
store69
.set_meta(CLIENT_ID_KEY, "")70
.map_err(|_| GoogleClientSaveError::Failed)?;71
delete_secret().await?;72
return Ok(GoogleClientSave::Cleared);73
}74
if secret.is_empty() {75
// The kept secret belongs to the saved id; a new id needs its own secret.76
if load_client_id(store) != id {77
return Err(GoogleClientSaveError::SecretRequired);78
}79
return match load_secret().await {80
Ok(existing) if !existing.trim().is_empty() => Ok(GoogleClientSave::Saved),81
_ => Err(GoogleClientSaveError::SecretRequired),82
};83
}84
// Secret before id: a failed keyring write must not leave a new id beside the old secret.85
store_secret(secret).await?;86
store87
.set_meta(CLIENT_ID_KEY, id)88
.map_err(|_| GoogleClientSaveError::Failed)?;89
Ok(GoogleClientSave::Saved)90
}91
92
async fn load_secret() -> Result<String, GoogleClientSaveError> {93
spawn_blocking(move || {94
let entry =95
keyring::Entry::new(SERVICE, ACCOUNT).map_err(|_| GoogleClientSaveError::Failed)?;96
entry97
.get_password()98
.map_err(|_| GoogleClientSaveError::Failed)99
})100
.await101
}102
103
async fn store_secret(secret: &str) -> Result<(), GoogleClientSaveError> {104
let secret = secret.to_owned();105
spawn_blocking(move || {106
let entry =107
keyring::Entry::new(SERVICE, ACCOUNT).map_err(|_| GoogleClientSaveError::Failed)?;108
entry109
.set_password(&secret)110
.map_err(|_| GoogleClientSaveError::Failed)111
})112
.await113
}114
115
async fn delete_secret() -> Result<(), GoogleClientSaveError> {116
spawn_blocking(move || {117
let entry =118
keyring::Entry::new(SERVICE, ACCOUNT).map_err(|_| GoogleClientSaveError::Failed)?;119
match entry.delete_credential() {120
Ok(()) => Ok(()),121
Err(keyring::Error::NoEntry) => Ok(()),122
Err(_) => Err(GoogleClientSaveError::Failed),123
}124
})125
.await126
}127
128
async fn spawn_blocking<T: Send + 'static>(129
work: impl FnOnce() -> Result<T, GoogleClientSaveError> + Send + 'static,130
) -> Result<T, GoogleClientSaveError> {131
match tokio::task::spawn_blocking(work).await {132
Ok(result) => result,133
Err(_) => Err(GoogleClientSaveError::Failed),134
}135
}@@ -34,6 +34,7 @@ pub mod find_in_chat;
34
34
pub mod forward_selection;
35
35
pub mod gifs;
36
36
pub mod google_calendar_sync;
37
pub mod google_oauth_client;
37
38
pub mod ics_sync;
38
39
pub mod image_view_gallery;
39
40
pub mod importance;
@@ -34,6 +34,7 @@ pub mod find_in_chat;34
pub mod forward_selection;34
pub mod forward_selection;35
pub mod gifs;35
pub mod gifs;36
pub mod google_calendar_sync;36
pub mod google_calendar_sync;37
pub mod google_oauth_client;37
pub mod ics_sync;38
pub mod ics_sync;38
pub mod image_view_gallery;39
pub mod image_view_gallery;39
pub mod importance;40
pub mod importance;@@ -63,6 +63,33 @@ pub struct Outgoing {
63
63
pub banner: Option<AnnouncementBanner>,
64
64
}
65
65
66
/// Teams shows a code block's language and Copy button only when a marker paragraph links to it.
67
/// The server adds the `x_` that Teams' own messages show on the marker's id.
68
fn link_code_blocks(html: &str) -> String {
69
let mut linked = String::with_capacity(html.len());
70
for (index, part) in html.split("<pre ").enumerate() {
71
if index > 0 {
72
// Derived from the body, so every html() of one message gives the same text.
73
let id = code_block_id(html, index);
74
linked.push_str(&format!(
75
"<p itemtype=\"{}\" id=\"codeBlockEditor-{id}\"> </p><pre itemid=\"codeBlockEditor-{id}\" ",
76
teams_core::CODE_BLOCK_ITEMTYPE
77
));
78
}
79
linked.push_str(part);
80
}
81
linked
82
}
83
84
fn code_block_id(html: &str, index: usize) -> uuid::Uuid {
85
use std::hash::{Hash, Hasher};
86
let mut hasher = std::hash::DefaultHasher::new();
87
(html, index).hash(&mut hasher);
88
let high = hasher.finish();
89
high.hash(&mut hasher);
90
uuid::Uuid::from_u64_pair(high, hasher.finish())
91
}
92
66
93
impl Outgoing {
67
94
/// Without list and quote markers, for previews.
68
95
pub fn text(&self) -> String {
@@ -90,7 +117,10 @@ impl Outgoing {
90
117
None => {}
91
118
}
92
119
}
93
teams_core::emoticon_tags(&html, crate::emoticons::send_tag)
120
link_code_blocks(&teams_core::emoticon_tags(
121
&html,
122
crate::emoticons::send_tag,
123
))
94
124
}
95
125
96
126
pub fn has_attachments(&self) -> bool {
@@ -120,3 +150,30 @@ impl Outgoing {
120
150
}
121
151
}
122
152
}
153
154
#[cfg(test)]
155
mod tests {
156
use super::*;
157
158
#[test]
159
fn each_code_block_gets_its_own_teams_marker() {
160
let html = "<p>a</p><pre class=\"language-rs\"><code>x</code></pre><pre class=\"language-py\"><code><pre y</code></pre>";
161
let linked = link_code_blocks(html);
162
let ids: Vec<&str> = linked
163
.split("itemid=\"codeBlockEditor-")
164
.skip(1)
165
.map(|rest| &rest[..36])
166
.collect();
167
assert_eq!(ids.len(), 2);
168
assert_ne!(ids[0], ids[1]);
169
for id in &ids {
170
assert!(linked.contains(&format!(
171
"<p itemtype=\"{}\" id=\"codeBlockEditor-{id}\"> </p><pre itemid=\"codeBlockEditor-{id}\" class=",
172
teams_core::CODE_BLOCK_ITEMTYPE
173
)));
174
}
175
assert!(linked.contains("<pre y"));
176
assert_eq!(link_code_blocks(html), linked);
177
assert_eq!(link_code_blocks("<p>no code</p>"), "<p>no code</p>");
178
}
179
}
@@ -63,6 +63,33 @@ pub struct Outgoing {63
pub banner: Option<AnnouncementBanner>,63
pub banner: Option<AnnouncementBanner>,64
}64
}65
65
66
/// Teams shows a code block's language and Copy button only when a marker paragraph links to it.67
/// The server adds the `x_` that Teams' own messages show on the marker's id.68
fn link_code_blocks(html: &str) -> String {69
let mut linked = String::with_capacity(html.len());70
for (index, part) in html.split("<pre ").enumerate() {71
if index > 0 {72
// Derived from the body, so every html() of one message gives the same text.73
let id = code_block_id(html, index);74
linked.push_str(&format!(75
"<p itemtype=\"{}\" id=\"codeBlockEditor-{id}\"> </p><pre itemid=\"codeBlockEditor-{id}\" ",76
teams_core::CODE_BLOCK_ITEMTYPE77
));78
}79
linked.push_str(part);80
}81
linked82
}83
84
fn code_block_id(html: &str, index: usize) -> uuid::Uuid {85
use std::hash::{Hash, Hasher};86
let mut hasher = std::hash::DefaultHasher::new();87
(html, index).hash(&mut hasher);88
let high = hasher.finish();89
high.hash(&mut hasher);90
uuid::Uuid::from_u64_pair(high, hasher.finish())91
}92
66
impl Outgoing {93
impl Outgoing {67
/// Without list and quote markers, for previews.94
/// Without list and quote markers, for previews.68
pub fn text(&self) -> String {95
pub fn text(&self) -> String {@@ -90,7 +117,10 @@ impl Outgoing {90
None => {}117
None => {}91
}118
}92
}119
}93
teams_core::emoticon_tags(&html, crate::emoticons::send_tag)120
link_code_blocks(&teams_core::emoticon_tags(121
&html,122
crate::emoticons::send_tag,123
))94
}124
}95
125
96
pub fn has_attachments(&self) -> bool {126
pub fn has_attachments(&self) -> bool {@@ -120,3 +150,30 @@ impl Outgoing {120
}150
}121
}151
}122
}152
}153
154
#[cfg(test)]155
mod tests {156
use super::*;157
158
#[test]159
fn each_code_block_gets_its_own_teams_marker() {160
let html = "<p>a</p><pre class=\"language-rs\"><code>x</code></pre><pre class=\"language-py\"><code><pre y</code></pre>";161
let linked = link_code_blocks(html);162
let ids: Vec<&str> = linked163
.split("itemid=\"codeBlockEditor-")164
.skip(1)165
.map(|rest| &rest[..36])166
.collect();167
assert_eq!(ids.len(), 2);168
assert_ne!(ids[0], ids[1]);169
for id in &ids {170
assert!(linked.contains(&format!(171
"<p itemtype=\"{}\" id=\"codeBlockEditor-{id}\"> </p><pre itemid=\"codeBlockEditor-{id}\" class=",172
teams_core::CODE_BLOCK_ITEMTYPE173
)));174
}175
assert!(linked.contains("<pre y"));176
assert_eq!(link_code_blocks(html), linked);177
assert_eq!(link_code_blocks("<p>no code</p>"), "<p>no code</p>");178
}179
}@@ -47,5 +47,5 @@ pub fn open_url_dialog(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut
47
47
48
48
#[cfg(not(windows))]
49
49
pub fn open_url_dialog(dialog: UrlDialog, _engine: Option<Arc<Engine>>, cx: &mut App) {
50
cx.open_url(&dialog.fallback_url);
50
app_base::open_link::open_url(cx, &dialog.fallback_url);
51
51
}
@@ -47,5 +47,5 @@ pub fn open_url_dialog(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut47
47
48
#[cfg(not(windows))]48
#[cfg(not(windows))]49
pub fn open_url_dialog(dialog: UrlDialog, _engine: Option<Arc<Engine>>, cx: &mut App) {49
pub fn open_url_dialog(dialog: UrlDialog, _engine: Option<Arc<Engine>>, cx: &mut App) {50
cx.open_url(&dialog.fallback_url);50
app_base::open_link::open_url(cx, &dialog.fallback_url);51
}51
}@@ -24,7 +24,7 @@ pub fn host() -> Option<Arc<WebViewTransport>> {
24
24
25
25
pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {
26
26
let Some(host) = HOST.get().cloned() else {
27
cx.open_url(&dialog.fallback_url);
27
app_base::open_link::open_url(cx, &dialog.fallback_url);
28
28
return;
29
29
};
30
30
let state = cx.global::<AppHandle>().0.clone();
@@ -110,7 +110,7 @@ async fn apply(
110
110
match effect {
111
111
Effect::Resize { width, height } => handle.resize(width, height),
112
112
Effect::OpenLink(link) => {
113
cx.update(|cx| cx.open_url(&link));
113
cx.update(|cx| app_base::open_link::open_url(cx, &link));
114
114
}
115
115
Effect::Submit(result) => {
116
116
let scope = dialog.scope.clone();
@@ -24,7 +24,7 @@ pub fn host() -> Option<Arc<WebViewTransport>> {24
24
25
pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {25
pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {26
let Some(host) = HOST.get().cloned() else {26
let Some(host) = HOST.get().cloned() else {27
cx.open_url(&dialog.fallback_url);27
app_base::open_link::open_url(cx, &dialog.fallback_url);28
return;28
return;29
};29
};30
let state = cx.global::<AppHandle>().0.clone();30
let state = cx.global::<AppHandle>().0.clone();@@ -110,7 +110,7 @@ async fn apply(110
match effect {110
match effect {111
Effect::Resize { width, height } => handle.resize(width, height),111
Effect::Resize { width, height } => handle.resize(width, height),112
Effect::OpenLink(link) => {112
Effect::OpenLink(link) => {113
cx.update(|cx| cx.open_url(&link));113
cx.update(|cx| app_base::open_link::open_url(cx, &link));114
}114
}115
Effect::Submit(result) => {115
Effect::Submit(result) => {116
let scope = dialog.scope.clone();116
let scope = dialog.scope.clone();@@ -5,14 +5,16 @@ use gpui_kit::*;
5
5
use teams_core::{Draft, FontSize, LineKind, MarkKind, SizeStep};
6
6
7
7
use crate::render::blocks::{Script, StyleFlags};
8
use crate::render::elements::{highlight_fill, readable_on};
8
use crate::render::elements::{highlight_fill, readable_on, token_style};
9
use crate::render::syntax;
9
10
use app_base::theme;
10
11
11
12
const CODE_PILL_RADIUS: f32 = 4.;
12
13
const CODE_BLOCK_RADIUS: f32 = 6.;
13
14
const QUOTE_BAR_WIDTH: f32 = 3.;
14
15
const QUOTE_INDENT: f32 = 12.;
15
const CODE_INDENT: f32 = 10.;
16
/// Room before code lines: the line numbers sit in it.
17
pub const CODE_INDENT: f32 = 36.;
16
18
const LIST_LEVEL_INDENT: f32 = 18.;
17
19
const HEADING_SCALES: [f32; 3] = [1.6, 1.35, 1.15];
18
20
const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;
@@ -24,6 +26,8 @@ pub struct DraftStyle {
24
26
pub ranges: Vec<RangeDecoration>,
25
27
pub markers: Vec<Range<usize>>,
26
28
pub indents: Vec<(usize, Pixels)>,
29
/// Code line numbers, each before the start of its line's content.
30
pub labels: Vec<(usize, SharedString)>,
27
31
}
28
32
29
33
fn line_indent(kind: &LineKind) -> f32 {
@@ -111,6 +115,34 @@ fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {
111
115
line_ranges[lines.start].start..line_ranges[lines.end - 1].end
112
116
}
113
117
118
/// A code line cut where its tokens start and end, so no two decorations overlap: the
119
/// input does not say which of two overlapping ones in a collection wins.
120
fn code_pieces(
121
line: Range<usize>,
122
tokens: &[(Range<usize>, HighlightStyle)],
123
) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
124
let plain = color(theme::text_strong());
125
let mut pieces = Vec::new();
126
let mut at = line.start;
127
for (range, style) in tokens {
128
let range = range.start.max(line.start)..range.end.min(line.end);
129
if range.start >= range.end || range.start < at {
130
continue;
131
}
132
if at < range.start {
133
pieces.push((at..range.start, plain));
134
}
135
let mut style = *style;
136
style.color = style.color.or(plain.color);
137
pieces.push((range.clone(), style));
138
at = range.end;
139
}
140
if at < line.end {
141
pieces.push((at..line.end, plain));
142
}
143
pieces.into_iter()
144
}
145
114
146
pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
115
147
let mut text = Vec::new();
116
148
let mut ranges = Vec::new();
@@ -152,6 +184,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
152
184
text.push(decoration);
153
185
}
154
186
}
187
let mut labels = Vec::new();
155
188
let kinds = draft.lines();
156
189
let mut index = 0;
157
190
while index < kinds.len() {
@@ -161,10 +194,32 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
161
194
.iter()
162
195
.take_while(|other| *other == kind)
163
196
.count();
197
// From after the header mark, so line one reads as a line start.
198
let tokens: Vec<(Range<usize>, HighlightStyle)> = match kind {
199
LineKind::Code(Some(language)) => {
200
let block =
201
draft.content_range(index).start..block_range(draft, index..run_end).end;
202
syntax::highlight(&draft.text()[block.clone()], language)
203
.unwrap_or_default()
204
.into_iter()
205
.map(|(range, token)| {
206
(
207
block.start + range.start..block.start + range.end,
208
token_style(token),
209
)
210
})
211
.collect()
212
}
213
_ => Vec::new(),
214
};
164
215
for line in index..run_end {
165
216
let marker = draft.marker_range(line);
166
217
let content = draft.content_range(line);
167
if !marker.is_empty() {
218
if matches!(kind, LineKind::Code(_)) {
219
labels.push((content.start, (line - index + 1).to_string().into()));
220
}
221
// A code block's header sits on its own row, so it hangs nothing.
222
if !marker.is_empty() && !matches!(kind, LineKind::Code(_)) {
168
223
markers.push(marker.clone());
169
224
if kind.is_list() {
170
225
text.push(TextDecoration::new(marker, color(theme::text_soft())));
@@ -177,10 +232,11 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
177
232
LineKind::Quote => {
178
233
text.push(TextDecoration::new(content, color(theme::text_soft())))
179
234
}
180
LineKind::Code(_) => text.push(
181
TextDecoration::new(content, color(theme::text_strong()))
182
.with_font_family(mono.clone()),
183
),
235
LineKind::Code(_) => {
236
text.extend(code_pieces(content, &tokens).map(|(range, style)| {
237
TextDecoration::new(range, style).with_font_family(mono.clone())
238
}))
239
}
184
240
LineKind::Heading(level) => text.push(heading_decoration(content, *level)),
185
241
_ => {}
186
242
}
@@ -190,6 +246,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
190
246
RangeDecoration::new(block_range(draft, index..run_end))
191
247
.with_style(RangeDecorationStyle::Block)
192
248
.with_color(theme::code_surface())
249
.with_border(theme::code_frame())
193
250
.with_radius(px(CODE_BLOCK_RADIUS)),
194
251
),
195
252
LineKind::Quote => Some(
@@ -208,6 +265,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
208
265
ranges,
209
266
markers,
210
267
indents,
268
labels,
211
269
}
212
270
}
213
271
@@ -252,7 +310,7 @@ mod tests {
252
310
[
253
311
(starts[1].start, gpui_kit::px(18.)),
254
312
(starts[2].start, gpui_kit::px(12.)),
255
(starts[3].start, gpui_kit::px(10.)),
313
(starts[3].start, gpui_kit::px(36.)),
256
314
]
257
315
);
258
316
assert!(!draft.text().contains('\u{2003}'));
@@ -271,6 +329,58 @@ mod tests {
271
329
assert!(block.end < draft.line_ranges()[2].start);
272
330
}
273
331
332
#[test]
333
fn code_with_a_language_is_highlighted_while_typing() {
334
let draft = Draft::from_lines(&[
335
line(LineKind::Code(Some("go".into())), "x // y"),
336
line(LineKind::Code(Some("go".into())), "z"),
337
]);
338
let style = draft_style(&draft, "Mono".into());
339
let ranges: Vec<_> = style.text.iter().map(|d| d.range.clone()).collect();
340
// "x " plain, the comment, then "z": all after the 3-byte header mark.
341
assert_eq!(ranges[..2], [3..5, 5..9]);
342
assert_eq!(
343
draft_style(
344
&Draft::from_lines(&[line(LineKind::Code(None), "x // y")]),
345
"Mono".into()
346
)
347
.text
348
.len(),
349
1
350
);
351
}
352
353
#[test]
354
fn the_first_code_line_starts_a_line_for_the_highlighter() {
355
let draft = Draft::from_lines(&[line(LineKind::Code(Some("markdown".into())), "# h")]);
356
let style = draft_style(&draft, "Mono".into());
357
assert_eq!(&draft.text()[style.text[0].range.clone()], "# h");
358
}
359
360
#[test]
361
fn python_keywords_are_highlighted_in_the_composer() {
362
let draft = Draft::from_lines(&[
363
line(LineKind::Code(Some("python".into())), "def f():"),
364
line(LineKind::Code(Some("python".into())), "class A:"),
365
]);
366
let style = draft_style(&draft, "Mono".into());
367
let words: Vec<_> = style
368
.text
369
.iter()
370
.map(|d| &draft.text()[d.range.clone()])
371
.collect();
372
assert!(
373
words.contains(&"def") && words.contains(&"class"),
374
"{words:?}"
375
);
376
let mut ranges: Vec<_> = style.text.iter().map(|d| d.range.clone()).collect();
377
ranges.sort_by_key(|range| range.start);
378
assert!(
379
ranges.windows(2).all(|pair| pair[0].end <= pair[1].start),
380
"{ranges:?}"
381
);
382
}
383
274
384
#[test]
275
385
fn a_lone_code_line_still_gets_a_block() {
276
386
let draft = Draft::from_lines(&[line(LineKind::Code(None), "")]);
@@ -5,14 +5,16 @@ use gpui_kit::*;5
use teams_core::{Draft, FontSize, LineKind, MarkKind, SizeStep};5
use teams_core::{Draft, FontSize, LineKind, MarkKind, SizeStep};6
6
7
use crate::render::blocks::{Script, StyleFlags};7
use crate::render::blocks::{Script, StyleFlags};8
use crate::render::elements::{highlight_fill, readable_on};8
use crate::render::elements::{highlight_fill, readable_on, token_style};9
use crate::render::syntax;9
use app_base::theme;10
use app_base::theme;10
11
11
const CODE_PILL_RADIUS: f32 = 4.;12
const CODE_PILL_RADIUS: f32 = 4.;12
const CODE_BLOCK_RADIUS: f32 = 6.;13
const CODE_BLOCK_RADIUS: f32 = 6.;13
const QUOTE_BAR_WIDTH: f32 = 3.;14
const QUOTE_BAR_WIDTH: f32 = 3.;14
const QUOTE_INDENT: f32 = 12.;15
const QUOTE_INDENT: f32 = 12.;15
const CODE_INDENT: f32 = 10.;16
/// Room before code lines: the line numbers sit in it.17
pub const CODE_INDENT: f32 = 36.;16
const LIST_LEVEL_INDENT: f32 = 18.;18
const LIST_LEVEL_INDENT: f32 = 18.;17
const HEADING_SCALES: [f32; 3] = [1.6, 1.35, 1.15];19
const HEADING_SCALES: [f32; 3] = [1.6, 1.35, 1.15];18
const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;20
const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;@@ -24,6 +26,8 @@ pub struct DraftStyle {24
pub ranges: Vec<RangeDecoration>,26
pub ranges: Vec<RangeDecoration>,25
pub markers: Vec<Range<usize>>,27
pub markers: Vec<Range<usize>>,26
pub indents: Vec<(usize, Pixels)>,28
pub indents: Vec<(usize, Pixels)>,29
/// Code line numbers, each before the start of its line's content.30
pub labels: Vec<(usize, SharedString)>,27
}31
}28
32
29
fn line_indent(kind: &LineKind) -> f32 {33
fn line_indent(kind: &LineKind) -> f32 {@@ -111,6 +115,34 @@ fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {111
line_ranges[lines.start].start..line_ranges[lines.end - 1].end115
line_ranges[lines.start].start..line_ranges[lines.end - 1].end112
}116
}113
117
118
/// A code line cut where its tokens start and end, so no two decorations overlap: the119
/// input does not say which of two overlapping ones in a collection wins.120
fn code_pieces(121
line: Range<usize>,122
tokens: &[(Range<usize>, HighlightStyle)],123
) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {124
let plain = color(theme::text_strong());125
let mut pieces = Vec::new();126
let mut at = line.start;127
for (range, style) in tokens {128
let range = range.start.max(line.start)..range.end.min(line.end);129
if range.start >= range.end || range.start < at {130
continue;131
}132
if at < range.start {133
pieces.push((at..range.start, plain));134
}135
let mut style = *style;136
style.color = style.color.or(plain.color);137
pieces.push((range.clone(), style));138
at = range.end;139
}140
if at < line.end {141
pieces.push((at..line.end, plain));142
}143
pieces.into_iter()144
}145
114
pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {146
pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {115
let mut text = Vec::new();147
let mut text = Vec::new();116
let mut ranges = Vec::new();148
let mut ranges = Vec::new();@@ -152,6 +184,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {152
text.push(decoration);184
text.push(decoration);153
}185
}154
}186
}187
let mut labels = Vec::new();155
let kinds = draft.lines();188
let kinds = draft.lines();156
let mut index = 0;189
let mut index = 0;157
while index < kinds.len() {190
while index < kinds.len() {@@ -161,10 +194,32 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {161
.iter()194
.iter()162
.take_while(|other| *other == kind)195
.take_while(|other| *other == kind)163
.count();196
.count();197
// From after the header mark, so line one reads as a line start.198
let tokens: Vec<(Range<usize>, HighlightStyle)> = match kind {199
LineKind::Code(Some(language)) => {200
let block =201
draft.content_range(index).start..block_range(draft, index..run_end).end;202
syntax::highlight(&draft.text()[block.clone()], language)203
.unwrap_or_default()204
.into_iter()205
.map(|(range, token)| {206
(207
block.start + range.start..block.start + range.end,208
token_style(token),209
)210
})211
.collect()212
}213
_ => Vec::new(),214
};164
for line in index..run_end {215
for line in index..run_end {165
let marker = draft.marker_range(line);216
let marker = draft.marker_range(line);166
let content = draft.content_range(line);217
let content = draft.content_range(line);167
if !marker.is_empty() {218
if matches!(kind, LineKind::Code(_)) {219
labels.push((content.start, (line - index + 1).to_string().into()));220
}221
// A code block's header sits on its own row, so it hangs nothing.222
if !marker.is_empty() && !matches!(kind, LineKind::Code(_)) {168
markers.push(marker.clone());223
markers.push(marker.clone());169
if kind.is_list() {224
if kind.is_list() {170
text.push(TextDecoration::new(marker, color(theme::text_soft())));225
text.push(TextDecoration::new(marker, color(theme::text_soft())));@@ -177,10 +232,11 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {177
LineKind::Quote => {232
LineKind::Quote => {178
text.push(TextDecoration::new(content, color(theme::text_soft())))233
text.push(TextDecoration::new(content, color(theme::text_soft())))179
}234
}180
LineKind::Code(_) => text.push(235
LineKind::Code(_) => {181
TextDecoration::new(content, color(theme::text_strong()))236
text.extend(code_pieces(content, &tokens).map(|(range, style)| {182
.with_font_family(mono.clone()),237
TextDecoration::new(range, style).with_font_family(mono.clone())183
),238
}))239
}184
LineKind::Heading(level) => text.push(heading_decoration(content, *level)),240
LineKind::Heading(level) => text.push(heading_decoration(content, *level)),185
_ => {}241
_ => {}186
}242
}@@ -190,6 +246,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {190
RangeDecoration::new(block_range(draft, index..run_end))246
RangeDecoration::new(block_range(draft, index..run_end))191
.with_style(RangeDecorationStyle::Block)247
.with_style(RangeDecorationStyle::Block)192
.with_color(theme::code_surface())248
.with_color(theme::code_surface())249
.with_border(theme::code_frame())193
.with_radius(px(CODE_BLOCK_RADIUS)),250
.with_radius(px(CODE_BLOCK_RADIUS)),194
),251
),195
LineKind::Quote => Some(252
LineKind::Quote => Some(@@ -208,6 +265,7 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {208
ranges,265
ranges,209
markers,266
markers,210
indents,267
indents,268
labels,211
}269
}212
}270
}213
271
@@ -252,7 +310,7 @@ mod tests {252
[310
[253
(starts[1].start, gpui_kit::px(18.)),311
(starts[1].start, gpui_kit::px(18.)),254
(starts[2].start, gpui_kit::px(12.)),312
(starts[2].start, gpui_kit::px(12.)),255
(starts[3].start, gpui_kit::px(10.)),313
(starts[3].start, gpui_kit::px(36.)),256
]314
]257
);315
);258
assert!(!draft.text().contains('\u{2003}'));316
assert!(!draft.text().contains('\u{2003}'));@@ -271,6 +329,58 @@ mod tests {271
assert!(block.end < draft.line_ranges()[2].start);329
assert!(block.end < draft.line_ranges()[2].start);272
}330
}273
331
332
#[test]333
fn code_with_a_language_is_highlighted_while_typing() {334
let draft = Draft::from_lines(&[335
line(LineKind::Code(Some("go".into())), "x // y"),336
line(LineKind::Code(Some("go".into())), "z"),337
]);338
let style = draft_style(&draft, "Mono".into());339
let ranges: Vec<_> = style.text.iter().map(|d| d.range.clone()).collect();340
// "x " plain, the comment, then "z": all after the 3-byte header mark.341
assert_eq!(ranges[..2], [3..5, 5..9]);342
assert_eq!(343
draft_style(344
&Draft::from_lines(&[line(LineKind::Code(None), "x // y")]),345
"Mono".into()346
)347
.text348
.len(),349
1350
);351
}352
353
#[test]354
fn the_first_code_line_starts_a_line_for_the_highlighter() {355
let draft = Draft::from_lines(&[line(LineKind::Code(Some("markdown".into())), "# h")]);356
let style = draft_style(&draft, "Mono".into());357
assert_eq!(&draft.text()[style.text[0].range.clone()], "# h");358
}359
360
#[test]361
fn python_keywords_are_highlighted_in_the_composer() {362
let draft = Draft::from_lines(&[363
line(LineKind::Code(Some("python".into())), "def f():"),364
line(LineKind::Code(Some("python".into())), "class A:"),365
]);366
let style = draft_style(&draft, "Mono".into());367
let words: Vec<_> = style368
.text369
.iter()370
.map(|d| &draft.text()[d.range.clone()])371
.collect();372
assert!(373
words.contains(&"def") && words.contains(&"class"),374
"{words:?}"375
);376
let mut ranges: Vec<_> = style.text.iter().map(|d| d.range.clone()).collect();377
ranges.sort_by_key(|range| range.start);378
assert!(379
ranges.windows(2).all(|pair| pair[0].end <= pair[1].start),380
"{ranges:?}"381
);382
}383
274
#[test]384
#[test]275
fn a_lone_code_line_still_gets_a_block() {385
fn a_lone_code_line_still_gets_a_block() {276
let draft = Draft::from_lines(&[line(LineKind::Code(None), "")]);386
let draft = Draft::from_lines(&[line(LineKind::Code(None), "")]);@@ -143,7 +143,9 @@ impl Inline {
143
143
pub fn with_trailing_room(&self, width_in_spaces: usize) -> Inline {
144
144
let mut padded = self.clone();
145
145
padded.push(
146
&"\u{2007}".repeat(width_in_spaces),
146
&super::selectable::TIME_ROOM
147
.to_string()
148
.repeat(width_in_spaces),
147
149
StyleFlags::default(),
148
150
None,
149
151
);
@@ -143,7 +143,9 @@ impl Inline {143
pub fn with_trailing_room(&self, width_in_spaces: usize) -> Inline {143
pub fn with_trailing_room(&self, width_in_spaces: usize) -> Inline {144
let mut padded = self.clone();144
let mut padded = self.clone();145
padded.push(145
padded.push(146
&"\u{2007}".repeat(width_in_spaces),146
&super::selectable::TIME_ROOM147
.to_string()148
.repeat(width_in_spaces),147
StyleFlags::default(),149
StyleFlags::default(),148
None,150
None,149
);151
);@@ -1,3 +1,4 @@
1
use gpui_kit::component::tooltip::Tooltip;
1
2
use gpui_kit::component::{h_flex, v_flex};
2
3
use gpui_kit::prelude::FluentBuilder as _;
3
4
use gpui_kit::*;
@@ -15,13 +16,17 @@ const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;
15
16
const MARKER_WIDTH: f32 = 18.;
16
17
const WIDE_MARKER_WIDTH: f32 = 26.;
17
18
const BULLETS: [&str; 3] = ["\u{2022}", "\u{25e6}", "\u{25aa}"];
18
const CODE_HEADER_MIN_LINES: usize = 3;
19
const PLAIN_LANGUAGE: &str = "text";
20
19
const MIN_CONTRAST: f32 = 4.5;
21
20
const HIGHLIGHT_ALPHA: f32 = 0.3;
22
21
const CODE_LINE_PADDING_X: f32 = 6.;
23
22
const CODE_LINE_PADDING_Y: f32 = 4.;
24
23
const CODE_LINE_RADIUS: f32 = 4.;
24
const COPIED_SHOWN: std::time::Duration = std::time::Duration::from_millis(1500);
25
26
// shortcut: one "Copied" at a time app-wide, which is all a click can produce.
27
// The click number lets a later click on the same block keep "Copied" for its full time.
28
static COPIED_BLOCK: std::sync::Mutex<Option<(String, u64)>> = std::sync::Mutex::new(None);
29
static COPY_CLICKS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
25
30
pub const CODE_LINE_TAG: &str = "message/code-line";
26
31
pub const CODE_BLOCK_TAG: &str = "message/code-block";
27
32
@@ -126,16 +131,38 @@ fn render_code(language: Option<&str>, code: &str, id: String, own: bool, cx: &A
126
131
.into_iter()
127
132
.map(|(range, token)| (range, token_style(token)))
128
133
.collect();
129
let body = div()
134
let numbers = (1..=code.split('\n').count())
135
.map(|number| number.to_string())
136
.collect::<Vec<_>>()
137
.join("\n");
138
// Lines do not wrap, so the numbers stay beside their lines; a long line scrolls.
139
let body = h_flex()
130
140
.w_full()
131
.px(px(10.))
141
.items_start()
132
142
.py(px(8.))
133
.child(SelectableRichText::new(
134
ElementId::Name(id.clone().into()),
135
code.to_owned(),
136
highlights,
137
));
138
let show_header = language.is_some() || code.lines().count() >= CODE_HEADER_MIN_LINES;
143
.child(
144
div()
145
.flex_none()
146
.pl(px(10.))
147
.pr(px(10.))
148
.text_right()
149
.text_color(code_meta(own))
150
.child(numbers),
151
)
152
.child(
153
div()
154
.id(ElementId::Name(format!("{id}-lines").into()))
155
.flex_1()
156
.min_w_0()
157
.pr(px(10.))
158
.overflow_x_scroll()
159
.whitespace_nowrap()
160
.child(SelectableRichText::new(
161
ElementId::Name(id.clone().into()),
162
code.to_owned(),
163
highlights,
164
)),
165
);
139
166
v_flex()
140
167
.debug_selector(|| CODE_BLOCK_TAG.into())
141
168
.w_full()
@@ -148,14 +175,15 @@ fn render_code(language: Option<&str>, code: &str, id: String, own: bool, cx: &A
148
175
.font_family(code_font(cx))
149
176
.text_size(px(12.5))
150
177
.line_height(relative(1.5))
151
.when(show_header, |container| {
152
container.child(code_header(
153
language.unwrap_or(PLAIN_LANGUAGE),
154
code,
155
&id,
156
own,
157
))
158
})
178
.child(code_header(
179
{
180
let id = language.unwrap_or(teams_core::PLAIN_LANGUAGE);
181
teams_core::code_language(id).map_or(id, |language| language.name)
182
},
183
code,
184
&id,
185
own,
186
))
159
187
.child(body)
160
188
.into_any_element()
161
189
}
@@ -194,18 +222,28 @@ fn code_text(own: bool) -> Hsla {
194
222
}
195
223
}
196
224
197
fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {
198
let muted = if own {
225
fn code_meta(own: bool) -> Hsla {
226
if own {
199
227
theme::own_meta()
200
228
} else {
201
229
theme::text_muted()
202
};
230
}
231
}
232
233
fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {
234
let muted = code_meta(own);
203
235
let code = code.to_owned();
236
let copy_id = format!("{id}-copy");
237
let copied = COPIED_BLOCK
238
.lock()
239
.is_ok_and(|block| block.as_ref().is_some_and(|(shown, _)| *shown == copy_id));
204
240
h_flex()
205
241
.w_full()
206
242
.h(px(26.))
207
243
.pl(px(10.))
208
.pr(px(6.))
244
.pr(px(4.))
245
.border_b_1()
246
.border_color(theme::code_frame())
209
247
.justify_between()
210
248
.items_center()
211
249
.font_family(theme::font_family())
@@ -214,23 +252,47 @@ fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {
214
252
.child(language.to_owned())
215
253
.child(
216
254
h_flex()
217
.id(ElementId::Name(format!("{id}-copy").into()))
218
.h(px(20.))
219
.px(px(6.))
220
.gap(px(4.))
255
.id(ElementId::Name(copy_id.clone().into()))
256
.size(px(20.))
257
.justify_center()
221
258
.items_center()
222
259
.rounded(px(4.))
223
260
.cursor_pointer()
224
261
.hover(|button| button.bg(theme::inline_code_fill(false)))
262
.tooltip(move |window, cx| {
263
Tooltip::new(if copied { "Copied" } else { "Copy" }).build(window, cx)
264
})
225
265
.on_click(move |_, _, cx| {
226
cx.write_to_clipboard(ClipboardItem::new_string(code.clone()))
266
cx.write_to_clipboard(ClipboardItem::new_string(code.clone()));
267
show_copied(copy_id.clone(), cx);
227
268
})
228
.child(symbol("content_copy", 13., muted))
229
.child("Copy"),
269
.child(symbol(
270
if copied { "check" } else { "content_copy" },
271
13.,
272
muted,
273
)),
230
274
)
231
275
}
232
276
233
fn token_style(token: Token) -> HighlightStyle {
277
fn show_copied(copy_id: String, cx: &mut App) {
278
let click = COPY_CLICKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
279
if let Ok(mut block) = COPIED_BLOCK.lock() {
280
*block = Some((copy_id.clone(), click));
281
}
282
cx.refresh_windows();
283
cx.spawn(async move |cx| {
284
cx.background_executor().timer(COPIED_SHOWN).await;
285
let ended = COPIED_BLOCK
286
.lock()
287
.is_ok_and(|mut block| block.take_if(|shown| shown.1 == click).is_some());
288
if ended {
289
cx.update(|cx| cx.refresh_windows());
290
}
291
})
292
.detach();
293
}
294
295
pub(crate) fn token_style(token: Token) -> HighlightStyle {
234
296
match token {
235
297
Token::Keyword => HighlightStyle {
236
298
color: Some(theme::accent_text()),
@@ -245,6 +307,44 @@ fn token_style(token: Token) -> HighlightStyle {
245
307
font_style: Some(FontStyle::Italic),
246
308
..Default::default()
247
309
},
310
Token::Type => HighlightStyle {
311
color: Some(theme::green()),
312
..Default::default()
313
},
314
Token::Title => HighlightStyle {
315
color: Some(theme::amber()),
316
..Default::default()
317
},
318
Token::Tag => HighlightStyle {
319
color: Some(theme::accent_text()),
320
..Default::default()
321
},
322
Token::Attribute => HighlightStyle {
323
color: Some(theme::amber()),
324
..Default::default()
325
},
326
Token::Heading => HighlightStyle {
327
color: Some(theme::accent_text()),
328
font_weight: Some(FontWeight::BOLD),
329
..Default::default()
330
},
331
Token::Strong => HighlightStyle {
332
font_weight: Some(FontWeight::BOLD),
333
..Default::default()
334
},
335
Token::Emphasis => HighlightStyle {
336
font_style: Some(FontStyle::Italic),
337
..Default::default()
338
},
339
Token::Link => HighlightStyle {
340
color: Some(theme::accent_soft()),
341
underline: Some(UnderlineStyle {
342
thickness: px(1.),
343
color: Some(theme::accent_soft()),
344
wavy: false,
345
}),
346
..Default::default()
347
},
248
348
}
249
349
}
250
350
@@ -1,3 +1,4 @@1
use gpui_kit::component::tooltip::Tooltip;1
use gpui_kit::component::{h_flex, v_flex};2
use gpui_kit::component::{h_flex, v_flex};2
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::*;4
use gpui_kit::*;@@ -15,13 +16,17 @@ const INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;15
const MARKER_WIDTH: f32 = 18.;16
const MARKER_WIDTH: f32 = 18.;16
const WIDE_MARKER_WIDTH: f32 = 26.;17
const WIDE_MARKER_WIDTH: f32 = 26.;17
const BULLETS: [&str; 3] = ["\u{2022}", "\u{25e6}", "\u{25aa}"];18
const BULLETS: [&str; 3] = ["\u{2022}", "\u{25e6}", "\u{25aa}"];18
const CODE_HEADER_MIN_LINES: usize = 3;19
const PLAIN_LANGUAGE: &str = "text";20
const MIN_CONTRAST: f32 = 4.5;19
const MIN_CONTRAST: f32 = 4.5;21
const HIGHLIGHT_ALPHA: f32 = 0.3;20
const HIGHLIGHT_ALPHA: f32 = 0.3;22
const CODE_LINE_PADDING_X: f32 = 6.;21
const CODE_LINE_PADDING_X: f32 = 6.;23
const CODE_LINE_PADDING_Y: f32 = 4.;22
const CODE_LINE_PADDING_Y: f32 = 4.;24
const CODE_LINE_RADIUS: f32 = 4.;23
const CODE_LINE_RADIUS: f32 = 4.;24
const COPIED_SHOWN: std::time::Duration = std::time::Duration::from_millis(1500);25
26
// shortcut: one "Copied" at a time app-wide, which is all a click can produce.27
// The click number lets a later click on the same block keep "Copied" for its full time.28
static COPIED_BLOCK: std::sync::Mutex<Option<(String, u64)>> = std::sync::Mutex::new(None);29
static COPY_CLICKS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);25
pub const CODE_LINE_TAG: &str = "message/code-line";30
pub const CODE_LINE_TAG: &str = "message/code-line";26
pub const CODE_BLOCK_TAG: &str = "message/code-block";31
pub const CODE_BLOCK_TAG: &str = "message/code-block";27
32
@@ -126,16 +131,38 @@ fn render_code(language: Option<&str>, code: &str, id: String, own: bool, cx: &A126
.into_iter()131
.into_iter()127
.map(|(range, token)| (range, token_style(token)))132
.map(|(range, token)| (range, token_style(token)))128
.collect();133
.collect();129
let body = div()134
let numbers = (1..=code.split('\n').count())135
.map(|number| number.to_string())136
.collect::<Vec<_>>()137
.join("\n");138
// Lines do not wrap, so the numbers stay beside their lines; a long line scrolls.139
let body = h_flex()130
.w_full()140
.w_full()131
.px(px(10.))141
.items_start()132
.py(px(8.))142
.py(px(8.))133
.child(SelectableRichText::new(143
.child(134
ElementId::Name(id.clone().into()),144
div()135
code.to_owned(),145
.flex_none()136
highlights,146
.pl(px(10.))137
));147
.pr(px(10.))138
let show_header = language.is_some() || code.lines().count() >= CODE_HEADER_MIN_LINES;148
.text_right()149
.text_color(code_meta(own))150
.child(numbers),151
)152
.child(153
div()154
.id(ElementId::Name(format!("{id}-lines").into()))155
.flex_1()156
.min_w_0()157
.pr(px(10.))158
.overflow_x_scroll()159
.whitespace_nowrap()160
.child(SelectableRichText::new(161
ElementId::Name(id.clone().into()),162
code.to_owned(),163
highlights,164
)),165
);139
v_flex()166
v_flex()140
.debug_selector(|| CODE_BLOCK_TAG.into())167
.debug_selector(|| CODE_BLOCK_TAG.into())141
.w_full()168
.w_full()@@ -148,14 +175,15 @@ fn render_code(language: Option<&str>, code: &str, id: String, own: bool, cx: &A148
.font_family(code_font(cx))175
.font_family(code_font(cx))149
.text_size(px(12.5))176
.text_size(px(12.5))150
.line_height(relative(1.5))177
.line_height(relative(1.5))151
.when(show_header, |container| {178
.child(code_header(152
container.child(code_header(179
{153
language.unwrap_or(PLAIN_LANGUAGE),180
let id = language.unwrap_or(teams_core::PLAIN_LANGUAGE);154
code,181
teams_core::code_language(id).map_or(id, |language| language.name)155
&id,182
},156
own,183
code,157
))184
&id,158
})185
own,186
))159
.child(body)187
.child(body)160
.into_any_element()188
.into_any_element()161
}189
}@@ -194,18 +222,28 @@ fn code_text(own: bool) -> Hsla {194
}222
}195
}223
}196
224
197
fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {225
fn code_meta(own: bool) -> Hsla {198
let muted = if own {226
if own {199
theme::own_meta()227
theme::own_meta()200
} else {228
} else {201
theme::text_muted()229
theme::text_muted()202
};230
}231
}232
233
fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {234
let muted = code_meta(own);203
let code = code.to_owned();235
let code = code.to_owned();236
let copy_id = format!("{id}-copy");237
let copied = COPIED_BLOCK238
.lock()239
.is_ok_and(|block| block.as_ref().is_some_and(|(shown, _)| *shown == copy_id));204
h_flex()240
h_flex()205
.w_full()241
.w_full()206
.h(px(26.))242
.h(px(26.))207
.pl(px(10.))243
.pl(px(10.))208
.pr(px(6.))244
.pr(px(4.))245
.border_b_1()246
.border_color(theme::code_frame())209
.justify_between()247
.justify_between()210
.items_center()248
.items_center()211
.font_family(theme::font_family())249
.font_family(theme::font_family())@@ -214,23 +252,47 @@ fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {214
.child(language.to_owned())252
.child(language.to_owned())215
.child(253
.child(216
h_flex()254
h_flex()217
.id(ElementId::Name(format!("{id}-copy").into()))255
.id(ElementId::Name(copy_id.clone().into()))218
.h(px(20.))256
.size(px(20.))219
.px(px(6.))257
.justify_center()220
.gap(px(4.))221
.items_center()258
.items_center()222
.rounded(px(4.))259
.rounded(px(4.))223
.cursor_pointer()260
.cursor_pointer()224
.hover(|button| button.bg(theme::inline_code_fill(false)))261
.hover(|button| button.bg(theme::inline_code_fill(false)))262
.tooltip(move |window, cx| {263
Tooltip::new(if copied { "Copied" } else { "Copy" }).build(window, cx)264
})225
.on_click(move |_, _, cx| {265
.on_click(move |_, _, cx| {226
cx.write_to_clipboard(ClipboardItem::new_string(code.clone()))266
cx.write_to_clipboard(ClipboardItem::new_string(code.clone()));267
show_copied(copy_id.clone(), cx);227
})268
})228
.child(symbol("content_copy", 13., muted))269
.child(symbol(229
.child("Copy"),270
if copied { "check" } else { "content_copy" },271
13.,272
muted,273
)),230
)274
)231
}275
}232
276
233
fn token_style(token: Token) -> HighlightStyle {277
fn show_copied(copy_id: String, cx: &mut App) {278
let click = COPY_CLICKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);279
if let Ok(mut block) = COPIED_BLOCK.lock() {280
*block = Some((copy_id.clone(), click));281
}282
cx.refresh_windows();283
cx.spawn(async move |cx| {284
cx.background_executor().timer(COPIED_SHOWN).await;285
let ended = COPIED_BLOCK286
.lock()287
.is_ok_and(|mut block| block.take_if(|shown| shown.1 == click).is_some());288
if ended {289
cx.update(|cx| cx.refresh_windows());290
}291
})292
.detach();293
}294
295
pub(crate) fn token_style(token: Token) -> HighlightStyle {234
match token {296
match token {235
Token::Keyword => HighlightStyle {297
Token::Keyword => HighlightStyle {236
color: Some(theme::accent_text()),298
color: Some(theme::accent_text()),@@ -245,6 +307,44 @@ fn token_style(token: Token) -> HighlightStyle {245
font_style: Some(FontStyle::Italic),307
font_style: Some(FontStyle::Italic),246
..Default::default()308
..Default::default()247
},309
},310
Token::Type => HighlightStyle {311
color: Some(theme::green()),312
..Default::default()313
},314
Token::Title => HighlightStyle {315
color: Some(theme::amber()),316
..Default::default()317
},318
Token::Tag => HighlightStyle {319
color: Some(theme::accent_text()),320
..Default::default()321
},322
Token::Attribute => HighlightStyle {323
color: Some(theme::amber()),324
..Default::default()325
},326
Token::Heading => HighlightStyle {327
color: Some(theme::accent_text()),328
font_weight: Some(FontWeight::BOLD),329
..Default::default()330
},331
Token::Strong => HighlightStyle {332
font_weight: Some(FontWeight::BOLD),333
..Default::default()334
},335
Token::Emphasis => HighlightStyle {336
font_style: Some(FontStyle::Italic),337
..Default::default()338
},339
Token::Link => HighlightStyle {340
color: Some(theme::accent_soft()),341
underline: Some(UnderlineStyle {342
thickness: px(1.),343
color: Some(theme::accent_soft()),344
wavy: false,345
}),346
..Default::default()347
},248
}348
}249
}349
}250
350
@@ -977,7 +977,7 @@ mod tests {
977
977
cx.opened_url().is_some()
978
978
});
979
979
assert!(link_x.is_some());
980
assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
980
assert_eq!(cx.opened_url().as_deref(), Some("https://example.com/"));
981
981
}
982
982
983
983
struct Links {
@@ -977,7 +977,7 @@ mod tests {977
cx.opened_url().is_some()977
cx.opened_url().is_some()978
});978
});979
assert!(link_x.is_some());979
assert!(link_x.is_some());980
assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));980
assert_eq!(cx.opened_url().as_deref(), Some("https://example.com/"));981
}981
}982
982
983
struct Links {983
struct Links {@@ -17,30 +17,8 @@ pub fn open_profile_link(url: &str, position: Point<Pixels>, cx: &mut App) -> bo
17
17
}
18
18
}
19
19
20
const OPENABLE_SCHEMES: [&str; 16] = [
21
"https://",
22
"http://",
23
"mailto:",
24
"tel:",
25
"sip:",
26
"callto:",
27
"msteams:",
28
"onenote:",
29
"ms-word:",
30
"ms-excel:",
31
"ms-powerpoint:",
32
"ms-visio:",
33
"ms-access:",
34
"ms-project:",
35
"ms-publisher:",
36
"ms-infopath:",
37
];
38
39
20
pub fn is_openable_link(url: &str) -> bool {
40
let lower = url.trim_start().to_ascii_lowercase();
41
OPENABLE_SCHEMES
42
.iter()
43
.any(|scheme| lower.starts_with(scheme))
21
app_base::open_link::is_openable_url(url)
44
22
}
45
23
46
24
pub fn open_link(url: &str, cx: &mut App) {
@@ -49,7 +27,7 @@ pub fn open_link(url: &str, cx: &mut App) {
49
27
}
50
28
match cx.try_global::<RenderHooks>().copied() {
51
29
Some(hooks) => (hooks.open_link)(url, cx),
52
None => cx.open_url(url),
30
None => app_base::open_link::open_url(cx, url),
53
31
}
54
32
}
55
33
@@ -17,30 +17,8 @@ pub fn open_profile_link(url: &str, position: Point<Pixels>, cx: &mut App) -> bo17
}17
}18
}18
}19
19
20
const OPENABLE_SCHEMES: [&str; 16] = [21
"https://",22
"http://",23
"mailto:",24
"tel:",25
"sip:",26
"callto:",27
"msteams:",28
"onenote:",29
"ms-word:",30
"ms-excel:",31
"ms-powerpoint:",32
"ms-visio:",33
"ms-access:",34
"ms-project:",35
"ms-publisher:",36
"ms-infopath:",37
];38
39
pub fn is_openable_link(url: &str) -> bool {20
pub fn is_openable_link(url: &str) -> bool {40
let lower = url.trim_start().to_ascii_lowercase();21
app_base::open_link::is_openable_url(url)41
OPENABLE_SCHEMES42
.iter()43
.any(|scheme| lower.starts_with(scheme))44
}22
}45
23
46
pub fn open_link(url: &str, cx: &mut App) {24
pub fn open_link(url: &str, cx: &mut App) {@@ -49,7 +27,7 @@ pub fn open_link(url: &str, cx: &mut App) {49
}27
}50
match cx.try_global::<RenderHooks>().copied() {28
match cx.try_global::<RenderHooks>().copied() {51
Some(hooks) => (hooks.open_link)(url, cx),29
Some(hooks) => (hooks.open_link)(url, cx),52
None => cx.open_url(url),30
None => app_base::open_link::open_url(cx, url),53
}31
}54
}32
}55
33
@@ -4,7 +4,7 @@ mod flow_text;
4
4
pub mod hooks;
5
5
mod link_tooltip;
6
6
mod selectable;
7
mod syntax;
7
pub(crate) mod syntax;
8
8
9
9
pub use blocks::{
10
10
Block, TableCell, layout_blocks, layout_card_blocks, strip_image_placeholders, table_images,
@@ -4,7 +4,7 @@ mod flow_text;4
pub mod hooks;4
pub mod hooks;5
mod link_tooltip;5
mod link_tooltip;6
mod selectable;6
mod selectable;7
mod syntax;7
pub(crate) mod syntax;8
8
9
pub use blocks::{9
pub use blocks::{10
Block, TableCell, layout_blocks, layout_card_blocks, strip_image_placeholders, table_images,10
Block, TableCell, layout_blocks, layout_card_blocks, strip_image_placeholders, table_images,@@ -12,7 +12,9 @@ use super::blocks::{CODE_PADDING, EMOJI_PLACEHOLDER};
12
12
use super::hooks::{open_link, open_profile_link};
13
13
use super::link_tooltip::LinkTooltip;
14
14
15
pub(super) const TIME_ROOM: char = '\u{2007}';
15
/// No-break space: it stays on the last word's line (GPUI wraps it as glue), and Google Sans Flex has it,
16
/// unlike the figure space (U+2007), whose fallback font left too little room for the time.
17
pub(super) const TIME_ROOM: char = '\u{00A0}';
16
18
pub(super) const HIT_SLOP: f32 = 12.;
17
19
18
20
#[derive(Clone)]
@@ -513,7 +515,7 @@ mod tests {
513
515
cx.opened_url().is_some()
514
516
});
515
517
assert!(link_x.is_some());
516
assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
518
assert_eq!(cx.opened_url().as_deref(), Some("https://example.com/"));
517
519
}
518
520
519
521
#[test]
@@ -12,7 +12,9 @@ use super::blocks::{CODE_PADDING, EMOJI_PLACEHOLDER};12
use super::hooks::{open_link, open_profile_link};12
use super::hooks::{open_link, open_profile_link};13
use super::link_tooltip::LinkTooltip;13
use super::link_tooltip::LinkTooltip;14
14
15
pub(super) const TIME_ROOM: char = '\u{2007}';15
/// No-break space: it stays on the last word's line (GPUI wraps it as glue), and Google Sans Flex has it,16
/// unlike the figure space (U+2007), whose fallback font left too little room for the time.17
pub(super) const TIME_ROOM: char = '\u{00A0}';16
pub(super) const HIT_SLOP: f32 = 12.;18
pub(super) const HIT_SLOP: f32 = 12.;17
19
18
#[derive(Clone)]20
#[derive(Clone)]@@ -513,7 +515,7 @@ mod tests {513
cx.opened_url().is_some()515
cx.opened_url().is_some()514
});516
});515
assert!(link_x.is_some());517
assert!(link_x.is_some());516
assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));518
assert_eq!(cx.opened_url().as_deref(), Some("https://example.com/"));517
}519
}518
520
519
#[test]521
#[test]@@ -6,20 +6,521 @@ pub enum Token {
6
6
String,
7
7
Number,
8
8
Comment,
9
Tag,
10
Attribute,
11
Heading,
12
Strong,
13
Emphasis,
14
Link,
15
/// Built-in types, functions and values: `bool`, `print`, `self`.
16
Type,
17
/// The name a definition gives: `f` in `def f`, `A` in `class A`.
18
Title,
9
19
}
10
20
21
/// A lexer for code: comments, strings, numbers and keywords.
11
22
struct Grammar {
12
23
line_comments: &'static [&'static str],
13
24
block_comment: Option<(&'static str, &'static str)>,
14
25
keywords: &'static [&'static str],
26
/// `'x'` is a character; other single quotes (Rust lifetimes) are left alone.
15
27
char_quotes: bool,
28
case_insensitive: bool,
29
/// Words after this prefix are keywords too, as `\section` in LaTeX.
30
command_prefix: Option<char>,
31
types: &'static [&'static str],
32
/// A word or string right before `:` is a key, as in JSON, YAML and CSS.
33
keys: bool,
34
/// `-` joins words, as in `font-size` and `Get-ChildItem`; such a word is a built-in.
35
dashed_words: bool,
16
36
}
17
37
18
const C_LIKE_KEYWORDS: &[&str] = &[
38
const CODE: Grammar = Grammar {
39
line_comments: &[],
40
block_comment: None,
41
keywords: &[],
42
char_quotes: false,
43
case_insensitive: false,
44
command_prefix: None,
45
types: &[],
46
keys: false,
47
dashed_words: false,
48
};
49
50
const fn c_style(keywords: &'static [&'static str]) -> Grammar {
51
Grammar {
52
line_comments: &["//"],
53
block_comment: Some(("/*", "*/")),
54
keywords,
55
..CODE
56
}
57
}
58
59
const fn hash_style(keywords: &'static [&'static str]) -> Grammar {
60
Grammar {
61
line_comments: &["#"],
62
keywords,
63
..CODE
64
}
65
}
66
67
const C_KEYWORDS: &[&str] = &[
68
"auto",
69
"break",
70
"case",
71
"char",
72
"const",
73
"continue",
74
"default",
75
"do",
76
"double",
77
"else",
78
"enum",
79
"extern",
80
"float",
81
"for",
82
"goto",
83
"if",
84
"inline",
85
"int",
86
"long",
87
"register",
88
"restrict",
89
"return",
90
"short",
91
"signed",
92
"sizeof",
93
"static",
94
"struct",
95
"switch",
96
"typedef",
97
"union",
98
"unsigned",
99
"void",
100
"volatile",
101
"while",
102
"NULL",
103
"true",
104
"false",
105
"bool",
106
"#include",
107
"#define",
108
"@interface",
109
"@implementation",
110
"@end",
111
"@property",
112
"self",
113
"nil",
114
];
115
const CPP_KEYWORDS: &[&str] = &[
116
"auto",
117
"bool",
118
"break",
119
"case",
120
"catch",
121
"char",
122
"class",
123
"const",
124
"constexpr",
125
"continue",
126
"default",
127
"delete",
128
"do",
129
"double",
130
"else",
131
"enum",
132
"explicit",
133
"extern",
134
"false",
135
"float",
136
"for",
137
"friend",
138
"goto",
139
"if",
140
"inline",
141
"int",
142
"long",
143
"namespace",
144
"new",
145
"noexcept",
146
"nullptr",
147
"operator",
148
"override",
149
"private",
150
"protected",
151
"public",
152
"return",
153
"short",
154
"signed",
155
"sizeof",
156
"static",
157
"struct",
158
"switch",
159
"template",
160
"this",
161
"throw",
162
"true",
163
"try",
164
"typedef",
165
"typename",
166
"union",
167
"unsigned",
168
"using",
169
"virtual",
170
"void",
171
"volatile",
172
"while",
173
];
174
const CSHARP_KEYWORDS: &[&str] = &[
175
"abstract",
176
"as",
177
"async",
178
"await",
179
"base",
180
"bool",
181
"break",
182
"case",
183
"catch",
184
"class",
185
"const",
186
"continue",
187
"default",
188
"delegate",
189
"do",
190
"else",
191
"enum",
192
"event",
193
"false",
194
"finally",
195
"for",
196
"foreach",
197
"get",
198
"if",
199
"in",
200
"int",
201
"interface",
202
"internal",
203
"is",
204
"new",
205
"null",
206
"object",
207
"out",
208
"override",
209
"private",
210
"protected",
211
"public",
212
"readonly",
213
"ref",
214
"return",
215
"sealed",
216
"set",
217
"static",
218
"string",
219
"struct",
220
"switch",
221
"this",
222
"throw",
223
"true",
224
"try",
225
"using",
226
"var",
227
"virtual",
228
"void",
229
"while",
230
];
231
const JAVA_KEYWORDS: &[&str] = &[
232
"abstract",
233
"boolean",
234
"break",
235
"case",
236
"catch",
237
"char",
238
"class",
239
"const",
240
"continue",
241
"default",
242
"do",
243
"double",
244
"else",
245
"enum",
246
"extends",
247
"false",
248
"final",
249
"finally",
250
"float",
251
"for",
252
"if",
253
"implements",
254
"import",
255
"instanceof",
256
"int",
257
"interface",
258
"long",
259
"new",
260
"null",
261
"package",
262
"private",
263
"protected",
264
"public",
265
"return",
266
"static",
267
"super",
268
"switch",
269
"this",
270
"throw",
271
"throws",
272
"true",
273
"try",
274
"var",
275
"void",
276
"while",
277
];
278
const JS_KEYWORDS: &[&str] = &[
279
"as",
280
"async",
281
"await",
282
"break",
283
"case",
284
"catch",
285
"class",
286
"const",
287
"continue",
288
"default",
289
"delete",
290
"do",
291
"else",
292
"enum",
293
"export",
294
"extends",
295
"false",
296
"finally",
297
"for",
298
"from",
299
"function",
300
"if",
301
"implements",
302
"import",
303
"in",
304
"instanceof",
305
"interface",
306
"let",
307
"new",
308
"null",
309
"of",
310
"private",
311
"protected",
312
"public",
313
"readonly",
314
"return",
315
"static",
316
"super",
317
"switch",
318
"this",
319
"throw",
320
"true",
321
"try",
322
"type",
323
"typeof",
324
"undefined",
325
"var",
326
"void",
327
"while",
328
"yield",
329
];
330
const DART_KEYWORDS: &[&str] = &[
331
"abstract",
332
"async",
333
"await",
334
"break",
335
"case",
336
"catch",
337
"class",
338
"const",
339
"continue",
340
"default",
341
"do",
342
"else",
343
"enum",
344
"extends",
345
"false",
346
"final",
347
"finally",
348
"for",
349
"if",
350
"implements",
351
"import",
352
"in",
353
"is",
354
"late",
355
"new",
356
"null",
357
"required",
358
"return",
359
"static",
360
"super",
361
"switch",
362
"this",
363
"throw",
364
"true",
365
"try",
366
"var",
367
"void",
368
"while",
369
"with",
370
"yield",
371
];
372
const GO_KEYWORDS: &[&str] = &[
373
"break",
374
"case",
375
"chan",
376
"const",
377
"continue",
378
"default",
379
"defer",
380
"else",
381
"fallthrough",
382
"for",
383
"func",
384
"go",
385
"goto",
386
"if",
387
"import",
388
"interface",
389
"map",
390
"package",
391
"range",
392
"return",
393
"select",
394
"struct",
395
"switch",
396
"type",
397
"var",
398
"true",
399
"false",
400
"nil",
401
"iota",
402
];
403
const KOTLIN_KEYWORDS: &[&str] = &[
404
"as",
405
"break",
406
"class",
407
"continue",
408
"data",
409
"do",
410
"else",
411
"false",
412
"for",
413
"fun",
414
"if",
415
"import",
416
"in",
417
"interface",
418
"is",
419
"null",
420
"object",
421
"override",
422
"package",
423
"private",
424
"return",
425
"super",
426
"this",
427
"throw",
428
"true",
429
"try",
430
"val",
431
"var",
432
"when",
433
"while",
434
];
435
const RUST_KEYWORDS: &[&str] = &[
436
"as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern",
437
"false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub",
438
"ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type",
439
"unsafe", "use", "where", "while",
440
];
441
const SCALA_KEYWORDS: &[&str] = &[
442
"abstract",
443
"case",
444
"catch",
445
"class",
446
"def",
447
"do",
448
"else",
449
"extends",
450
"false",
451
"final",
452
"finally",
453
"for",
454
"if",
455
"implicit",
456
"import",
457
"lazy",
458
"match",
459
"new",
460
"null",
461
"object",
462
"override",
463
"package",
464
"private",
465
"protected",
466
"return",
467
"sealed",
468
"super",
469
"this",
470
"throw",
471
"trait",
472
"true",
473
"try",
474
"type",
475
"val",
476
"var",
477
"while",
478
"with",
479
"yield",
480
];
481
const SWIFT_KEYWORDS: &[&str] = &[
482
"as",
483
"break",
484
"case",
485
"catch",
486
"class",
487
"continue",
488
"default",
489
"defer",
490
"do",
491
"else",
492
"enum",
493
"extension",
494
"false",
495
"for",
496
"func",
497
"guard",
498
"if",
499
"import",
500
"in",
501
"init",
502
"let",
503
"nil",
504
"private",
505
"protocol",
506
"public",
507
"return",
508
"self",
509
"static",
510
"struct",
511
"switch",
512
"throw",
513
"throws",
514
"true",
515
"try",
516
"var",
517
"where",
518
"while",
519
];
520
const PHP_KEYWORDS: &[&str] = &[
19
521
"abstract",
522
"array",
20
523
"as",
21
"async",
22
"await",
23
524
"break",
24
525
"case",
25
526
"catch",
@@ -28,129 +529,735 @@ const C_LIKE_KEYWORDS: &[&str] = &[
28
529
"continue",
29
530
"default",
30
531
"do",
532
"echo",
31
533
"else",
32
"enum",
33
"export",
534
"elseif",
34
535
"extends",
35
536
"false",
36
537
"final",
37
538
"finally",
38
"fn",
39
539
"for",
40
"from",
41
"func",
540
"foreach",
42
541
"function",
43
"go",
44
542
"if",
45
"impl",
46
"import",
47
"in",
543
"implements",
544
"include",
48
545
"interface",
49
"let",
50
"loop",
51
"match",
52
"mod",
53
"mut",
54
546
"namespace",
55
547
"new",
56
548
"null",
57
"override",
58
"package",
59
549
"private",
60
550
"protected",
61
"pub",
62
551
"public",
63
"readonly",
552
"require",
64
553
"return",
65
"self",
66
554
"static",
67
"struct",
68
"super",
69
555
"switch",
70
"this",
71
556
"throw",
72
"trait",
73
557
"true",
74
558
"try",
75
"type",
76
"typeof",
77
559
"use",
78
"using",
79
"var",
80
"void",
81
"where",
82
560
"while",
83
"yield",
84
561
];
85
562
const PYTHON_KEYWORDS: &[&str] = &[
86
"and", "as", "async", "await", "break", "class", "continue", "def", "del", "elif", "else",
87
"except", "False", "finally", "for", "from", "if", "import", "in", "is", "lambda", "None",
88
"not", "or", "pass", "raise", "return", "True", "try", "while", "with", "yield",
563
"and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif",
564
"else", "except", "False", "finally", "for", "from", "global", "if", "import", "in", "is",
565
"lambda", "None", "nonlocal", "not", "or", "pass", "raise", "return", "True", "try", "while",
566
"with", "yield",
567
];
568
const RUBY_KEYWORDS: &[&str] = &[
569
"and", "begin", "break", "case", "class", "def", "do", "else", "elsif", "end", "ensure",
570
"false", "for", "if", "in", "module", "next", "nil", "not", "or", "require", "rescue",
571
"return", "self", "super", "then", "true", "unless", "until", "when", "while", "yield",
572
];
573
const PERL_KEYWORDS: &[&str] = &[
574
"else", "elsif", "for", "foreach", "if", "last", "local", "my", "next", "our", "package",
575
"print", "require", "return", "sub", "unless", "until", "use", "while",
576
];
577
const R_KEYWORDS: &[&str] = &[
578
"break", "else", "FALSE", "for", "function", "if", "in", "NA", "next", "NULL", "repeat",
579
"return", "TRUE", "while", "library",
89
580
];
90
581
const SHELL_KEYWORDS: &[&str] = &[
91
"case", "do", "done", "elif", "else", "esac", "export", "fi", "for", "function", "if", "in",
92
"local", "return", "then", "while",
582
"case", "do", "done", "echo", "elif", "else", "esac", "exit", "export", "fi", "for",
583
"function", "if", "in", "local", "return", "set", "then", "until", "while",
584
];
585
const POWERSHELL_KEYWORDS: &[&str] = &[
586
"begin", "break", "catch", "class", "continue", "do", "else", "elseif", "end", "exit",
587
"filter", "finally", "for", "foreach", "function", "if", "in", "param", "process", "return",
588
"switch", "throw", "trap", "try", "until", "while", "$true", "$false", "$null",
589
];
590
const DOS_KEYWORDS: &[&str] = &[
591
"call", "cd", "copy", "defined", "del", "do", "echo", "else", "endlocal", "equ", "exist",
592
"exit", "for", "goto", "if", "in", "mkdir", "neq", "not", "pause", "set", "setlocal", "shift",
593
"start",
594
];
595
const DOCKER_KEYWORDS: &[&str] = &[
596
"add",
597
"arg",
598
"as",
599
"cmd",
600
"copy",
601
"entrypoint",
602
"env",
603
"expose",
604
"from",
605
"healthcheck",
606
"label",
607
"onbuild",
608
"run",
609
"shell",
610
"stopsignal",
611
"user",
612
"volume",
613
"workdir",
93
614
];
94
615
const SQL_KEYWORDS: &[&str] = &[
95
"and", "as", "by", "create", "delete", "from", "group", "insert", "into", "join", "left",
96
"not", "null", "on", "or", "order", "select", "set", "table", "update", "values", "where",
616
"alter", "and", "as", "asc", "between", "by", "case", "create", "delete", "desc", "distinct",
617
"drop", "else", "end", "exists", "from", "group", "having", "in", "inner", "insert", "into",
618
"is", "join", "left", "like", "limit", "not", "null", "on", "or", "order", "outer", "right",
619
"select", "set", "table", "then", "union", "update", "values", "when", "where", "with",
620
];
621
const KQL_KEYWORDS: &[&str] = &[
622
"and",
623
"asc",
624
"by",
625
"count",
626
"desc",
627
"distinct",
628
"extend",
629
"join",
630
"let",
631
"limit",
632
"or",
633
"order",
634
"project",
635
"render",
636
"sort",
637
"summarize",
638
"take",
639
"top",
640
"union",
641
"where",
642
];
643
const GRAPHQL_KEYWORDS: &[&str] = &[
644
"enum",
645
"extend",
646
"false",
647
"fragment",
648
"implements",
649
"input",
650
"interface",
651
"mutation",
652
"null",
653
"on",
654
"query",
655
"scalar",
656
"schema",
657
"subscription",
658
"true",
659
"type",
660
"union",
661
];
662
const HTTP_KEYWORDS: &[&str] = &[
663
"CONNECT", "DELETE", "GET", "HEAD", "HTTP", "OPTIONS", "PATCH", "POST", "PUT", "TRACE",
664
];
665
const VB_KEYWORDS: &[&str] = &[
666
"and", "as", "boolean", "byval", "byref", "call", "case", "class", "const", "dim", "do",
667
"each", "else", "elseif", "end", "exit", "false", "for", "function", "if", "imports", "in",
668
"integer", "is", "loop", "module", "new", "next", "not", "nothing", "or", "private", "public",
669
"return", "select", "set", "string", "sub", "then", "to", "true", "while", "with",
670
];
671
const VERILOG_KEYWORDS: &[&str] = &[
672
"always",
673
"assign",
674
"begin",
675
"case",
676
"else",
677
"end",
678
"endcase",
679
"endmodule",
680
"for",
681
"if",
682
"initial",
683
"input",
684
"integer",
685
"module",
686
"negedge",
687
"output",
688
"parameter",
689
"posedge",
690
"reg",
691
"wire",
692
];
693
const VHDL_KEYWORDS: &[&str] = &[
694
"architecture",
695
"begin",
696
"case",
697
"downto",
698
"else",
699
"elsif",
700
"end",
701
"entity",
702
"for",
703
"generic",
704
"if",
705
"in",
706
"is",
707
"library",
708
"loop",
709
"map",
710
"of",
711
"others",
712
"out",
713
"port",
714
"process",
715
"signal",
716
"then",
717
"to",
718
"use",
719
"variable",
720
"when",
721
"while",
722
];
723
const OCTAVE_KEYWORDS: &[&str] = &[
724
"break",
725
"case",
726
"catch",
727
"continue",
728
"else",
729
"elseif",
730
"end",
731
"for",
732
"function",
733
"if",
734
"otherwise",
735
"return",
736
"switch",
737
"try",
738
"while",
739
];
740
const LISP_KEYWORDS: &[&str] = &[
741
"cond",
742
"defmacro",
743
"defparameter",
744
"defun",
745
"defvar",
746
"if",
747
"lambda",
748
"let",
749
"nil",
750
"progn",
751
"quote",
752
"setf",
753
"setq",
754
"t",
755
"unless",
756
"when",
97
757
];
758
const LITERALS: &[&str] = &["true", "false", "null", "yes", "no", "on", "off", "~"];
98
759
99
const C_LIKE: Grammar = Grammar {
100
line_comments: &["//"],
101
block_comment: Some(("/*", "*/")),
102
keywords: C_LIKE_KEYWORDS,
103
char_quotes: false,
760
const C: Grammar = Grammar {
761
types: &[
762
"size_t", "int8_t", "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t", "uint32_t",
763
"uint64_t", "FILE", "printf", "scanf", "malloc", "free", "memcpy", "strlen", "BOOL", "YES",
764
"NO", "id", "NSString", "NSLog",
765
],
766
char_quotes: true,
767
..c_style(C_KEYWORDS)
768
};
769
const CPP: Grammar = Grammar {
770
types: &[
771
"std",
772
"string",
773
"vector",
774
"map",
775
"set",
776
"size_t",
777
"cout",
778
"cin",
779
"endl",
780
"unique_ptr",
781
"shared_ptr",
782
"make_unique",
783
"make_shared",
784
"printf",
785
],
786
char_quotes: true,
787
..c_style(CPP_KEYWORDS)
788
};
789
const CSHARP: Grammar = Grammar {
790
types: &[
791
"byte",
792
"char",
793
"decimal",
794
"double",
795
"float",
796
"long",
797
"Console",
798
"List",
799
"Dictionary",
800
"Task",
801
"DateTime",
802
"Exception",
803
"nameof",
804
],
805
char_quotes: true,
806
..c_style(CSHARP_KEYWORDS)
807
};
808
const JAVA: Grammar = Grammar {
809
types: &[
810
"byte",
811
"short",
812
"String",
813
"Integer",
814
"Long",
815
"Double",
816
"Boolean",
817
"Object",
818
"List",
819
"Map",
820
"ArrayList",
821
"HashMap",
822
"System",
823
"Exception",
824
"Override",
825
],
826
char_quotes: true,
827
..c_style(JAVA_KEYWORDS)
828
};
829
const RUST: Grammar = Grammar {
830
types: &[
831
"i8",
832
"i16",
833
"i32",
834
"i64",
835
"i128",
836
"isize",
837
"u8",
838
"u16",
839
"u32",
840
"u64",
841
"u128",
842
"usize",
843
"f32",
844
"f64",
845
"bool",
846
"char",
847
"str",
848
"String",
849
"Vec",
850
"Option",
851
"Some",
852
"None",
853
"Result",
854
"Ok",
855
"Err",
856
"Box",
857
"Rc",
858
"Arc",
859
"println",
860
"print",
861
"format",
862
"vec",
863
"panic",
864
"assert",
865
"assert_eq",
866
],
867
char_quotes: true,
868
..c_style(RUST_KEYWORDS)
869
};
870
const KOTLIN: Grammar = Grammar {
871
types: &[
872
"Int", "Long", "Double", "Boolean", "String", "Unit", "Any", "List", "Map", "println",
873
"listOf", "mapOf", "setOf",
874
],
875
char_quotes: true,
876
..c_style(KOTLIN_KEYWORDS)
104
877
};
105
const CHAR_LIKE: Grammar = Grammar {
878
const SCALA: Grammar = Grammar {
879
types: &[
880
"Int", "Long", "Double", "Boolean", "String", "Unit", "Any", "List", "Map", "Option",
881
"Some", "None", "println",
882
],
106
883
char_quotes: true,
107
..C_LIKE
884
..c_style(SCALA_KEYWORDS)
885
};
886
const JS: Grammar = Grammar {
887
types: &[
888
"console", "document", "window", "Promise", "Array", "Object", "JSON", "Math", "Date",
889
"Error", "Map", "Set", "string", "number", "boolean", "any", "unknown", "never", "require",
890
"module",
891
],
892
..c_style(JS_KEYWORDS)
893
};
894
const DART: Grammar = Grammar {
895
types: &[
896
"int", "double", "num", "String", "bool", "List", "Map", "Set", "dynamic", "Future",
897
"Stream", "print",
898
],
899
..c_style(DART_KEYWORDS)
900
};
901
const GO: Grammar = Grammar {
902
types: &[
903
"bool",
904
"byte",
905
"complex64",
906
"complex128",
907
"error",
908
"float32",
909
"float64",
910
"int",
911
"int8",
912
"int16",
913
"int32",
914
"int64",
915
"rune",
916
"string",
917
"uint",
918
"uint8",
919
"uint16",
920
"uint32",
921
"uint64",
922
"uintptr",
923
"any",
924
"append",
925
"cap",
926
"close",
927
"copy",
928
"delete",
929
"len",
930
"make",
931
"new",
932
"panic",
933
"print",
934
"println",
935
"recover",
936
],
937
..c_style(GO_KEYWORDS)
938
};
939
const SWIFT: Grammar = Grammar {
940
types: &[
941
"Int",
942
"Double",
943
"Float",
944
"Bool",
945
"String",
946
"Character",
947
"Array",
948
"Dictionary",
949
"Set",
950
"Optional",
951
"Any",
952
"print",
953
],
954
..c_style(SWIFT_KEYWORDS)
955
};
956
const CSS: Grammar = Grammar {
957
keys: true,
958
dashed_words: true,
959
..c_style(&[])
108
960
};
109
const HASH: Grammar = Grammar {
110
line_comments: &["#"],
961
const JSON: Grammar = Grammar {
962
keys: true,
963
..c_style(LITERALS)
964
};
965
const VERILOG: Grammar = Grammar {
966
types: &["$display", "$finish", "$time", "logic", "bit"],
967
..c_style(VERILOG_KEYWORDS)
968
};
969
const PHP: Grammar = Grammar {
970
types: &[
971
"$this",
972
"array",
973
"count",
974
"isset",
975
"empty",
976
"strlen",
977
"json_encode",
978
"json_decode",
979
"var_dump",
980
"print_r",
981
],
982
line_comments: &["//", "#"],
983
..c_style(PHP_KEYWORDS)
984
};
985
const KQL: Grammar = Grammar {
986
types: &[
987
"ago", "now", "datetime", "bin", "dcount", "tostring", "toint", "strcat", "count", "sum",
988
"avg",
989
],
111
990
block_comment: None,
112
keywords: PYTHON_KEYWORDS,
113
char_quotes: false,
991
case_insensitive: true,
992
..c_style(KQL_KEYWORDS)
993
};
994
const PYTHON: Grammar = Grammar {
995
types: &[
996
"self",
997
"cls",
998
"print",
999
"len",
1000
"range",
1001
"int",
1002
"str",
1003
"float",
1004
"bool",
1005
"bytes",
1006
"list",
1007
"dict",
1008
"set",
1009
"tuple",
1010
"object",
1011
"open",
1012
"super",
1013
"isinstance",
1014
"enumerate",
1015
"zip",
1016
"map",
1017
"filter",
1018
"sorted",
1019
"sum",
1020
"min",
1021
"max",
1022
"abs",
1023
"type",
1024
"Exception",
1025
],
1026
..hash_style(PYTHON_KEYWORDS)
1027
};
1028
const RUBY: Grammar = Grammar {
1029
types: &[
1030
"puts",
1031
"print",
1032
"p",
1033
"attr_accessor",
1034
"attr_reader",
1035
"attr_writer",
1036
"lambda",
1037
"proc",
1038
"raise",
1039
],
1040
..hash_style(RUBY_KEYWORDS)
1041
};
1042
const PERL: Grammar = Grammar {
1043
types: &[
1044
"chomp", "die", "join", "keys", "push", "shift", "split", "values", "open", "close",
1045
],
1046
..hash_style(PERL_KEYWORDS)
1047
};
1048
const R: Grammar = Grammar {
1049
types: &[
1050
"c", "list", "print", "paste", "length", "vector", "matrix", "sum", "mean", "cat",
1051
],
1052
..hash_style(R_KEYWORDS)
114
1053
};
115
1054
const SHELL: Grammar = Grammar {
116
line_comments: &["#"],
117
block_comment: None,
118
keywords: SHELL_KEYWORDS,
119
char_quotes: false,
1055
types: &[
1056
"cd", "ls", "pwd", "grep", "sed", "awk", "cat", "cp", "mv", "rm", "mkdir", "touch",
1057
"chmod", "sudo", "git", "docker", "kubectl", "curl", "wget", "read", "printf", "source",
1058
"test", "true", "false",
1059
],
1060
..hash_style(SHELL_KEYWORDS)
1061
};
1062
const YAML: Grammar = Grammar {
1063
keys: true,
1064
..hash_style(LITERALS)
1065
};
1066
const GRAPHQL: Grammar = Grammar {
1067
types: &["String", "Int", "Float", "Boolean", "ID"],
1068
..hash_style(GRAPHQL_KEYWORDS)
1069
};
1070
const DOCKER: Grammar = Grammar {
1071
case_insensitive: true,
1072
..hash_style(DOCKER_KEYWORDS)
1073
};
1074
const POWERSHELL: Grammar = Grammar {
1075
dashed_words: true,
1076
block_comment: Some(("<#", "#>")),
1077
case_insensitive: true,
1078
..hash_style(POWERSHELL_KEYWORDS)
1079
};
1080
const DOS: Grammar = Grammar {
1081
line_comments: &["::", "rem ", "REM ", "@rem "],
1082
case_insensitive: true,
1083
keywords: DOS_KEYWORDS,
1084
..CODE
120
1085
};
121
1086
const SQL: Grammar = Grammar {
1087
types: &[
1088
"int",
1089
"integer",
1090
"bigint",
1091
"varchar",
1092
"char",
1093
"text",
1094
"date",
1095
"timestamp",
1096
"boolean",
1097
"decimal",
1098
"count",
1099
"sum",
1100
"avg",
1101
"min",
1102
"max",
1103
"coalesce",
1104
"now",
1105
],
122
1106
line_comments: &["--"],
123
1107
block_comment: Some(("/*", "*/")),
124
1108
keywords: SQL_KEYWORDS,
125
char_quotes: false,
1109
case_insensitive: true,
1110
..CODE
126
1111
};
127
const MARKUP: Grammar = Grammar {
128
line_comments: &[],
129
block_comment: Some(("<!--", "-->")),
130
keywords: &[],
131
char_quotes: false,
1112
const VHDL: Grammar = Grammar {
1113
types: &[
1114
"std_logic",
1115
"std_logic_vector",
1116
"integer",
1117
"boolean",
1118
"unsigned",
1119
"signed",
1120
"rising_edge",
1121
],
1122
line_comments: &["--"],
1123
keywords: VHDL_KEYWORDS,
1124
case_insensitive: true,
1125
..CODE
1126
};
1127
const VB: Grammar = Grammar {
1128
line_comments: &["'", "rem ", "REM "],
1129
keywords: VB_KEYWORDS,
1130
case_insensitive: true,
1131
..CODE
1132
};
1133
const OCTAVE: Grammar = Grammar {
1134
types: &[
1135
"disp", "zeros", "ones", "size", "numel", "length", "plot", "printf", "fprintf", "true",
1136
"false",
1137
],
1138
line_comments: &["%", "#"],
1139
block_comment: Some(("%{", "%}")),
1140
keywords: OCTAVE_KEYWORDS,
1141
..CODE
1142
};
1143
const LISP: Grammar = Grammar {
1144
types: &[
1145
"car", "cdr", "cons", "list", "format", "print", "append", "mapcar", "funcall", "apply",
1146
],
1147
line_comments: &[";"],
1148
block_comment: Some(("#|", "|#")),
1149
keywords: LISP_KEYWORDS,
1150
..CODE
1151
};
1152
const HTTP: Grammar = Grammar {
1153
keys: true,
1154
dashed_words: true,
1155
keywords: HTTP_KEYWORDS,
1156
..CODE
1157
};
1158
const LATEX: Grammar = Grammar {
1159
line_comments: &["%"],
1160
command_prefix: Some('\\'),
1161
..CODE
132
1162
};
133
1163
134
fn grammar_for(language: &str) -> Option<&'static Grammar> {
135
match language.to_ascii_lowercase().as_str() {
136
"rust" | "rs" | "c" | "cpp" | "c++" | "csharp" | "cs" | "c#" | "java" | "go" | "kotlin"
137
| "scala" => Some(&CHAR_LIKE),
138
"javascript" | "js" | "jsx" | "typescript" | "ts" | "tsx" | "swift" | "php" | "json"
139
| "css" | "scss" | "less" | "dart" => Some(&C_LIKE),
140
"python" | "py" | "ruby" | "rb" | "yaml" | "yml" | "toml" | "r" | "perl" | "dockerfile"
141
| "makefile" => Some(&HASH),
142
"bash" | "sh" | "shell" | "zsh" | "powershell" | "ps1" => Some(&SHELL),
143
"sql" | "tsql" | "plsql" | "lua" => Some(&SQL),
144
"html" | "xml" | "svg" | "markdown" | "md" => Some(&MARKUP),
145
_ => None,
146
}
1164
enum Rules {
1165
Code(&'static Grammar),
1166
Markup,
1167
Markdown,
1168
}
1169
1170
/// The rules for a code block language: one arm per Teams language id (see
1171
/// `teams_core::CODE_LANGUAGES`); a language without an arm stays plain.
1172
fn rules_for(language: &str) -> Option<Rules> {
1173
let id = teams_core::code_language(language).map_or_else(
1174
|| language.to_ascii_lowercase(),
1175
|known| known.id.to_ascii_lowercase(),
1176
);
1177
let grammar = match id.as_str() {
1178
"html" | "xml" | "jsp" => return Some(Rules::Markup),
1179
"markdown" => return Some(Rules::Markdown),
1180
"bash" => &SHELL,
1181
"c" | "objectivec" => &C,
1182
"cpp" => &CPP,
1183
"csharp" => &CSHARP,
1184
"css" | "scss" | "less" => &CSS,
1185
"dart" => &DART,
1186
"dockerfile" => &DOCKER,
1187
"dos" => &DOS,
1188
"go" => &GO,
1189
"graphql" => &GRAPHQL,
1190
"http" => &HTTP,
1191
"java" => &JAVA,
1192
"javascript" | "jsx" | "typescript" => &JS,
1193
"json" => &JSON,
1194
"kotlin" => &KOTLIN,
1195
"kql" => &KQL,
1196
"latex" => &LATEX,
1197
"lisp" => &LISP,
1198
"octave" => &OCTAVE,
1199
"perl" => &PERL,
1200
"php" => &PHP,
1201
"powershell" => &POWERSHELL,
1202
"python" => &PYTHON,
1203
"r" => &R,
1204
"ruby" => &RUBY,
1205
"rust" => &RUST,
1206
"scala" => &SCALA,
1207
"sql" | "tsql" | "plsql" => &SQL,
1208
"swift" => &SWIFT,
1209
"vbnet" | "vbscript" => &VB,
1210
"verilog" => &VERILOG,
1211
"vhdl" => &VHDL,
1212
"yaml" | "toml" => &YAML,
1213
_ => return None,
1214
};
1215
Some(Rules::Code(grammar))
147
1216
}
148
1217
149
1218
pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)>> {
150
let grammar = grammar_for(language)?;
151
let sql = grammar.keywords == SQL_KEYWORDS;
1219
Some(match rules_for(language)? {
1220
Rules::Code(grammar) => highlight_code(code, grammar),
1221
Rules::Markup => highlight_markup(code),
1222
Rules::Markdown => highlight_markdown(code),
1223
})
1224
}
1225
1226
/// Keywords whose next word is the name being defined.
1227
const DEFINITIONS: &[&str] = &[
1228
"class",
1229
"def",
1230
"enum",
1231
"fn",
1232
"fun",
1233
"func",
1234
"function",
1235
"interface",
1236
"module",
1237
"object",
1238
"protocol",
1239
"struct",
1240
"sub",
1241
"trait",
1242
"type",
1243
];
1244
1245
/// Only spaces, or a YAML list dash, before `at` on its line.
1246
fn starts_line(code: &str, at: usize) -> bool {
1247
let line = &code[code[..at].rfind('\n').map_or(0, |end| end + 1)..at];
1248
matches!(line.trim(), "" | "-")
1249
}
1250
1251
/// Followed by `:` (not `::`) after optional spaces.
1252
fn before_colon(code: &str, end: usize) -> bool {
1253
let rest = code[end..].trim_start_matches([' ', '\t']);
1254
rest.starts_with(':') && !rest.starts_with("::")
1255
}
1256
1257
fn highlight_code(code: &str, grammar: &Grammar) -> Vec<(Range<usize>, Token)> {
152
1258
let mut tokens = Vec::new();
153
1259
let mut index = 0;
1260
let mut defines = false;
154
1261
while index < code.len() {
155
1262
let rest = &code[index..];
156
1263
if let Some((open, close)) = grammar.block_comment
@@ -163,11 +1270,12 @@ pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)
163
1270
index = end;
164
1271
continue;
165
1272
}
166
if grammar
167
.line_comments
168
.iter()
169
.any(|marker| rest.starts_with(marker))
170
{
1273
let line_start = index == 0 || code.as_bytes()[index - 1] == b'\n';
1274
if grammar.line_comments.iter().any(|marker| {
1275
rest.starts_with(marker)
1276
// A word comment such as `rem ` only counts at the start of a line.
1277
&& (!marker.ends_with(' ') || line_start || code[..index].ends_with(' '))
1278
}) {
171
1279
let end = rest.find('\n').map_or(code.len(), |offset| index + offset);
172
1280
tokens.push((index..end, Token::Comment));
173
1281
index = end;
@@ -180,7 +1288,11 @@ pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)
180
1288
}
181
1289
if matches!(character, '"' | '\'' | '`') {
182
1290
let end = string_end(code, index, character);
183
tokens.push((index..end, Token::String));
1291
let key = grammar.keys && before_colon(code, end);
1292
tokens.push((
1293
index..end,
1294
if key { Token::Attribute } else { Token::String },
1295
));
184
1296
index = end;
185
1297
continue;
186
1298
}
@@ -192,28 +1304,190 @@ pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)
192
1304
index += length;
193
1305
continue;
194
1306
}
195
if character.is_alphabetic() || character == '_' {
196
let length = rest
197
.find(|next: char| !(next.is_alphanumeric() || next == '_'))
198
.unwrap_or(rest.len());
1307
let command = grammar.command_prefix == Some(character);
1308
if character.is_alphabetic() || matches!(character, '_' | '$' | '@' | '#') || command {
1309
let dashed = grammar.dashed_words;
1310
let length = character.len_utf8()
1311
+ rest[character.len_utf8()..]
1312
.find(|next: char| {
1313
!(next.is_alphanumeric() || next == '_' || dashed && next == '-')
1314
})
1315
.unwrap_or(rest.len() - character.len_utf8());
1316
let length = rest[..length].trim_end_matches('-').len();
199
1317
let word = &rest[..length];
200
let is_keyword = if sql {
201
grammar
202
.keywords
203
.iter()
204
.any(|keyword| keyword.eq_ignore_ascii_case(word))
1318
let same = |known: &&str| {
1319
if grammar.case_insensitive {
1320
known.eq_ignore_ascii_case(word)
1321
} else {
1322
*known == word
1323
}
1324
};
1325
let end = index + length;
1326
let token = if command && length > 1 || grammar.keywords.iter().any(same) {
1327
Some(Token::Keyword)
1328
} else if grammar.keys && starts_line(code, index) && before_colon(code, end) {
1329
Some(Token::Attribute)
1330
} else if defines {
1331
Some(Token::Title)
1332
} else if grammar.types.iter().any(same) || dashed && word.contains('-') {
1333
Some(Token::Type)
205
1334
} else {
206
grammar.keywords.contains(&word)
1335
None
207
1336
};
208
if is_keyword {
209
tokens.push((index..index + length, Token::Keyword));
210
}
211
index += length;
1337
defines = token == Some(Token::Keyword) && DEFINITIONS.iter().any(same);
1338
tokens.extend(token.map(|token| (index..end, token)));
1339
index = end;
212
1340
continue;
213
1341
}
1342
if !character.is_whitespace() {
1343
defines = false;
1344
}
214
1345
index += character.len_utf8();
215
1346
}
216
Some(tokens)
1347
tokens
1348
}
1349
1350
/// HTML and XML: tag names, attribute names, quoted values and comments.
1351
fn highlight_markup(code: &str) -> Vec<(Range<usize>, Token)> {
1352
let mut tokens = Vec::new();
1353
let mut index = 0;
1354
while let Some(offset) = code[index..].find('<') {
1355
let start = index + offset;
1356
let rest = &code[start..];
1357
if rest.starts_with("<!--") {
1358
let end = rest.find("-->").map_or(code.len(), |at| start + at + 3);
1359
tokens.push((start..end, Token::Comment));
1360
index = end;
1361
continue;
1362
}
1363
let name_start = start + 1 + usize::from(rest[1..].starts_with(['/', '!', '?']));
1364
let name_end = name_start
1365
+ code[name_start..]
1366
.find(|next: char| {
1367
!(next.is_alphanumeric() || matches!(next, '-' | ':' | '_' | '.'))
1368
})
1369
.unwrap_or(code.len() - name_start);
1370
if name_end == name_start {
1371
index = start + 1;
1372
continue;
1373
}
1374
tokens.push((name_start..name_end, Token::Tag));
1375
let close = code[name_end..]
1376
.find('>')
1377
.map_or(code.len(), |at| name_end + at);
1378
let mut at = name_end;
1379
while at < close {
1380
let character = code[at..].chars().next().unwrap_or_default();
1381
if matches!(character, '"' | '\'') {
1382
let end = code[at + 1..close]
1383
.find(character)
1384
.map_or(close, |end| at + 1 + end + 1);
1385
tokens.push((at..end, Token::String));
1386
at = end;
1387
} else if character.is_alphabetic() {
1388
let end = at
1389
+ code[at..close]
1390
.find(|next: char| {
1391
!(next.is_alphanumeric() || matches!(next, '-' | ':' | '_'))
1392
})
1393
.unwrap_or(close - at);
1394
tokens.push((at..end, Token::Attribute));
1395
at = end;
1396
} else {
1397
at += character.len_utf8();
1398
}
1399
}
1400
index = (close + 1).min(code.len());
1401
}
1402
tokens
1403
}
1404
1405
/// Markdown by line: headings, quotes, list markers, fenced code, then inline code, bold,
1406
/// italic and links.
1407
fn highlight_markdown(code: &str) -> Vec<(Range<usize>, Token)> {
1408
let mut tokens = Vec::new();
1409
let mut fenced = false;
1410
let mut start = 0;
1411
for line in code.split('\n') {
1412
let range = start..start + line.len();
1413
start = range.end + 1;
1414
let trimmed = line.trim_start();
1415
let indent = range.start + line.len() - trimmed.len();
1416
if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
1417
fenced = !fenced;
1418
tokens.push((range, Token::String));
1419
continue;
1420
}
1421
if fenced {
1422
tokens.push((range, Token::String));
1423
continue;
1424
}
1425
let hashes = trimmed.bytes().take_while(|byte| *byte == b'#').count();
1426
if (1..=6).contains(&hashes) && trimmed[hashes..].starts_with(' ') {
1427
tokens.push((range, Token::Heading));
1428
continue;
1429
}
1430
if trimmed.starts_with('>') {
1431
tokens.push((range, Token::Comment));
1432
continue;
1433
}
1434
let marker = list_marker(trimmed);
1435
if marker > 0 {
1436
tokens.push((indent..indent + marker, Token::Keyword));
1437
}
1438
inline_markdown(code, indent + marker..range.end, &mut tokens);
1439
}
1440
tokens
1441
}
1442
1443
/// Byte length of a `- `, `* `, `+ ` or `1. ` list marker.
1444
fn list_marker(line: &str) -> usize {
1445
if line.starts_with(['-', '*', '+']) && line[1..].starts_with(' ') {
1446
return 1;
1447
}
1448
let digits = line.bytes().take_while(u8::is_ascii_digit).count();
1449
if digits > 0 && line[digits..].starts_with(". ") {
1450
digits + 1
1451
} else {
1452
0
1453
}
1454
}
1455
1456
fn inline_markdown(code: &str, range: Range<usize>, tokens: &mut Vec<(Range<usize>, Token)>) {
1457
let mut index = range.start;
1458
while index < range.end {
1459
let rest = &code[index..range.end];
1460
let span = |open: &str, close: &str| {
1461
rest.strip_prefix(open)?
1462
.find(close)
1463
.filter(|length| *length > 0)
1464
.map(|length| index + open.len() + length + close.len())
1465
};
1466
let found = if rest.starts_with('`') {
1467
span("`", "`").map(|end| (end, Token::String))
1468
} else if rest.starts_with("**") || rest.starts_with("__") {
1469
span(&rest[..2], &rest[..2]).map(|end| (end, Token::Strong))
1470
} else if rest.starts_with(['*', '_']) {
1471
span(&rest[..1], &rest[..1]).map(|end| (end, Token::Emphasis))
1472
} else if rest.starts_with('[') {
1473
rest.find("](")
1474
.and_then(|label| {
1475
rest[label..]
1476
.find(')')
1477
.map(|close| index + label + close + 1)
1478
})
1479
.map(|end| (end, Token::Link))
1480
} else {
1481
None
1482
};
1483
match found {
1484
Some((end, token)) => {
1485
tokens.push((index..end, token));
1486
index = end;
1487
}
1488
None => index += rest.chars().next().map_or(1, char::len_utf8),
1489
}
1490
}
217
1491
}
218
1492
219
1493
fn is_char_literal(rest: &str) -> bool {
@@ -261,6 +1535,7 @@ mod tests {
261
1535
vec![
262
1536
("// x", Token::Comment),
263
1537
("fn", Token::Keyword),
1538
("a", Token::Title),
264
1539
("\"b\"", Token::String),
265
1540
]
266
1541
);
@@ -283,7 +1558,13 @@ mod tests {
283
1558
fn rust_lifetime_is_not_a_string() {
284
1559
assert_eq!(
285
1560
kinds("fn a<'b>(x: &'b str) -> char { 'c' }", "rust"),
286
vec![("fn", Token::Keyword), ("'c'", Token::String),]
1561
vec![
1562
("fn", Token::Keyword),
1563
("a", Token::Title),
1564
("str", Token::Type),
1565
("char", Token::Type),
1566
("'c'", Token::String),
1567
]
287
1568
);
288
1569
assert_eq!(kinds(r"'\n'", "rust"), vec![(r"'\n'", Token::String)]);
289
1570
}
@@ -296,6 +1577,7 @@ mod tests {
296
1577
#[test]
297
1578
fn unknown_language_has_no_highlight() {
298
1579
assert!(highlight("x", "brainfuck").is_none());
1580
assert!(highlight("x", "plaintext").is_none());
299
1581
}
300
1582
301
1583
#[test]
@@ -307,4 +1589,102 @@ mod tests {
307
1589
.any(|(text, _)| *text == "1")
308
1590
);
309
1591
}
1592
1593
#[test]
1594
fn every_teams_language_but_plain_text_has_rules() {
1595
let missing: Vec<_> = teams_core::CODE_LANGUAGES
1596
.iter()
1597
.filter(|language| language.id != teams_core::PLAIN_LANGUAGE)
1598
.filter(|language| rules_for(language.id).is_none())
1599
.map(|language| language.id)
1600
.collect();
1601
assert!(missing.is_empty(), "no highlighting for {missing:?}");
1602
}
1603
1604
#[test]
1605
fn markup_colours_tags_attributes_and_values() {
1606
assert_eq!(
1607
kinds("<a href=\"x\">t</a><!-- c -->", "html"),
1608
vec![
1609
("a", Token::Tag),
1610
("href", Token::Attribute),
1611
("\"x\"", Token::String),
1612
("a", Token::Tag),
1613
("<!-- c -->", Token::Comment),
1614
]
1615
);
1616
}
1617
1618
#[test]
1619
fn markdown_colours_its_blocks_and_inline_marks() {
1620
assert_eq!(
1621
kinds(
1622
"# Title\n- **b** and *i* `c` [l](u)\n> q\n```\nx\n```",
1623
"md"
1624
),
1625
vec", Token::Link),
1632
("> q", Token::Comment),
1633
("```", Token::String),
1634
("x", Token::String),
1635
("```", Token::String),
1636
]
1637
);
1638
}
1639
1640
#[test]
1641
fn definitions_types_and_keys() {
1642
assert_eq!(
1643
kinds("def f(self): print(1)", "python"),
1644
vec![
1645
("def", Token::Keyword),
1646
("f", Token::Title),
1647
("self", Token::Type),
1648
("print", Token::Type),
1649
("1", Token::Number),
1650
]
1651
);
1652
assert_eq!(
1653
kinds("func ok() bool", "go"),
1654
vec![
1655
("func", Token::Keyword),
1656
("ok", Token::Title),
1657
("bool", Token::Type)
1658
]
1659
);
1660
assert_eq!(
1661
kinds("{\"a\": \"b\"}", "json"),
1662
vec![("\"a\"", Token::Attribute), ("\"b\"", Token::String)]
1663
);
1664
assert_eq!(
1665
kinds("name: x\nurl: http://y", "yaml"),
1666
vec![("name", Token::Attribute), ("url", Token::Attribute)]
1667
);
1668
assert_eq!(
1669
kinds(" font-size: 2px;", "css")[0],
1670
("font-size", Token::Attribute)
1671
);
1672
assert_eq!(
1673
kinds("Get-ChildItem -Path .", "powershell")[0],
1674
("Get-ChildItem", Token::Type)
1675
);
1676
}
1677
1678
#[test]
1679
fn word_comments_and_latex_commands() {
1680
assert_eq!(
1681
kinds("rem x\necho", "dos"),
1682
vec![("rem x", Token::Comment), ("echo", Token::Keyword)]
1683
);
1684
assert_eq!(
1685
kinds("\\section{a} % c", "latex"),
1686
vec![("\\section", Token::Keyword), ("% c", Token::Comment)]
1687
);
1688
assert_eq!(kinds("FROM x", "dockerFile")[0], ("FROM", Token::Keyword));
1689
}
310
1690
}
@@ -6,20 +6,521 @@ pub enum Token {6
String,6
String,7
Number,7
Number,8
Comment,8
Comment,9
Tag,10
Attribute,11
Heading,12
Strong,13
Emphasis,14
Link,15
/// Built-in types, functions and values: `bool`, `print`, `self`.16
Type,17
/// The name a definition gives: `f` in `def f`, `A` in `class A`.18
Title,9
}19
}10
20
21
/// A lexer for code: comments, strings, numbers and keywords.11
struct Grammar {22
struct Grammar {12
line_comments: &'static [&'static str],23
line_comments: &'static [&'static str],13
block_comment: Option<(&'static str, &'static str)>,24
block_comment: Option<(&'static str, &'static str)>,14
keywords: &'static [&'static str],25
keywords: &'static [&'static str],26
/// `'x'` is a character; other single quotes (Rust lifetimes) are left alone.15
char_quotes: bool,27
char_quotes: bool,28
case_insensitive: bool,29
/// Words after this prefix are keywords too, as `\section` in LaTeX.30
command_prefix: Option<char>,31
types: &'static [&'static str],32
/// A word or string right before `:` is a key, as in JSON, YAML and CSS.33
keys: bool,34
/// `-` joins words, as in `font-size` and `Get-ChildItem`; such a word is a built-in.35
dashed_words: bool,16
}36
}17
37
18
const C_LIKE_KEYWORDS: &[&str] = &[38
const CODE: Grammar = Grammar {39
line_comments: &[],40
block_comment: None,41
keywords: &[],42
char_quotes: false,43
case_insensitive: false,44
command_prefix: None,45
types: &[],46
keys: false,47
dashed_words: false,48
};49
50
const fn c_style(keywords: &'static [&'static str]) -> Grammar {51
Grammar {52
line_comments: &["//"],53
block_comment: Some(("/*", "*/")),54
keywords,55
..CODE56
}57
}58
59
const fn hash_style(keywords: &'static [&'static str]) -> Grammar {60
Grammar {61
line_comments: &["#"],62
keywords,63
..CODE64
}65
}66
67
const C_KEYWORDS: &[&str] = &[68
"auto",69
"break",70
"case",71
"char",72
"const",73
"continue",74
"default",75
"do",76
"double",77
"else",78
"enum",79
"extern",80
"float",81
"for",82
"goto",83
"if",84
"inline",85
"int",86
"long",87
"register",88
"restrict",89
"return",90
"short",91
"signed",92
"sizeof",93
"static",94
"struct",95
"switch",96
"typedef",97
"union",98
"unsigned",99
"void",100
"volatile",101
"while",102
"NULL",103
"true",104
"false",105
"bool",106
"#include",107
"#define",108
"@interface",109
"@implementation",110
"@end",111
"@property",112
"self",113
"nil",114
];115
const CPP_KEYWORDS: &[&str] = &[116
"auto",117
"bool",118
"break",119
"case",120
"catch",121
"char",122
"class",123
"const",124
"constexpr",125
"continue",126
"default",127
"delete",128
"do",129
"double",130
"else",131
"enum",132
"explicit",133
"extern",134
"false",135
"float",136
"for",137
"friend",138
"goto",139
"if",140
"inline",141
"int",142
"long",143
"namespace",144
"new",145
"noexcept",146
"nullptr",147
"operator",148
"override",149
"private",150
"protected",151
"public",152
"return",153
"short",154
"signed",155
"sizeof",156
"static",157
"struct",158
"switch",159
"template",160
"this",161
"throw",162
"true",163
"try",164
"typedef",165
"typename",166
"union",167
"unsigned",168
"using",169
"virtual",170
"void",171
"volatile",172
"while",173
];174
const CSHARP_KEYWORDS: &[&str] = &[175
"abstract",176
"as",177
"async",178
"await",179
"base",180
"bool",181
"break",182
"case",183
"catch",184
"class",185
"const",186
"continue",187
"default",188
"delegate",189
"do",190
"else",191
"enum",192
"event",193
"false",194
"finally",195
"for",196
"foreach",197
"get",198
"if",199
"in",200
"int",201
"interface",202
"internal",203
"is",204
"new",205
"null",206
"object",207
"out",208
"override",209
"private",210
"protected",211
"public",212
"readonly",213
"ref",214
"return",215
"sealed",216
"set",217
"static",218
"string",219
"struct",220
"switch",221
"this",222
"throw",223
"true",224
"try",225
"using",226
"var",227
"virtual",228
"void",229
"while",230
];231
const JAVA_KEYWORDS: &[&str] = &[232
"abstract",233
"boolean",234
"break",235
"case",236
"catch",237
"char",238
"class",239
"const",240
"continue",241
"default",242
"do",243
"double",244
"else",245
"enum",246
"extends",247
"false",248
"final",249
"finally",250
"float",251
"for",252
"if",253
"implements",254
"import",255
"instanceof",256
"int",257
"interface",258
"long",259
"new",260
"null",261
"package",262
"private",263
"protected",264
"public",265
"return",266
"static",267
"super",268
"switch",269
"this",270
"throw",271
"throws",272
"true",273
"try",274
"var",275
"void",276
"while",277
];278
const JS_KEYWORDS: &[&str] = &[279
"as",280
"async",281
"await",282
"break",283
"case",284
"catch",285
"class",286
"const",287
"continue",288
"default",289
"delete",290
"do",291
"else",292
"enum",293
"export",294
"extends",295
"false",296
"finally",297
"for",298
"from",299
"function",300
"if",301
"implements",302
"import",303
"in",304
"instanceof",305
"interface",306
"let",307
"new",308
"null",309
"of",310
"private",311
"protected",312
"public",313
"readonly",314
"return",315
"static",316
"super",317
"switch",318
"this",319
"throw",320
"true",321
"try",322
"type",323
"typeof",324
"undefined",325
"var",326
"void",327
"while",328
"yield",329
];330
const DART_KEYWORDS: &[&str] = &[331
"abstract",332
"async",333
"await",334
"break",335
"case",336
"catch",337
"class",338
"const",339
"continue",340
"default",341
"do",342
"else",343
"enum",344
"extends",345
"false",346
"final",347
"finally",348
"for",349
"if",350
"implements",351
"import",352
"in",353
"is",354
"late",355
"new",356
"null",357
"required",358
"return",359
"static",360
"super",361
"switch",362
"this",363
"throw",364
"true",365
"try",366
"var",367
"void",368
"while",369
"with",370
"yield",371
];372
const GO_KEYWORDS: &[&str] = &[373
"break",374
"case",375
"chan",376
"const",377
"continue",378
"default",379
"defer",380
"else",381
"fallthrough",382
"for",383
"func",384
"go",385
"goto",386
"if",387
"import",388
"interface",389
"map",390
"package",391
"range",392
"return",393
"select",394
"struct",395
"switch",396
"type",397
"var",398
"true",399
"false",400
"nil",401
"iota",402
];403
const KOTLIN_KEYWORDS: &[&str] = &[404
"as",405
"break",406
"class",407
"continue",408
"data",409
"do",410
"else",411
"false",412
"for",413
"fun",414
"if",415
"import",416
"in",417
"interface",418
"is",419
"null",420
"object",421
"override",422
"package",423
"private",424
"return",425
"super",426
"this",427
"throw",428
"true",429
"try",430
"val",431
"var",432
"when",433
"while",434
];435
const RUST_KEYWORDS: &[&str] = &[436
"as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern",437
"false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub",438
"ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type",439
"unsafe", "use", "where", "while",440
];441
const SCALA_KEYWORDS: &[&str] = &[442
"abstract",443
"case",444
"catch",445
"class",446
"def",447
"do",448
"else",449
"extends",450
"false",451
"final",452
"finally",453
"for",454
"if",455
"implicit",456
"import",457
"lazy",458
"match",459
"new",460
"null",461
"object",462
"override",463
"package",464
"private",465
"protected",466
"return",467
"sealed",468
"super",469
"this",470
"throw",471
"trait",472
"true",473
"try",474
"type",475
"val",476
"var",477
"while",478
"with",479
"yield",480
];481
const SWIFT_KEYWORDS: &[&str] = &[482
"as",483
"break",484
"case",485
"catch",486
"class",487
"continue",488
"default",489
"defer",490
"do",491
"else",492
"enum",493
"extension",494
"false",495
"for",496
"func",497
"guard",498
"if",499
"import",500
"in",501
"init",502
"let",503
"nil",504
"private",505
"protocol",506
"public",507
"return",508
"self",509
"static",510
"struct",511
"switch",512
"throw",513
"throws",514
"true",515
"try",516
"var",517
"where",518
"while",519
];520
const PHP_KEYWORDS: &[&str] = &[19
"abstract",521
"abstract",522
"array",20
"as",523
"as",21
"async",22
"await",23
"break",524
"break",24
"case",525
"case",25
"catch",526
"catch",@@ -28,129 +529,735 @@ const C_LIKE_KEYWORDS: &[&str] = &[28
"continue",529
"continue",29
"default",530
"default",30
"do",531
"do",532
"echo",31
"else",533
"else",32
"enum",534
"elseif",33
"export",34
"extends",535
"extends",35
"false",536
"false",36
"final",537
"final",37
"finally",538
"finally",38
"fn",39
"for",539
"for",40
"from",540
"foreach",41
"func",42
"function",541
"function",43
"go",44
"if",542
"if",45
"impl",543
"implements",46
"import",544
"include",47
"in",48
"interface",545
"interface",49
"let",50
"loop",51
"match",52
"mod",53
"mut",54
"namespace",546
"namespace",55
"new",547
"new",56
"null",548
"null",57
"override",58
"package",59
"private",549
"private",60
"protected",550
"protected",61
"pub",62
"public",551
"public",63
"readonly",552
"require",64
"return",553
"return",65
"self",66
"static",554
"static",67
"struct",68
"super",69
"switch",555
"switch",70
"this",71
"throw",556
"throw",72
"trait",73
"true",557
"true",74
"try",558
"try",75
"type",76
"typeof",77
"use",559
"use",78
"using",79
"var",80
"void",81
"where",82
"while",560
"while",83
"yield",84
];561
];85
const PYTHON_KEYWORDS: &[&str] = &[562
const PYTHON_KEYWORDS: &[&str] = &[86
"and", "as", "async", "await", "break", "class", "continue", "def", "del", "elif", "else",563
"and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif",87
"except", "False", "finally", "for", "from", "if", "import", "in", "is", "lambda", "None",564
"else", "except", "False", "finally", "for", "from", "global", "if", "import", "in", "is",88
"not", "or", "pass", "raise", "return", "True", "try", "while", "with", "yield",565
"lambda", "None", "nonlocal", "not", "or", "pass", "raise", "return", "True", "try", "while",566
"with", "yield",567
];568
const RUBY_KEYWORDS: &[&str] = &[569
"and", "begin", "break", "case", "class", "def", "do", "else", "elsif", "end", "ensure",570
"false", "for", "if", "in", "module", "next", "nil", "not", "or", "require", "rescue",571
"return", "self", "super", "then", "true", "unless", "until", "when", "while", "yield",572
];573
const PERL_KEYWORDS: &[&str] = &[574
"else", "elsif", "for", "foreach", "if", "last", "local", "my", "next", "our", "package",575
"print", "require", "return", "sub", "unless", "until", "use", "while",576
];577
const R_KEYWORDS: &[&str] = &[578
"break", "else", "FALSE", "for", "function", "if", "in", "NA", "next", "NULL", "repeat",579
"return", "TRUE", "while", "library",89
];580
];90
const SHELL_KEYWORDS: &[&str] = &[581
const SHELL_KEYWORDS: &[&str] = &[91
"case", "do", "done", "elif", "else", "esac", "export", "fi", "for", "function", "if", "in",582
"case", "do", "done", "echo", "elif", "else", "esac", "exit", "export", "fi", "for",92
"local", "return", "then", "while",583
"function", "if", "in", "local", "return", "set", "then", "until", "while",584
];585
const POWERSHELL_KEYWORDS: &[&str] = &[586
"begin", "break", "catch", "class", "continue", "do", "else", "elseif", "end", "exit",587
"filter", "finally", "for", "foreach", "function", "if", "in", "param", "process", "return",588
"switch", "throw", "trap", "try", "until", "while", "$true", "$false", "$null",589
];590
const DOS_KEYWORDS: &[&str] = &[591
"call", "cd", "copy", "defined", "del", "do", "echo", "else", "endlocal", "equ", "exist",592
"exit", "for", "goto", "if", "in", "mkdir", "neq", "not", "pause", "set", "setlocal", "shift",593
"start",594
];595
const DOCKER_KEYWORDS: &[&str] = &[596
"add",597
"arg",598
"as",599
"cmd",600
"copy",601
"entrypoint",602
"env",603
"expose",604
"from",605
"healthcheck",606
"label",607
"onbuild",608
"run",609
"shell",610
"stopsignal",611
"user",612
"volume",613
"workdir",93
];614
];94
const SQL_KEYWORDS: &[&str] = &[615
const SQL_KEYWORDS: &[&str] = &[95
"and", "as", "by", "create", "delete", "from", "group", "insert", "into", "join", "left",616
"alter", "and", "as", "asc", "between", "by", "case", "create", "delete", "desc", "distinct",96
"not", "null", "on", "or", "order", "select", "set", "table", "update", "values", "where",617
"drop", "else", "end", "exists", "from", "group", "having", "in", "inner", "insert", "into",618
"is", "join", "left", "like", "limit", "not", "null", "on", "or", "order", "outer", "right",619
"select", "set", "table", "then", "union", "update", "values", "when", "where", "with",620
];621
const KQL_KEYWORDS: &[&str] = &[622
"and",623
"asc",624
"by",625
"count",626
"desc",627
"distinct",628
"extend",629
"join",630
"let",631
"limit",632
"or",633
"order",634
"project",635
"render",636
"sort",637
"summarize",638
"take",639
"top",640
"union",641
"where",642
];643
const GRAPHQL_KEYWORDS: &[&str] = &[644
"enum",645
"extend",646
"false",647
"fragment",648
"implements",649
"input",650
"interface",651
"mutation",652
"null",653
"on",654
"query",655
"scalar",656
"schema",657
"subscription",658
"true",659
"type",660
"union",661
];662
const HTTP_KEYWORDS: &[&str] = &[663
"CONNECT", "DELETE", "GET", "HEAD", "HTTP", "OPTIONS", "PATCH", "POST", "PUT", "TRACE",664
];665
const VB_KEYWORDS: &[&str] = &[666
"and", "as", "boolean", "byval", "byref", "call", "case", "class", "const", "dim", "do",667
"each", "else", "elseif", "end", "exit", "false", "for", "function", "if", "imports", "in",668
"integer", "is", "loop", "module", "new", "next", "not", "nothing", "or", "private", "public",669
"return", "select", "set", "string", "sub", "then", "to", "true", "while", "with",670
];671
const VERILOG_KEYWORDS: &[&str] = &[672
"always",673
"assign",674
"begin",675
"case",676
"else",677
"end",678
"endcase",679
"endmodule",680
"for",681
"if",682
"initial",683
"input",684
"integer",685
"module",686
"negedge",687
"output",688
"parameter",689
"posedge",690
"reg",691
"wire",692
];693
const VHDL_KEYWORDS: &[&str] = &[694
"architecture",695
"begin",696
"case",697
"downto",698
"else",699
"elsif",700
"end",701
"entity",702
"for",703
"generic",704
"if",705
"in",706
"is",707
"library",708
"loop",709
"map",710
"of",711
"others",712
"out",713
"port",714
"process",715
"signal",716
"then",717
"to",718
"use",719
"variable",720
"when",721
"while",722
];723
const OCTAVE_KEYWORDS: &[&str] = &[724
"break",725
"case",726
"catch",727
"continue",728
"else",729
"elseif",730
"end",731
"for",732
"function",733
"if",734
"otherwise",735
"return",736
"switch",737
"try",738
"while",739
];740
const LISP_KEYWORDS: &[&str] = &[741
"cond",742
"defmacro",743
"defparameter",744
"defun",745
"defvar",746
"if",747
"lambda",748
"let",749
"nil",750
"progn",751
"quote",752
"setf",753
"setq",754
"t",755
"unless",756
"when",97
];757
];758
const LITERALS: &[&str] = &["true", "false", "null", "yes", "no", "on", "off", "~"];98
759
99
const C_LIKE: Grammar = Grammar {760
const C: Grammar = Grammar {100
line_comments: &["//"],761
types: &[101
block_comment: Some(("/*", "*/")),762
"size_t", "int8_t", "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t", "uint32_t",102
keywords: C_LIKE_KEYWORDS,763
"uint64_t", "FILE", "printf", "scanf", "malloc", "free", "memcpy", "strlen", "BOOL", "YES",103
char_quotes: false,764
"NO", "id", "NSString", "NSLog",765
],766
char_quotes: true,767
..c_style(C_KEYWORDS)768
};769
const CPP: Grammar = Grammar {770
types: &[771
"std",772
"string",773
"vector",774
"map",775
"set",776
"size_t",777
"cout",778
"cin",779
"endl",780
"unique_ptr",781
"shared_ptr",782
"make_unique",783
"make_shared",784
"printf",785
],786
char_quotes: true,787
..c_style(CPP_KEYWORDS)788
};789
const CSHARP: Grammar = Grammar {790
types: &[791
"byte",792
"char",793
"decimal",794
"double",795
"float",796
"long",797
"Console",798
"List",799
"Dictionary",800
"Task",801
"DateTime",802
"Exception",803
"nameof",804
],805
char_quotes: true,806
..c_style(CSHARP_KEYWORDS)807
};808
const JAVA: Grammar = Grammar {809
types: &[810
"byte",811
"short",812
"String",813
"Integer",814
"Long",815
"Double",816
"Boolean",817
"Object",818
"List",819
"Map",820
"ArrayList",821
"HashMap",822
"System",823
"Exception",824
"Override",825
],826
char_quotes: true,827
..c_style(JAVA_KEYWORDS)828
};829
const RUST: Grammar = Grammar {830
types: &[831
"i8",832
"i16",833
"i32",834
"i64",835
"i128",836
"isize",837
"u8",838
"u16",839
"u32",840
"u64",841
"u128",842
"usize",843
"f32",844
"f64",845
"bool",846
"char",847
"str",848
"String",849
"Vec",850
"Option",851
"Some",852
"None",853
"Result",854
"Ok",855
"Err",856
"Box",857
"Rc",858
"Arc",859
"println",860
"print",861
"format",862
"vec",863
"panic",864
"assert",865
"assert_eq",866
],867
char_quotes: true,868
..c_style(RUST_KEYWORDS)869
};870
const KOTLIN: Grammar = Grammar {871
types: &[872
"Int", "Long", "Double", "Boolean", "String", "Unit", "Any", "List", "Map", "println",873
"listOf", "mapOf", "setOf",874
],875
char_quotes: true,876
..c_style(KOTLIN_KEYWORDS)104
};877
};105
const CHAR_LIKE: Grammar = Grammar {878
const SCALA: Grammar = Grammar {879
types: &[880
"Int", "Long", "Double", "Boolean", "String", "Unit", "Any", "List", "Map", "Option",881
"Some", "None", "println",882
],106
char_quotes: true,883
char_quotes: true,107
..C_LIKE884
..c_style(SCALA_KEYWORDS)885
};886
const JS: Grammar = Grammar {887
types: &[888
"console", "document", "window", "Promise", "Array", "Object", "JSON", "Math", "Date",889
"Error", "Map", "Set", "string", "number", "boolean", "any", "unknown", "never", "require",890
"module",891
],892
..c_style(JS_KEYWORDS)893
};894
const DART: Grammar = Grammar {895
types: &[896
"int", "double", "num", "String", "bool", "List", "Map", "Set", "dynamic", "Future",897
"Stream", "print",898
],899
..c_style(DART_KEYWORDS)900
};901
const GO: Grammar = Grammar {902
types: &[903
"bool",904
"byte",905
"complex64",906
"complex128",907
"error",908
"float32",909
"float64",910
"int",911
"int8",912
"int16",913
"int32",914
"int64",915
"rune",916
"string",917
"uint",918
"uint8",919
"uint16",920
"uint32",921
"uint64",922
"uintptr",923
"any",924
"append",925
"cap",926
"close",927
"copy",928
"delete",929
"len",930
"make",931
"new",932
"panic",933
"print",934
"println",935
"recover",936
],937
..c_style(GO_KEYWORDS)938
};939
const SWIFT: Grammar = Grammar {940
types: &[941
"Int",942
"Double",943
"Float",944
"Bool",945
"String",946
"Character",947
"Array",948
"Dictionary",949
"Set",950
"Optional",951
"Any",952
"print",953
],954
..c_style(SWIFT_KEYWORDS)955
};956
const CSS: Grammar = Grammar {957
keys: true,958
dashed_words: true,959
..c_style(&[])108
};960
};109
const HASH: Grammar = Grammar {961
const JSON: Grammar = Grammar {110
line_comments: &["#"],962
keys: true,963
..c_style(LITERALS)964
};965
const VERILOG: Grammar = Grammar {966
types: &["$display", "$finish", "$time", "logic", "bit"],967
..c_style(VERILOG_KEYWORDS)968
};969
const PHP: Grammar = Grammar {970
types: &[971
"$this",972
"array",973
"count",974
"isset",975
"empty",976
"strlen",977
"json_encode",978
"json_decode",979
"var_dump",980
"print_r",981
],982
line_comments: &["//", "#"],983
..c_style(PHP_KEYWORDS)984
};985
const KQL: Grammar = Grammar {986
types: &[987
"ago", "now", "datetime", "bin", "dcount", "tostring", "toint", "strcat", "count", "sum",988
"avg",989
],111
block_comment: None,990
block_comment: None,112
keywords: PYTHON_KEYWORDS,991
case_insensitive: true,113
char_quotes: false,992
..c_style(KQL_KEYWORDS)993
};994
const PYTHON: Grammar = Grammar {995
types: &[996
"self",997
"cls",998
"print",999
"len",1000
"range",1001
"int",1002
"str",1003
"float",1004
"bool",1005
"bytes",1006
"list",1007
"dict",1008
"set",1009
"tuple",1010
"object",1011
"open",1012
"super",1013
"isinstance",1014
"enumerate",1015
"zip",1016
"map",1017
"filter",1018
"sorted",1019
"sum",1020
"min",1021
"max",1022
"abs",1023
"type",1024
"Exception",1025
],1026
..hash_style(PYTHON_KEYWORDS)1027
};1028
const RUBY: Grammar = Grammar {1029
types: &[1030
"puts",1031
"print",1032
"p",1033
"attr_accessor",1034
"attr_reader",1035
"attr_writer",1036
"lambda",1037
"proc",1038
"raise",1039
],1040
..hash_style(RUBY_KEYWORDS)1041
};1042
const PERL: Grammar = Grammar {1043
types: &[1044
"chomp", "die", "join", "keys", "push", "shift", "split", "values", "open", "close",1045
],1046
..hash_style(PERL_KEYWORDS)1047
};1048
const R: Grammar = Grammar {1049
types: &[1050
"c", "list", "print", "paste", "length", "vector", "matrix", "sum", "mean", "cat",1051
],1052
..hash_style(R_KEYWORDS)114
};1053
};115
const SHELL: Grammar = Grammar {1054
const SHELL: Grammar = Grammar {116
line_comments: &["#"],1055
types: &[117
block_comment: None,1056
"cd", "ls", "pwd", "grep", "sed", "awk", "cat", "cp", "mv", "rm", "mkdir", "touch",118
keywords: SHELL_KEYWORDS,1057
"chmod", "sudo", "git", "docker", "kubectl", "curl", "wget", "read", "printf", "source",119
char_quotes: false,1058
"test", "true", "false",1059
],1060
..hash_style(SHELL_KEYWORDS)1061
};1062
const YAML: Grammar = Grammar {1063
keys: true,1064
..hash_style(LITERALS)1065
};1066
const GRAPHQL: Grammar = Grammar {1067
types: &["String", "Int", "Float", "Boolean", "ID"],1068
..hash_style(GRAPHQL_KEYWORDS)1069
};1070
const DOCKER: Grammar = Grammar {1071
case_insensitive: true,1072
..hash_style(DOCKER_KEYWORDS)1073
};1074
const POWERSHELL: Grammar = Grammar {1075
dashed_words: true,1076
block_comment: Some(("<#", "#>")),1077
case_insensitive: true,1078
..hash_style(POWERSHELL_KEYWORDS)1079
};1080
const DOS: Grammar = Grammar {1081
line_comments: &["::", "rem ", "REM ", "@rem "],1082
case_insensitive: true,1083
keywords: DOS_KEYWORDS,1084
..CODE120
};1085
};121
const SQL: Grammar = Grammar {1086
const SQL: Grammar = Grammar {1087
types: &[1088
"int",1089
"integer",1090
"bigint",1091
"varchar",1092
"char",1093
"text",1094
"date",1095
"timestamp",1096
"boolean",1097
"decimal",1098
"count",1099
"sum",1100
"avg",1101
"min",1102
"max",1103
"coalesce",1104
"now",1105
],122
line_comments: &["--"],1106
line_comments: &["--"],123
block_comment: Some(("/*", "*/")),1107
block_comment: Some(("/*", "*/")),124
keywords: SQL_KEYWORDS,1108
keywords: SQL_KEYWORDS,125
char_quotes: false,1109
case_insensitive: true,1110
..CODE126
};1111
};127
const MARKUP: Grammar = Grammar {1112
const VHDL: Grammar = Grammar {128
line_comments: &[],1113
types: &[129
block_comment: Some(("<!--", "-->")),1114
"std_logic",130
keywords: &[],1115
"std_logic_vector",131
char_quotes: false,1116
"integer",1117
"boolean",1118
"unsigned",1119
"signed",1120
"rising_edge",1121
],1122
line_comments: &["--"],1123
keywords: VHDL_KEYWORDS,1124
case_insensitive: true,1125
..CODE1126
};1127
const VB: Grammar = Grammar {1128
line_comments: &["'", "rem ", "REM "],1129
keywords: VB_KEYWORDS,1130
case_insensitive: true,1131
..CODE1132
};1133
const OCTAVE: Grammar = Grammar {1134
types: &[1135
"disp", "zeros", "ones", "size", "numel", "length", "plot", "printf", "fprintf", "true",1136
"false",1137
],1138
line_comments: &["%", "#"],1139
block_comment: Some(("%{", "%}")),1140
keywords: OCTAVE_KEYWORDS,1141
..CODE1142
};1143
const LISP: Grammar = Grammar {1144
types: &[1145
"car", "cdr", "cons", "list", "format", "print", "append", "mapcar", "funcall", "apply",1146
],1147
line_comments: &[";"],1148
block_comment: Some(("#|", "|#")),1149
keywords: LISP_KEYWORDS,1150
..CODE1151
};1152
const HTTP: Grammar = Grammar {1153
keys: true,1154
dashed_words: true,1155
keywords: HTTP_KEYWORDS,1156
..CODE1157
};1158
const LATEX: Grammar = Grammar {1159
line_comments: &["%"],1160
command_prefix: Some('\\'),1161
..CODE132
};1162
};133
1163
134
fn grammar_for(language: &str) -> Option<&'static Grammar> {1164
enum Rules {135
match language.to_ascii_lowercase().as_str() {1165
Code(&'static Grammar),136
"rust" | "rs" | "c" | "cpp" | "c++" | "csharp" | "cs" | "c#" | "java" | "go" | "kotlin"1166
Markup,137
| "scala" => Some(&CHAR_LIKE),1167
Markdown,138
"javascript" | "js" | "jsx" | "typescript" | "ts" | "tsx" | "swift" | "php" | "json"1168
}139
| "css" | "scss" | "less" | "dart" => Some(&C_LIKE),1169
140
"python" | "py" | "ruby" | "rb" | "yaml" | "yml" | "toml" | "r" | "perl" | "dockerfile"1170
/// The rules for a code block language: one arm per Teams language id (see141
| "makefile" => Some(&HASH),1171
/// `teams_core::CODE_LANGUAGES`); a language without an arm stays plain.142
"bash" | "sh" | "shell" | "zsh" | "powershell" | "ps1" => Some(&SHELL),1172
fn rules_for(language: &str) -> Option<Rules> {143
"sql" | "tsql" | "plsql" | "lua" => Some(&SQL),1173
let id = teams_core::code_language(language).map_or_else(144
"html" | "xml" | "svg" | "markdown" | "md" => Some(&MARKUP),1174
|| language.to_ascii_lowercase(),145
_ => None,1175
|known| known.id.to_ascii_lowercase(),146
}1176
);1177
let grammar = match id.as_str() {1178
"html" | "xml" | "jsp" => return Some(Rules::Markup),1179
"markdown" => return Some(Rules::Markdown),1180
"bash" => &SHELL,1181
"c" | "objectivec" => &C,1182
"cpp" => &CPP,1183
"csharp" => &CSHARP,1184
"css" | "scss" | "less" => &CSS,1185
"dart" => &DART,1186
"dockerfile" => &DOCKER,1187
"dos" => &DOS,1188
"go" => &GO,1189
"graphql" => &GRAPHQL,1190
"http" => &HTTP,1191
"java" => &JAVA,1192
"javascript" | "jsx" | "typescript" => &JS,1193
"json" => &JSON,1194
"kotlin" => &KOTLIN,1195
"kql" => &KQL,1196
"latex" => &LATEX,1197
"lisp" => &LISP,1198
"octave" => &OCTAVE,1199
"perl" => &PERL,1200
"php" => &PHP,1201
"powershell" => &POWERSHELL,1202
"python" => &PYTHON,1203
"r" => &R,1204
"ruby" => &RUBY,1205
"rust" => &RUST,1206
"scala" => &SCALA,1207
"sql" | "tsql" | "plsql" => &SQL,1208
"swift" => &SWIFT,1209
"vbnet" | "vbscript" => &VB,1210
"verilog" => &VERILOG,1211
"vhdl" => &VHDL,1212
"yaml" | "toml" => &YAML,1213
_ => return None,1214
};1215
Some(Rules::Code(grammar))147
}1216
}148
1217
149
pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)>> {1218
pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)>> {150
let grammar = grammar_for(language)?;1219
Some(match rules_for(language)? {151
let sql = grammar.keywords == SQL_KEYWORDS;1220
Rules::Code(grammar) => highlight_code(code, grammar),1221
Rules::Markup => highlight_markup(code),1222
Rules::Markdown => highlight_markdown(code),1223
})1224
}1225
1226
/// Keywords whose next word is the name being defined.1227
const DEFINITIONS: &[&str] = &[1228
"class",1229
"def",1230
"enum",1231
"fn",1232
"fun",1233
"func",1234
"function",1235
"interface",1236
"module",1237
"object",1238
"protocol",1239
"struct",1240
"sub",1241
"trait",1242
"type",1243
];1244
1245
/// Only spaces, or a YAML list dash, before `at` on its line.1246
fn starts_line(code: &str, at: usize) -> bool {1247
let line = &code[code[..at].rfind('\n').map_or(0, |end| end + 1)..at];1248
matches!(line.trim(), "" | "-")1249
}1250
1251
/// Followed by `:` (not `::`) after optional spaces.1252
fn before_colon(code: &str, end: usize) -> bool {1253
let rest = code[end..].trim_start_matches([' ', '\t']);1254
rest.starts_with(':') && !rest.starts_with("::")1255
}1256
1257
fn highlight_code(code: &str, grammar: &Grammar) -> Vec<(Range<usize>, Token)> {152
let mut tokens = Vec::new();1258
let mut tokens = Vec::new();153
let mut index = 0;1259
let mut index = 0;1260
let mut defines = false;154
while index < code.len() {1261
while index < code.len() {155
let rest = &code[index..];1262
let rest = &code[index..];156
if let Some((open, close)) = grammar.block_comment1263
if let Some((open, close)) = grammar.block_comment@@ -163,11 +1270,12 @@ pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)163
index = end;1270
index = end;164
continue;1271
continue;165
}1272
}166
if grammar1273
let line_start = index == 0 || code.as_bytes()[index - 1] == b'\n';167
.line_comments1274
if grammar.line_comments.iter().any(|marker| {168
.iter()1275
rest.starts_with(marker)169
.any(|marker| rest.starts_with(marker))1276
// A word comment such as `rem ` only counts at the start of a line.170
{1277
&& (!marker.ends_with(' ') || line_start || code[..index].ends_with(' '))1278
}) {171
let end = rest.find('\n').map_or(code.len(), |offset| index + offset);1279
let end = rest.find('\n').map_or(code.len(), |offset| index + offset);172
tokens.push((index..end, Token::Comment));1280
tokens.push((index..end, Token::Comment));173
index = end;1281
index = end;@@ -180,7 +1288,11 @@ pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)180
}1288
}181
if matches!(character, '"' | '\'' | '`') {1289
if matches!(character, '"' | '\'' | '`') {182
let end = string_end(code, index, character);1290
let end = string_end(code, index, character);183
tokens.push((index..end, Token::String));1291
let key = grammar.keys && before_colon(code, end);1292
tokens.push((1293
index..end,1294
if key { Token::Attribute } else { Token::String },1295
));184
index = end;1296
index = end;185
continue;1297
continue;186
}1298
}@@ -192,28 +1304,190 @@ pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)192
index += length;1304
index += length;193
continue;1305
continue;194
}1306
}195
if character.is_alphabetic() || character == '_' {1307
let command = grammar.command_prefix == Some(character);196
let length = rest1308
if character.is_alphabetic() || matches!(character, '_' | '$' | '@' | '#') || command {197
.find(|next: char| !(next.is_alphanumeric() || next == '_'))1309
let dashed = grammar.dashed_words;198
.unwrap_or(rest.len());1310
let length = character.len_utf8()1311
+ rest[character.len_utf8()..]1312
.find(|next: char| {1313
!(next.is_alphanumeric() || next == '_' || dashed && next == '-')1314
})1315
.unwrap_or(rest.len() - character.len_utf8());1316
let length = rest[..length].trim_end_matches('-').len();199
let word = &rest[..length];1317
let word = &rest[..length];200
let is_keyword = if sql {1318
let same = |known: &&str| {201
grammar1319
if grammar.case_insensitive {202
.keywords1320
known.eq_ignore_ascii_case(word)203
.iter()1321
} else {204
.any(|keyword| keyword.eq_ignore_ascii_case(word))1322
*known == word1323
}1324
};1325
let end = index + length;1326
let token = if command && length > 1 || grammar.keywords.iter().any(same) {1327
Some(Token::Keyword)1328
} else if grammar.keys && starts_line(code, index) && before_colon(code, end) {1329
Some(Token::Attribute)1330
} else if defines {1331
Some(Token::Title)1332
} else if grammar.types.iter().any(same) || dashed && word.contains('-') {1333
Some(Token::Type)205
} else {1334
} else {206
grammar.keywords.contains(&word)1335
None207
};1336
};208
if is_keyword {1337
defines = token == Some(Token::Keyword) && DEFINITIONS.iter().any(same);209
tokens.push((index..index + length, Token::Keyword));1338
tokens.extend(token.map(|token| (index..end, token)));210
}1339
index = end;211
index += length;212
continue;1340
continue;213
}1341
}1342
if !character.is_whitespace() {1343
defines = false;1344
}214
index += character.len_utf8();1345
index += character.len_utf8();215
}1346
}216
Some(tokens)1347
tokens1348
}1349
1350
/// HTML and XML: tag names, attribute names, quoted values and comments.1351
fn highlight_markup(code: &str) -> Vec<(Range<usize>, Token)> {1352
let mut tokens = Vec::new();1353
let mut index = 0;1354
while let Some(offset) = code[index..].find('<') {1355
let start = index + offset;1356
let rest = &code[start..];1357
if rest.starts_with("<!--") {1358
let end = rest.find("-->").map_or(code.len(), |at| start + at + 3);1359
tokens.push((start..end, Token::Comment));1360
index = end;1361
continue;1362
}1363
let name_start = start + 1 + usize::from(rest[1..].starts_with(['/', '!', '?']));1364
let name_end = name_start1365
+ code[name_start..]1366
.find(|next: char| {1367
!(next.is_alphanumeric() || matches!(next, '-' | ':' | '_' | '.'))1368
})1369
.unwrap_or(code.len() - name_start);1370
if name_end == name_start {1371
index = start + 1;1372
continue;1373
}1374
tokens.push((name_start..name_end, Token::Tag));1375
let close = code[name_end..]1376
.find('>')1377
.map_or(code.len(), |at| name_end + at);1378
let mut at = name_end;1379
while at < close {1380
let character = code[at..].chars().next().unwrap_or_default();1381
if matches!(character, '"' | '\'') {1382
let end = code[at + 1..close]1383
.find(character)1384
.map_or(close, |end| at + 1 + end + 1);1385
tokens.push((at..end, Token::String));1386
at = end;1387
} else if character.is_alphabetic() {1388
let end = at1389
+ code[at..close]1390
.find(|next: char| {1391
!(next.is_alphanumeric() || matches!(next, '-' | ':' | '_'))1392
})1393
.unwrap_or(close - at);1394
tokens.push((at..end, Token::Attribute));1395
at = end;1396
} else {1397
at += character.len_utf8();1398
}1399
}1400
index = (close + 1).min(code.len());1401
}1402
tokens1403
}1404
1405
/// Markdown by line: headings, quotes, list markers, fenced code, then inline code, bold,1406
/// italic and links.1407
fn highlight_markdown(code: &str) -> Vec<(Range<usize>, Token)> {1408
let mut tokens = Vec::new();1409
let mut fenced = false;1410
let mut start = 0;1411
for line in code.split('\n') {1412
let range = start..start + line.len();1413
start = range.end + 1;1414
let trimmed = line.trim_start();1415
let indent = range.start + line.len() - trimmed.len();1416
if trimmed.starts_with("```") || trimmed.starts_with("~~~") {1417
fenced = !fenced;1418
tokens.push((range, Token::String));1419
continue;1420
}1421
if fenced {1422
tokens.push((range, Token::String));1423
continue;1424
}1425
let hashes = trimmed.bytes().take_while(|byte| *byte == b'#').count();1426
if (1..=6).contains(&hashes) && trimmed[hashes..].starts_with(' ') {1427
tokens.push((range, Token::Heading));1428
continue;1429
}1430
if trimmed.starts_with('>') {1431
tokens.push((range, Token::Comment));1432
continue;1433
}1434
let marker = list_marker(trimmed);1435
if marker > 0 {1436
tokens.push((indent..indent + marker, Token::Keyword));1437
}1438
inline_markdown(code, indent + marker..range.end, &mut tokens);1439
}1440
tokens1441
}1442
1443
/// Byte length of a `- `, `* `, `+ ` or `1. ` list marker.1444
fn list_marker(line: &str) -> usize {1445
if line.starts_with(['-', '*', '+']) && line[1..].starts_with(' ') {1446
return 1;1447
}1448
let digits = line.bytes().take_while(u8::is_ascii_digit).count();1449
if digits > 0 && line[digits..].starts_with(". ") {1450
digits + 11451
} else {1452
01453
}1454
}1455
1456
fn inline_markdown(code: &str, range: Range<usize>, tokens: &mut Vec<(Range<usize>, Token)>) {1457
let mut index = range.start;1458
while index < range.end {1459
let rest = &code[index..range.end];1460
let span = |open: &str, close: &str| {1461
rest.strip_prefix(open)?1462
.find(close)1463
.filter(|length| *length > 0)1464
.map(|length| index + open.len() + length + close.len())1465
};1466
let found = if rest.starts_with('`') {1467
span("`", "`").map(|end| (end, Token::String))1468
} else if rest.starts_with("**") || rest.starts_with("__") {1469
span(&rest[..2], &rest[..2]).map(|end| (end, Token::Strong))1470
} else if rest.starts_with(['*', '_']) {1471
span(&rest[..1], &rest[..1]).map(|end| (end, Token::Emphasis))1472
} else if rest.starts_with('[') {1473
rest.find("](")1474
.and_then(|label| {1475
rest[label..]1476
.find(')')1477
.map(|close| index + label + close + 1)1478
})1479
.map(|end| (end, Token::Link))1480
} else {1481
None1482
};1483
match found {1484
Some((end, token)) => {1485
tokens.push((index..end, token));1486
index = end;1487
}1488
None => index += rest.chars().next().map_or(1, char::len_utf8),1489
}1490
}217
}1491
}218
1492
219
fn is_char_literal(rest: &str) -> bool {1493
fn is_char_literal(rest: &str) -> bool {@@ -261,6 +1535,7 @@ mod tests {261
vec![1535
vec![262
("// x", Token::Comment),1536
("// x", Token::Comment),263
("fn", Token::Keyword),1537
("fn", Token::Keyword),1538
("a", Token::Title),264
("\"b\"", Token::String),1539
("\"b\"", Token::String),265
]1540
]266
);1541
);@@ -283,7 +1558,13 @@ mod tests {283
fn rust_lifetime_is_not_a_string() {1558
fn rust_lifetime_is_not_a_string() {284
assert_eq!(1559
assert_eq!(285
kinds("fn a<'b>(x: &'b str) -> char { 'c' }", "rust"),1560
kinds("fn a<'b>(x: &'b str) -> char { 'c' }", "rust"),286
vec![("fn", Token::Keyword), ("'c'", Token::String),]1561
vec![1562
("fn", Token::Keyword),1563
("a", Token::Title),1564
("str", Token::Type),1565
("char", Token::Type),1566
("'c'", Token::String),1567
]287
);1568
);288
assert_eq!(kinds(r"'\n'", "rust"), vec![(r"'\n'", Token::String)]);1569
assert_eq!(kinds(r"'\n'", "rust"), vec![(r"'\n'", Token::String)]);289
}1570
}@@ -296,6 +1577,7 @@ mod tests {296
#[test]1577
#[test]297
fn unknown_language_has_no_highlight() {1578
fn unknown_language_has_no_highlight() {298
assert!(highlight("x", "brainfuck").is_none());1579
assert!(highlight("x", "brainfuck").is_none());1580
assert!(highlight("x", "plaintext").is_none());299
}1581
}300
1582
301
#[test]1583
#[test]@@ -307,4 +1589,102 @@ mod tests {307
.any(|(text, _)| *text == "1")1589
.any(|(text, _)| *text == "1")308
);1590
);309
}1591
}1592
1593
#[test]1594
fn every_teams_language_but_plain_text_has_rules() {1595
let missing: Vec<_> = teams_core::CODE_LANGUAGES1596
.iter()1597
.filter(|language| language.id != teams_core::PLAIN_LANGUAGE)1598
.filter(|language| rules_for(language.id).is_none())1599
.map(|language| language.id)1600
.collect();1601
assert!(missing.is_empty(), "no highlighting for {missing:?}");1602
}1603
1604
#[test]1605
fn markup_colours_tags_attributes_and_values() {1606
assert_eq!(1607
kinds("<a href=\"x\">t</a><!-- c -->", "html"),1608
vec![1609
("a", Token::Tag),1610
("href", Token::Attribute),1611
("\"x\"", Token::String),1612
("a", Token::Tag),1613
("<!-- c -->", Token::Comment),1614
]1615
);1616
}1617
1618
#[test]1619
fn markdown_colours_its_blocks_and_inline_marks() {1620
assert_eq!(1621
kinds(1622
"# Title\n- **b** and *i* `c` [l](u)\n> q\n```\nx\n```",1623
"md"1624
),1625
vec", Token::Link),1632
("> q", Token::Comment),1633
("```", Token::String),1634
("x", Token::String),1635
("```", Token::String),1636
]1637
);1638
}1639
1640
#[test]1641
fn definitions_types_and_keys() {1642
assert_eq!(1643
kinds("def f(self): print(1)", "python"),1644
vec![1645
("def", Token::Keyword),1646
("f", Token::Title),1647
("self", Token::Type),1648
("print", Token::Type),1649
("1", Token::Number),1650
]1651
);1652
assert_eq!(1653
kinds("func ok() bool", "go"),1654
vec![1655
("func", Token::Keyword),1656
("ok", Token::Title),1657
("bool", Token::Type)1658
]1659
);1660
assert_eq!(1661
kinds("{\"a\": \"b\"}", "json"),1662
vec![("\"a\"", Token::Attribute), ("\"b\"", Token::String)]1663
);1664
assert_eq!(1665
kinds("name: x\nurl: http://y", "yaml"),1666
vec![("name", Token::Attribute), ("url", Token::Attribute)]1667
);1668
assert_eq!(1669
kinds(" font-size: 2px;", "css")[0],1670
("font-size", Token::Attribute)1671
);1672
assert_eq!(1673
kinds("Get-ChildItem -Path .", "powershell")[0],1674
("Get-ChildItem", Token::Type)1675
);1676
}1677
1678
#[test]1679
fn word_comments_and_latex_commands() {1680
assert_eq!(1681
kinds("rem x\necho", "dos"),1682
vec![("rem x", Token::Comment), ("echo", Token::Keyword)]1683
);1684
assert_eq!(1685
kinds("\\section{a} % c", "latex"),1686
vec![("\\section", Token::Keyword), ("% c", Token::Comment)]1687
);1688
assert_eq!(kinds("FROM x", "dockerFile")[0], ("FROM", Token::Keyword));1689
}310
}1690
}@@ -143,5 +143,10 @@ mod tests {
143
143
tr("settings.calendar.not_in_build"),
144
144
"Google Kalender ist in diesem Build nicht enthalten."
145
145
);
146
assert_eq!(
147
tr("settings.calendar.google_client_status_own"),
148
"Eigener Client"
149
);
150
assert!(tr("settings.calendar.google_client_guide_5").contains("«Google verbinden»"));
146
151
}
147
152
}
@@ -143,5 +143,10 @@ mod tests {143
tr("settings.calendar.not_in_build"),143
tr("settings.calendar.not_in_build"),144
"Google Kalender ist in diesem Build nicht enthalten."144
"Google Kalender ist in diesem Build nicht enthalten."145
);145
);146
assert_eq!(147
tr("settings.calendar.google_client_status_own"),148
"Eigener Client"149
);150
assert!(tr("settings.calendar.google_client_guide_5").contains("«Google verbinden»"));146
}151
}147
}152
}@@ -2,6 +2,7 @@ use std::cell::Cell;
2
2
use std::rc::Rc;
3
3
4
4
use gpui_kit::*;
5
use session::trusted_url::{HostRule, trusted_https_url};
5
6
6
7
#[cfg(windows)]
7
8
mod native_windows;
@@ -17,18 +18,20 @@ pub use native::available;
17
18
#[cfg(windows)]
18
19
pub use native::configure;
19
20
21
const SHAREPOINT_DOMAIN: &str = "sharepoint.com";
22
const SHAREPOINT_HOSTS: [HostRule; 1] = [HostRule::Domain(SHAREPOINT_DOMAIN)];
20
23
const PERSONAL_SITE: &str = "/personal/";
21
24
const TEAM_SITES: [&str; 2] = ["/sites/", "/teams/"];
22
25
const PLAYER_OPTIONS: &str = "%7B%22ust%22%3Atrue%2C%22hv%22%3A%22CopyEmbedCode%22%7D";
23
26
24
27
/// SharePoint's embeddable player for a video stored in OneDrive or a team site.
25
28
pub fn player_url(content_url: &str) -> Option<String> {
26
let rest = content_url.strip_prefix("https://")?;
27
let (host, path) = rest.split_once('/')?;
28
if !host.ends_with(".sharepoint.com") {
29
let parsed = trusted_https_url(content_url, &SHAREPOINT_HOSTS)?;
30
let host = parsed.host_str()?;
31
if host == SHAREPOINT_DOMAIN {
29
32
return None;
30
33
}
31
let path = format!("/{}", path.split(['?', '#']).next()?);
34
let path = parsed.path();
32
35
let site_prefix = std::iter::once(PERSONAL_SITE)
33
36
.chain(TEAM_SITES)
34
37
.find(|prefix| path.starts_with(prefix))?;
@@ -67,7 +70,7 @@ pub fn play(key: SharedString, content_url: &str, window: &mut Window, cx: &mut
67
70
};
68
71
cx.spawn(async move |cx| {
69
72
while let Some(target) = new_windows.recv().await {
70
cx.update(|cx| cx.open_url(&target));
73
cx.update(|cx| app_base::open_link::open_url(cx, &target));
71
74
}
72
75
})
73
76
.detach();
@@ -188,6 +191,14 @@ mod tests {
188
191
#[test]
189
192
fn other_hosts_have_no_inline_player() {
190
193
assert_eq!(player_url("https://example.com/personal/a/clip.mp4"), None);
194
assert_eq!(
195
player_url("https://evil.example?a.sharepoint.com/personal/x/y.mp4"),
196
None
197
);
198
assert_eq!(
199
player_url("https://evil.example\\.sharepoint.com/personal/x/y.mp4"),
200
None
201
);
191
202
assert_eq!(player_url("https://contoso.sharepoint.com/clip.mp4"), None);
192
203
assert_eq!(
193
204
player_url("https://contoso-my.sharepoint.com/personal/"),
@@ -2,6 +2,7 @@ use std::cell::Cell;2
use std::rc::Rc;2
use std::rc::Rc;3
3
4
use gpui_kit::*;4
use gpui_kit::*;5
use session::trusted_url::{HostRule, trusted_https_url};5
6
6
#[cfg(windows)]7
#[cfg(windows)]7
mod native_windows;8
mod native_windows;@@ -17,18 +18,20 @@ pub use native::available;17
#[cfg(windows)]18
#[cfg(windows)]18
pub use native::configure;19
pub use native::configure;19
20
21
const SHAREPOINT_DOMAIN: &str = "sharepoint.com";22
const SHAREPOINT_HOSTS: [HostRule; 1] = [HostRule::Domain(SHAREPOINT_DOMAIN)];20
const PERSONAL_SITE: &str = "/personal/";23
const PERSONAL_SITE: &str = "/personal/";21
const TEAM_SITES: [&str; 2] = ["/sites/", "/teams/"];24
const TEAM_SITES: [&str; 2] = ["/sites/", "/teams/"];22
const PLAYER_OPTIONS: &str = "%7B%22ust%22%3Atrue%2C%22hv%22%3A%22CopyEmbedCode%22%7D";25
const PLAYER_OPTIONS: &str = "%7B%22ust%22%3Atrue%2C%22hv%22%3A%22CopyEmbedCode%22%7D";23
26
24
/// SharePoint's embeddable player for a video stored in OneDrive or a team site.27
/// SharePoint's embeddable player for a video stored in OneDrive or a team site.25
pub fn player_url(content_url: &str) -> Option<String> {28
pub fn player_url(content_url: &str) -> Option<String> {26
let rest = content_url.strip_prefix("https://")?;29
let parsed = trusted_https_url(content_url, &SHAREPOINT_HOSTS)?;27
let (host, path) = rest.split_once('/')?;30
let host = parsed.host_str()?;28
if !host.ends_with(".sharepoint.com") {31
if host == SHAREPOINT_DOMAIN {29
return None;32
return None;30
}33
}31
let path = format!("/{}", path.split(['?', '#']).next()?);34
let path = parsed.path();32
let site_prefix = std::iter::once(PERSONAL_SITE)35
let site_prefix = std::iter::once(PERSONAL_SITE)33
.chain(TEAM_SITES)36
.chain(TEAM_SITES)34
.find(|prefix| path.starts_with(prefix))?;37
.find(|prefix| path.starts_with(prefix))?;@@ -67,7 +70,7 @@ pub fn play(key: SharedString, content_url: &str, window: &mut Window, cx: &mut67
};70
};68
cx.spawn(async move |cx| {71
cx.spawn(async move |cx| {69
while let Some(target) = new_windows.recv().await {72
while let Some(target) = new_windows.recv().await {70
cx.update(|cx| cx.open_url(&target));73
cx.update(|cx| app_base::open_link::open_url(cx, &target));71
}74
}72
})75
})73
.detach();76
.detach();@@ -188,6 +191,14 @@ mod tests {188
#[test]191
#[test]189
fn other_hosts_have_no_inline_player() {192
fn other_hosts_have_no_inline_player() {190
assert_eq!(player_url("https://example.com/personal/a/clip.mp4"), None);193
assert_eq!(player_url("https://example.com/personal/a/clip.mp4"), None);194
assert_eq!(195
player_url("https://evil.example?a.sharepoint.com/personal/x/y.mp4"),196
None197
);198
assert_eq!(199
player_url("https://evil.example\\.sharepoint.com/personal/x/y.mp4"),200
None201
);191
assert_eq!(player_url("https://contoso.sharepoint.com/clip.mp4"), None);202
assert_eq!(player_url("https://contoso.sharepoint.com/clip.mp4"), None);192
assert_eq!(203
assert_eq!(193
player_url("https://contoso-my.sharepoint.com/personal/"),204
player_url("https://contoso-my.sharepoint.com/personal/"),@@ -220,7 +220,7 @@ pub(crate) fn notice(text: String, cx: &mut App) {
220
220
221
221
pub(crate) fn open_external(url: &str, cx: &mut App) {
222
222
let Some(handle) = cx.try_global::<AppHandle>() else {
223
cx.open_url(url);
223
app_base::open_link::open_url(cx, url);
224
224
return;
225
225
};
226
226
let store = handle.0.read(cx).store.clone();
@@ -220,7 +220,7 @@ pub(crate) fn notice(text: String, cx: &mut App) {220
220
221
pub(crate) fn open_external(url: &str, cx: &mut App) {221
pub(crate) fn open_external(url: &str, cx: &mut App) {222
let Some(handle) = cx.try_global::<AppHandle>() else {222
let Some(handle) = cx.try_global::<AppHandle>() else {223
cx.open_url(url);223
app_base::open_link::open_url(cx, url);224
return;224
return;225
};225
};226
let store = handle.0.read(cx).store.clone();226
let store = handle.0.read(cx).store.clone();@@ -1153,7 +1153,7 @@ pub fn open_ticket_link(url: &str, cx: &mut App) -> bool {
1153
1153
if is_demo(cx) {
1154
1154
match demo_detail(id) {
1155
1155
Some(detail) => cx.defer(move |cx| show_window(detail, cx)),
1156
None => cx.open_url(&url),
1156
None => app_base::open_link::open_url(cx, &url),
1157
1157
}
1158
1158
return true;
1159
1159
}
@@ -1170,7 +1170,7 @@ pub fn open_ticket_link(url: &str, cx: &mut App) -> bool {
1170
1170
forget_token(cx);
1171
1171
}
1172
1172
// Geen toegang of Asclepius niet bereikbaar: een gewone link.
1173
cx.open_url(&url);
1173
app_base::open_link::open_url(cx, &url);
1174
1174
}
1175
1175
});
1176
1176
})
@@ -1153,7 +1153,7 @@ pub fn open_ticket_link(url: &str, cx: &mut App) -> bool {1153
if is_demo(cx) {1153
if is_demo(cx) {1154
match demo_detail(id) {1154
match demo_detail(id) {1155
Some(detail) => cx.defer(move |cx| show_window(detail, cx)),1155
Some(detail) => cx.defer(move |cx| show_window(detail, cx)),1156
None => cx.open_url(&url),1156
None => app_base::open_link::open_url(cx, &url),1157
}1157
}1158
return true;1158
return true;1159
}1159
}@@ -1170,7 +1170,7 @@ pub fn open_ticket_link(url: &str, cx: &mut App) -> bool {1170
forget_token(cx);1170
forget_token(cx);1171
}1171
}1172
// Geen toegang of Asclepius niet bereikbaar: een gewone link.1172
// Geen toegang of Asclepius niet bereikbaar: een gewone link.1173
cx.open_url(&url);1173
app_base::open_link::open_url(cx, &url);1174
}1174
}1175
});1175
});1176
})1176
})@@ -74,7 +74,7 @@ pub fn spawn(clock: Arc<ParkClock>, browser: browser::Browser, endpoint: &str) {
74
74
if !browser.teams_has_msal_cache().await || !clock.due(Instant::now()) {
75
75
continue;
76
76
}
77
match park(&transport).await {
77
match park(&transport, browser.behind_mcas()).await {
78
78
Ok(true) => log::info!("Teams tab parked"),
79
79
Ok(false) => {}
80
80
Err(error) => log::warn!("parking the Teams tab failed: {error}"),
@@ -83,13 +83,13 @@ pub fn spawn(clock: Arc<ParkClock>, browser: browser::Browser, endpoint: &str) {
83
83
});
84
84
}
85
85
86
async fn park(transport: &session::CdpTransport) -> session::Result<bool> {
86
async fn park(transport: &session::CdpTransport, mcas: bool) -> session::Result<bool> {
87
87
let app = session::App::Teams;
88
88
let Some((control, _)) = transport.open(app, false).await? else {
89
89
return Ok(false);
90
90
};
91
91
control
92
.call("Page.navigate", json!({ "url": app.park_url() }))
92
.call("Page.navigate", json!({ "url": app.park_url(mcas) }))
93
93
.await?;
94
94
Ok(true)
95
95
}
@@ -74,7 +74,7 @@ pub fn spawn(clock: Arc<ParkClock>, browser: browser::Browser, endpoint: &str) {74
if !browser.teams_has_msal_cache().await || !clock.due(Instant::now()) {74
if !browser.teams_has_msal_cache().await || !clock.due(Instant::now()) {75
continue;75
continue;76
}76
}77
match park(&transport).await {77
match park(&transport, browser.behind_mcas()).await {78
Ok(true) => log::info!("Teams tab parked"),78
Ok(true) => log::info!("Teams tab parked"),79
Ok(false) => {}79
Ok(false) => {}80
Err(error) => log::warn!("parking the Teams tab failed: {error}"),80
Err(error) => log::warn!("parking the Teams tab failed: {error}"),@@ -83,13 +83,13 @@ pub fn spawn(clock: Arc<ParkClock>, browser: browser::Browser, endpoint: &str) {83
});83
});84
}84
}85
85
86
async fn park(transport: &session::CdpTransport) -> session::Result<bool> {86
async fn park(transport: &session::CdpTransport, mcas: bool) -> session::Result<bool> {87
let app = session::App::Teams;87
let app = session::App::Teams;88
let Some((control, _)) = transport.open(app, false).await? else {88
let Some((control, _)) = transport.open(app, false).await? else {89
return Ok(false);89
return Ok(false);90
};90
};91
control91
control92
.call("Page.navigate", json!({ "url": app.park_url() }))92
.call("Page.navigate", json!({ "url": app.park_url(mcas) }))93
.await?;93
.await?;94
Ok(true)94
Ok(true)95
}95
}@@ -473,7 +473,7 @@ fn build_dialog(dialog: Dialog, cx: &App) -> Dialog {
473
473
decline(&open, cx);
474
474
set_stage(Stage::Idle, cx);
475
475
close_dialog(window, cx);
476
cx.open_url(&url);
476
app_base::open_link::open_url(cx, &url);
477
477
}),
478
478
),
479
479
)
@@ -473,7 +473,7 @@ fn build_dialog(dialog: Dialog, cx: &App) -> Dialog {473
decline(&open, cx);473
decline(&open, cx);474
set_stage(Stage::Idle, cx);474
set_stage(Stage::Idle, cx);475
close_dialog(window, cx);475
close_dialog(window, cx);476
cx.open_url(&url);476
app_base::open_link::open_url(cx, &url);477
}),477
}),478
),478
),479
)479
)@@ -32,6 +32,7 @@ pub fn render_view(app: &Entity<AppState>, cx: &App) -> Div {
32
32
33
33
pub fn render_accounts(
34
34
app: &Entity<AppState>,
35
google_client: Option<&Entity<super::google_client_form::GoogleClientForm>>,
35
36
caldav: Option<&Entity<super::caldav_form::CalDavForm>>,
36
37
ics: Option<&Entity<super::caldav_form::IcsForm>>,
37
38
cx: &App,
@@ -40,8 +41,11 @@ pub fn render_accounts(
40
41
let pending = app.read(cx).google_connect_pending().is_some();
41
42
let mut body = v_flex()
42
43
.w_full()
43
.child(caption(tr("settings.calendar.section_google")))
44
.child(connect_row(app, accounts.has_google(), pending));
44
.child(caption(tr("settings.calendar.section_google")));
45
if let Some(form) = google_client {
46
body = body.child(form.clone());
47
}
48
body = body.child(connect_row(app, accounts.has_google(), pending));
45
49
for account in &accounts.google_accounts {
46
50
body = body.child(account_block(app, account, &accounts));
47
51
}
@@ -32,6 +32,7 @@ pub fn render_view(app: &Entity<AppState>, cx: &App) -> Div {32
32
33
pub fn render_accounts(33
pub fn render_accounts(34
app: &Entity<AppState>,34
app: &Entity<AppState>,35
google_client: Option<&Entity<super::google_client_form::GoogleClientForm>>,35
caldav: Option<&Entity<super::caldav_form::CalDavForm>>,36
caldav: Option<&Entity<super::caldav_form::CalDavForm>>,36
ics: Option<&Entity<super::caldav_form::IcsForm>>,37
ics: Option<&Entity<super::caldav_form::IcsForm>>,37
cx: &App,38
cx: &App,@@ -40,8 +41,11 @@ pub fn render_accounts(40
let pending = app.read(cx).google_connect_pending().is_some();41
let pending = app.read(cx).google_connect_pending().is_some();41
let mut body = v_flex()42
let mut body = v_flex()42
.w_full()43
.w_full()43
.child(caption(tr("settings.calendar.section_google")))44
.child(caption(tr("settings.calendar.section_google")));44
.child(connect_row(app, accounts.has_google(), pending));45
if let Some(form) = google_client {46
body = body.child(form.clone());47
}48
body = body.child(connect_row(app, accounts.has_google(), pending));45
for account in &accounts.google_accounts {49
for account in &accounts.google_accounts {46
body = body.child(account_block(app, account, &accounts));50
body = body.child(account_block(app, account, &accounts));47
}51
}@@ -8,6 +8,7 @@ use gpui_kit::*;
8
8
9
9
use super::caldav_form::{CalDavForm, IcsForm};
10
10
use super::devices::DevicesView;
11
use super::google_client_form::GoogleClientForm;
11
12
use super::help::HelpView;
12
13
use super::mcp::McpView;
13
14
use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};
@@ -69,6 +70,7 @@ pub struct SettingsDialog {
69
70
help: Option<Entity<HelpView>>,
70
71
mcp: Option<Entity<McpView>>,
71
72
agents: Option<Entity<AgentsSettings>>,
73
google_client: Option<Entity<GoogleClientForm>>,
72
74
caldav: Option<Entity<CalDavForm>>,
73
75
ics: Option<Entity<IcsForm>>,
74
76
body_scroll: ScrollHandle,
@@ -111,6 +113,7 @@ impl SettingsDialog {
111
113
help: None,
112
114
mcp: None,
113
115
agents: None,
116
google_client: None,
114
117
caldav: None,
115
118
ics: None,
116
119
body_scroll: ScrollHandle::new(),
@@ -158,6 +161,10 @@ impl SettingsDialog {
158
161
.map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));
159
162
}
160
163
if section == SettingsSection::CalendarAccounts {
164
if self.google_client.is_none() {
165
let app = self.app.clone();
166
self.google_client = Some(cx.new(|cx| GoogleClientForm::new(app, window, cx)));
167
}
161
168
if self.caldav.is_none() {
162
169
let app = self.app.clone();
163
170
self.caldav = Some(cx.new(|cx| CalDavForm::new(app, window, cx)));
@@ -219,10 +226,14 @@ impl SettingsDialog {
219
226
SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),
220
227
SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),
221
228
SettingsSection::Calendar => calendar::render_view(&self.app, cx).into_any_element(),
222
SettingsSection::CalendarAccounts => {
223
calendar::render_accounts(&self.app, self.caldav.as_ref(), self.ics.as_ref(), cx)
224
.into_any_element()
225
}
229
SettingsSection::CalendarAccounts => calendar::render_accounts(
230
&self.app,
231
self.google_client.as_ref(),
232
self.caldav.as_ref(),
233
self.ics.as_ref(),
234
cx,
235
)
236
.into_any_element(),
226
237
SettingsSection::Devices => self
227
238
.devices
228
239
.clone()
@@ -8,6 +8,7 @@ use gpui_kit::*;8
8
9
use super::caldav_form::{CalDavForm, IcsForm};9
use super::caldav_form::{CalDavForm, IcsForm};10
use super::devices::DevicesView;10
use super::devices::DevicesView;11
use super::google_client_form::GoogleClientForm;11
use super::help::HelpView;12
use super::help::HelpView;12
use super::mcp::McpView;13
use super::mcp::McpView;13
use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};14
use super::nav::{NavLayout, NavSearch, first_match, label, matches, render_nav};@@ -69,6 +70,7 @@ pub struct SettingsDialog {69
help: Option<Entity<HelpView>>,70
help: Option<Entity<HelpView>>,70
mcp: Option<Entity<McpView>>,71
mcp: Option<Entity<McpView>>,71
agents: Option<Entity<AgentsSettings>>,72
agents: Option<Entity<AgentsSettings>>,73
google_client: Option<Entity<GoogleClientForm>>,72
caldav: Option<Entity<CalDavForm>>,74
caldav: Option<Entity<CalDavForm>>,73
ics: Option<Entity<IcsForm>>,75
ics: Option<Entity<IcsForm>>,74
body_scroll: ScrollHandle,76
body_scroll: ScrollHandle,@@ -111,6 +113,7 @@ impl SettingsDialog {111
help: None,113
help: None,112
mcp: None,114
mcp: None,113
agents: None,115
agents: None,116
google_client: None,114
caldav: None,117
caldav: None,115
ics: None,118
ics: None,116
body_scroll: ScrollHandle::new(),119
body_scroll: ScrollHandle::new(),@@ -158,6 +161,10 @@ impl SettingsDialog {158
.map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));161
.map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));159
}162
}160
if section == SettingsSection::CalendarAccounts {163
if section == SettingsSection::CalendarAccounts {164
if self.google_client.is_none() {165
let app = self.app.clone();166
self.google_client = Some(cx.new(|cx| GoogleClientForm::new(app, window, cx)));167
}161
if self.caldav.is_none() {168
if self.caldav.is_none() {162
let app = self.app.clone();169
let app = self.app.clone();163
self.caldav = Some(cx.new(|cx| CalDavForm::new(app, window, cx)));170
self.caldav = Some(cx.new(|cx| CalDavForm::new(app, window, cx)));@@ -219,10 +226,14 @@ impl SettingsDialog {219
SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),226
SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),220
SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),227
SettingsSection::Calls => calls::render(&self.center, cx).into_any_element(),221
SettingsSection::Calendar => calendar::render_view(&self.app, cx).into_any_element(),228
SettingsSection::Calendar => calendar::render_view(&self.app, cx).into_any_element(),222
SettingsSection::CalendarAccounts => {229
SettingsSection::CalendarAccounts => calendar::render_accounts(223
calendar::render_accounts(&self.app, self.caldav.as_ref(), self.ics.as_ref(), cx)230
&self.app,224
.into_any_element()231
self.google_client.as_ref(),225
}232
self.caldav.as_ref(),233
self.ics.as_ref(),234
cx,235
)236
.into_any_element(),226
SettingsSection::Devices => self237
SettingsSection::Devices => self227
.devices238
.devices228
.clone()239
.clone()@@ -0,0 +1,224 @@
1
use gpui_kit::component::input::{Input, InputContentType, InputState};
2
use gpui_kit::component::{h_flex, v_flex};
3
use gpui_kit::*;
4
5
use super::rows::{ROW_INSET, control_row, stacked_field, text_button};
6
use crate::app_state::AppState;
7
use crate::i18n::tr;
8
use crate::theme;
9
10
pub struct GoogleClientForm {
11
app: Entity<AppState>,
12
client_id: Entity<InputState>,
13
secret: Entity<InputState>,
14
saved_id: String,
15
secret_present: bool,
16
submits: u64,
17
saving: bool,
18
}
19
20
impl GoogleClientForm {
21
pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
22
let saved_id = crate::google_oauth_client::load_client_id(&app.read(cx).store);
23
let client_id =
24
cx.new(|cx| InputState::new(window, cx).placeholder("….apps.googleusercontent.com"));
25
if !saved_id.is_empty() {
26
let text = saved_id.clone();
27
client_id.update(cx, |input, cx| input.set_value(text, window, cx));
28
}
29
let secret = cx.new(|cx| InputState::new(window, cx));
30
secret.update(cx, |input, cx| input.toggle_masked(window, cx));
31
if !saved_id.is_empty() {
32
cx.spawn_in(window, async move |form, cx| {
33
let present =
34
crate::runtime::spawn(crate::google_oauth_client::secret_is_stored()).await;
35
if !matches!(present, Ok(true)) {
36
return;
37
}
38
form.update_in(cx, |form, window, cx| {
39
if form.submits > 0 {
40
return;
41
}
42
form.secret_present = true;
43
form.secret.update(cx, |input, cx| {
44
input.set_placeholder(
45
tr("settings.calendar.google_client_secret_kept"),
46
window,
47
cx,
48
);
49
});
50
cx.notify();
51
})
52
.ok();
53
})
54
.detach();
55
}
56
GoogleClientForm {
57
app,
58
client_id,
59
secret,
60
saved_id,
61
secret_present: false,
62
submits: 0,
63
saving: false,
64
}
65
}
66
67
fn status_detail(&self) -> String {
68
if !self.saved_id.is_empty() && self.secret_present {
69
tr("settings.calendar.google_client_status_own")
70
} else if chatsvc::client_id_from_env().is_some() {
71
tr("settings.calendar.google_client_status_builtin")
72
} else {
73
tr("settings.calendar.google_client_status_missing")
74
}
75
}
76
77
fn submit(&mut self, clear: bool, window: &mut Window, cx: &mut Context<Self>) {
78
if self.saving {
79
return;
80
}
81
self.saving = true;
82
self.submits += 1;
83
let client_id = if clear {
84
String::new()
85
} else {
86
self.client_id.read(cx).value().to_string()
87
};
88
let secret = if clear {
89
String::new()
90
} else {
91
self.secret.read(cx).value().to_string()
92
};
93
let store = self.app.read(cx).store.clone();
94
let connected = self.app.read(cx).calendar_accounts().has_google();
95
let app = self.app.clone();
96
let id_field = self.client_id.clone();
97
let secret_field = self.secret.clone();
98
let saved_label = client_id.trim().to_owned();
99
cx.spawn_in(window, async move |form, cx| {
100
let result = crate::runtime::spawn(async move {
101
crate::google_oauth_client::save(&store, &client_id, &secret).await
102
})
103
.await;
104
form.update_in(cx, |form, window, cx| {
105
form.saving = false;
106
let notice = match result {
107
Ok(Ok(crate::google_oauth_client::GoogleClientSave::Saved)) => {
108
form.saved_id = saved_label;
109
form.secret_present = true;
110
secret_field.update(cx, |input, cx| input.set_value("", window, cx));
111
if connected {
112
tr("settings.calendar.google_client_saved_reconnect")
113
} else {
114
tr("settings.calendar.google_client_saved")
115
}
116
}
117
Ok(Ok(crate::google_oauth_client::GoogleClientSave::Cleared)) => {
118
form.saved_id.clear();
119
form.secret_present = false;
120
id_field.update(cx, |input, cx| input.set_value("", window, cx));
121
secret_field.update(cx, |input, cx| {
122
input.set_value("", window, cx);
123
input.set_placeholder("", window, cx);
124
});
125
if connected {
126
tr("settings.calendar.google_client_cleared_reconnect")
127
} else {
128
tr("settings.calendar.google_client_cleared")
129
}
130
}
131
Ok(Err(crate::google_oauth_client::GoogleClientSaveError::SecretRequired)) => {
132
tr("settings.calendar.google_client_secret_required")
133
}
134
_ => tr("settings.calendar.google_client_save_failed"),
135
};
136
if form.secret_present {
137
secret_field.update(cx, |input, cx| {
138
input.set_placeholder(
139
tr("settings.calendar.google_client_secret_kept"),
140
window,
141
cx,
142
);
143
});
144
}
145
app.update(cx, |state, cx| state.raise_notice(notice, None, cx));
146
cx.notify();
147
})
148
.ok();
149
})
150
.detach();
151
}
152
}
153
154
impl Render for GoogleClientForm {
155
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
156
let save = cx.entity().clone();
157
let reset = cx.entity().clone();
158
v_flex()
159
.w_full()
160
.gap(px(8.))
161
.child(control_row(
162
tr("settings.calendar.google_client_status_title"),
163
self.status_detail(),
164
div(),
165
))
166
.child(stacked_field(
167
tr("settings.calendar.google_client_id"),
168
"",
169
Input::new(&self.client_id),
170
))
171
.child(stacked_field(
172
tr("settings.calendar.google_client_secret"),
173
"",
174
Input::new(&self.secret)
175
.content_type(InputContentType::Password)
176
.mask_toggle(),
177
))
178
.child(guide())
179
.child(control_row(
180
tr("settings.calendar.google_client_save"),
181
"",
182
h_flex()
183
.gap_2()
184
.child(
185
text_button(
186
"settings-google-client-save",
187
tr("settings.calendar.google_client_save"),
188
)
189
.on_click(move |_, window, cx| {
190
save.update(cx, |form, cx| form.submit(false, window, cx))
191
}),
192
)
193
.child(
194
text_button(
195
"settings-google-client-reset",
196
tr("settings.calendar.google_client_reset"),
197
)
198
.on_click(move |_, window, cx| {
199
reset.update(cx, |form, cx| form.submit(true, window, cx))
200
}),
201
),
202
))
203
}
204
}
205
206
fn guide() -> Div {
207
v_flex()
208
.w_full()
209
.px(px(ROW_INSET))
210
.child(guide_line(tr("settings.calendar.google_client_guide_1")))
211
.child(guide_line(tr("settings.calendar.google_client_guide_2")))
212
.child(guide_line(tr("settings.calendar.google_client_guide_3")))
213
.child(guide_line(tr("settings.calendar.google_client_guide_4")))
214
.child(guide_line(tr("settings.calendar.google_client_guide_5")))
215
}
216
217
fn guide_line(text: String) -> Div {
218
div()
219
.w_full()
220
.text_size(px(12.))
221
.line_height(px(16.))
222
.text_color(theme::text_muted())
223
.child(text)
224
}
@@ -0,0 +1,224 @@1
use gpui_kit::component::input::{Input, InputContentType, InputState};2
use gpui_kit::component::{h_flex, v_flex};3
use gpui_kit::*;4
5
use super::rows::{ROW_INSET, control_row, stacked_field, text_button};6
use crate::app_state::AppState;7
use crate::i18n::tr;8
use crate::theme;9
10
pub struct GoogleClientForm {11
app: Entity<AppState>,12
client_id: Entity<InputState>,13
secret: Entity<InputState>,14
saved_id: String,15
secret_present: bool,16
submits: u64,17
saving: bool,18
}19
20
impl GoogleClientForm {21
pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {22
let saved_id = crate::google_oauth_client::load_client_id(&app.read(cx).store);23
let client_id =24
cx.new(|cx| InputState::new(window, cx).placeholder("….apps.googleusercontent.com"));25
if !saved_id.is_empty() {26
let text = saved_id.clone();27
client_id.update(cx, |input, cx| input.set_value(text, window, cx));28
}29
let secret = cx.new(|cx| InputState::new(window, cx));30
secret.update(cx, |input, cx| input.toggle_masked(window, cx));31
if !saved_id.is_empty() {32
cx.spawn_in(window, async move |form, cx| {33
let present =34
crate::runtime::spawn(crate::google_oauth_client::secret_is_stored()).await;35
if !matches!(present, Ok(true)) {36
return;37
}38
form.update_in(cx, |form, window, cx| {39
if form.submits > 0 {40
return;41
}42
form.secret_present = true;43
form.secret.update(cx, |input, cx| {44
input.set_placeholder(45
tr("settings.calendar.google_client_secret_kept"),46
window,47
cx,48
);49
});50
cx.notify();51
})52
.ok();53
})54
.detach();55
}56
GoogleClientForm {57
app,58
client_id,59
secret,60
saved_id,61
secret_present: false,62
submits: 0,63
saving: false,64
}65
}66
67
fn status_detail(&self) -> String {68
if !self.saved_id.is_empty() && self.secret_present {69
tr("settings.calendar.google_client_status_own")70
} else if chatsvc::client_id_from_env().is_some() {71
tr("settings.calendar.google_client_status_builtin")72
} else {73
tr("settings.calendar.google_client_status_missing")74
}75
}76
77
fn submit(&mut self, clear: bool, window: &mut Window, cx: &mut Context<Self>) {78
if self.saving {79
return;80
}81
self.saving = true;82
self.submits += 1;83
let client_id = if clear {84
String::new()85
} else {86
self.client_id.read(cx).value().to_string()87
};88
let secret = if clear {89
String::new()90
} else {91
self.secret.read(cx).value().to_string()92
};93
let store = self.app.read(cx).store.clone();94
let connected = self.app.read(cx).calendar_accounts().has_google();95
let app = self.app.clone();96
let id_field = self.client_id.clone();97
let secret_field = self.secret.clone();98
let saved_label = client_id.trim().to_owned();99
cx.spawn_in(window, async move |form, cx| {100
let result = crate::runtime::spawn(async move {101
crate::google_oauth_client::save(&store, &client_id, &secret).await102
})103
.await;104
form.update_in(cx, |form, window, cx| {105
form.saving = false;106
let notice = match result {107
Ok(Ok(crate::google_oauth_client::GoogleClientSave::Saved)) => {108
form.saved_id = saved_label;109
form.secret_present = true;110
secret_field.update(cx, |input, cx| input.set_value("", window, cx));111
if connected {112
tr("settings.calendar.google_client_saved_reconnect")113
} else {114
tr("settings.calendar.google_client_saved")115
}116
}117
Ok(Ok(crate::google_oauth_client::GoogleClientSave::Cleared)) => {118
form.saved_id.clear();119
form.secret_present = false;120
id_field.update(cx, |input, cx| input.set_value("", window, cx));121
secret_field.update(cx, |input, cx| {122
input.set_value("", window, cx);123
input.set_placeholder("", window, cx);124
});125
if connected {126
tr("settings.calendar.google_client_cleared_reconnect")127
} else {128
tr("settings.calendar.google_client_cleared")129
}130
}131
Ok(Err(crate::google_oauth_client::GoogleClientSaveError::SecretRequired)) => {132
tr("settings.calendar.google_client_secret_required")133
}134
_ => tr("settings.calendar.google_client_save_failed"),135
};136
if form.secret_present {137
secret_field.update(cx, |input, cx| {138
input.set_placeholder(139
tr("settings.calendar.google_client_secret_kept"),140
window,141
cx,142
);143
});144
}145
app.update(cx, |state, cx| state.raise_notice(notice, None, cx));146
cx.notify();147
})148
.ok();149
})150
.detach();151
}152
}153
154
impl Render for GoogleClientForm {155
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {156
let save = cx.entity().clone();157
let reset = cx.entity().clone();158
v_flex()159
.w_full()160
.gap(px(8.))161
.child(control_row(162
tr("settings.calendar.google_client_status_title"),163
self.status_detail(),164
div(),165
))166
.child(stacked_field(167
tr("settings.calendar.google_client_id"),168
"",169
Input::new(&self.client_id),170
))171
.child(stacked_field(172
tr("settings.calendar.google_client_secret"),173
"",174
Input::new(&self.secret)175
.content_type(InputContentType::Password)176
.mask_toggle(),177
))178
.child(guide())179
.child(control_row(180
tr("settings.calendar.google_client_save"),181
"",182
h_flex()183
.gap_2()184
.child(185
text_button(186
"settings-google-client-save",187
tr("settings.calendar.google_client_save"),188
)189
.on_click(move |_, window, cx| {190
save.update(cx, |form, cx| form.submit(false, window, cx))191
}),192
)193
.child(194
text_button(195
"settings-google-client-reset",196
tr("settings.calendar.google_client_reset"),197
)198
.on_click(move |_, window, cx| {199
reset.update(cx, |form, cx| form.submit(true, window, cx))200
}),201
),202
))203
}204
}205
206
fn guide() -> Div {207
v_flex()208
.w_full()209
.px(px(ROW_INSET))210
.child(guide_line(tr("settings.calendar.google_client_guide_1")))211
.child(guide_line(tr("settings.calendar.google_client_guide_2")))212
.child(guide_line(tr("settings.calendar.google_client_guide_3")))213
.child(guide_line(tr("settings.calendar.google_client_guide_4")))214
.child(guide_line(tr("settings.calendar.google_client_guide_5")))215
}216
217
fn guide_line(text: String) -> Div {218
div()219
.w_full()220
.text_size(px(12.))221
.line_height(px(16.))222
.text_color(theme::text_muted())223
.child(text)224
}@@ -335,7 +335,9 @@ impl McpView {
335
335
this.update(cx, |this, cx| {
336
336
this.install_busy = None;
337
337
match result {
338
Ok(Some(InstallReport::OpenUrl(url))) => cx.open_url(&url),
338
Ok(Some(InstallReport::OpenUrl(url))) => {
339
app_base::open_link::open_url(cx, &url)
340
}
339
341
Ok(_) => {}
340
342
Err(error) => {
341
343
this.install_errors.insert(target, error.to_string());
@@ -335,7 +335,9 @@ impl McpView {335
this.update(cx, |this, cx| {335
this.update(cx, |this, cx| {336
this.install_busy = None;336
this.install_busy = None;337
match result {337
match result {338
Ok(Some(InstallReport::OpenUrl(url))) => cx.open_url(&url),338
Ok(Some(InstallReport::OpenUrl(url))) => {339
app_base::open_link::open_url(cx, &url)340
}339
Ok(_) => {}341
Ok(_) => {}340
Err(error) => {342
Err(error) => {341
this.install_errors.insert(target, error.to_string());343
this.install_errors.insert(target, error.to_string());@@ -8,6 +8,7 @@ mod chats;
8
8
mod devices;
9
9
mod dialog;
10
10
mod general;
11
mod google_client_form;
11
12
mod help;
12
13
mod kvt;
13
14
mod mcp;
@@ -8,6 +8,7 @@ mod chats;8
mod devices;8
mod devices;9
mod dialog;9
mod dialog;10
mod general;10
mod general;11
mod google_client_form;11
mod help;12
mod help;12
mod kvt;13
mod kvt;13
mod mcp;14
mod mcp;@@ -906,7 +906,7 @@ fn click_handler(
906
906
match &action.kind {
907
907
CardActionKind::OpenUrl(url) => {
908
908
let url = url.clone();
909
Some(Rc::new(move |cx| cx.open_url(&url)))
909
Some(Rc::new(move |cx| app_base::open_link::open_url(cx, &url)))
910
910
}
911
911
CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
912
912
let action = action.clone();
@@ -906,7 +906,7 @@ fn click_handler(906
match &action.kind {906
match &action.kind {907
CardActionKind::OpenUrl(url) => {907
CardActionKind::OpenUrl(url) => {908
let url = url.clone();908
let url = url.clone();909
Some(Rc::new(move |cx| cx.open_url(&url)))909
Some(Rc::new(move |cx| app_base::open_link::open_url(cx, &url)))910
}910
}911
CardActionKind::Submit(_) | CardActionKind::Execute(_) => {911
CardActionKind::Submit(_) | CardActionKind::Execute(_) => {912
let action = action.clone();912
let action = action.clone();@@ -438,7 +438,7 @@ fn file_view(
438
438
.bg(theme::accent()),
439
439
)
440
440
})
441
.on_click(move |_, _, cx| cx.open_url(&url))
441
.on_click(move |_, _, cx| app_base::open_link::open_url(cx, &url))
442
442
.into_any_element()
443
443
}
444
444
@@ -438,7 +438,7 @@ fn file_view(438
.bg(theme::accent()),438
.bg(theme::accent()),439
)439
)440
})440
})441
.on_click(move |_, _, cx| cx.open_url(&url))441
.on_click(move |_, _, cx| app_base::open_link::open_url(cx, &url))442
.into_any_element()442
.into_any_element()443
}443
}444
444
@@ -49,7 +49,7 @@ pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {
49
49
})
50
50
.on_click(move |_, _, cx| {
51
51
cx.stop_propagation();
52
cx.open_url(&source_url);
52
app_base::open_link::open_url(cx, &source_url);
53
53
})
54
54
.child(poster)
55
55
.child(
@@ -49,7 +49,7 @@ pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {49
})49
})50
.on_click(move |_, _, cx| {50
.on_click(move |_, _, cx| {51
cx.stop_propagation();51
cx.stop_propagation();52
cx.open_url(&source_url);52
app_base::open_link::open_url(cx, &source_url);53
})53
})54
.child(poster)54
.child(poster)55
.child(55
.child(@@ -25,14 +25,15 @@ use gpui_kit::component::{
25
25
use gpui_kit::prelude::FluentBuilder as _;
26
26
use gpui_kit::*;
27
27
use teams_core::{
28
Draft, DraftLine, Edit, EnterKeyBehavior, FileReference, FormatState, LineKind, LinkPreview,
29
MarkKind, MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TABLE_MARK, TableEdit,
30
TypingStyle, UpArrowBehavior, UploadedFile, changed_span, has_markdown, link_url, map_offset,
31
reverse_edits,
28
CODE_HEADER_MARK, Draft, DraftLine, Edit, EnterKeyBehavior, FileReference, FormatState,
29
LineKind, LinkPreview, MarkKind, MentionCandidate, MentionInput, OBJECT_MARK, SizeStep,
30
TABLE_MARK, TableEdit, TypingStyle, UpArrowBehavior, UploadedFile, changed_span, has_markdown,
31
link_url, map_offset, reverse_edits,
32
32
};
33
33
34
34
mod attach_menu;
35
35
mod cloud_picker;
36
mod code_language;
36
37
pub(crate) mod delivery;
37
38
mod drafts;
38
39
mod format_menus;
@@ -79,6 +80,7 @@ use crate::runtime;
79
80
use crate::scheduled_rows::scheduled_label;
80
81
use crate::theme::{self, ElevatedSurface as _};
81
82
use crate::typing::OutgoingTyping;
83
use code_language::is_code_header_token;
82
84
use format_menus::{FormatPopup, paragraph_label};
83
85
use rule::{is_rule_token, render_rule_token};
84
86
use slash::SlashPopup;
@@ -104,6 +106,15 @@ const COMPOSER_BUTTON_SIZE: f32 = 32.;
104
106
const COMPOSER_BUTTON_INSET: f32 = 6.;
105
107
pub const COMPOSER_BOX_TAG: &str = "composer";
106
108
pub const COMPOSER_ACTIONS_TAG: &str = "composer/actions";
109
fn send_divider() -> Div {
110
div()
111
.flex_none()
112
.w(px(1.))
113
.h(px(SEND_DIVIDER_HEIGHT))
114
.ml(px(COMPOSER_BUTTON_INSET))
115
.bg(theme::border())
116
}
117
107
118
pub const COMPOSER_STACKED_ACTIONS_TAG: &str = "composer/stacked-actions";
108
119
const STACKED_ACTIONS_WIDTH: f32 = 400.;
109
120
pub const COMPOSER_INPUT_TAG: &str = "composer/input";
@@ -260,6 +271,8 @@ pub struct Composer {
260
271
table_counter: usize,
261
272
table_picker: Option<TablePicker>,
262
273
table_menu: Option<TableMenu>,
274
/// The first line of the code block whose language menu is open.
275
code_language_menu: Option<usize>,
263
276
format_popup: Option<FormatPopup>,
264
277
format_overflow: bool,
265
278
format_bar: HashSet<String>,
@@ -537,6 +550,7 @@ impl Composer {
537
550
table_counter: 0,
538
551
table_picker: None,
539
552
table_menu: None,
553
code_language_menu: None,
540
554
format_popup: None,
541
555
format_overflow: false,
542
556
format_bar: HashSet::new(),
@@ -636,6 +650,8 @@ impl Composer {
636
650
self.report_typing(!value.trim().is_empty(), cx);
637
651
let previous = std::mem::replace(&mut self.previous_value, value.clone());
638
652
if previous != value {
653
// The menu names its block by line, which an edit can move.
654
self.code_language_menu = None;
639
655
let (start, old_end, new_end) = changed_span(&previous, &value);
640
656
self.shift_anchors(start, old_end, new_end);
641
657
}
@@ -921,6 +937,7 @@ impl Composer {
921
937
ranges.set(style.ranges, cx);
922
938
self.input.update(cx, |state, cx| {
923
939
state.set_line_indents(style.indents, cx);
940
state.set_line_labels(style.labels, theme::text_faint(), cx);
924
941
state.set_hanging_indents(style.markers, cx);
925
942
});
926
943
}
@@ -939,6 +956,7 @@ impl Composer {
939
956
});
940
957
self.previous_value = draft.text().to_owned();
941
958
self.draft = draft;
959
self.code_language_menu = None;
942
960
self.pending_style = None;
943
961
self.conversion = None;
944
962
self.pasted_markdown = None;
@@ -1488,7 +1506,7 @@ impl Composer {
1488
1506
let text = if selected.contains(TABLE_MARK) {
1489
1507
Draft::from_lines(&lines).plain_text()
1490
1508
} else {
1491
selected.replace(OBJECT_MARK, "")
1509
selected.replace([OBJECT_MARK, CODE_HEADER_MARK], "")
1492
1510
};
1493
1511
if text.is_empty() {
1494
1512
return true;
@@ -3106,11 +3124,18 @@ impl Render for Composer {
3106
3124
.children(attach)
3107
3125
.children(self.render_rewrite_button(cx))
3108
3126
.children(self.render_plus_button(cx));
3127
// Teams gives a code block the full width and keeps the actions right, beside Send.
3128
let below_code = self
3129
.draft
3130
.lines()
3131
.iter()
3132
.any(|kind| matches!(kind, LineKind::Code(_)));
3109
3133
let stacked = !post_layout
3110
&& self
3111
.composer_bounds
3112
.get()
3113
.is_some_and(|bounds| f32::from(bounds.size.width) < STACKED_ACTIONS_WIDTH);
3134
&& (below_code
3135
|| self
3136
.composer_bounds
3137
.get()
3138
.is_some_and(|bounds| f32::from(bounds.size.width) < STACKED_ACTIONS_WIDTH));
3114
3139
let mut send = Some(send);
3115
3140
let (row_actions, stacked_actions, post_footer) = if post_layout {
3116
3141
(
@@ -3136,6 +3161,15 @@ impl Render for Composer {
3136
3161
.unwrap_or(false)
3137
3162
})
3138
3163
.token(move |context, _, cx| {
3164
if context.is_block() && is_code_header_token(context.token()) {
3165
let weak = tokens_composer.clone();
3166
let (at, width) = (context.range().start, context.available_width());
3167
if let Ok(header) = tokens_composer
3168
.read_with(cx, |this, _| this.render_code_header(weak, at, width))
3169
{
3170
return header;
3171
}
3172
}
3139
3173
if context.is_block() && is_rule_token(context.token()) {
3140
3174
return render_rule_token(
3141
3175
context.available_width(),
@@ -3518,7 +3552,10 @@ impl Render for Composer {
3518
3552
}
3519
3553
}))
3520
3554
.capture_action(cx.listener(|this, _: &Escape, window, cx| {
3521
if this.table_picker.take().is_some() || this.table_menu.take().is_some() {
3555
if this.table_picker.take().is_some()
3556
|| this.table_menu.take().is_some()
3557
|| this.code_language_menu.take().is_some()
3558
{
3522
3559
cx.notify();
3523
3560
cx.stop_propagation();
3524
3561
return;
@@ -3579,6 +3616,7 @@ impl Render for Composer {
3579
3616
.children(self.render_slash_popup(cx))
3580
3617
.children(self.render_emoji_popup(window, cx))
3581
3618
.children(self.render_toolbar(focused, cx))
3619
.children(self.render_code_language_menu(cx))
3582
3620
.children(self.render_schedule(cx))
3583
3621
.children(self.render_delivery_menu(cx))
3584
3622
.children(self.render_plus_menu(cx))
@@ -3658,15 +3696,7 @@ impl Render for Composer {
3658
3696
)
3659
3697
.children(row_actions)
3660
3698
.when_some(send.filter(|_| !post_layout), |row, send| {
3661
row.child(
3662
div()
3663
.flex_none()
3664
.w(px(1.))
3665
.h(px(SEND_DIVIDER_HEIGHT))
3666
.ml(px(COMPOSER_BUTTON_INSET))
3667
.bg(theme::border()),
3668
)
3669
.child(send)
3699
row.child(send_divider()).child(send)
3670
3700
}),
3671
3701
)
3672
3702
.children(stacked_actions.map(|(actions, send)| {
@@ -3676,8 +3706,12 @@ impl Render for Composer {
3676
3706
.items_center()
3677
3707
.px(px(COMPOSER_BUTTON_INSET))
3678
3708
.pb(px(COMPOSER_BUTTON_INSET))
3709
.when(below_code, |row| row.child(div().flex_1()))
3679
3710
.child(actions)
3680
.child(div().flex_1())
3711
.when(!below_code, |row| row.child(div().flex_1()))
3712
.when(below_code && send.is_some(), |row| {
3713
row.child(send_divider())
3714
})
3681
3715
.children(send)
3682
3716
}))
3683
3717
.children(post_footer),
@@ -4781,16 +4815,135 @@ mod tests {
4781
4815
}
4782
4816
4783
4817
#[gpui_kit::test]
4784
fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {
4818
fn backspace_after_a_fence_gives_it_back_for_a_language(cx: &mut TestAppContext) {
4785
4819
let mut typist = typist(cx);
4786
4820
typist.type_text("```");
4821
assert_eq!(typist.draft().lines(), [teams_core::LineKind::Code(None)]);
4822
typist.press("backspace");
4823
assert_eq!(typist.value(), "```");
4824
typist.type_text("py");
4787
4825
typist.press("enter");
4826
assert_eq!(
4827
typist.draft().lines(),
4828
[teams_core::LineKind::Code(Some("python".into()))]
4829
);
4830
}
4831
4832
#[gpui_kit::test]
4833
fn the_language_picker_in_the_header_sets_the_whole_code_block(cx: &mut TestAppContext) {
4834
use gpui_kit::VisualTestContext;
4835
4836
use super::super::code_language::{CODE_LANGUAGE_ROW_TAG, CODE_LANGUAGE_TAG};
4837
4838
let mut typist = typist(cx);
4839
typist.type_text("x");
4840
typist.press("shift-enter");
4841
typist.type_text("```");
4842
typist.type_text("a");
4843
typist.press("enter");
4844
typist.type_text("b");
4845
let composer = typist.composer.clone();
4846
let handle = typist.handle;
4847
let mut visual = VisualTestContext::from_window(handle, typist.cx);
4848
visual.update(|window, cx| window.render_frame(cx));
4849
let header = visual
4850
.debug_bounds(CODE_LANGUAGE_TAG)
4851
.expect("a header on the block");
4852
visual.simulate_click(header.center(), Default::default());
4853
visual.run_until_parked();
4854
assert_eq!(
4855
composer.read_with(&visual, |composer, _| composer.code_language_menu),
4856
Some(1)
4857
);
4858
visual.update(|window, cx| window.render_frame(cx));
4859
let row = visual
4860
.debug_bounds(Box::leak(
4861
format!("{CODE_LANGUAGE_ROW_TAG}dart").into_boxed_str(),
4862
))
4863
.expect("Dart in the open menu");
4864
visual.simulate_click(row.center(), Default::default());
4865
visual.run_until_parked();
4866
let draft = composer.read_with(&visual, |composer, _| composer.draft.clone());
4867
let dart = teams_core::LineKind::Code(Some("dart".into()));
4868
assert_eq!(
4869
draft.lines(),
4870
[teams_core::LineKind::Text, dart.clone(), dart]
4871
);
4872
assert_eq!(
4873
draft.to_html(),
4874
"x<pre class=\"language-dart skipProofing\" spellcheck=\"false\"><code>a<br>b</code></pre>"
4875
);
4876
}
4877
4878
#[gpui_kit::test]
4879
fn code_typed_after_picking_a_language_is_highlighted(cx: &mut TestAppContext) {
4880
let mut typist = typist(cx);
4881
typist.type_text("```");
4882
let composer = typist.composer.clone();
4883
typist.act(|window, cx| {
4884
composer.update(cx, |composer, cx| {
4885
composer.choose_code_language(0, "python", window, cx)
4886
})
4887
});
4888
typist.type_text("def f():");
4889
typist.press("enter");
4890
typist.type_text("class A: pass");
4891
let draft = typist.draft();
4892
assert_eq!(
4893
draft.lines()[1],
4894
teams_core::LineKind::Code(Some("python".into()))
4895
);
4896
let style = super::super::draft_style(&draft, "Mono".into());
4897
let words: Vec<_> = style
4898
.text
4899
.iter()
4900
.map(|decoration| &draft.text()[decoration.range.clone()])
4901
.collect();
4902
for keyword in ["def", "class", "pass"] {
4903
assert!(words.contains(&keyword), "{keyword} in {words:?}");
4904
}
4905
}
4906
4907
#[gpui_kit::test]
4908
fn copied_code_leaves_its_header_behind_and_escape_closes_the_picker(
4909
cx: &mut TestAppContext,
4910
) {
4911
let mut typist = typist(cx);
4912
typist.type_text("x");
4913
typist.press("shift-enter");
4914
typist.type_text("```");
4915
typist.type_text("a");
4916
let composer = typist.composer.clone();
4917
let (input, end) = typist.cx.update(|cx| {
4918
let composer = composer.read(cx);
4919
(composer.input.clone(), composer.draft.text().len())
4920
});
4921
typist.act(|_, cx| {
4922
input.update(cx, |state, cx| state.set_selected_range(0..end, cx));
4923
composer.update(cx, |composer, cx| {
4924
composer.copy_selection(cx);
4925
composer.code_language_menu = Some(1);
4926
})
4927
});
4928
let copied = typist.cx.read_from_clipboard().and_then(|item| item.text());
4929
assert_eq!(copied.as_deref(), Some("x\na"));
4930
typist.press("escape");
4931
assert_eq!(
4932
typist.cx.update(|cx| composer.read(cx).code_language_menu),
4933
None
4934
);
4935
}
4936
4937
#[gpui_kit::test]
4938
fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {
4939
let mut typist = typist(cx);
4940
typist.type_text("```");
4788
4941
typist.type_text("a");
4789
4942
typist.press("enter");
4790
4943
typist.type_text("b");
4791
4944
typist.press("up end delete");
4792
4945
assert_eq!(
4793
typist.outgoing().html(),
4946
typist.outgoing().draft.to_html(),
4794
4947
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>"
4795
4948
);
4796
4949
}
@@ -4800,7 +4953,6 @@ mod tests {
4800
4953
fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) {
4801
4954
let mut typist = typist(cx);
4802
4955
typist.type_text("```");
4803
typist.press("enter");
4804
4956
typist.type_text(" x");
4805
4957
typist.press("ctrl-a ctrl-c");
4806
4958
let text = typist.cx.read_from_clipboard().and_then(|item| item.text());
@@ -4942,13 +5094,15 @@ mod tests {
4942
5094
fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) {
4943
5095
let mut typist = typist(cx);
4944
5096
typist.type_text("```");
4945
typist.press("enter");
4946
5097
typist.type_text(":) ");
4947
5098
typist
4948
5099
.cx
4949
5100
.write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));
4950
5101
typist.press("ctrl-v");
4951
assert_eq!(typist.value(), ":) **x**");
5102
assert_eq!(
5103
typist.value(),
5104
format!("{}:) **x**", teams_core::CODE_HEADER_MARK)
5105
);
4952
5106
let composer = typist.composer.clone();
4953
5107
assert!(
4954
5108
typist
@@ -4957,7 +5111,7 @@ mod tests {
4957
5111
);
4958
5112
let outgoing = typist.outgoing();
4959
5113
assert_eq!(
4960
outgoing.html(),
5114
outgoing.draft.to_html(),
4961
5115
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>"
4962
5116
);
4963
5117
}
@@ -25,14 +25,15 @@ use gpui_kit::component::{25
use gpui_kit::prelude::FluentBuilder as _;25
use gpui_kit::prelude::FluentBuilder as _;26
use gpui_kit::*;26
use gpui_kit::*;27
use teams_core::{27
use teams_core::{28
Draft, DraftLine, Edit, EnterKeyBehavior, FileReference, FormatState, LineKind, LinkPreview,28
CODE_HEADER_MARK, Draft, DraftLine, Edit, EnterKeyBehavior, FileReference, FormatState,29
MarkKind, MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TABLE_MARK, TableEdit,29
LineKind, LinkPreview, MarkKind, MentionCandidate, MentionInput, OBJECT_MARK, SizeStep,30
TypingStyle, UpArrowBehavior, UploadedFile, changed_span, has_markdown, link_url, map_offset,30
TABLE_MARK, TableEdit, TypingStyle, UpArrowBehavior, UploadedFile, changed_span, has_markdown,31
reverse_edits,31
link_url, map_offset, reverse_edits,32
};32
};33
33
34
mod attach_menu;34
mod attach_menu;35
mod cloud_picker;35
mod cloud_picker;36
mod code_language;36
pub(crate) mod delivery;37
pub(crate) mod delivery;37
mod drafts;38
mod drafts;38
mod format_menus;39
mod format_menus;@@ -79,6 +80,7 @@ use crate::runtime;79
use crate::scheduled_rows::scheduled_label;80
use crate::scheduled_rows::scheduled_label;80
use crate::theme::{self, ElevatedSurface as _};81
use crate::theme::{self, ElevatedSurface as _};81
use crate::typing::OutgoingTyping;82
use crate::typing::OutgoingTyping;83
use code_language::is_code_header_token;82
use format_menus::{FormatPopup, paragraph_label};84
use format_menus::{FormatPopup, paragraph_label};83
use rule::{is_rule_token, render_rule_token};85
use rule::{is_rule_token, render_rule_token};84
use slash::SlashPopup;86
use slash::SlashPopup;@@ -104,6 +106,15 @@ const COMPOSER_BUTTON_SIZE: f32 = 32.;104
const COMPOSER_BUTTON_INSET: f32 = 6.;106
const COMPOSER_BUTTON_INSET: f32 = 6.;105
pub const COMPOSER_BOX_TAG: &str = "composer";107
pub const COMPOSER_BOX_TAG: &str = "composer";106
pub const COMPOSER_ACTIONS_TAG: &str = "composer/actions";108
pub const COMPOSER_ACTIONS_TAG: &str = "composer/actions";109
fn send_divider() -> Div {110
div()111
.flex_none()112
.w(px(1.))113
.h(px(SEND_DIVIDER_HEIGHT))114
.ml(px(COMPOSER_BUTTON_INSET))115
.bg(theme::border())116
}117
107
pub const COMPOSER_STACKED_ACTIONS_TAG: &str = "composer/stacked-actions";118
pub const COMPOSER_STACKED_ACTIONS_TAG: &str = "composer/stacked-actions";108
const STACKED_ACTIONS_WIDTH: f32 = 400.;119
const STACKED_ACTIONS_WIDTH: f32 = 400.;109
pub const COMPOSER_INPUT_TAG: &str = "composer/input";120
pub const COMPOSER_INPUT_TAG: &str = "composer/input";@@ -260,6 +271,8 @@ pub struct Composer {260
table_counter: usize,271
table_counter: usize,261
table_picker: Option<TablePicker>,272
table_picker: Option<TablePicker>,262
table_menu: Option<TableMenu>,273
table_menu: Option<TableMenu>,274
/// The first line of the code block whose language menu is open.275
code_language_menu: Option<usize>,263
format_popup: Option<FormatPopup>,276
format_popup: Option<FormatPopup>,264
format_overflow: bool,277
format_overflow: bool,265
format_bar: HashSet<String>,278
format_bar: HashSet<String>,@@ -537,6 +550,7 @@ impl Composer {537
table_counter: 0,550
table_counter: 0,538
table_picker: None,551
table_picker: None,539
table_menu: None,552
table_menu: None,553
code_language_menu: None,540
format_popup: None,554
format_popup: None,541
format_overflow: false,555
format_overflow: false,542
format_bar: HashSet::new(),556
format_bar: HashSet::new(),@@ -636,6 +650,8 @@ impl Composer {636
self.report_typing(!value.trim().is_empty(), cx);650
self.report_typing(!value.trim().is_empty(), cx);637
let previous = std::mem::replace(&mut self.previous_value, value.clone());651
let previous = std::mem::replace(&mut self.previous_value, value.clone());638
if previous != value {652
if previous != value {653
// The menu names its block by line, which an edit can move.654
self.code_language_menu = None;639
let (start, old_end, new_end) = changed_span(&previous, &value);655
let (start, old_end, new_end) = changed_span(&previous, &value);640
self.shift_anchors(start, old_end, new_end);656
self.shift_anchors(start, old_end, new_end);641
}657
}@@ -921,6 +937,7 @@ impl Composer {921
ranges.set(style.ranges, cx);937
ranges.set(style.ranges, cx);922
self.input.update(cx, |state, cx| {938
self.input.update(cx, |state, cx| {923
state.set_line_indents(style.indents, cx);939
state.set_line_indents(style.indents, cx);940
state.set_line_labels(style.labels, theme::text_faint(), cx);924
state.set_hanging_indents(style.markers, cx);941
state.set_hanging_indents(style.markers, cx);925
});942
});926
}943
}@@ -939,6 +956,7 @@ impl Composer {939
});956
});940
self.previous_value = draft.text().to_owned();957
self.previous_value = draft.text().to_owned();941
self.draft = draft;958
self.draft = draft;959
self.code_language_menu = None;942
self.pending_style = None;960
self.pending_style = None;943
self.conversion = None;961
self.conversion = None;944
self.pasted_markdown = None;962
self.pasted_markdown = None;@@ -1488,7 +1506,7 @@ impl Composer {1488
let text = if selected.contains(TABLE_MARK) {1506
let text = if selected.contains(TABLE_MARK) {1489
Draft::from_lines(&lines).plain_text()1507
Draft::from_lines(&lines).plain_text()1490
} else {1508
} else {1491
selected.replace(OBJECT_MARK, "")1509
selected.replace([OBJECT_MARK, CODE_HEADER_MARK], "")1492
};1510
};1493
if text.is_empty() {1511
if text.is_empty() {1494
return true;1512
return true;@@ -3106,11 +3124,18 @@ impl Render for Composer {3106
.children(attach)3124
.children(attach)3107
.children(self.render_rewrite_button(cx))3125
.children(self.render_rewrite_button(cx))3108
.children(self.render_plus_button(cx));3126
.children(self.render_plus_button(cx));3127
// Teams gives a code block the full width and keeps the actions right, beside Send.3128
let below_code = self3129
.draft3130
.lines()3131
.iter()3132
.any(|kind| matches!(kind, LineKind::Code(_)));3109
let stacked = !post_layout3133
let stacked = !post_layout3110
&& self3134
&& (below_code3111
.composer_bounds3135
|| self3112
.get()3136
.composer_bounds3113
.is_some_and(|bounds| f32::from(bounds.size.width) < STACKED_ACTIONS_WIDTH);3137
.get()3138
.is_some_and(|bounds| f32::from(bounds.size.width) < STACKED_ACTIONS_WIDTH));3114
let mut send = Some(send);3139
let mut send = Some(send);3115
let (row_actions, stacked_actions, post_footer) = if post_layout {3140
let (row_actions, stacked_actions, post_footer) = if post_layout {3116
(3141
(@@ -3136,6 +3161,15 @@ impl Render for Composer {3136
.unwrap_or(false)3161
.unwrap_or(false)3137
})3162
})3138
.token(move |context, _, cx| {3163
.token(move |context, _, cx| {3164
if context.is_block() && is_code_header_token(context.token()) {3165
let weak = tokens_composer.clone();3166
let (at, width) = (context.range().start, context.available_width());3167
if let Ok(header) = tokens_composer3168
.read_with(cx, |this, _| this.render_code_header(weak, at, width))3169
{3170
return header;3171
}3172
}3139
if context.is_block() && is_rule_token(context.token()) {3173
if context.is_block() && is_rule_token(context.token()) {3140
return render_rule_token(3174
return render_rule_token(3141
context.available_width(),3175
context.available_width(),@@ -3518,7 +3552,10 @@ impl Render for Composer {3518
}3552
}3519
}))3553
}))3520
.capture_action(cx.listener(|this, _: &Escape, window, cx| {3554
.capture_action(cx.listener(|this, _: &Escape, window, cx| {3521
if this.table_picker.take().is_some() || this.table_menu.take().is_some() {3555
if this.table_picker.take().is_some()3556
|| this.table_menu.take().is_some()3557
|| this.code_language_menu.take().is_some()3558
{3522
cx.notify();3559
cx.notify();3523
cx.stop_propagation();3560
cx.stop_propagation();3524
return;3561
return;@@ -3579,6 +3616,7 @@ impl Render for Composer {3579
.children(self.render_slash_popup(cx))3616
.children(self.render_slash_popup(cx))3580
.children(self.render_emoji_popup(window, cx))3617
.children(self.render_emoji_popup(window, cx))3581
.children(self.render_toolbar(focused, cx))3618
.children(self.render_toolbar(focused, cx))3619
.children(self.render_code_language_menu(cx))3582
.children(self.render_schedule(cx))3620
.children(self.render_schedule(cx))3583
.children(self.render_delivery_menu(cx))3621
.children(self.render_delivery_menu(cx))3584
.children(self.render_plus_menu(cx))3622
.children(self.render_plus_menu(cx))@@ -3658,15 +3696,7 @@ impl Render for Composer {3658
)3696
)3659
.children(row_actions)3697
.children(row_actions)3660
.when_some(send.filter(|_| !post_layout), |row, send| {3698
.when_some(send.filter(|_| !post_layout), |row, send| {3661
row.child(3699
row.child(send_divider()).child(send)3662
div()3663
.flex_none()3664
.w(px(1.))3665
.h(px(SEND_DIVIDER_HEIGHT))3666
.ml(px(COMPOSER_BUTTON_INSET))3667
.bg(theme::border()),3668
)3669
.child(send)3670
}),3700
}),3671
)3701
)3672
.children(stacked_actions.map(|(actions, send)| {3702
.children(stacked_actions.map(|(actions, send)| {@@ -3676,8 +3706,12 @@ impl Render for Composer {3676
.items_center()3706
.items_center()3677
.px(px(COMPOSER_BUTTON_INSET))3707
.px(px(COMPOSER_BUTTON_INSET))3678
.pb(px(COMPOSER_BUTTON_INSET))3708
.pb(px(COMPOSER_BUTTON_INSET))3709
.when(below_code, |row| row.child(div().flex_1()))3679
.child(actions)3710
.child(actions)3680
.child(div().flex_1())3711
.when(!below_code, |row| row.child(div().flex_1()))3712
.when(below_code && send.is_some(), |row| {3713
row.child(send_divider())3714
})3681
.children(send)3715
.children(send)3682
}))3716
}))3683
.children(post_footer),3717
.children(post_footer),@@ -4781,16 +4815,135 @@ mod tests {4781
}4815
}4782
4816
4783
#[gpui_kit::test]4817
#[gpui_kit::test]4784
fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {4818
fn backspace_after_a_fence_gives_it_back_for_a_language(cx: &mut TestAppContext) {4785
let mut typist = typist(cx);4819
let mut typist = typist(cx);4786
typist.type_text("```");4820
typist.type_text("```");4821
assert_eq!(typist.draft().lines(), [teams_core::LineKind::Code(None)]);4822
typist.press("backspace");4823
assert_eq!(typist.value(), "```");4824
typist.type_text("py");4787
typist.press("enter");4825
typist.press("enter");4826
assert_eq!(4827
typist.draft().lines(),4828
[teams_core::LineKind::Code(Some("python".into()))]4829
);4830
}4831
4832
#[gpui_kit::test]4833
fn the_language_picker_in_the_header_sets_the_whole_code_block(cx: &mut TestAppContext) {4834
use gpui_kit::VisualTestContext;4835
4836
use super::super::code_language::{CODE_LANGUAGE_ROW_TAG, CODE_LANGUAGE_TAG};4837
4838
let mut typist = typist(cx);4839
typist.type_text("x");4840
typist.press("shift-enter");4841
typist.type_text("```");4842
typist.type_text("a");4843
typist.press("enter");4844
typist.type_text("b");4845
let composer = typist.composer.clone();4846
let handle = typist.handle;4847
let mut visual = VisualTestContext::from_window(handle, typist.cx);4848
visual.update(|window, cx| window.render_frame(cx));4849
let header = visual4850
.debug_bounds(CODE_LANGUAGE_TAG)4851
.expect("a header on the block");4852
visual.simulate_click(header.center(), Default::default());4853
visual.run_until_parked();4854
assert_eq!(4855
composer.read_with(&visual, |composer, _| composer.code_language_menu),4856
Some(1)4857
);4858
visual.update(|window, cx| window.render_frame(cx));4859
let row = visual4860
.debug_bounds(Box::leak(4861
format!("{CODE_LANGUAGE_ROW_TAG}dart").into_boxed_str(),4862
))4863
.expect("Dart in the open menu");4864
visual.simulate_click(row.center(), Default::default());4865
visual.run_until_parked();4866
let draft = composer.read_with(&visual, |composer, _| composer.draft.clone());4867
let dart = teams_core::LineKind::Code(Some("dart".into()));4868
assert_eq!(4869
draft.lines(),4870
[teams_core::LineKind::Text, dart.clone(), dart]4871
);4872
assert_eq!(4873
draft.to_html(),4874
"x<pre class=\"language-dart skipProofing\" spellcheck=\"false\"><code>a<br>b</code></pre>"4875
);4876
}4877
4878
#[gpui_kit::test]4879
fn code_typed_after_picking_a_language_is_highlighted(cx: &mut TestAppContext) {4880
let mut typist = typist(cx);4881
typist.type_text("```");4882
let composer = typist.composer.clone();4883
typist.act(|window, cx| {4884
composer.update(cx, |composer, cx| {4885
composer.choose_code_language(0, "python", window, cx)4886
})4887
});4888
typist.type_text("def f():");4889
typist.press("enter");4890
typist.type_text("class A: pass");4891
let draft = typist.draft();4892
assert_eq!(4893
draft.lines()[1],4894
teams_core::LineKind::Code(Some("python".into()))4895
);4896
let style = super::super::draft_style(&draft, "Mono".into());4897
let words: Vec<_> = style4898
.text4899
.iter()4900
.map(|decoration| &draft.text()[decoration.range.clone()])4901
.collect();4902
for keyword in ["def", "class", "pass"] {4903
assert!(words.contains(&keyword), "{keyword} in {words:?}");4904
}4905
}4906
4907
#[gpui_kit::test]4908
fn copied_code_leaves_its_header_behind_and_escape_closes_the_picker(4909
cx: &mut TestAppContext,4910
) {4911
let mut typist = typist(cx);4912
typist.type_text("x");4913
typist.press("shift-enter");4914
typist.type_text("```");4915
typist.type_text("a");4916
let composer = typist.composer.clone();4917
let (input, end) = typist.cx.update(|cx| {4918
let composer = composer.read(cx);4919
(composer.input.clone(), composer.draft.text().len())4920
});4921
typist.act(|_, cx| {4922
input.update(cx, |state, cx| state.set_selected_range(0..end, cx));4923
composer.update(cx, |composer, cx| {4924
composer.copy_selection(cx);4925
composer.code_language_menu = Some(1);4926
})4927
});4928
let copied = typist.cx.read_from_clipboard().and_then(|item| item.text());4929
assert_eq!(copied.as_deref(), Some("x\na"));4930
typist.press("escape");4931
assert_eq!(4932
typist.cx.update(|cx| composer.read(cx).code_language_menu),4933
None4934
);4935
}4936
4937
#[gpui_kit::test]4938
fn delete_at_a_code_line_end_joins_without_padding(cx: &mut TestAppContext) {4939
let mut typist = typist(cx);4940
typist.type_text("```");4788
typist.type_text("a");4941
typist.type_text("a");4789
typist.press("enter");4942
typist.press("enter");4790
typist.type_text("b");4943
typist.type_text("b");4791
typist.press("up end delete");4944
typist.press("up end delete");4792
assert_eq!(4945
assert_eq!(4793
typist.outgoing().html(),4946
typist.outgoing().draft.to_html(),4794
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>"4947
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>ab</code></pre>"4795
);4948
);4796
}4949
}@@ -4800,7 +4953,6 @@ mod tests {4800
fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) {4953
fn copied_code_has_no_padding_in_the_plain_text(cx: &mut TestAppContext) {4801
let mut typist = typist(cx);4954
let mut typist = typist(cx);4802
typist.type_text("```");4955
typist.type_text("```");4803
typist.press("enter");4804
typist.type_text(" x");4956
typist.type_text(" x");4805
typist.press("ctrl-a ctrl-c");4957
typist.press("ctrl-a ctrl-c");4806
let text = typist.cx.read_from_clipboard().and_then(|item| item.text());4958
let text = typist.cx.read_from_clipboard().and_then(|item| item.text());@@ -4942,13 +5094,15 @@ mod tests {4942
fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) {5094
fn code_blocks_take_markdown_and_smileys_literally(cx: &mut TestAppContext) {4943
let mut typist = typist(cx);5095
let mut typist = typist(cx);4944
typist.type_text("```");5096
typist.type_text("```");4945
typist.press("enter");4946
typist.type_text(":) ");5097
typist.type_text(":) ");4947
typist5098
typist4948
.cx5099
.cx4949
.write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));5100
.write_to_clipboard(gpui_kit::ClipboardItem::new_string("**x**".to_owned()));4950
typist.press("ctrl-v");5101
typist.press("ctrl-v");4951
assert_eq!(typist.value(), ":) **x**");5102
assert_eq!(5103
typist.value(),5104
format!("{}:) **x**", teams_core::CODE_HEADER_MARK)5105
);4952
let composer = typist.composer.clone();5106
let composer = typist.composer.clone();4953
assert!(5107
assert!(4954
typist5108
typist@@ -4957,7 +5111,7 @@ mod tests {4957
);5111
);4958
let outgoing = typist.outgoing();5112
let outgoing = typist.outgoing();4959
assert_eq!(5113
assert_eq!(4960
outgoing.html(),5114
outgoing.draft.to_html(),4961
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>"5115
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>:) **x**</code></pre>"4962
);5116
);4963
}5117
}@@ -0,0 +1,204 @@
1
use gpui_kit::component::input::InlineToken;
2
use gpui_kit::component::{h_flex, v_flex};
3
use gpui_kit::prelude::FluentBuilder as _;
4
use gpui_kit::*;
5
use teams_core::{CODE_HEADER_MARK, CODE_LANGUAGES, LineKind, PLAIN_LANGUAGE};
6
7
use super::Composer;
8
use crate::theme::{self, ElevatedSurface as _};
9
use crate::views::draft_style::CODE_INDENT;
10
use crate::views::widgets::symbol;
11
12
const TOKEN_PREFIX: &str = "code-header-";
13
pub(super) const CODE_LANGUAGE_TAG: &str = "composer/code-language";
14
pub(super) const CODE_LANGUAGE_ROW_TAG: &str = "composer/code-language-row-";
15
const HEADER_HEIGHT: f32 = 36.;
16
/// Room between the rule and the first code line.
17
const CODE_TOP_GAP: f32 = 6.;
18
const MENU_WIDTH: f32 = 180.;
19
const MENU_HEIGHT: f32 = 280.;
20
21
pub(super) fn is_code_header_token(token: &InlineToken) -> bool {
22
token.id().starts_with(TOKEN_PREFIX)
23
}
24
25
impl Composer {
26
/// Every code block's first line gets its header token in place of the header mark.
27
pub(super) fn sync_code_headers(&mut self, window: &mut Window, cx: &mut Context<Self>) {
28
if self.input.read(cx).value().as_ref() != self.draft.text() {
29
return;
30
}
31
let tokens: Vec<_> = self
32
.input
33
.read(cx)
34
.tokens()
35
.iter()
36
.filter(|span| is_code_header_token(span.token()))
37
.map(|span| span.range())
38
.collect();
39
let marks: Vec<_> = self
40
.draft
41
.text()
42
.match_indices(CODE_HEADER_MARK)
43
.map(|(at, mark)| at..at + mark.len())
44
.filter(|mark| !tokens.contains(mark))
45
.collect();
46
for mark in marks {
47
self.table_counter += 1;
48
let token = InlineToken::new(
49
format!("{TOKEN_PREFIX}{}", self.table_counter),
50
CODE_HEADER_MARK.to_string(),
51
)
52
.header();
53
self.input.update(cx, |state, cx| {
54
let selection = state.selected_range();
55
if state
56
.replace_range_with_token(mark, token, window, cx)
57
.is_ok()
58
{
59
state.set_selected_range(selection, cx);
60
}
61
});
62
}
63
}
64
65
/// Teams' code block header: the language, which opens its picker, over a rule.
66
pub(super) fn render_code_header(
67
&self,
68
composer: WeakEntity<Composer>,
69
at: usize,
70
width: Pixels,
71
) -> AnyElement {
72
let line = self.draft.line_at(at);
73
let language = match self.draft.lines().get(line) {
74
Some(LineKind::Code(language)) => language.clone(),
75
_ => None,
76
};
77
let chosen = language.unwrap_or_else(|| PLAIN_LANGUAGE.to_owned());
78
let name = teams_core::code_language(&chosen)
79
.map_or(chosen.clone(), |language| language.name.to_owned());
80
let open = self.code_language_menu == Some(line);
81
let toggle = composer.clone();
82
let button = h_flex()
83
.id(ElementId::Name(format!("code-language-{at}").into()))
84
.debug_selector(|| CODE_LANGUAGE_TAG.into())
85
.h(px(24.))
86
.px(px(6.))
87
.gap(px(4.))
88
.items_center()
89
.rounded(px(4.))
90
.text_size(px(13.))
91
.text_color(theme::text())
92
.cursor_pointer()
93
.hover(|button| button.bg(theme::popup_hover()))
94
.on_mouse_down(MouseButton::Left, |_, window, cx| {
95
window.prevent_default();
96
cx.stop_propagation();
97
})
98
.on_click(move |_, _, cx| {
99
toggle
100
.update(cx, |this, cx| {
101
this.code_language_menu = (!open).then_some(line);
102
cx.notify();
103
})
104
.ok();
105
})
106
.child(symbol("code", 14., theme::text_muted()))
107
.child(name)
108
.child(symbol("keyboard_arrow_down", 14., theme::text_muted()));
109
v_flex()
110
.w(width)
111
.pb(px(CODE_TOP_GAP))
112
.child(
113
h_flex()
114
.h(px(HEADER_HEIGHT))
115
.px(px(6.))
116
.items_center()
117
.border_b_1()
118
.border_color(theme::code_frame())
119
.child(button),
120
)
121
.into_any_element()
122
}
123
124
/// The open picker, drawn over the composer: inside the input it could not be clicked
125
/// where it reaches past the input's bounds.
126
pub(super) fn render_code_language_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
127
let line = self.code_language_menu?;
128
let at = self.draft.line_ranges().get(line)?.start;
129
let LineKind::Code(language) = self.draft.lines().get(line)? else {
130
return None;
131
};
132
let chosen = language
133
.as_deref()
134
.and_then(teams_core::code_language)
135
.map_or(PLAIN_LANGUAGE, |language| language.id);
136
let header = self.input.read(cx).range_to_bounds(&(at..at))?;
137
let rows = CODE_LANGUAGES.iter().map(|language| {
138
let (id, name) = (language.id, language.name);
139
div()
140
.id(ElementId::Name(format!("code-language-{id}").into()))
141
.debug_selector(move || format!("{CODE_LANGUAGE_ROW_TAG}{id}"))
142
.px(px(10.))
143
.py(px(5.))
144
.rounded(px(6.))
145
.text_size(px(13.))
146
.text_color(theme::text())
147
.cursor_pointer()
148
.when(id == chosen, |row| row.bg(theme::popup_hover()))
149
.hover(|row| row.bg(theme::popup_hover()))
150
.on_mouse_down(MouseButton::Left, |_, window, cx| {
151
window.prevent_default();
152
cx.stop_propagation();
153
})
154
.on_click(cx.listener(move |this, _, window, cx| {
155
this.choose_code_language(at, id, window, cx)
156
}))
157
.child(name)
158
});
159
// Lined up with the block's edge, left of the line indent where `at` sits.
160
let left = header.left() - px(CODE_INDENT);
161
Some(
162
deferred(
163
// Above the header, as in Teams: the composer sits at the window's bottom.
164
anchored()
165
.position(point(left, header.top()))
166
.anchor(Anchor::BottomLeft)
167
.snap_to_window_with_margin(px(8.))
168
.child(
169
v_flex()
170
.id("code-language-menu")
171
.mb(px(4.))
172
.w(px(MENU_WIDTH))
173
.max_h(px(MENU_HEIGHT))
174
.overflow_y_scroll()
175
.p(px(4.))
176
.rounded(px(10.))
177
.flyout_surface()
178
.occlude()
179
.on_mouse_down_out(cx.listener(|this, _, _, cx| {
180
this.code_language_menu = None;
181
cx.notify();
182
}))
183
.children(rows),
184
),
185
)
186
.with_priority(1)
187
.into_any_element(),
188
)
189
}
190
191
pub(super) fn choose_code_language(
192
&mut self,
193
at: usize,
194
id: &str,
195
window: &mut Window,
196
cx: &mut Context<Self>,
197
) {
198
let language = (id != PLAIN_LANGUAGE).then(|| id.to_owned());
199
self.draft.set_code_language(at, language);
200
self.code_language_menu = None;
201
self.commit(None, window, cx);
202
cx.notify();
203
}
204
}
@@ -0,0 +1,204 @@1
use gpui_kit::component::input::InlineToken;2
use gpui_kit::component::{h_flex, v_flex};3
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::*;5
use teams_core::{CODE_HEADER_MARK, CODE_LANGUAGES, LineKind, PLAIN_LANGUAGE};6
7
use super::Composer;8
use crate::theme::{self, ElevatedSurface as _};9
use crate::views::draft_style::CODE_INDENT;10
use crate::views::widgets::symbol;11
12
const TOKEN_PREFIX: &str = "code-header-";13
pub(super) const CODE_LANGUAGE_TAG: &str = "composer/code-language";14
pub(super) const CODE_LANGUAGE_ROW_TAG: &str = "composer/code-language-row-";15
const HEADER_HEIGHT: f32 = 36.;16
/// Room between the rule and the first code line.17
const CODE_TOP_GAP: f32 = 6.;18
const MENU_WIDTH: f32 = 180.;19
const MENU_HEIGHT: f32 = 280.;20
21
pub(super) fn is_code_header_token(token: &InlineToken) -> bool {22
token.id().starts_with(TOKEN_PREFIX)23
}24
25
impl Composer {26
/// Every code block's first line gets its header token in place of the header mark.27
pub(super) fn sync_code_headers(&mut self, window: &mut Window, cx: &mut Context<Self>) {28
if self.input.read(cx).value().as_ref() != self.draft.text() {29
return;30
}31
let tokens: Vec<_> = self32
.input33
.read(cx)34
.tokens()35
.iter()36
.filter(|span| is_code_header_token(span.token()))37
.map(|span| span.range())38
.collect();39
let marks: Vec<_> = self40
.draft41
.text()42
.match_indices(CODE_HEADER_MARK)43
.map(|(at, mark)| at..at + mark.len())44
.filter(|mark| !tokens.contains(mark))45
.collect();46
for mark in marks {47
self.table_counter += 1;48
let token = InlineToken::new(49
format!("{TOKEN_PREFIX}{}", self.table_counter),50
CODE_HEADER_MARK.to_string(),51
)52
.header();53
self.input.update(cx, |state, cx| {54
let selection = state.selected_range();55
if state56
.replace_range_with_token(mark, token, window, cx)57
.is_ok()58
{59
state.set_selected_range(selection, cx);60
}61
});62
}63
}64
65
/// Teams' code block header: the language, which opens its picker, over a rule.66
pub(super) fn render_code_header(67
&self,68
composer: WeakEntity<Composer>,69
at: usize,70
width: Pixels,71
) -> AnyElement {72
let line = self.draft.line_at(at);73
let language = match self.draft.lines().get(line) {74
Some(LineKind::Code(language)) => language.clone(),75
_ => None,76
};77
let chosen = language.unwrap_or_else(|| PLAIN_LANGUAGE.to_owned());78
let name = teams_core::code_language(&chosen)79
.map_or(chosen.clone(), |language| language.name.to_owned());80
let open = self.code_language_menu == Some(line);81
let toggle = composer.clone();82
let button = h_flex()83
.id(ElementId::Name(format!("code-language-{at}").into()))84
.debug_selector(|| CODE_LANGUAGE_TAG.into())85
.h(px(24.))86
.px(px(6.))87
.gap(px(4.))88
.items_center()89
.rounded(px(4.))90
.text_size(px(13.))91
.text_color(theme::text())92
.cursor_pointer()93
.hover(|button| button.bg(theme::popup_hover()))94
.on_mouse_down(MouseButton::Left, |_, window, cx| {95
window.prevent_default();96
cx.stop_propagation();97
})98
.on_click(move |_, _, cx| {99
toggle100
.update(cx, |this, cx| {101
this.code_language_menu = (!open).then_some(line);102
cx.notify();103
})104
.ok();105
})106
.child(symbol("code", 14., theme::text_muted()))107
.child(name)108
.child(symbol("keyboard_arrow_down", 14., theme::text_muted()));109
v_flex()110
.w(width)111
.pb(px(CODE_TOP_GAP))112
.child(113
h_flex()114
.h(px(HEADER_HEIGHT))115
.px(px(6.))116
.items_center()117
.border_b_1()118
.border_color(theme::code_frame())119
.child(button),120
)121
.into_any_element()122
}123
124
/// The open picker, drawn over the composer: inside the input it could not be clicked125
/// where it reaches past the input's bounds.126
pub(super) fn render_code_language_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {127
let line = self.code_language_menu?;128
let at = self.draft.line_ranges().get(line)?.start;129
let LineKind::Code(language) = self.draft.lines().get(line)? else {130
return None;131
};132
let chosen = language133
.as_deref()134
.and_then(teams_core::code_language)135
.map_or(PLAIN_LANGUAGE, |language| language.id);136
let header = self.input.read(cx).range_to_bounds(&(at..at))?;137
let rows = CODE_LANGUAGES.iter().map(|language| {138
let (id, name) = (language.id, language.name);139
div()140
.id(ElementId::Name(format!("code-language-{id}").into()))141
.debug_selector(move || format!("{CODE_LANGUAGE_ROW_TAG}{id}"))142
.px(px(10.))143
.py(px(5.))144
.rounded(px(6.))145
.text_size(px(13.))146
.text_color(theme::text())147
.cursor_pointer()148
.when(id == chosen, |row| row.bg(theme::popup_hover()))149
.hover(|row| row.bg(theme::popup_hover()))150
.on_mouse_down(MouseButton::Left, |_, window, cx| {151
window.prevent_default();152
cx.stop_propagation();153
})154
.on_click(cx.listener(move |this, _, window, cx| {155
this.choose_code_language(at, id, window, cx)156
}))157
.child(name)158
});159
// Lined up with the block's edge, left of the line indent where `at` sits.160
let left = header.left() - px(CODE_INDENT);161
Some(162
deferred(163
// Above the header, as in Teams: the composer sits at the window's bottom.164
anchored()165
.position(point(left, header.top()))166
.anchor(Anchor::BottomLeft)167
.snap_to_window_with_margin(px(8.))168
.child(169
v_flex()170
.id("code-language-menu")171
.mb(px(4.))172
.w(px(MENU_WIDTH))173
.max_h(px(MENU_HEIGHT))174
.overflow_y_scroll()175
.p(px(4.))176
.rounded(px(10.))177
.flyout_surface()178
.occlude()179
.on_mouse_down_out(cx.listener(|this, _, _, cx| {180
this.code_language_menu = None;181
cx.notify();182
}))183
.children(rows),184
),185
)186
.with_priority(1)187
.into_any_element(),188
)189
}190
191
pub(super) fn choose_code_language(192
&mut self,193
at: usize,194
id: &str,195
window: &mut Window,196
cx: &mut Context<Self>,197
) {198
let language = (id != PLAIN_LANGUAGE).then(|| id.to_owned());199
self.draft.set_code_language(at, language);200
self.code_language_menu = None;201
self.commit(None, window, cx);202
cx.notify();203
}204
}@@ -171,6 +171,7 @@ impl Composer {
171
171
self.sync_table_view(&id, &table, window, cx);
172
172
}
173
173
self.sync_rules(window, cx);
174
self.sync_code_headers(window, cx);
174
175
}
175
176
176
177
fn sync_table_view(
@@ -171,6 +171,7 @@ impl Composer {171
self.sync_table_view(&id, &table, window, cx);171
self.sync_table_view(&id, &table, window, cx);172
}172
}173
self.sync_rules(window, cx);173
self.sync_rules(window, cx);174
self.sync_code_headers(window, cx);174
}175
}175
176
176
fn sync_table_view(177
fn sync_table_view(@@ -1890,6 +1890,7 @@ impl ConversationView {
1890
1890
self.rebuild_generation += 1;
1891
1891
let generation = self.rebuild_generation;
1892
1892
let store = self.app.read(cx).store.clone();
1893
let date_style = app_base::format::current_date_style();
1893
1894
cx.spawn(async move |this, cx| {
1894
1895
let (plan, loaded) = cx
1895
1896
.background_spawn(async move {
@@ -1905,6 +1906,8 @@ impl ConversationView {
1905
1906
};
1906
1907
let (plan, loaded, context, built) = cx
1907
1908
.background_spawn(async move {
1909
// The regional format is per thread: without it the times fall back to 24 h.
1910
app_base::format::set_date_style(date_style);
1908
1911
let built = build_rows(&plan, &loaded, &context);
1909
1912
(plan, loaded, context, built)
1910
1913
})
@@ -1890,6 +1890,7 @@ impl ConversationView {1890
self.rebuild_generation += 1;1890
self.rebuild_generation += 1;1891
let generation = self.rebuild_generation;1891
let generation = self.rebuild_generation;1892
let store = self.app.read(cx).store.clone();1892
let store = self.app.read(cx).store.clone();1893
let date_style = app_base::format::current_date_style();1893
cx.spawn(async move |this, cx| {1894
cx.spawn(async move |this, cx| {1894
let (plan, loaded) = cx1895
let (plan, loaded) = cx1895
.background_spawn(async move {1896
.background_spawn(async move {@@ -1905,6 +1906,8 @@ impl ConversationView {1905
};1906
};1906
let (plan, loaded, context, built) = cx1907
let (plan, loaded, context, built) = cx1907
.background_spawn(async move {1908
.background_spawn(async move {1909
// The regional format is per thread: without it the times fall back to 24 h.1910
app_base::format::set_date_style(date_style);1908
let built = build_rows(&plan, &loaded, &context);1911
let built = build_rows(&plan, &loaded, &context);1909
(plan, loaded, context, built)1912
(plan, loaded, context, built)1910
})1913
})@@ -274,7 +274,7 @@ impl ConversationView {
274
274
self.select_occurrence(index, cx);
275
275
}
276
276
}
277
(_, Some(url)) => cx.open_url(url),
277
(_, Some(url)) => app_base::open_link::open_url(cx, url),
278
278
(_, None) => {}
279
279
}
280
280
}
@@ -478,7 +478,7 @@ impl ConversationView {
478
478
RecapCommand::Retry => self.select_occurrence(self.recap.selected, cx),
479
479
RecapCommand::Play => {
480
480
if let Some(occurrence) = self.selected_occurrence() {
481
cx.open_url(&occurrence.recording_url);
481
app_base::open_link::open_url(cx, &occurrence.recording_url);
482
482
}
483
483
}
484
484
RecapCommand::Download(download) => self.pick_save_target(download, cx),
@@ -274,7 +274,7 @@ impl ConversationView {274
self.select_occurrence(index, cx);274
self.select_occurrence(index, cx);275
}275
}276
}276
}277
(_, Some(url)) => cx.open_url(url),277
(_, Some(url)) => app_base::open_link::open_url(cx, url),278
(_, None) => {}278
(_, None) => {}279
}279
}280
}280
}@@ -478,7 +478,7 @@ impl ConversationView {478
RecapCommand::Retry => self.select_occurrence(self.recap.selected, cx),478
RecapCommand::Retry => self.select_occurrence(self.recap.selected, cx),479
RecapCommand::Play => {479
RecapCommand::Play => {480
if let Some(occurrence) = self.selected_occurrence() {480
if let Some(occurrence) = self.selected_occurrence() {481
cx.open_url(&occurrence.recording_url);481
app_base::open_link::open_url(cx, &occurrence.recording_url);482
}482
}483
}483
}484
RecapCommand::Download(download) => self.pick_save_target(download, cx),484
RecapCommand::Download(download) => self.pick_save_target(download, cx),@@ -166,12 +166,15 @@ impl RenderEnv {
166
166
let (view, key, handle) = (view.clone(), message.key.clone(), window.window_handle());
167
167
boxed(move |cx| {
168
168
let (view, key) = (view.clone(), key.clone());
169
handle
170
.update(cx, move |_, window, cx| {
171
view.update(cx, |this, cx| this.retry(&key, window, cx))
172
.ok();
173
})
174
.ok();
169
// The click runs inside this window's update, which `handle.update` cannot reenter.
170
cx.defer(move |cx| {
171
handle
172
.update(cx, move |_, window, cx| {
173
view.update(cx, |this, cx| this.retry(&key, window, cx))
174
.ok();
175
})
176
.ok();
177
});
175
178
})
176
179
});
177
180
let scheduled = view.upgrade().and_then(|entity| {
@@ -166,12 +166,15 @@ impl RenderEnv {166
let (view, key, handle) = (view.clone(), message.key.clone(), window.window_handle());166
let (view, key, handle) = (view.clone(), message.key.clone(), window.window_handle());167
boxed(move |cx| {167
boxed(move |cx| {168
let (view, key) = (view.clone(), key.clone());168
let (view, key) = (view.clone(), key.clone());169
handle169
// The click runs inside this window's update, which `handle.update` cannot reenter.170
.update(cx, move |_, window, cx| {170
cx.defer(move |cx| {171
view.update(cx, |this, cx| this.retry(&key, window, cx))171
handle172
.ok();172
.update(cx, move |_, window, cx| {173
})173
view.update(cx, |this, cx| this.retry(&key, window, cx))174
.ok();174
.ok();175
})176
.ok();177
});175
})178
})176
});179
});177
let scheduled = view.upgrade().and_then(|entity| {180
let scheduled = view.upgrade().and_then(|entity| {@@ -435,29 +435,34 @@ impl ConversationView {
435
435
cx: &App,
436
436
) -> Option<ScheduledRowActions> {
437
437
let draft_id = draft_id_of(&row.key)?.to_owned();
438
// These links run inside this window's update, which `handle.update` cannot reenter: defer it.
438
439
let handle = window.window_handle();
439
440
let link = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> RowAction {
440
441
let (view, draft_id) = (view.clone(), draft_id.clone());
441
442
Some(Box::new(move |cx: &mut App| {
442
443
let (view, draft_id) = (view.clone(), draft_id.clone());
443
handle
444
.update(cx, move |_, window, cx| {
445
view.update(cx, |this, cx| run(this, &draft_id, window, cx))
446
.ok();
447
})
448
.ok();
444
cx.defer(move |cx| {
445
handle
446
.update(cx, move |_, window, cx| {
447
view.update(cx, |this, cx| run(this, &draft_id, window, cx))
448
.ok();
449
})
450
.ok();
451
});
449
452
}))
450
453
};
451
454
let retry: RowAction = {
452
455
let view = view.clone();
453
456
Some(Box::new(move |cx: &mut App| {
454
457
let view = view.clone();
455
handle
456
.update(cx, move |_, window, cx| {
457
view.update(cx, |this, cx| this.retry_scheduled(window, cx))
458
.ok();
459
})
460
.ok();
458
cx.defer(move |cx| {
459
handle
460
.update(cx, move |_, window, cx| {
461
view.update(cx, |this, cx| this.retry_scheduled(window, cx))
462
.ok();
463
})
464
.ok();
465
});
461
466
}))
462
467
};
463
468
let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
@@ -435,29 +435,34 @@ impl ConversationView {435
cx: &App,435
cx: &App,436
) -> Option<ScheduledRowActions> {436
) -> Option<ScheduledRowActions> {437
let draft_id = draft_id_of(&row.key)?.to_owned();437
let draft_id = draft_id_of(&row.key)?.to_owned();438
// These links run inside this window's update, which `handle.update` cannot reenter: defer it.438
let handle = window.window_handle();439
let handle = window.window_handle();439
let link = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> RowAction {440
let link = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> RowAction {440
let (view, draft_id) = (view.clone(), draft_id.clone());441
let (view, draft_id) = (view.clone(), draft_id.clone());441
Some(Box::new(move |cx: &mut App| {442
Some(Box::new(move |cx: &mut App| {442
let (view, draft_id) = (view.clone(), draft_id.clone());443
let (view, draft_id) = (view.clone(), draft_id.clone());443
handle444
cx.defer(move |cx| {444
.update(cx, move |_, window, cx| {445
handle445
view.update(cx, |this, cx| run(this, &draft_id, window, cx))446
.update(cx, move |_, window, cx| {446
.ok();447
view.update(cx, |this, cx| run(this, &draft_id, window, cx))447
})448
.ok();448
.ok();449
})450
.ok();451
});449
}))452
}))450
};453
};451
let retry: RowAction = {454
let retry: RowAction = {452
let view = view.clone();455
let view = view.clone();453
Some(Box::new(move |cx: &mut App| {456
Some(Box::new(move |cx: &mut App| {454
let view = view.clone();457
let view = view.clone();455
handle458
cx.defer(move |cx| {456
.update(cx, move |_, window, cx| {459
handle457
view.update(cx, |this, cx| this.retry_scheduled(window, cx))460
.update(cx, move |_, window, cx| {458
.ok();461
view.update(cx, |this, cx| this.retry_scheduled(window, cx))459
})462
.ok();460
.ok();463
})464
.ok();465
});461
}))466
}))462
};467
};463
let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {468
let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {@@ -87,7 +87,8 @@ const IMPORTANCE_LABEL_SIZE: f32 = 12.;
87
87
const IMPORTANCE_LINE_HEIGHT: f32 = 16.;
88
88
const COMPACT_IMPORTANCE_LINE_HEIGHT: f32 = 14.;
89
89
pub(super) const BUBBLE_PADDING_X: f32 = 12.;
90
const FIGURE_SPACE_WIDTH: f32 = 7.4;
90
/// Advance of the no-break space that reserves the time's room: 489/2000 em in Google Sans Flex Regular at `BODY_SIZE`.
91
const TIME_ROOM_WIDTH: f32 = 3.3;
91
92
const PULSE_PERIOD: Duration = Duration::from_millis(1600);
92
93
const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);
93
94
pub const JUMP_HIGHLIGHT_PERIOD: Duration = Duration::from_millis(2400);
@@ -653,7 +654,7 @@ fn meta_room(row: &MessageRow, own: bool, saved: bool) -> usize {
653
654
if own {
654
655
width += META_CHECK_SIZE + 4.;
655
656
}
656
(width / FIGURE_SPACE_WIDTH).ceil() as usize
657
(width / TIME_ROOM_WIDTH).ceil() as usize
657
658
}
658
659
659
660
fn with_meta_room(blocks: &[Block], room: usize) -> Option<Vec<Block>> {
@@ -87,7 +87,8 @@ const IMPORTANCE_LABEL_SIZE: f32 = 12.;87
const IMPORTANCE_LINE_HEIGHT: f32 = 16.;87
const IMPORTANCE_LINE_HEIGHT: f32 = 16.;88
const COMPACT_IMPORTANCE_LINE_HEIGHT: f32 = 14.;88
const COMPACT_IMPORTANCE_LINE_HEIGHT: f32 = 14.;89
pub(super) const BUBBLE_PADDING_X: f32 = 12.;89
pub(super) const BUBBLE_PADDING_X: f32 = 12.;90
const FIGURE_SPACE_WIDTH: f32 = 7.4;90
/// Advance of the no-break space that reserves the time's room: 489/2000 em in Google Sans Flex Regular at `BODY_SIZE`.91
const TIME_ROOM_WIDTH: f32 = 3.3;91
const PULSE_PERIOD: Duration = Duration::from_millis(1600);92
const PULSE_PERIOD: Duration = Duration::from_millis(1600);92
const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);93
const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);93
pub const JUMP_HIGHLIGHT_PERIOD: Duration = Duration::from_millis(2400);94
pub const JUMP_HIGHLIGHT_PERIOD: Duration = Duration::from_millis(2400);@@ -653,7 +654,7 @@ fn meta_room(row: &MessageRow, own: bool, saved: bool) -> usize {653
if own {654
if own {654
width += META_CHECK_SIZE + 4.;655
width += META_CHECK_SIZE + 4.;655
}656
}656
(width / FIGURE_SPACE_WIDTH).ceil() as usize657
(width / TIME_ROOM_WIDTH).ceil() as usize657
}658
}658
659
659
fn with_meta_room(blocks: &[Block], room: usize) -> Option<Vec<Block>> {660
fn with_meta_room(blocks: &[Block], room: usize) -> Option<Vec<Block>> {@@ -358,7 +358,7 @@ impl ProfileCard {
358
358
row.child(
359
359
icon_action("profile-email", IconName::Mail, EMAIL.to_owned()).on_click(
360
360
cx.listener(move |_, _, _, cx| {
361
cx.open_url(&mailto_url(&address));
361
app_base::open_link::open_url(cx, &mailto_url(&address));
362
362
cx.emit(ProfileCardEvent::Close);
363
363
}),
364
364
),
@@ -358,7 +358,7 @@ impl ProfileCard {358
row.child(358
row.child(359
icon_action("profile-email", IconName::Mail, EMAIL.to_owned()).on_click(359
icon_action("profile-email", IconName::Mail, EMAIL.to_owned()).on_click(360
cx.listener(move |_, _, _, cx| {360
cx.listener(move |_, _, _, cx| {361
cx.open_url(&mailto_url(&address));361
app_base::open_link::open_url(cx, &mailto_url(&address));362
cx.emit(ProfileCardEvent::Close);362
cx.emit(ProfileCardEvent::Close);363
}),363
}),364
),364
),@@ -112,7 +112,7 @@ fn open_link(url: &str, cx: &mut App) {
112
112
.clone()
113
113
.update(cx, |state, cx| state.raise_notice(text, None, cx));
114
114
}
115
cx.open_url(url);
115
app_base::open_link::open_url(cx, url);
116
116
}
117
117
118
118
fn opening_link_text(url: &str) -> String {
@@ -312,7 +312,7 @@ impl AppShell {
312
312
if !this.open_message(conversation_id, message_id, cx)
313
313
&& let Some(link) = link
314
314
{
315
cx.open_url(link);
315
app_base::open_link::open_url(cx, link);
316
316
}
317
317
}
318
318
},
@@ -112,7 +112,7 @@ fn open_link(url: &str, cx: &mut App) {112
.clone()112
.clone()113
.update(cx, |state, cx| state.raise_notice(text, None, cx));113
.update(cx, |state, cx| state.raise_notice(text, None, cx));114
}114
}115
cx.open_url(url);115
app_base::open_link::open_url(cx, url);116
}116
}117
117
118
fn opening_link_text(url: &str) -> String {118
fn opening_link_text(url: &str) -> String {@@ -312,7 +312,7 @@ impl AppShell {312
if !this.open_message(conversation_id, message_id, cx)312
if !this.open_message(conversation_id, message_id, cx)313
&& let Some(link) = link313
&& let Some(link) = link314
{314
{315
cx.open_url(link);315
app_base::open_link::open_url(cx, link);316
}316
}317
}317
}318
},318
},@@ -52,7 +52,7 @@ impl BidiTransport {
52
52
}
53
53
54
54
fn is_app_url(app: App, url: &str) -> bool {
55
app.origins().iter().any(|origin| url.starts_with(origin))
55
app.is_app_url(url)
56
56
}
57
57
58
58
fn no_browser(error: BrowserError) -> Error {
@@ -67,6 +67,10 @@ fn protocol(error: BrowserError) -> Error {
67
67
}
68
68
69
69
impl Transport for BidiTransport {
70
fn supports_cdp(&self) -> bool {
71
false
72
}
73
70
74
fn check(&self) -> BoxFuture<'_, Result<()>> {
71
75
Box::pin(async move { self.contexts().await.map(drop) })
72
76
}
@@ -98,7 +102,9 @@ impl Transport for BidiTransport {
98
102
return Ok(());
99
103
};
100
104
if app.is_park_url(&context.url) {
101
self.bidi.navigate(&context.id, app.start_url()).await
105
self.bidi
106
.navigate(&context.id, app.start_url_like(&context.url))
107
.await
102
108
} else {
103
109
let params = json!({"context": context.id, "wait": "none"});
104
110
self.bidi
@@ -52,7 +52,7 @@ impl BidiTransport {52
}52
}53
53
54
fn is_app_url(app: App, url: &str) -> bool {54
fn is_app_url(app: App, url: &str) -> bool {55
app.origins().iter().any(|origin| url.starts_with(origin))55
app.is_app_url(url)56
}56
}57
57
58
fn no_browser(error: BrowserError) -> Error {58
fn no_browser(error: BrowserError) -> Error {@@ -67,6 +67,10 @@ fn protocol(error: BrowserError) -> Error {67
}67
}68
68
69
impl Transport for BidiTransport {69
impl Transport for BidiTransport {70
fn supports_cdp(&self) -> bool {71
false72
}73
70
fn check(&self) -> BoxFuture<'_, Result<()>> {74
fn check(&self) -> BoxFuture<'_, Result<()>> {71
Box::pin(async move { self.contexts().await.map(drop) })75
Box::pin(async move { self.contexts().await.map(drop) })72
}76
}@@ -98,7 +102,9 @@ impl Transport for BidiTransport {98
return Ok(());102
return Ok(());99
};103
};100
if app.is_park_url(&context.url) {104
if app.is_park_url(&context.url) {101
self.bidi.navigate(&context.id, app.start_url()).await105
self.bidi106
.navigate(&context.id, app.start_url_like(&context.url))107
.await102
} else {108
} else {103
let params = json!({"context": context.id, "wait": "none"});109
let params = json!({"context": context.id, "wait": "none"});104
self.bidi110
self.bidi@@ -80,6 +80,9 @@ struct Inner {
80
80
timeouts: Timeouts,
81
81
operation: Mutex<()>,
82
82
wanted: AtomicBool,
83
/// Teams of this profile runs behind the MCAS proxy, loaded from the marker next to the
84
/// mode file.
85
mcas: AtomicBool,
83
86
/// Set for a Firefox browser, which speaks WebDriver BiDi instead of CDP.
84
87
bidi: Option<Bidi>,
85
88
}
@@ -89,8 +92,28 @@ pub struct Browser {
89
92
inner: Arc<Inner>,
90
93
}
91
94
92
pub(crate) fn start_urls() -> Vec<String> {
93
APPS.iter().map(|app| app.start_url().to_owned()).collect()
95
/// Marker that Teams runs behind the MCAS proxy, next to the mode file
96
/// (`rusty-teams-chrome.mode` gives `rusty-teams-chrome.mcas`).
97
fn mcas_marker(config: &Config) -> std::path::PathBuf {
98
config.mode_file.with_extension("mcas")
99
}
100
101
fn write_mcas_marker(marker: &std::path::Path) -> std::io::Result<()> {
102
std::fs::write(marker, "mcas")
103
}
104
105
/// A marker that is gone already is fine.
106
fn remove_mcas_marker(marker: &std::path::Path) -> std::io::Result<()> {
107
match std::fs::remove_file(marker) {
108
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
109
other => other,
110
}
111
}
112
113
pub(crate) fn start_urls(mcas: bool) -> Vec<String> {
114
APPS.iter()
115
.map(|app| app.start_url(mcas).to_owned())
116
.collect()
94
117
}
95
118
96
119
pub(crate) fn jitter_between(min: Duration, max: Duration, random: u64) -> Duration {
@@ -123,6 +146,7 @@ impl Browser {
123
146
timeouts: Timeouts,
124
147
) -> Browser {
125
148
let bidi = (config.engine == Engine::Firefox).then(|| Bidi::new(config.port));
149
let mcas = AtomicBool::new(mcas_marker(&config).exists());
126
150
Browser {
127
151
inner: Arc::new(Inner {
128
152
bidi,
@@ -131,6 +155,7 @@ impl Browser {
131
155
timeouts,
132
156
operation: Mutex::new(()),
133
157
wanted: AtomicBool::new(false),
158
mcas,
134
159
}),
135
160
}
136
161
}
@@ -205,12 +230,52 @@ impl Browser {
205
230
}
206
231
207
232
pub async fn tabs(&self) -> Result<Vec<Tab>, BrowserError> {
208
if let Some(bidi) = &self.inner.bidi {
209
return bidi.tabs().await;
233
let tabs = if let Some(bidi) = &self.inner.bidi {
234
bidi.tabs().await?
235
} else {
236
let response =
237
http::request(self.inner.config.port, "GET", "/json/list", HTTP_TIMEOUT).await?;
238
targets::parse_tabs(&response.body)?
239
};
240
self.note_mcas(&tabs);
241
Ok(tabs)
242
}
243
244
/// Once Teams shows up behind the MCAS proxy, later launches and parking go there too.
245
/// The marker next to the mode file keeps that across app restarts.
246
fn note_mcas(&self, tabs: &[Tab]) {
247
if self.behind_mcas() || !targets::has_mcas_app_tab(tabs) {
248
return;
249
}
250
log::info!("Teams runs behind the Defender for Cloud Apps proxy: using the proxied origin");
251
self.inner.mcas.store(true, Ordering::SeqCst);
252
let marker = mcas_marker(&self.inner.config);
253
if let Err(error) = write_mcas_marker(&marker) {
254
log::warn!(
255
"could not remember the MCAS proxy in {}: {error}",
256
marker.display()
257
);
258
}
259
}
260
261
/// True when this profile's Teams runs behind the MCAS proxy: start and park go there.
262
pub fn behind_mcas(&self) -> bool {
263
self.inner.mcas.load(Ordering::SeqCst)
264
}
265
266
/// Teams signed in on its own host, so the MCAS proxy is not needed (anymore).
267
fn forget_mcas(&self) {
268
if !self.behind_mcas() {
269
return;
270
}
271
log::info!(
272
"Teams signed in without the Defender for Cloud Apps proxy: using the plain origin"
273
);
274
self.inner.mcas.store(false, Ordering::SeqCst);
275
let marker = mcas_marker(&self.inner.config);
276
if let Err(error) = remove_mcas_marker(&marker) {
277
log::warn!("could not remove {}: {error}", marker.display());
210
278
}
211
let response =
212
http::request(self.inner.config.port, "GET", "/json/list", HTTP_TIMEOUT).await?;
213
targets::parse_tabs(&response.body)
214
279
}
215
280
216
281
pub async fn ensure_running(&self) -> Result<(), BrowserError> {
@@ -241,7 +306,7 @@ impl Browser {
241
306
return self.open_tab(app).await;
242
307
};
243
308
if let Some(bidi) = &self.inner.bidi {
244
let navigate = bidi.navigate(&tab.id, app.start_url());
309
let navigate = bidi.navigate(&tab.id, app.start_url(self.behind_mcas()));
245
310
return tokio::time::timeout(CDP_TIMEOUT, navigate)
246
311
.await
247
312
.map_err(|_| BrowserError::Cdp("browsingContext.navigate timed out".into()))?;
@@ -253,7 +318,7 @@ impl Browser {
253
318
cdp_call(
254
319
&url,
255
320
"Page.navigate",
256
json!({ "url": app.start_url() }),
321
json!({ "url": app.start_url(self.behind_mcas()) }),
257
322
CDP_TIMEOUT,
258
323
)
259
324
.await
@@ -311,7 +376,17 @@ impl Browser {
311
376
if tab.parked {
312
377
return false;
313
378
}
314
let expression = crate::sign_in_ready::PAGE_EXPRESSION;
379
let ready = self.page_sign_in_ready(tab).await;
380
// only forget when no tab at all is proxied, else a plain tab next to a proxied one
381
// would flip the flag on every poll
382
if ready && !targets::has_mcas_app_tab(&tabs) {
383
self.forget_mcas();
384
}
385
ready
386
}
387
388
async fn page_sign_in_ready(&self, tab: &Tab) -> bool {
389
let expression = crate::sign_in_ready::PAGE_EXPRESSION.as_str();
315
390
if let Some(bidi) = &self.inner.bidi {
316
391
let evaluate = tokio::time::timeout(
317
392
self.inner.timeouts.probe,
@@ -345,7 +420,9 @@ impl Browser {
345
420
}
346
421
self.inner.wanted.store(true, Ordering::SeqCst);
347
422
self.stop_locked(false).await?;
348
self.launch_with_urls_locked(false, start_urls()).await
423
// the window starts on the plain host, behind MCAS the sign-in redirects to the proxy
424
// by itself. So a user who is not behind MCAS anymore gets the plain origin back.
425
self.launch_with_urls_locked(false, start_urls(false)).await
349
426
}
350
427
351
428
pub async fn headless(&self) -> Result<(), BrowserError> {
@@ -450,11 +527,14 @@ impl Browser {
450
527
451
528
async fn open_tab(&self, app: App) -> Result<(), BrowserError> {
452
529
if let Some(bidi) = &self.inner.bidi {
453
return tokio::time::timeout(OPEN_TAB_TIMEOUT, bidi.open_tab(app.start_url()))
454
.await
455
.map_err(|_| BrowserError::Cdp("opening the app tab timed out".into()))?;
530
return tokio::time::timeout(
531
OPEN_TAB_TIMEOUT,
532
bidi.open_tab(app.start_url(self.behind_mcas())),
533
)
534
.await
535
.map_err(|_| BrowserError::Cdp("opening the app tab timed out".into()))?;
456
536
}
457
let path = format!("/json/new?{}", app.start_url());
537
let path = format!("/json/new?{}", app.start_url(self.behind_mcas()));
458
538
let response =
459
539
http::request(self.inner.config.port, "PUT", &path, OPEN_TAB_TIMEOUT).await?;
460
540
if response.status != 200 {
@@ -467,7 +547,8 @@ impl Browser {
467
547
}
468
548
469
549
async fn launch_locked(&self, headless: bool) -> Result<(), BrowserError> {
470
self.launch_with_urls_locked(headless, start_urls()).await
550
self.launch_with_urls_locked(headless, start_urls(self.behind_mcas()))
551
.await
471
552
}
472
553
473
554
async fn launch_with_urls_locked(
@@ -629,7 +710,7 @@ async fn keep_msal_cache_key(websocket_url: &str) {
629
710
.map_or(0, |elapsed| elapsed.as_secs());
630
711
let outcome = async {
631
712
let cookies = cdp_call(websocket_url, "Storage.getCookies", json!({}), CDP_TIMEOUT).await?;
632
let Some(params) = crate::msal_key::persisted_key_cookies(&cookies, now_secs) else {
713
let Some(params) = session::msal_key::persisted_key_cookies(&cookies, now_secs) else {
633
714
return Ok(());
634
715
};
635
716
cdp_call(websocket_url, "Storage.setCookies", params, CDP_TIMEOUT)
@@ -681,6 +762,21 @@ mod tests {
681
762
682
763
#[test]
683
764
fn only_teams_starts() {
684
assert_eq!(start_urls(), ["https://teams.cloud.microsoft/"]);
765
assert_eq!(start_urls(false), ["https://teams.cloud.microsoft/"]);
766
assert_eq!(start_urls(true), ["https://teams.cloud.microsoft.mcas.ms/"]);
767
}
768
769
#[test]
770
fn mcas_marker_sits_next_to_the_mode_file_and_comes_and_goes() {
771
let dir = tempfile::tempdir().unwrap();
772
let mode_file = dir.path().join("rusty-teams-chrome.mode");
773
let marker = mode_file.with_extension("mcas");
774
assert!(marker.ends_with("rusty-teams-chrome.mcas"));
775
write_mcas_marker(&marker).unwrap();
776
assert!(marker.exists());
777
remove_mcas_marker(&marker).unwrap();
778
assert!(!marker.exists());
779
// removing twice is not an error
780
remove_mcas_marker(&marker).unwrap();
685
781
}
686
782
}
@@ -80,6 +80,9 @@ struct Inner {80
timeouts: Timeouts,80
timeouts: Timeouts,81
operation: Mutex<()>,81
operation: Mutex<()>,82
wanted: AtomicBool,82
wanted: AtomicBool,83
/// Teams of this profile runs behind the MCAS proxy, loaded from the marker next to the84
/// mode file.85
mcas: AtomicBool,83
/// Set for a Firefox browser, which speaks WebDriver BiDi instead of CDP.86
/// Set for a Firefox browser, which speaks WebDriver BiDi instead of CDP.84
bidi: Option<Bidi>,87
bidi: Option<Bidi>,85
}88
}@@ -89,8 +92,28 @@ pub struct Browser {89
inner: Arc<Inner>,92
inner: Arc<Inner>,90
}93
}91
94
92
pub(crate) fn start_urls() -> Vec<String> {95
/// Marker that Teams runs behind the MCAS proxy, next to the mode file93
APPS.iter().map(|app| app.start_url().to_owned()).collect()96
/// (`rusty-teams-chrome.mode` gives `rusty-teams-chrome.mcas`).97
fn mcas_marker(config: &Config) -> std::path::PathBuf {98
config.mode_file.with_extension("mcas")99
}100
101
fn write_mcas_marker(marker: &std::path::Path) -> std::io::Result<()> {102
std::fs::write(marker, "mcas")103
}104
105
/// A marker that is gone already is fine.106
fn remove_mcas_marker(marker: &std::path::Path) -> std::io::Result<()> {107
match std::fs::remove_file(marker) {108
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),109
other => other,110
}111
}112
113
pub(crate) fn start_urls(mcas: bool) -> Vec<String> {114
APPS.iter()115
.map(|app| app.start_url(mcas).to_owned())116
.collect()94
}117
}95
118
96
pub(crate) fn jitter_between(min: Duration, max: Duration, random: u64) -> Duration {119
pub(crate) fn jitter_between(min: Duration, max: Duration, random: u64) -> Duration {@@ -123,6 +146,7 @@ impl Browser {123
timeouts: Timeouts,146
timeouts: Timeouts,124
) -> Browser {147
) -> Browser {125
let bidi = (config.engine == Engine::Firefox).then(|| Bidi::new(config.port));148
let bidi = (config.engine == Engine::Firefox).then(|| Bidi::new(config.port));149
let mcas = AtomicBool::new(mcas_marker(&config).exists());126
Browser {150
Browser {127
inner: Arc::new(Inner {151
inner: Arc::new(Inner {128
bidi,152
bidi,@@ -131,6 +155,7 @@ impl Browser {131
timeouts,155
timeouts,132
operation: Mutex::new(()),156
operation: Mutex::new(()),133
wanted: AtomicBool::new(false),157
wanted: AtomicBool::new(false),158
mcas,134
}),159
}),135
}160
}136
}161
}@@ -205,12 +230,52 @@ impl Browser {205
}230
}206
231
207
pub async fn tabs(&self) -> Result<Vec<Tab>, BrowserError> {232
pub async fn tabs(&self) -> Result<Vec<Tab>, BrowserError> {208
if let Some(bidi) = &self.inner.bidi {233
let tabs = if let Some(bidi) = &self.inner.bidi {209
return bidi.tabs().await;234
bidi.tabs().await?235
} else {236
let response =237
http::request(self.inner.config.port, "GET", "/json/list", HTTP_TIMEOUT).await?;238
targets::parse_tabs(&response.body)?239
};240
self.note_mcas(&tabs);241
Ok(tabs)242
}243
244
/// Once Teams shows up behind the MCAS proxy, later launches and parking go there too.245
/// The marker next to the mode file keeps that across app restarts.246
fn note_mcas(&self, tabs: &[Tab]) {247
if self.behind_mcas() || !targets::has_mcas_app_tab(tabs) {248
return;249
}250
log::info!("Teams runs behind the Defender for Cloud Apps proxy: using the proxied origin");251
self.inner.mcas.store(true, Ordering::SeqCst);252
let marker = mcas_marker(&self.inner.config);253
if let Err(error) = write_mcas_marker(&marker) {254
log::warn!(255
"could not remember the MCAS proxy in {}: {error}",256
marker.display()257
);258
}259
}260
261
/// True when this profile's Teams runs behind the MCAS proxy: start and park go there.262
pub fn behind_mcas(&self) -> bool {263
self.inner.mcas.load(Ordering::SeqCst)264
}265
266
/// Teams signed in on its own host, so the MCAS proxy is not needed (anymore).267
fn forget_mcas(&self) {268
if !self.behind_mcas() {269
return;270
}271
log::info!(272
"Teams signed in without the Defender for Cloud Apps proxy: using the plain origin"273
);274
self.inner.mcas.store(false, Ordering::SeqCst);275
let marker = mcas_marker(&self.inner.config);276
if let Err(error) = remove_mcas_marker(&marker) {277
log::warn!("could not remove {}: {error}", marker.display());210
}278
}211
let response =212
http::request(self.inner.config.port, "GET", "/json/list", HTTP_TIMEOUT).await?;213
targets::parse_tabs(&response.body)214
}279
}215
280
216
pub async fn ensure_running(&self) -> Result<(), BrowserError> {281
pub async fn ensure_running(&self) -> Result<(), BrowserError> {@@ -241,7 +306,7 @@ impl Browser {241
return self.open_tab(app).await;306
return self.open_tab(app).await;242
};307
};243
if let Some(bidi) = &self.inner.bidi {308
if let Some(bidi) = &self.inner.bidi {244
let navigate = bidi.navigate(&tab.id, app.start_url());309
let navigate = bidi.navigate(&tab.id, app.start_url(self.behind_mcas()));245
return tokio::time::timeout(CDP_TIMEOUT, navigate)310
return tokio::time::timeout(CDP_TIMEOUT, navigate)246
.await311
.await247
.map_err(|_| BrowserError::Cdp("browsingContext.navigate timed out".into()))?;312
.map_err(|_| BrowserError::Cdp("browsingContext.navigate timed out".into()))?;@@ -253,7 +318,7 @@ impl Browser {253
cdp_call(318
cdp_call(254
&url,319
&url,255
"Page.navigate",320
"Page.navigate",256
json!({ "url": app.start_url() }),321
json!({ "url": app.start_url(self.behind_mcas()) }),257
CDP_TIMEOUT,322
CDP_TIMEOUT,258
)323
)259
.await324
.await@@ -311,7 +376,17 @@ impl Browser {311
if tab.parked {376
if tab.parked {312
return false;377
return false;313
}378
}314
let expression = crate::sign_in_ready::PAGE_EXPRESSION;379
let ready = self.page_sign_in_ready(tab).await;380
// only forget when no tab at all is proxied, else a plain tab next to a proxied one381
// would flip the flag on every poll382
if ready && !targets::has_mcas_app_tab(&tabs) {383
self.forget_mcas();384
}385
ready386
}387
388
async fn page_sign_in_ready(&self, tab: &Tab) -> bool {389
let expression = crate::sign_in_ready::PAGE_EXPRESSION.as_str();315
if let Some(bidi) = &self.inner.bidi {390
if let Some(bidi) = &self.inner.bidi {316
let evaluate = tokio::time::timeout(391
let evaluate = tokio::time::timeout(317
self.inner.timeouts.probe,392
self.inner.timeouts.probe,@@ -345,7 +420,9 @@ impl Browser {345
}420
}346
self.inner.wanted.store(true, Ordering::SeqCst);421
self.inner.wanted.store(true, Ordering::SeqCst);347
self.stop_locked(false).await?;422
self.stop_locked(false).await?;348
self.launch_with_urls_locked(false, start_urls()).await423
// the window starts on the plain host, behind MCAS the sign-in redirects to the proxy424
// by itself. So a user who is not behind MCAS anymore gets the plain origin back.425
self.launch_with_urls_locked(false, start_urls(false)).await349
}426
}350
427
351
pub async fn headless(&self) -> Result<(), BrowserError> {428
pub async fn headless(&self) -> Result<(), BrowserError> {@@ -450,11 +527,14 @@ impl Browser {450
527
451
async fn open_tab(&self, app: App) -> Result<(), BrowserError> {528
async fn open_tab(&self, app: App) -> Result<(), BrowserError> {452
if let Some(bidi) = &self.inner.bidi {529
if let Some(bidi) = &self.inner.bidi {453
return tokio::time::timeout(OPEN_TAB_TIMEOUT, bidi.open_tab(app.start_url()))530
return tokio::time::timeout(454
.await531
OPEN_TAB_TIMEOUT,455
.map_err(|_| BrowserError::Cdp("opening the app tab timed out".into()))?;532
bidi.open_tab(app.start_url(self.behind_mcas())),533
)534
.await535
.map_err(|_| BrowserError::Cdp("opening the app tab timed out".into()))?;456
}536
}457
let path = format!("/json/new?{}", app.start_url());537
let path = format!("/json/new?{}", app.start_url(self.behind_mcas()));458
let response =538
let response =459
http::request(self.inner.config.port, "PUT", &path, OPEN_TAB_TIMEOUT).await?;539
http::request(self.inner.config.port, "PUT", &path, OPEN_TAB_TIMEOUT).await?;460
if response.status != 200 {540
if response.status != 200 {@@ -467,7 +547,8 @@ impl Browser {467
}547
}468
548
469
async fn launch_locked(&self, headless: bool) -> Result<(), BrowserError> {549
async fn launch_locked(&self, headless: bool) -> Result<(), BrowserError> {470
self.launch_with_urls_locked(headless, start_urls()).await550
self.launch_with_urls_locked(headless, start_urls(self.behind_mcas()))551
.await471
}552
}472
553
473
async fn launch_with_urls_locked(554
async fn launch_with_urls_locked(@@ -629,7 +710,7 @@ async fn keep_msal_cache_key(websocket_url: &str) {629
.map_or(0, |elapsed| elapsed.as_secs());710
.map_or(0, |elapsed| elapsed.as_secs());630
let outcome = async {711
let outcome = async {631
let cookies = cdp_call(websocket_url, "Storage.getCookies", json!({}), CDP_TIMEOUT).await?;712
let cookies = cdp_call(websocket_url, "Storage.getCookies", json!({}), CDP_TIMEOUT).await?;632
let Some(params) = crate::msal_key::persisted_key_cookies(&cookies, now_secs) else {713
let Some(params) = session::msal_key::persisted_key_cookies(&cookies, now_secs) else {633
return Ok(());714
return Ok(());634
};715
};635
cdp_call(websocket_url, "Storage.setCookies", params, CDP_TIMEOUT)716
cdp_call(websocket_url, "Storage.setCookies", params, CDP_TIMEOUT)@@ -681,6 +762,21 @@ mod tests {681
762
682
#[test]763
#[test]683
fn only_teams_starts() {764
fn only_teams_starts() {684
assert_eq!(start_urls(), ["https://teams.cloud.microsoft/"]);765
assert_eq!(start_urls(false), ["https://teams.cloud.microsoft/"]);766
assert_eq!(start_urls(true), ["https://teams.cloud.microsoft.mcas.ms/"]);767
}768
769
#[test]770
fn mcas_marker_sits_next_to_the_mode_file_and_comes_and_goes() {771
let dir = tempfile::tempdir().unwrap();772
let mode_file = dir.path().join("rusty-teams-chrome.mode");773
let marker = mode_file.with_extension("mcas");774
assert!(marker.ends_with("rusty-teams-chrome.mcas"));775
write_mcas_marker(&marker).unwrap();776
assert!(marker.exists());777
remove_mcas_marker(&marker).unwrap();778
assert!(!marker.exists());779
// removing twice is not an error780
remove_mcas_marker(&marker).unwrap();685
}781
}686
}782
}@@ -6,7 +6,6 @@ mod error;
6
6
mod host;
7
7
mod http;
8
8
mod launch;
9
mod msal_key;
10
9
mod process;
11
10
mod sign_in_choice;
12
11
mod sign_in_ready;
@@ -6,7 +6,6 @@ mod error;6
mod host;6
mod host;7
mod http;7
mod http;8
mod launch;8
mod launch;9
mod msal_key;10
mod process;9
mod process;11
mod sign_in_choice;10
mod sign_in_choice;12
mod sign_in_ready;11
mod sign_in_ready;@@ -5,12 +5,17 @@
5
5
//! encryption cookie. Merely decrypting sealed entries is not enough either once the encryption
6
6
//! cookie persists across restarts, because an expired session still unseals its old entries.
7
7
8
use std::sync::LazyLock;
9
8
10
use serde_json::Value;
9
11
10
12
/// Page script. Returns `{opened, freshAccess}`. `opened` counts sealed entries decrypted with
11
13
/// the `msal.cache.encryption` cookie. `freshAccess` is a bearer access token whose `expiresOn`
12
14
/// is still in the future, in the clear or among the opened entries.
13
pub(crate) const PAGE_EXPRESSION: &str = r#"(async () => {
15
pub(crate) static PAGE_EXPRESSION: LazyLock<String> =
16
LazyLock::new(|| PAGE_TEMPLATE.replace("__UNSEAL__", session::UNSEAL_SCRIPT));
17
18
const PAGE_TEMPLATE: &str = r#"(async () => {
14
19
const sealed = [];
15
20
const plain = [];
16
21
for (let index = 0; index < localStorage.length; index++) {
@@ -21,28 +26,8 @@ pub(crate) const PAGE_EXPRESSION: &str = r#"(async () => {
21
26
if (entry.id && entry.nonce && entry.data) sealed.push([key, entry]);
22
27
else plain.push(entry);
23
28
}
24
const openedEntries = [];
25
const cookie = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith('msal.cache.encryption='));
26
let sealing = null;
27
try { sealing = cookie && JSON.parse(decodeURIComponent(cookie.slice(cookie.indexOf('=') + 1))); } catch (error) {}
28
if (sealing && sealing.key && sealing.id && sealed.length) {
29
const bytes = (text) => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=')), (character) => character.charCodeAt(0));
30
const base = await crypto.subtle.importKey('raw', bytes(sealing.key), 'HKDF', false, ['deriveKey']);
31
for (const [key, entry] of sealed) {
32
if (entry.id !== sealing.id) continue;
33
const contexts = [...(String(key).match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) || []), ''];
34
for (const context of new Set(contexts)) {
35
try {
36
const derived = await crypto.subtle.deriveKey(
37
{name: 'HKDF', salt: bytes(entry.nonce), hash: 'SHA-256', info: new TextEncoder().encode(context)},
38
base, {name: 'AES-GCM', length: 256}, false, ['decrypt']);
39
const data = await crypto.subtle.decrypt({name: 'AES-GCM', iv: new Uint8Array(12)}, derived, bytes(entry.data));
40
openedEntries.push(JSON.parse(new TextDecoder().decode(data)));
41
break;
42
} catch (error) {}
43
}
44
}
45
}
29
const unsealEntries = __UNSEAL__;
30
const openedEntries = (await unsealEntries(sealed, new Map())).map(([key, entry]) => entry);
46
31
const now = Date.now();
47
32
const fresh = (entry) => entry && entry.credentialType === 'AccessToken' && (!entry.tokenType || entry.tokenType === 'Bearer') && Number(entry.expiresOn) * 1000 > now && typeof entry.secret === 'string' && entry.secret.length > 0;
48
33
return {opened: openedEntries.length, freshAccess: plain.some(fresh) || openedEntries.some(fresh)};
@@ -5,12 +5,17 @@5
//! encryption cookie. Merely decrypting sealed entries is not enough either once the encryption5
//! encryption cookie. Merely decrypting sealed entries is not enough either once the encryption6
//! cookie persists across restarts, because an expired session still unseals its old entries.6
//! cookie persists across restarts, because an expired session still unseals its old entries.7
7
8
use std::sync::LazyLock;9
8
use serde_json::Value;10
use serde_json::Value;9
11
10
/// Page script. Returns `{opened, freshAccess}`. `opened` counts sealed entries decrypted with12
/// Page script. Returns `{opened, freshAccess}`. `opened` counts sealed entries decrypted with11
/// the `msal.cache.encryption` cookie. `freshAccess` is a bearer access token whose `expiresOn`13
/// the `msal.cache.encryption` cookie. `freshAccess` is a bearer access token whose `expiresOn`12
/// is still in the future, in the clear or among the opened entries.14
/// is still in the future, in the clear or among the opened entries.13
pub(crate) const PAGE_EXPRESSION: &str = r#"(async () => {15
pub(crate) static PAGE_EXPRESSION: LazyLock<String> =16
LazyLock::new(|| PAGE_TEMPLATE.replace("__UNSEAL__", session::UNSEAL_SCRIPT));17
18
const PAGE_TEMPLATE: &str = r#"(async () => {14
const sealed = [];19
const sealed = [];15
const plain = [];20
const plain = [];16
for (let index = 0; index < localStorage.length; index++) {21
for (let index = 0; index < localStorage.length; index++) {@@ -21,28 +26,8 @@ pub(crate) const PAGE_EXPRESSION: &str = r#"(async () => {21
if (entry.id && entry.nonce && entry.data) sealed.push([key, entry]);26
if (entry.id && entry.nonce && entry.data) sealed.push([key, entry]);22
else plain.push(entry);27
else plain.push(entry);23
}28
}24
const openedEntries = [];29
const unsealEntries = __UNSEAL__;25
const cookie = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith('msal.cache.encryption='));30
const openedEntries = (await unsealEntries(sealed, new Map())).map(([key, entry]) => entry);26
let sealing = null;27
try { sealing = cookie && JSON.parse(decodeURIComponent(cookie.slice(cookie.indexOf('=') + 1))); } catch (error) {}28
if (sealing && sealing.key && sealing.id && sealed.length) {29
const bytes = (text) => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=')), (character) => character.charCodeAt(0));30
const base = await crypto.subtle.importKey('raw', bytes(sealing.key), 'HKDF', false, ['deriveKey']);31
for (const [key, entry] of sealed) {32
if (entry.id !== sealing.id) continue;33
const contexts = [...(String(key).match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) || []), ''];34
for (const context of new Set(contexts)) {35
try {36
const derived = await crypto.subtle.deriveKey(37
{name: 'HKDF', salt: bytes(entry.nonce), hash: 'SHA-256', info: new TextEncoder().encode(context)},38
base, {name: 'AES-GCM', length: 256}, false, ['decrypt']);39
const data = await crypto.subtle.decrypt({name: 'AES-GCM', iv: new Uint8Array(12)}, derived, bytes(entry.data));40
openedEntries.push(JSON.parse(new TextDecoder().decode(data)));41
break;42
} catch (error) {}43
}44
}45
}46
const now = Date.now();31
const now = Date.now();47
const fresh = (entry) => entry && entry.credentialType === 'AccessToken' && (!entry.tokenType || entry.tokenType === 'Bearer') && Number(entry.expiresOn) * 1000 > now && typeof entry.secret === 'string' && entry.secret.length > 0;32
const fresh = (entry) => entry && entry.credentialType === 'AccessToken' && (!entry.tokenType || entry.tokenType === 'Bearer') && Number(entry.expiresOn) * 1000 > now && typeof entry.secret === 'string' && entry.secret.length > 0;48
return {opened: openedEntries.length, freshAccess: plain.some(fresh) || openedEntries.some(fresh)};33
return {opened: openedEntries.length, freshAccess: plain.some(fresh) || openedEntries.some(fresh)};@@ -8,6 +8,22 @@ use crate::error::BrowserError;
8
8
const LOGIN_HOSTS: [&str; 2] = ["login.microsoftonline.com", "login.live.com"];
9
9
/// Outlook tabs earlier versions opened next to Teams; nothing uses them any more.
10
10
const RETIRED_HOSTS: [&str; 2] = ["outlook.office.com", "outlook.cloud.microsoft"];
11
/// The real app host, also when a MCAS session proxy sits in front of it
12
/// (teams.cloud.microsoft.mcas.ms is teams.cloud.microsoft).
13
fn unproxied_host(host: &str) -> &str {
14
host.strip_suffix(session::MCAS_SUFFIX).unwrap_or(host)
15
}
16
17
/// True when an app tab is served through the MCAS proxy.
18
pub(crate) fn has_mcas_app_tab(tabs: &[Tab]) -> bool {
19
tabs.iter().any(|tab| {
20
tab.app.is_some()
21
&& tab
22
.host
23
.as_deref()
24
.is_some_and(|host| unproxied_host(host) != host)
25
})
26
}
11
27
12
28
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
13
29
#[serde(rename_all = "lowercase")]
@@ -18,9 +34,10 @@ pub enum App {
18
34
pub const APPS: [App; 1] = [App::Teams];
19
35
20
36
impl App {
21
pub fn start_url(self) -> &'static str {
37
/// With `mcas` through the MCAS proxy, else on the app's own host.
38
pub fn start_url(self, mcas: bool) -> &'static str {
22
39
match self {
23
App::Teams => "https://teams.cloud.microsoft/",
40
App::Teams => session::App::Teams.start_url(mcas),
24
41
}
25
42
}
26
43
@@ -127,6 +144,7 @@ pub(crate) fn tab_from_url(id: String, url: &str) -> Tab {
127
144
let secure = https_host(url);
128
145
let app = secure
129
146
.as_deref()
147
.map(unproxied_host)
130
148
.and_then(|host| APPS.into_iter().find(|app| app.hosts().contains(&host)));
131
149
let login = secure
132
150
.as_deref()
@@ -257,6 +275,27 @@ mod tests {
257
275
);
258
276
}
259
277
278
#[test]
279
fn mcas_proxied_teams_host_is_teams() {
280
let list = r#"[
281
{"id":"M","type":"page","url":"https://teams.cloud.microsoft.mcas.ms/"},
282
{"id":"P","type":"page","url":"https://teams.cloud.microsoft.mcas.ms/robots.txt"},
283
{"id":"E","type":"page","url":"https://teams.cloud.microsoft.evil.example/"},
284
{"id":"N","type":"page","url":"https://evil.mcas.ms/"}
285
]"#;
286
let tabs = parse_tabs(list.as_bytes()).unwrap();
287
assert_eq!(tabs[0].app, Some(App::Teams));
288
assert!(!tabs[0].parked);
289
assert_eq!(tabs[1].app, Some(App::Teams));
290
assert!(tabs[1].parked);
291
assert_eq!(tabs[2].app, None);
292
assert_eq!(tabs[3].app, None);
293
assert_eq!(login_state(&tabs), LoginState::NotRequired);
294
assert!(has_mcas_app_tab(&tabs[..1]));
295
assert!(!has_mcas_app_tab(&tabs[3..]));
296
assert!(!has_mcas_app_tab(&parse_tabs(LIST.as_bytes()).unwrap()));
297
}
298
260
299
fn page(id: &str, url: &str) -> Tab {
261
300
tab_from_url(id.to_owned(), url)
262
301
}
@@ -8,6 +8,22 @@ use crate::error::BrowserError;8
const LOGIN_HOSTS: [&str; 2] = ["login.microsoftonline.com", "login.live.com"];8
const LOGIN_HOSTS: [&str; 2] = ["login.microsoftonline.com", "login.live.com"];9
/// Outlook tabs earlier versions opened next to Teams; nothing uses them any more.9
/// Outlook tabs earlier versions opened next to Teams; nothing uses them any more.10
const RETIRED_HOSTS: [&str; 2] = ["outlook.office.com", "outlook.cloud.microsoft"];10
const RETIRED_HOSTS: [&str; 2] = ["outlook.office.com", "outlook.cloud.microsoft"];11
/// The real app host, also when a MCAS session proxy sits in front of it12
/// (teams.cloud.microsoft.mcas.ms is teams.cloud.microsoft).13
fn unproxied_host(host: &str) -> &str {14
host.strip_suffix(session::MCAS_SUFFIX).unwrap_or(host)15
}16
17
/// True when an app tab is served through the MCAS proxy.18
pub(crate) fn has_mcas_app_tab(tabs: &[Tab]) -> bool {19
tabs.iter().any(|tab| {20
tab.app.is_some()21
&& tab22
.host23
.as_deref()24
.is_some_and(|host| unproxied_host(host) != host)25
})26
}11
27
12
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]28
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]13
#[serde(rename_all = "lowercase")]29
#[serde(rename_all = "lowercase")]@@ -18,9 +34,10 @@ pub enum App {18
pub const APPS: [App; 1] = [App::Teams];34
pub const APPS: [App; 1] = [App::Teams];19
35
20
impl App {36
impl App {21
pub fn start_url(self) -> &'static str {37
/// With `mcas` through the MCAS proxy, else on the app's own host.38
pub fn start_url(self, mcas: bool) -> &'static str {22
match self {39
match self {23
App::Teams => "https://teams.cloud.microsoft/",40
App::Teams => session::App::Teams.start_url(mcas),24
}41
}25
}42
}26
43
@@ -127,6 +144,7 @@ pub(crate) fn tab_from_url(id: String, url: &str) -> Tab {127
let secure = https_host(url);144
let secure = https_host(url);128
let app = secure145
let app = secure129
.as_deref()146
.as_deref()147
.map(unproxied_host)130
.and_then(|host| APPS.into_iter().find(|app| app.hosts().contains(&host)));148
.and_then(|host| APPS.into_iter().find(|app| app.hosts().contains(&host)));131
let login = secure149
let login = secure132
.as_deref()150
.as_deref()@@ -257,6 +275,27 @@ mod tests {257
);275
);258
}276
}259
277
278
#[test]279
fn mcas_proxied_teams_host_is_teams() {280
let list = r#"[281
{"id":"M","type":"page","url":"https://teams.cloud.microsoft.mcas.ms/"},282
{"id":"P","type":"page","url":"https://teams.cloud.microsoft.mcas.ms/robots.txt"},283
{"id":"E","type":"page","url":"https://teams.cloud.microsoft.evil.example/"},284
{"id":"N","type":"page","url":"https://evil.mcas.ms/"}285
]"#;286
let tabs = parse_tabs(list.as_bytes()).unwrap();287
assert_eq!(tabs[0].app, Some(App::Teams));288
assert!(!tabs[0].parked);289
assert_eq!(tabs[1].app, Some(App::Teams));290
assert!(tabs[1].parked);291
assert_eq!(tabs[2].app, None);292
assert_eq!(tabs[3].app, None);293
assert_eq!(login_state(&tabs), LoginState::NotRequired);294
assert!(has_mcas_app_tab(&tabs[..1]));295
assert!(!has_mcas_app_tab(&tabs[3..]));296
assert!(!has_mcas_app_tab(&parse_tabs(LIST.as_bytes()).unwrap()));297
}298
260
fn page(id: &str, url: &str) -> Tab {299
fn page(id: &str, url: &str) -> Tab {261
tab_from_url(id.to_owned(), url)300
tab_from_url(id.to_owned(), url)262
}301
}@@ -502,3 +502,21 @@ async fn hung_stop_falls_back_to_kill_when_close_is_ignored() {
502
502
assert_eq!(*harness.launcher.kills.lock().unwrap(), 1);
503
503
assert_eq!(harness.launcher.requests.lock().unwrap().len(), 2);
504
504
}
505
506
#[tokio::test]
507
async fn the_mcas_proxy_is_remembered_per_profile_not_per_process() {
508
let proxied = harness().await;
509
let plain = harness().await;
510
proxied
511
.mock
512
.start(&["https://teams.cloud.microsoft.mcas.ms/v2/"])
513
.await;
514
plain.mock.start(&[TEAMS]).await;
515
proxied.browser.tabs().await.unwrap();
516
plain.browser.tabs().await.unwrap();
517
assert!(proxied.browser.behind_mcas());
518
assert!(proxied.mode_file.with_extension("mcas").exists());
519
// a second profile in the same process does not pick it up
520
assert!(!plain.browser.behind_mcas());
521
assert!(!plain.mode_file.with_extension("mcas").exists());
522
}
@@ -502,3 +502,21 @@ async fn hung_stop_falls_back_to_kill_when_close_is_ignored() {502
assert_eq!(*harness.launcher.kills.lock().unwrap(), 1);502
assert_eq!(*harness.launcher.kills.lock().unwrap(), 1);503
assert_eq!(harness.launcher.requests.lock().unwrap().len(), 2);503
assert_eq!(harness.launcher.requests.lock().unwrap().len(), 2);504
}504
}505
506
#[tokio::test]507
async fn the_mcas_proxy_is_remembered_per_profile_not_per_process() {508
let proxied = harness().await;509
let plain = harness().await;510
proxied511
.mock512
.start(&["https://teams.cloud.microsoft.mcas.ms/v2/"])513
.await;514
plain.mock.start(&[TEAMS]).await;515
proxied.browser.tabs().await.unwrap();516
plain.browser.tabs().await.unwrap();517
assert!(proxied.browser.behind_mcas());518
assert!(proxied.mode_file.with_extension("mcas").exists());519
// a second profile in the same process does not pick it up520
assert!(!plain.browser.behind_mcas());521
assert!(!plain.mode_file.with_extension("mcas").exists());522
}@@ -23,6 +23,7 @@ serde.workspace = true
23
23
webrtc-sys = "=0.3.48"
24
24
serde_json.workspace = true
25
25
session.workspace = true
26
url.workspace = true
26
27
thiserror.workspace = true
27
28
tract-onnx = "0.23"
28
29
tokio.workspace = true
@@ -31,6 +32,11 @@ uuid.workspace = true
31
32
[target.'cfg(target_os = "linux")'.dependencies]
32
33
libc = "0.2"
33
34
35
[target.'cfg(target_os = "macos")'.dependencies]
36
libc = "0.2"
37
objc2 = "0.6"
38
objc2-foundation = { version = "0.3", features = ["NSProcessInfo"] }
39
34
40
[target.'cfg(not(windows))'.dependencies]
35
41
ort = { version = "=2.0.0-rc.14", default-features = false, features = ["std", "ndarray", "load-dynamic", "api-31"] }
36
42
@@ -23,6 +23,7 @@ serde.workspace = true23
webrtc-sys = "=0.3.48"23
webrtc-sys = "=0.3.48"24
serde_json.workspace = true24
serde_json.workspace = true25
session.workspace = true25
session.workspace = true26
url.workspace = true26
thiserror.workspace = true27
thiserror.workspace = true27
tract-onnx = "0.23"28
tract-onnx = "0.23"28
tokio.workspace = true29
tokio.workspace = true@@ -31,6 +32,11 @@ uuid.workspace = true31
[target.'cfg(target_os = "linux")'.dependencies]32
[target.'cfg(target_os = "linux")'.dependencies]32
libc = "0.2"33
libc = "0.2"33
34
35
[target.'cfg(target_os = "macos")'.dependencies]36
libc = "0.2"37
objc2 = "0.6"38
objc2-foundation = { version = "0.3", features = ["NSProcessInfo"] }39
34
[target.'cfg(not(windows))'.dependencies]40
[target.'cfg(not(windows))'.dependencies]35
ort = { version = "=2.0.0-rc.14", default-features = false, features = ["std", "ndarray", "load-dynamic", "api-31"] }41
ort = { version = "=2.0.0-rc.14", default-features = false, features = ["std", "ndarray", "load-dynamic", "api-31"] }36
42
@@ -439,6 +439,12 @@ impl CallEngine {
439
439
advance(&mut state, CallSignal::LocalLeave, &control);
440
440
None
441
441
}
442
Err(error)
443
if accept_found_no_call(&error) && matches!(state, CallState::Connecting) =>
444
{
445
advance(&mut state, CallSignal::LocalLeave, &control);
446
None
447
}
442
448
Err(error) => {
443
449
advance(&mut state, CallSignal::Error(error.to_string()), &control);
444
450
Some(error)
@@ -471,6 +477,18 @@ impl CallEngine {
471
477
}
472
478
}
473
479
480
/// Teams answers 404 when the caller already hung up. While we are still connecting
481
/// that is a cancelled ring, not a failed call.
482
pub(super) fn accept_found_no_call(error: &Error) -> bool {
483
let Error::Signaling(reason) = error else {
484
return false;
485
};
486
let reason = reason.to_ascii_lowercase();
487
reason.contains("post acceptance")
488
&& reason.contains("http 404")
489
&& reason.contains("does not exist")
490
}
491
474
492
async fn setup_step<T, E>(
475
493
control: &mut CallControl,
476
494
step: impl std::future::Future<Output = std::result::Result<T, E>>,
@@ -566,6 +584,7 @@ async fn drive(
566
584
let mut input = options.input.clone();
567
585
let mut output = options.output.clone();
568
586
let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
587
audio.set_device_tracks_enabled(false);
569
588
control.send(CallUpdate::ListenOnly(audio.listen_only));
570
589
let mut device_lists = devices::list_devices(&factory);
571
590
let mut applied_input = devices::applied_device(
@@ -880,8 +899,7 @@ async fn drive(
880
899
live.audio
881
900
.as_ref()
882
901
.expect("audio set above")
883
.track
884
.set_enabled(initial.track_enabled);
902
.set_device_tracks_enabled(initial.track_enabled);
885
903
if muted {
886
904
control.send(CallUpdate::Muted(true));
887
905
}
@@ -921,6 +939,7 @@ async fn drive(
921
939
let mut capability = MeetingCapability::default();
922
940
let mut previous_packets = 0u64;
923
941
let mut ticks = 0u32;
942
let mut host_cpu = std::collections::HashMap::new();
924
943
let mut segmentation_model: Option<&'static str> = None;
925
944
let mut health_sampler = HealthSampler::default();
926
945
let mut quality_tracker = QualityTracker::default();
@@ -1080,7 +1099,7 @@ async fn drive(
1080
1099
&factory,
1081
1100
options,
1082
1101
&input,
1083
muted,
1102
muted || local_hold,
1084
1103
remote_audio.clone(),
1085
1104
¤t.peer,
1086
1105
&track,
@@ -1350,7 +1369,7 @@ async fn drive(
1350
1369
Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1351
1370
Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1352
1371
local_video.stop_share();
1353
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
1372
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
1354
1373
clear_share(control);
1355
1374
control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1356
1375
}
@@ -2006,7 +2025,7 @@ async fn drive(
2006
2025
timeline.record("remote audio track", "receiving");
2007
2026
let had_far_end = remote_audio.replace(remote_track.clone()).is_some();
2008
2027
if !had_far_end && software_audio.is_some() {
2009
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2028
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2010
2029
}
2011
2030
if options.record_remote {
2012
2031
tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));
@@ -2080,7 +2099,7 @@ async fn drive(
2080
2099
let audio = live.audio.as_ref().expect("audio set above");
2081
2100
muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);
2082
2101
audio_disabled = true;
2083
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, None, false, &mut software_audio, mic_settings, control, timeline);
2102
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, None, false, &mut software_audio, mic_settings, control, timeline);
2084
2103
if audio.uses_devices() {
2085
2104
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
2086
2105
factory.set_adm_recording_enabled(false);
@@ -2097,7 +2116,7 @@ async fn drive(
2097
2116
input = choice;
2098
2117
control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
2099
2118
if software_audio.is_some() {
2100
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2119
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2101
2120
}
2102
2121
}
2103
2122
Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {
@@ -2107,7 +2126,7 @@ async fn drive(
2107
2126
if let Some(audio) = live.audio.as_ref() {
2108
2127
track = audio.device_track(mic_settings).clone();
2109
2128
}
2110
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), device_ns_changed, &mut software_audio, mic_settings, control, timeline);
2129
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), device_ns_changed, &mut software_audio, mic_settings, control, timeline);
2111
2130
}
2112
2131
Some(CallCommand::SetMicSettings(settings)) => {
2113
2132
mic_settings = settings;
@@ -2315,7 +2334,7 @@ async fn drive(
2315
2334
match local_video.start_share(&source) {
2316
2335
Ok(()) => {
2317
2336
announce_share(control, &source);
2318
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2337
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2319
2338
match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2320
2339
Ok((browser_offer, signaled, reply_tags)) => {
2321
2340
timeline.record_sdp("local offer", &signaled.sdp);
@@ -2358,7 +2377,7 @@ async fn drive(
2358
2377
&mut media_description_request,
2359
2378
timeline,
2360
2379
);
2361
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2380
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2362
2381
}
2363
2382
Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2364
2383
}
@@ -2375,7 +2394,7 @@ async fn drive(
2375
2394
} else if direct && local_video.sharing() {
2376
2395
local_video.stop_share();
2377
2396
clear_share(control);
2378
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2397
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2379
2398
match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2380
2399
Ok((browser_offer, signaled, reply_tags)) => {
2381
2400
timeline.record_sdp("local offer", &signaled.sdp);
@@ -2387,7 +2406,7 @@ async fn drive(
2387
2406
}
2388
2407
} else if local_video.sharing() {
2389
2408
local_video.stop_share();
2390
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2409
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2391
2410
clear_share(control);
2392
2411
tell_media_descriptions(
2393
2412
&remote,
@@ -2403,7 +2422,7 @@ async fn drive(
2403
2422
}
2404
2423
Some(CallCommand::SetShareSound(on)) => {
2405
2424
share_sound_wanted = on;
2406
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2425
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2407
2426
}
2408
2427
Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true),
2409
2428
Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {
@@ -2804,6 +2823,20 @@ async fn drive(
2804
2823
segmentation_model = Some(model);
2805
2824
}
2806
2825
}
2826
if crate::host_load::recorded_on_this_platform()
2827
&& ticks.is_multiple_of(HEALTH_EVERY_TICKS)
2828
{
2829
let current = crate::host_load::thread_cpu();
2830
let deltas = crate::host_load::cpu_deltas(¤t, &mut host_cpu);
2831
timeline.record(
2832
"host load",
2833
crate::host_load::host_load_line(
2834
&deltas,
2835
&local_video.effects_label(),
2836
crate::host_load::thermal_state(),
2837
),
2838
);
2839
}
2807
2840
if ticks.is_multiple_of(HEALTH_EVERY_TICKS) {
2808
2841
control.send(CallUpdate::Sample(StatsSample {
2809
2842
audio_in_packets: snapshot.inbound_packets,
@@ -2939,7 +2972,7 @@ async fn drive(
2939
2972
record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2940
2973
}
2941
2974
if input_changed && software_audio.is_some() {
2942
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2975
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2943
2976
}
2944
2977
}
2945
2978
}
@@ -3058,6 +3091,23 @@ fn far_future() -> Instant {
3058
3091
3059
3092
#[cfg(test)]
3060
3093
mod tests {
3094
#[test]
3095
fn a_missing_call_on_accept_while_connecting_is_a_cancel() {
3096
let gone = Error::Signaling(
3097
"POST acceptance answered HTTP 404 {\"Message\":\"The requested call does not exist.\"}"
3098
.into(),
3099
);
3100
assert!(accept_found_no_call(&gone));
3101
let other = Error::Signaling("POST acceptance answered HTTP 500 boom".into());
3102
assert!(!accept_found_no_call(&other));
3103
let roster = Error::Signaling(
3104
"POST roster answered HTTP 404 {\"Message\":\"The requested call does not exist.\"}"
3105
.into(),
3106
);
3107
assert!(!accept_found_no_call(&roster));
3108
assert!(!accept_found_no_call(&Error::Cancelled));
3109
}
3110
3061
3111
#[test]
3062
3112
fn gathering_settles_shortly_after_a_udp_relay_or_when_complete() {
3063
3113
assert!(!gathering_settled(false, None));
@@ -439,6 +439,12 @@ impl CallEngine {439
advance(&mut state, CallSignal::LocalLeave, &control);439
advance(&mut state, CallSignal::LocalLeave, &control);440
None440
None441
}441
}442
Err(error)443
if accept_found_no_call(&error) && matches!(state, CallState::Connecting) =>444
{445
advance(&mut state, CallSignal::LocalLeave, &control);446
None447
}442
Err(error) => {448
Err(error) => {443
advance(&mut state, CallSignal::Error(error.to_string()), &control);449
advance(&mut state, CallSignal::Error(error.to_string()), &control);444
Some(error)450
Some(error)@@ -471,6 +477,18 @@ impl CallEngine {471
}477
}472
}478
}473
479
480
/// Teams answers 404 when the caller already hung up. While we are still connecting481
/// that is a cancelled ring, not a failed call.482
pub(super) fn accept_found_no_call(error: &Error) -> bool {483
let Error::Signaling(reason) = error else {484
return false;485
};486
let reason = reason.to_ascii_lowercase();487
reason.contains("post acceptance")488
&& reason.contains("http 404")489
&& reason.contains("does not exist")490
}491
474
async fn setup_step<T, E>(492
async fn setup_step<T, E>(475
control: &mut CallControl,493
control: &mut CallControl,476
step: impl std::future::Future<Output = std::result::Result<T, E>>,494
step: impl std::future::Future<Output = std::result::Result<T, E>>,@@ -566,6 +584,7 @@ async fn drive(566
let mut input = options.input.clone();584
let mut input = options.input.clone();567
let mut output = options.output.clone();585
let mut output = options.output.clone();568
let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);586
let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);587
audio.set_device_tracks_enabled(false);569
control.send(CallUpdate::ListenOnly(audio.listen_only));588
control.send(CallUpdate::ListenOnly(audio.listen_only));570
let mut device_lists = devices::list_devices(&factory);589
let mut device_lists = devices::list_devices(&factory);571
let mut applied_input = devices::applied_device(590
let mut applied_input = devices::applied_device(@@ -880,8 +899,7 @@ async fn drive(880
live.audio899
live.audio881
.as_ref()900
.as_ref()882
.expect("audio set above")901
.expect("audio set above")883
.track902
.set_device_tracks_enabled(initial.track_enabled);884
.set_enabled(initial.track_enabled);885
if muted {903
if muted {886
control.send(CallUpdate::Muted(true));904
control.send(CallUpdate::Muted(true));887
}905
}@@ -921,6 +939,7 @@ async fn drive(921
let mut capability = MeetingCapability::default();939
let mut capability = MeetingCapability::default();922
let mut previous_packets = 0u64;940
let mut previous_packets = 0u64;923
let mut ticks = 0u32;941
let mut ticks = 0u32;942
let mut host_cpu = std::collections::HashMap::new();924
let mut segmentation_model: Option<&'static str> = None;943
let mut segmentation_model: Option<&'static str> = None;925
let mut health_sampler = HealthSampler::default();944
let mut health_sampler = HealthSampler::default();926
let mut quality_tracker = QualityTracker::default();945
let mut quality_tracker = QualityTracker::default();@@ -1080,7 +1099,7 @@ async fn drive(1080
&factory,1099
&factory,1081
options,1100
options,1082
&input,1101
&input,1083
muted,1102
muted || local_hold,1084
remote_audio.clone(),1103
remote_audio.clone(),1085
¤t.peer,1104
¤t.peer,1086
&track,1105
&track,@@ -1350,7 +1369,7 @@ async fn drive(1350
Change::Camera(on) => control.send(CallUpdate::Camera(on)),1369
Change::Camera(on) => control.send(CallUpdate::Camera(on)),1351
Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {1370
Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {1352
local_video.stop_share();1371
local_video.stop_share();1353
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);1372
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);1354
clear_share(control);1373
clear_share(control);1355
control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));1374
control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));1356
}1375
}@@ -2006,7 +2025,7 @@ async fn drive(2006
timeline.record("remote audio track", "receiving");2025
timeline.record("remote audio track", "receiving");2007
let had_far_end = remote_audio.replace(remote_track.clone()).is_some();2026
let had_far_end = remote_audio.replace(remote_track.clone()).is_some();2008
if !had_far_end && software_audio.is_some() {2027
if !had_far_end && software_audio.is_some() {2009
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);2028
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);2010
}2029
}2011
if options.record_remote {2030
if options.record_remote {2012
tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));2031
tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));@@ -2080,7 +2099,7 @@ async fn drive(2080
let audio = live.audio.as_ref().expect("audio set above");2099
let audio = live.audio.as_ref().expect("audio set above");2081
muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);2100
muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);2082
audio_disabled = true;2101
audio_disabled = true;2083
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, None, false, &mut software_audio, mic_settings, control, timeline);2102
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, None, false, &mut software_audio, mic_settings, control, timeline);2084
if audio.uses_devices() {2103
if audio.uses_devices() {2085
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;2104
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;2086
factory.set_adm_recording_enabled(false);2105
factory.set_adm_recording_enabled(false);@@ -2097,7 +2116,7 @@ async fn drive(2097
input = choice;2116
input = choice;2098
control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });2117
control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });2099
if software_audio.is_some() {2118
if software_audio.is_some() {2100
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);2119
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);2101
}2120
}2102
}2121
}2103
Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {2122
Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {@@ -2107,7 +2126,7 @@ async fn drive(2107
if let Some(audio) = live.audio.as_ref() {2126
if let Some(audio) = live.audio.as_ref() {2108
track = audio.device_track(mic_settings).clone();2127
track = audio.device_track(mic_settings).clone();2109
}2128
}2110
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), device_ns_changed, &mut software_audio, mic_settings, control, timeline);2129
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), device_ns_changed, &mut software_audio, mic_settings, control, timeline);2111
}2130
}2112
Some(CallCommand::SetMicSettings(settings)) => {2131
Some(CallCommand::SetMicSettings(settings)) => {2113
mic_settings = settings;2132
mic_settings = settings;@@ -2315,7 +2334,7 @@ async fn drive(2315
match local_video.start_share(&source) {2334
match local_video.start_share(&source) {2316
Ok(()) => {2335
Ok(()) => {2317
announce_share(control, &source);2336
announce_share(control, &source);2318
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);2337
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);2319
match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {2338
match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {2320
Ok((browser_offer, signaled, reply_tags)) => {2339
Ok((browser_offer, signaled, reply_tags)) => {2321
timeline.record_sdp("local offer", &signaled.sdp);2340
timeline.record_sdp("local offer", &signaled.sdp);@@ -2358,7 +2377,7 @@ async fn drive(2358
&mut media_description_request,2377
&mut media_description_request,2359
timeline,2378
timeline,2360
);2379
);2361
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);2380
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);2362
}2381
}2363
Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),2382
Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),2364
}2383
}@@ -2375,7 +2394,7 @@ async fn drive(2375
} else if direct && local_video.sharing() {2394
} else if direct && local_video.sharing() {2376
local_video.stop_share();2395
local_video.stop_share();2377
clear_share(control);2396
clear_share(control);2378
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);2397
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);2379
match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {2398
match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {2380
Ok((browser_offer, signaled, reply_tags)) => {2399
Ok((browser_offer, signaled, reply_tags)) => {2381
timeline.record_sdp("local offer", &signaled.sdp);2400
timeline.record_sdp("local offer", &signaled.sdp);@@ -2387,7 +2406,7 @@ async fn drive(2387
}2406
}2388
} else if local_video.sharing() {2407
} else if local_video.sharing() {2389
local_video.stop_share();2408
local_video.stop_share();2390
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);2409
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);2391
clear_share(control);2410
clear_share(control);2392
tell_media_descriptions(2411
tell_media_descriptions(2393
&remote,2412
&remote,@@ -2403,7 +2422,7 @@ async fn drive(2403
}2422
}2404
Some(CallCommand::SetShareSound(on)) => {2423
Some(CallCommand::SetShareSound(on)) => {2405
share_sound_wanted = on;2424
share_sound_wanted = on;2406
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);2425
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);2407
}2426
}2408
Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true),2427
Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true),2409
Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {2428
Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {@@ -2804,6 +2823,20 @@ async fn drive(2804
segmentation_model = Some(model);2823
segmentation_model = Some(model);2805
}2824
}2806
}2825
}2826
if crate::host_load::recorded_on_this_platform()2827
&& ticks.is_multiple_of(HEALTH_EVERY_TICKS)2828
{2829
let current = crate::host_load::thread_cpu();2830
let deltas = crate::host_load::cpu_deltas(¤t, &mut host_cpu);2831
timeline.record(2832
"host load",2833
crate::host_load::host_load_line(2834
&deltas,2835
&local_video.effects_label(),2836
crate::host_load::thermal_state(),2837
),2838
);2839
}2807
if ticks.is_multiple_of(HEALTH_EVERY_TICKS) {2840
if ticks.is_multiple_of(HEALTH_EVERY_TICKS) {2808
control.send(CallUpdate::Sample(StatsSample {2841
control.send(CallUpdate::Sample(StatsSample {2809
audio_in_packets: snapshot.inbound_packets,2842
audio_in_packets: snapshot.inbound_packets,@@ -2939,7 +2972,7 @@ async fn drive(2939
record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());2972
record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());2940
}2973
}2941
if input_changed && software_audio.is_some() {2974
if input_changed && software_audio.is_some() {2942
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);2975
sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);2943
}2976
}2944
}2977
}2945
}2978
}@@ -3058,6 +3091,23 @@ fn far_future() -> Instant {3058
3091
3059
#[cfg(test)]3092
#[cfg(test)]3060
mod tests {3093
mod tests {3094
#[test]3095
fn a_missing_call_on_accept_while_connecting_is_a_cancel() {3096
let gone = Error::Signaling(3097
"POST acceptance answered HTTP 404 {\"Message\":\"The requested call does not exist.\"}"3098
.into(),3099
);3100
assert!(accept_found_no_call(&gone));3101
let other = Error::Signaling("POST acceptance answered HTTP 500 boom".into());3102
assert!(!accept_found_no_call(&other));3103
let roster = Error::Signaling(3104
"POST roster answered HTTP 404 {\"Message\":\"The requested call does not exist.\"}"3105
.into(),3106
);3107
assert!(!accept_found_no_call(&roster));3108
assert!(!accept_found_no_call(&Error::Cancelled));3109
}3110
3061
#[test]3111
#[test]3062
fn gathering_settles_shortly_after_a_udp_relay_or_when_complete() {3112
fn gathering_settles_shortly_after_a_udp_relay_or_when_complete() {3063
assert!(!gathering_settled(false, None));3113
assert!(!gathering_settled(false, None));@@ -0,0 +1,305 @@
1
use std::collections::HashMap;
2
3
/// One thread and the CPU time it has used since the process started, in milliseconds.
4
/// `id` is the kernel thread id, not the Mach port and not the pthread name.
5
#[derive(Debug, Clone, PartialEq, Eq)]
6
pub struct ThreadCpu {
7
pub id: u64,
8
pub name: String,
9
pub cpu_ms: u64,
10
}
11
12
pub fn recorded_on_this_platform() -> bool {
13
cfg!(target_os = "macos")
14
}
15
16
/// CPU used since the previous sample, summed by thread name. The first sample reports the
17
/// time already used. Threads that share a name (tokio workers) stay separate in `previous`
18
/// and add up on the line.
19
pub fn cpu_deltas(current: &[ThreadCpu], previous: &mut HashMap<u64, u64>) -> Vec<(String, u64)> {
20
let mut seen = Vec::with_capacity(current.len());
21
let mut totals: HashMap<String, u64> = HashMap::new();
22
for thread in current {
23
let before = previous.get(&thread.id).copied().unwrap_or(0);
24
*totals.entry(thread.name.clone()).or_default() += thread.cpu_ms.saturating_sub(before);
25
previous.insert(thread.id, thread.cpu_ms);
26
seen.push(thread.id);
27
}
28
previous.retain(|id, _| seen.contains(id));
29
let mut deltas: Vec<(String, u64)> = totals.into_iter().collect();
30
deltas.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0)));
31
deltas
32
}
33
34
const SHOWN_THREADS: usize = 8;
35
36
pub fn host_load_line(deltas: &[(String, u64)], effects: &str, thermal: &str) -> String {
37
let active: Vec<_> = deltas.iter().filter(|(_, cpu_ms)| *cpu_ms > 0).collect();
38
let threads = if active.is_empty() {
39
"no thread cpu".to_owned()
40
} else {
41
let shown = active.len().min(SHOWN_THREADS);
42
let mut parts: Vec<String> = active[..shown]
43
.iter()
44
.map(|(name, cpu_ms)| format!("{name} {cpu_ms}ms"))
45
.collect();
46
if active.len() > SHOWN_THREADS {
47
let rest: u64 = active[SHOWN_THREADS..]
48
.iter()
49
.map(|(_, cpu_ms)| *cpu_ms)
50
.sum();
51
parts.push(format!("others {rest}ms"));
52
}
53
parts.join(", ")
54
};
55
format!("{threads}; {effects}; thermal {thermal}")
56
}
57
58
/// Cumulative CPU time per thread. Empty off macOS, and empty when the kernel call fails.
59
pub fn thread_cpu() -> Vec<ThreadCpu> {
60
#[cfg(target_os = "macos")]
61
{
62
macos::thread_cpu()
63
}
64
#[cfg(not(target_os = "macos"))]
65
{
66
Vec::new()
67
}
68
}
69
70
pub fn thermal_state() -> &'static str {
71
#[cfg(target_os = "macos")]
72
{
73
macos::thermal_state()
74
}
75
#[cfg(not(target_os = "macos"))]
76
{
77
"unavailable"
78
}
79
}
80
81
#[cfg(target_os = "macos")]
82
mod macos {
83
use super::ThreadCpu;
84
85
unsafe extern "C" {
86
fn mach_port_deallocate(
87
task: libc::mach_port_t,
88
name: libc::mach_port_t,
89
) -> libc::kern_return_t;
90
}
91
92
pub fn thermal_state() -> &'static str {
93
let state = objc2_foundation::NSProcessInfo::processInfo().thermalState();
94
match state {
95
objc2_foundation::NSProcessInfoThermalState::Nominal => "nominal",
96
objc2_foundation::NSProcessInfoThermalState::Fair => "fair",
97
objc2_foundation::NSProcessInfoThermalState::Serious => "serious",
98
objc2_foundation::NSProcessInfoThermalState::Critical => "critical",
99
_ => "unknown",
100
}
101
}
102
103
pub fn thread_cpu() -> Vec<ThreadCpu> {
104
unsafe {
105
let task = libc::mach_task_self();
106
let mut threads: libc::thread_act_array_t = std::ptr::null_mut();
107
let mut count: libc::mach_msg_type_number_t = 0;
108
if libc::task_threads(task, &mut threads, &mut count) != libc::KERN_SUCCESS {
109
return Vec::new();
110
}
111
let mut found = Vec::with_capacity(count as usize);
112
for index in 0..count {
113
let thread = *threads.add(index as usize);
114
let mut info: libc::thread_basic_info = std::mem::zeroed();
115
let mut info_count = libc::THREAD_BASIC_INFO_COUNT;
116
let status = libc::thread_info(
117
thread,
118
libc::THREAD_BASIC_INFO,
119
&mut info as *mut libc::thread_basic_info as libc::thread_info_t,
120
&mut info_count,
121
);
122
if status == libc::KERN_SUCCESS
123
&& let Some(id) = thread_id(thread)
124
{
125
found.push(ThreadCpu {
126
id,
127
name: thread_name(thread),
128
cpu_ms: cpu_ms(&info),
129
});
130
}
131
// task_threads hands back a send right per thread. Freeing the array does not release those.
132
let _ = mach_port_deallocate(task, thread);
133
}
134
let bytes = count as libc::vm_size_t
135
* std::mem::size_of::<libc::thread_act_t>() as libc::vm_size_t;
136
let _ = libc::vm_deallocate(task, threads as libc::vm_address_t, bytes);
137
found
138
}
139
}
140
141
fn cpu_ms(info: &libc::thread_basic_info) -> u64 {
142
let part = |time: libc::time_value_t| {
143
let seconds = i64::from(time.seconds).max(0);
144
let micros = i64::from(time.microseconds).max(0);
145
seconds.saturating_mul(1000) + micros / 1000
146
};
147
part(info.user_time).saturating_add(part(info.system_time)) as u64
148
}
149
150
/// Stable across samples. The Mach port from `task_threads` is reused after
151
/// `mach_port_deallocate`, so it cannot key the previous sample.
152
fn thread_id(thread: libc::thread_act_t) -> Option<u64> {
153
unsafe {
154
let mut info: libc::thread_identifier_info = std::mem::zeroed();
155
let mut count = libc::THREAD_IDENTIFIER_INFO_COUNT;
156
let status = libc::thread_info(
157
thread,
158
libc::THREAD_IDENTIFIER_INFO,
159
&mut info as *mut libc::thread_identifier_info as libc::thread_info_t,
160
&mut count,
161
);
162
if status == libc::KERN_SUCCESS && info.thread_id != 0 {
163
Some(info.thread_id)
164
} else {
165
None
166
}
167
}
168
}
169
170
fn thread_name(thread: libc::thread_act_t) -> String {
171
unsafe {
172
let pthread = libc::pthread_from_mach_thread_np(thread);
173
if !pthread.is_null() {
174
let mut buffer = [0u8; 64];
175
if libc::pthread_getname_np(pthread, buffer.as_mut_ptr().cast(), buffer.len()) == 0
176
{
177
let end = buffer
178
.iter()
179
.position(|byte| *byte == 0)
180
.unwrap_or(buffer.len());
181
if let Ok(name) = std::str::from_utf8(&buffer[..end]) {
182
let name = name.trim();
183
if !name.is_empty() {
184
return name.to_owned();
185
}
186
}
187
}
188
}
189
format!("tid-{thread}")
190
}
191
}
192
}
193
194
#[cfg(test)]
195
mod tests {
196
use super::*;
197
198
#[test]
199
fn a_host_load_line_names_the_hot_thread_the_effects_and_the_thermal_state() {
200
let mut previous = HashMap::new();
201
let first = cpu_deltas(
202
&[
203
ThreadCpu {
204
id: 1,
205
name: "camera".into(),
206
cpu_ms: 40,
207
},
208
ThreadCpu {
209
id: 2,
210
name: "camera effects".into(),
211
cpu_ms: 5,
212
},
213
],
214
&mut previous,
215
);
216
let line = host_load_line(
217
&first,
218
"blur=off standout=off framing=off brightness=off soft_focus=off",
219
"nominal",
220
);
221
assert_eq!(
222
line,
223
"camera 40ms, camera effects 5ms; blur=off standout=off framing=off brightness=off soft_focus=off; thermal nominal"
224
);
225
let second = cpu_deltas(
226
&[
227
ThreadCpu {
228
id: 1,
229
name: "camera".into(),
230
cpu_ms: 90,
231
},
232
ThreadCpu {
233
id: 2,
234
name: "camera effects".into(),
235
cpu_ms: 5,
236
},
237
],
238
&mut previous,
239
);
240
assert_eq!(
241
second,
242
vec![("camera".into(), 50), ("camera effects".into(), 0)]
243
);
244
}
245
246
#[test]
247
fn shared_thread_names_sum_and_idle_threads_fold_out_of_the_line() {
248
let mut previous = HashMap::new();
249
let first = cpu_deltas(
250
&[
251
ThreadCpu {
252
id: 10,
253
name: "teams-net".into(),
254
cpu_ms: 5_000,
255
},
256
ThreadCpu {
257
id: 11,
258
name: "teams-net".into(),
259
cpu_ms: 300,
260
},
261
],
262
&mut previous,
263
);
264
assert_eq!(first, vec![("teams-net".into(), 5_300)]);
265
let second = cpu_deltas(
266
&[
267
ThreadCpu {
268
id: 10,
269
name: "teams-net".into(),
270
cpu_ms: 5_300,
271
},
272
ThreadCpu {
273
id: 11,
274
name: "teams-net".into(),
275
cpu_ms: 800,
276
},
277
],
278
&mut previous,
279
);
280
assert_eq!(second, vec![("teams-net".into(), 800)]);
281
let mut busy = Vec::new();
282
for index in 0..10 {
283
busy.push((format!("t{index}"), 10 - index));
284
}
285
busy.push(("idle".into(), 0));
286
let line = host_load_line(
287
&busy,
288
"blur=off standout=off framing=off brightness=off soft_focus=off",
289
"unknown",
290
);
291
assert_eq!(
292
line,
293
"t0 10ms, t1 9ms, t2 8ms, t3 7ms, t4 6ms, t5 5ms, t6 4ms, t7 3ms, others 3ms; blur=off standout=off framing=off brightness=off soft_focus=off; thermal unknown"
294
);
295
}
296
297
#[test]
298
fn host_load_is_recorded_only_on_macos() {
299
assert_eq!(recorded_on_this_platform(), cfg!(target_os = "macos"));
300
if !recorded_on_this_platform() {
301
assert!(thread_cpu().is_empty());
302
assert_eq!(thermal_state(), "unavailable");
303
}
304
}
305
}
@@ -0,0 +1,305 @@1
use std::collections::HashMap;2
3
/// One thread and the CPU time it has used since the process started, in milliseconds.4
/// `id` is the kernel thread id, not the Mach port and not the pthread name.5
#[derive(Debug, Clone, PartialEq, Eq)]6
pub struct ThreadCpu {7
pub id: u64,8
pub name: String,9
pub cpu_ms: u64,10
}11
12
pub fn recorded_on_this_platform() -> bool {13
cfg!(target_os = "macos")14
}15
16
/// CPU used since the previous sample, summed by thread name. The first sample reports the17
/// time already used. Threads that share a name (tokio workers) stay separate in `previous`18
/// and add up on the line.19
pub fn cpu_deltas(current: &[ThreadCpu], previous: &mut HashMap<u64, u64>) -> Vec<(String, u64)> {20
let mut seen = Vec::with_capacity(current.len());21
let mut totals: HashMap<String, u64> = HashMap::new();22
for thread in current {23
let before = previous.get(&thread.id).copied().unwrap_or(0);24
*totals.entry(thread.name.clone()).or_default() += thread.cpu_ms.saturating_sub(before);25
previous.insert(thread.id, thread.cpu_ms);26
seen.push(thread.id);27
}28
previous.retain(|id, _| seen.contains(id));29
let mut deltas: Vec<(String, u64)> = totals.into_iter().collect();30
deltas.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0)));31
deltas32
}33
34
const SHOWN_THREADS: usize = 8;35
36
pub fn host_load_line(deltas: &[(String, u64)], effects: &str, thermal: &str) -> String {37
let active: Vec<_> = deltas.iter().filter(|(_, cpu_ms)| *cpu_ms > 0).collect();38
let threads = if active.is_empty() {39
"no thread cpu".to_owned()40
} else {41
let shown = active.len().min(SHOWN_THREADS);42
let mut parts: Vec<String> = active[..shown]43
.iter()44
.map(|(name, cpu_ms)| format!("{name} {cpu_ms}ms"))45
.collect();46
if active.len() > SHOWN_THREADS {47
let rest: u64 = active[SHOWN_THREADS..]48
.iter()49
.map(|(_, cpu_ms)| *cpu_ms)50
.sum();51
parts.push(format!("others {rest}ms"));52
}53
parts.join(", ")54
};55
format!("{threads}; {effects}; thermal {thermal}")56
}57
58
/// Cumulative CPU time per thread. Empty off macOS, and empty when the kernel call fails.59
pub fn thread_cpu() -> Vec<ThreadCpu> {60
#[cfg(target_os = "macos")]61
{62
macos::thread_cpu()63
}64
#[cfg(not(target_os = "macos"))]65
{66
Vec::new()67
}68
}69
70
pub fn thermal_state() -> &'static str {71
#[cfg(target_os = "macos")]72
{73
macos::thermal_state()74
}75
#[cfg(not(target_os = "macos"))]76
{77
"unavailable"78
}79
}80
81
#[cfg(target_os = "macos")]82
mod macos {83
use super::ThreadCpu;84
85
unsafe extern "C" {86
fn mach_port_deallocate(87
task: libc::mach_port_t,88
name: libc::mach_port_t,89
) -> libc::kern_return_t;90
}91
92
pub fn thermal_state() -> &'static str {93
let state = objc2_foundation::NSProcessInfo::processInfo().thermalState();94
match state {95
objc2_foundation::NSProcessInfoThermalState::Nominal => "nominal",96
objc2_foundation::NSProcessInfoThermalState::Fair => "fair",97
objc2_foundation::NSProcessInfoThermalState::Serious => "serious",98
objc2_foundation::NSProcessInfoThermalState::Critical => "critical",99
_ => "unknown",100
}101
}102
103
pub fn thread_cpu() -> Vec<ThreadCpu> {104
unsafe {105
let task = libc::mach_task_self();106
let mut threads: libc::thread_act_array_t = std::ptr::null_mut();107
let mut count: libc::mach_msg_type_number_t = 0;108
if libc::task_threads(task, &mut threads, &mut count) != libc::KERN_SUCCESS {109
return Vec::new();110
}111
let mut found = Vec::with_capacity(count as usize);112
for index in 0..count {113
let thread = *threads.add(index as usize);114
let mut info: libc::thread_basic_info = std::mem::zeroed();115
let mut info_count = libc::THREAD_BASIC_INFO_COUNT;116
let status = libc::thread_info(117
thread,118
libc::THREAD_BASIC_INFO,119
&mut info as *mut libc::thread_basic_info as libc::thread_info_t,120
&mut info_count,121
);122
if status == libc::KERN_SUCCESS123
&& let Some(id) = thread_id(thread)124
{125
found.push(ThreadCpu {126
id,127
name: thread_name(thread),128
cpu_ms: cpu_ms(&info),129
});130
}131
// task_threads hands back a send right per thread. Freeing the array does not release those.132
let _ = mach_port_deallocate(task, thread);133
}134
let bytes = count as libc::vm_size_t135
* std::mem::size_of::<libc::thread_act_t>() as libc::vm_size_t;136
let _ = libc::vm_deallocate(task, threads as libc::vm_address_t, bytes);137
found138
}139
}140
141
fn cpu_ms(info: &libc::thread_basic_info) -> u64 {142
let part = |time: libc::time_value_t| {143
let seconds = i64::from(time.seconds).max(0);144
let micros = i64::from(time.microseconds).max(0);145
seconds.saturating_mul(1000) + micros / 1000146
};147
part(info.user_time).saturating_add(part(info.system_time)) as u64148
}149
150
/// Stable across samples. The Mach port from `task_threads` is reused after151
/// `mach_port_deallocate`, so it cannot key the previous sample.152
fn thread_id(thread: libc::thread_act_t) -> Option<u64> {153
unsafe {154
let mut info: libc::thread_identifier_info = std::mem::zeroed();155
let mut count = libc::THREAD_IDENTIFIER_INFO_COUNT;156
let status = libc::thread_info(157
thread,158
libc::THREAD_IDENTIFIER_INFO,159
&mut info as *mut libc::thread_identifier_info as libc::thread_info_t,160
&mut count,161
);162
if status == libc::KERN_SUCCESS && info.thread_id != 0 {163
Some(info.thread_id)164
} else {165
None166
}167
}168
}169
170
fn thread_name(thread: libc::thread_act_t) -> String {171
unsafe {172
let pthread = libc::pthread_from_mach_thread_np(thread);173
if !pthread.is_null() {174
let mut buffer = [0u8; 64];175
if libc::pthread_getname_np(pthread, buffer.as_mut_ptr().cast(), buffer.len()) == 0176
{177
let end = buffer178
.iter()179
.position(|byte| *byte == 0)180
.unwrap_or(buffer.len());181
if let Ok(name) = std::str::from_utf8(&buffer[..end]) {182
let name = name.trim();183
if !name.is_empty() {184
return name.to_owned();185
}186
}187
}188
}189
format!("tid-{thread}")190
}191
}192
}193
194
#[cfg(test)]195
mod tests {196
use super::*;197
198
#[test]199
fn a_host_load_line_names_the_hot_thread_the_effects_and_the_thermal_state() {200
let mut previous = HashMap::new();201
let first = cpu_deltas(202
&[203
ThreadCpu {204
id: 1,205
name: "camera".into(),206
cpu_ms: 40,207
},208
ThreadCpu {209
id: 2,210
name: "camera effects".into(),211
cpu_ms: 5,212
},213
],214
&mut previous,215
);216
let line = host_load_line(217
&first,218
"blur=off standout=off framing=off brightness=off soft_focus=off",219
"nominal",220
);221
assert_eq!(222
line,223
"camera 40ms, camera effects 5ms; blur=off standout=off framing=off brightness=off soft_focus=off; thermal nominal"224
);225
let second = cpu_deltas(226
&[227
ThreadCpu {228
id: 1,229
name: "camera".into(),230
cpu_ms: 90,231
},232
ThreadCpu {233
id: 2,234
name: "camera effects".into(),235
cpu_ms: 5,236
},237
],238
&mut previous,239
);240
assert_eq!(241
second,242
vec![("camera".into(), 50), ("camera effects".into(), 0)]243
);244
}245
246
#[test]247
fn shared_thread_names_sum_and_idle_threads_fold_out_of_the_line() {248
let mut previous = HashMap::new();249
let first = cpu_deltas(250
&[251
ThreadCpu {252
id: 10,253
name: "teams-net".into(),254
cpu_ms: 5_000,255
},256
ThreadCpu {257
id: 11,258
name: "teams-net".into(),259
cpu_ms: 300,260
},261
],262
&mut previous,263
);264
assert_eq!(first, vec![("teams-net".into(), 5_300)]);265
let second = cpu_deltas(266
&[267
ThreadCpu {268
id: 10,269
name: "teams-net".into(),270
cpu_ms: 5_300,271
},272
ThreadCpu {273
id: 11,274
name: "teams-net".into(),275
cpu_ms: 800,276
},277
],278
&mut previous,279
);280
assert_eq!(second, vec![("teams-net".into(), 800)]);281
let mut busy = Vec::new();282
for index in 0..10 {283
busy.push((format!("t{index}"), 10 - index));284
}285
busy.push(("idle".into(), 0));286
let line = host_load_line(287
&busy,288
"blur=off standout=off framing=off brightness=off soft_focus=off",289
"unknown",290
);291
assert_eq!(292
line,293
"t0 10ms, t1 9ms, t2 8ms, t3 7ms, t4 6ms, t5 5ms, t6 4ms, t7 3ms, others 3ms; blur=off standout=off framing=off brightness=off soft_focus=off; thermal unknown"294
);295
}296
297
#[test]298
fn host_load_is_recorded_only_on_macos() {299
assert_eq!(recorded_on_this_platform(), cfg!(target_os = "macos"));300
if !recorded_on_this_platform() {301
assert!(thread_cpu().is_empty());302
assert_eq!(thermal_state(), "unavailable");303
}304
}305
}@@ -25,6 +25,7 @@ pub mod error;
25
25
pub mod framing;
26
26
pub mod health;
27
27
pub mod hold;
28
pub mod host_load;
28
29
pub mod join;
29
30
pub mod latest;
30
31
pub mod level;
@@ -25,6 +25,7 @@ pub mod error;25
pub mod framing;25
pub mod framing;26
pub mod health;26
pub mod health;27
pub mod hold;27
pub mod hold;28
pub mod host_load;28
pub mod join;29
pub mod join;29
pub mod latest;30
pub mod latest;30
pub mod level;31
pub mod level;@@ -448,9 +448,21 @@ enum ActiveShareStop {
448
448
}
449
449
450
450
/// Classifies an error received while a portal share is active.
451
fn active_portal_error(error: CaptureError) -> Option<ActiveShareStop> {
451
///
452
/// Wayland reports a desktop stop, a closed window, and a PipeWire or compositor
453
/// failure after the first frame all as `Permanent`. Those stay quiet: the portal
454
/// does not say which one it was, and a notice would fire on every Stop sharing.
455
/// A permanent error before the first frame still shows a notice. macOS uses
456
/// `StoppedByUser` for the menu-bar stop, so a later `Permanent` there stays a
457
/// failure notice.
458
fn active_portal_error(
459
error: CaptureError,
460
delegated: bool,
461
seen_frame: bool,
462
) -> Option<ActiveShareStop> {
452
463
match error {
453
464
CaptureError::StoppedByUser => Some(ActiveShareStop::Quiet),
465
CaptureError::Permanent if delegated && seen_frame => Some(ActiveShareStop::Quiet),
454
466
CaptureError::StartFailed | CaptureError::Interrupted => {
455
467
Some(ActiveShareStop::Notice("macOS stopped the capture"))
456
468
}
@@ -492,6 +504,7 @@ pub(crate) fn start_portal_capture(
492
504
let gone_mark = gone_since.clone();
493
505
let active_end: Arc<Mutex<Option<ActiveShareStop>>> = Arc::default();
494
506
let end_mark = active_end.clone();
507
let seen_frame = Arc::new(AtomicBool::new(false));
495
508
capturer.start_capture(None, move |result| {
496
509
if !gate.load(Ordering::SeqCst) {
497
510
let Some(events) = &frame_events else { return };
@@ -506,6 +519,7 @@ pub(crate) fn start_portal_capture(
506
519
}
507
520
match result {
508
521
Ok(frame) => {
522
seen_frame.store(true, Ordering::SeqCst);
509
523
if let Ok(mut since) = gone_mark.lock() {
510
524
*since = None;
511
525
}
@@ -526,7 +540,8 @@ pub(crate) fn start_portal_capture(
526
540
}
527
541
}
528
542
Err(error) => {
529
if let Some(stop_reason) = active_portal_error(error)
543
if let Some(stop_reason) =
544
active_portal_error(error, delegated, seen_frame.load(Ordering::SeqCst))
530
545
&& let Ok(mut slot) = end_mark.lock()
531
546
{
532
547
slot.get_or_insert(stop_reason);
@@ -682,23 +697,37 @@ mod tests {
682
697
#[test]
683
698
fn active_portal_errors_separate_user_stop_from_failures() {
684
699
assert_eq!(
685
active_portal_error(CaptureError::StoppedByUser),
700
active_portal_error(CaptureError::StoppedByUser, false, false),
686
701
Some(ActiveShareStop::Quiet)
687
702
);
688
703
assert_eq!(
689
active_portal_error(CaptureError::Interrupted),
704
active_portal_error(CaptureError::Interrupted, true, true),
690
705
Some(ActiveShareStop::Notice("macOS stopped the capture"))
691
706
);
692
707
assert_eq!(
693
active_portal_error(CaptureError::StartFailed),
708
active_portal_error(CaptureError::StartFailed, true, true),
694
709
Some(ActiveShareStop::Notice("macOS stopped the capture"))
695
710
);
696
711
assert_eq!(
697
active_portal_error(CaptureError::Permanent),
712
active_portal_error(CaptureError::Permanent, true, true),
713
Some(ActiveShareStop::Quiet)
714
);
715
assert_eq!(
716
active_portal_error(CaptureError::Permanent, true, false),
717
Some(ActiveShareStop::Notice("the system stopped the capture"))
718
);
719
assert_eq!(
720
active_portal_error(CaptureError::Permanent, false, true),
698
721
Some(ActiveShareStop::Notice("the system stopped the capture"))
699
722
);
700
assert_eq!(active_portal_error(CaptureError::SourceGone), None);
701
assert_eq!(active_portal_error(CaptureError::Temporary), None);
723
assert_eq!(
724
active_portal_error(CaptureError::SourceGone, true, true),
725
None
726
);
727
assert_eq!(
728
active_portal_error(CaptureError::Temporary, true, true),
729
None
730
);
702
731
}
703
732
}
704
733
@@ -448,9 +448,21 @@ enum ActiveShareStop {448
}448
}449
449
450
/// Classifies an error received while a portal share is active.450
/// Classifies an error received while a portal share is active.451
fn active_portal_error(error: CaptureError) -> Option<ActiveShareStop> {451
///452
/// Wayland reports a desktop stop, a closed window, and a PipeWire or compositor453
/// failure after the first frame all as `Permanent`. Those stay quiet: the portal454
/// does not say which one it was, and a notice would fire on every Stop sharing.455
/// A permanent error before the first frame still shows a notice. macOS uses456
/// `StoppedByUser` for the menu-bar stop, so a later `Permanent` there stays a457
/// failure notice.458
fn active_portal_error(459
error: CaptureError,460
delegated: bool,461
seen_frame: bool,462
) -> Option<ActiveShareStop> {452
match error {463
match error {453
CaptureError::StoppedByUser => Some(ActiveShareStop::Quiet),464
CaptureError::StoppedByUser => Some(ActiveShareStop::Quiet),465
CaptureError::Permanent if delegated && seen_frame => Some(ActiveShareStop::Quiet),454
CaptureError::StartFailed | CaptureError::Interrupted => {466
CaptureError::StartFailed | CaptureError::Interrupted => {455
Some(ActiveShareStop::Notice("macOS stopped the capture"))467
Some(ActiveShareStop::Notice("macOS stopped the capture"))456
}468
}@@ -492,6 +504,7 @@ pub(crate) fn start_portal_capture(492
let gone_mark = gone_since.clone();504
let gone_mark = gone_since.clone();493
let active_end: Arc<Mutex<Option<ActiveShareStop>>> = Arc::default();505
let active_end: Arc<Mutex<Option<ActiveShareStop>>> = Arc::default();494
let end_mark = active_end.clone();506
let end_mark = active_end.clone();507
let seen_frame = Arc::new(AtomicBool::new(false));495
capturer.start_capture(None, move |result| {508
capturer.start_capture(None, move |result| {496
if !gate.load(Ordering::SeqCst) {509
if !gate.load(Ordering::SeqCst) {497
let Some(events) = &frame_events else { return };510
let Some(events) = &frame_events else { return };@@ -506,6 +519,7 @@ pub(crate) fn start_portal_capture(506
}519
}507
match result {520
match result {508
Ok(frame) => {521
Ok(frame) => {522
seen_frame.store(true, Ordering::SeqCst);509
if let Ok(mut since) = gone_mark.lock() {523
if let Ok(mut since) = gone_mark.lock() {510
*since = None;524
*since = None;511
}525
}@@ -526,7 +540,8 @@ pub(crate) fn start_portal_capture(526
}540
}527
}541
}528
Err(error) => {542
Err(error) => {529
if let Some(stop_reason) = active_portal_error(error)543
if let Some(stop_reason) =544
active_portal_error(error, delegated, seen_frame.load(Ordering::SeqCst))530
&& let Ok(mut slot) = end_mark.lock()545
&& let Ok(mut slot) = end_mark.lock()531
{546
{532
slot.get_or_insert(stop_reason);547
slot.get_or_insert(stop_reason);@@ -682,23 +697,37 @@ mod tests {682
#[test]697
#[test]683
fn active_portal_errors_separate_user_stop_from_failures() {698
fn active_portal_errors_separate_user_stop_from_failures() {684
assert_eq!(699
assert_eq!(685
active_portal_error(CaptureError::StoppedByUser),700
active_portal_error(CaptureError::StoppedByUser, false, false),686
Some(ActiveShareStop::Quiet)701
Some(ActiveShareStop::Quiet)687
);702
);688
assert_eq!(703
assert_eq!(689
active_portal_error(CaptureError::Interrupted),704
active_portal_error(CaptureError::Interrupted, true, true),690
Some(ActiveShareStop::Notice("macOS stopped the capture"))705
Some(ActiveShareStop::Notice("macOS stopped the capture"))691
);706
);692
assert_eq!(707
assert_eq!(693
active_portal_error(CaptureError::StartFailed),708
active_portal_error(CaptureError::StartFailed, true, true),694
Some(ActiveShareStop::Notice("macOS stopped the capture"))709
Some(ActiveShareStop::Notice("macOS stopped the capture"))695
);710
);696
assert_eq!(711
assert_eq!(697
active_portal_error(CaptureError::Permanent),712
active_portal_error(CaptureError::Permanent, true, true),713
Some(ActiveShareStop::Quiet)714
);715
assert_eq!(716
active_portal_error(CaptureError::Permanent, true, false),717
Some(ActiveShareStop::Notice("the system stopped the capture"))718
);719
assert_eq!(720
active_portal_error(CaptureError::Permanent, false, true),698
Some(ActiveShareStop::Notice("the system stopped the capture"))721
Some(ActiveShareStop::Notice("the system stopped the capture"))699
);722
);700
assert_eq!(active_portal_error(CaptureError::SourceGone), None);723
assert_eq!(701
assert_eq!(active_portal_error(CaptureError::Temporary), None);724
active_portal_error(CaptureError::SourceGone, true, true),725
None726
);727
assert_eq!(728
active_portal_error(CaptureError::Temporary, true, true),729
None730
);702
}731
}703
}732
}704
733
@@ -1,7 +1,9 @@
1
1
use std::collections::BTreeMap;
2
2
3
3
use serde_json::{Map, Value, json};
4
use session::trusted_url::{HostRule, trusted_https_url};
4
5
use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session};
6
use url::{Position, Url};
5
7
6
8
use crate::captions::{self, BotAction};
7
9
use crate::error::{Error, Result};
@@ -25,8 +27,7 @@ const ENDPOINT_CAPABILITIES: u64 = 73463;
25
27
const ONE_TO_ONE_THREAD_SUFFIX: &str = "@unq.gbl.spaces";
26
28
const DIRECT_REQUIRED_FEATURES: &str = "nonByPass";
27
29
const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;
28
const ALLOWED_HOST_SUFFIXES: [&str; 2] =
29
[".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];
30
const TEAMS_HOSTS: [HostRule; 1] = [HostRule::Domain("teams.microsoft.com")];
30
31
const BACKEND_SUFFIX: &str = ".skype.com";
31
32
const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";
32
33
const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";
@@ -143,25 +144,32 @@ impl Conversation {
143
144
}
144
145
}
145
146
146
fn host_of(url: &str) -> Result<&str> {
147
url.strip_prefix("https://")
148
.and_then(|rest| rest.split(['/', '?']).next())
149
.map(|authority| authority.split(':').next().unwrap_or(authority))
150
.ok_or_else(|| Error::Signaling("link is not https".into()))
147
fn plain_https(url: &str) -> Result<Url> {
148
Url::parse(url)
149
.ok()
150
.filter(|parsed| {
151
parsed.scheme() == "https"
152
&& parsed.username().is_empty()
153
&& parsed.password().is_none()
154
&& parsed.port().is_none()
155
&& parsed.host_str().is_some()
156
})
157
.ok_or_else(|| Error::Signaling("link is not plain https".into()))
151
158
}
152
159
153
160
/// Bearer requests only go to Teams hosts; links come from server answers.
154
161
pub fn ensure_teams_url(url: &str) -> Result<()> {
155
let host = host_of(url)?;
156
if ALLOWED_HOST_SUFFIXES
157
.iter()
158
.any(|suffix| host.ends_with(suffix))
159
|| host == "teams.microsoft.com"
160
{
161
Ok(())
162
} else {
163
Err(Error::Signaling(format!("refusing link to host {host}")))
164
}
162
trusted_teams_url(url).map(|_| ())
163
}
164
165
fn trusted_teams_url(url: &str) -> Result<Url> {
166
trusted_https_url(url, &TEAMS_HOSTS).ok_or_else(|| {
167
let host = Url::parse(url)
168
.ok()
169
.and_then(|parsed| parsed.host_str().map(str::to_owned))
170
.unwrap_or_default();
171
Error::Signaling(format!("refusing link to host {host}"))
172
})
165
173
}
166
174
167
175
fn is_backend_host(host: &str) -> bool {
@@ -176,15 +184,12 @@ fn is_backend_host(host: &str) -> bool {
176
184
177
185
/// Push links may name a backend host directly; the browser always reaches those through flightproxy.
178
186
pub fn routed_url(url: &str) -> Result<String> {
179
let host = host_of(url)?;
187
let parsed = plain_https(url)?;
188
let host = parsed.host_str().unwrap_or_default();
180
189
if !is_backend_host(host) {
181
ensure_teams_url(url)?;
182
return Ok(url.to_owned());
190
return Ok(trusted_teams_url(url)?.into());
183
191
}
184
let rest = &url["https://".len()..];
185
let path = rest
186
.find(['/', '?'])
187
.map_or("", |position| &rest[position..]);
192
let path = &parsed[Position::BeforePath..];
188
193
Ok(format!("{FLIGHTPROXY_EP}/{host}{path}"))
189
194
}
190
195
@@ -797,8 +802,9 @@ impl Signaling {
797
802
}
798
803
799
804
async fn bot_command(&self, command_url: &str, body: Value, label: &str) -> Result<u16> {
805
let command_url = trusted_teams_url(command_url)?;
800
806
let arguments = json!({
801
"url": command_url,
807
"url": command_url.as_str(),
802
808
"body": body,
803
809
"recorderResource": captions::RECORDER_RESOURCE,
804
810
"recorderScope": captions::RECORDER_SCOPE,
@@ -1651,6 +1657,14 @@ mod tests {
1651
1657
assert!(ensure_teams_url("https://conv-euno-06-prod-aks.conv.skype.com/conv/1").is_err());
1652
1658
assert!(ensure_teams_url("https://evil.example/?x=.teams.microsoft.com").is_err());
1653
1659
assert!(ensure_teams_url("http://api.flightproxy.teams.microsoft.com/x").is_err());
1660
for bypass in [
1661
"https://evil.example\\.teams.microsoft.com/x",
1662
"https://evil.example#.teams.microsoft.com/x",
1663
"https://a.teams.microsoft.com:x@evil.example/",
1664
] {
1665
assert!(ensure_teams_url(bypass).is_err(), "{bypass}");
1666
assert!(routed_url(bypass).is_err(), "{bypass}");
1667
}
1654
1668
}
1655
1669
1656
1670
#[test]
@@ -1665,7 +1679,12 @@ mod tests {
1665
1679
"https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y"
1666
1680
);
1667
1681
assert!(routed_url("https://evil.skype.com.example/x").is_err());
1668
assert!(routed_url("https://Evil.skype.com/x").is_err());
1682
assert_eq!(
1683
routed_url("https://CC.skype.com/x").unwrap(),
1684
format!("{FLIGHTPROXY_EP}/cc.skype.com/x")
1685
);
1686
assert!(routed_url("https://cc.skype.com:x@evil.example/x").is_err());
1687
assert!(routed_url("https://evil.example\\.cc.skype.com/x").is_err());
1669
1688
assert!(routed_url("https://user@cc.skype.com/x").is_err());
1670
1689
assert!(routed_url("http://cc.skype.com/x").is_err());
1671
1690
assert!(routed_url("https://.skype.com/x").is_err());
@@ -1,7 +1,9 @@1
use std::collections::BTreeMap;1
use std::collections::BTreeMap;2
2
3
use serde_json::{Map, Value, json};3
use serde_json::{Map, Value, json};4
use session::trusted_url::{HostRule, trusted_https_url};4
use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session};5
use session::{ApiResponse, App, GRAPH, Method, Request, SPACES, Scope, Session};6
use url::{Position, Url};5
7
6
use crate::captions::{self, BotAction};8
use crate::captions::{self, BotAction};7
use crate::error::{Error, Result};9
use crate::error::{Error, Result};@@ -25,8 +27,7 @@ const ENDPOINT_CAPABILITIES: u64 = 73463;25
const ONE_TO_ONE_THREAD_SUFFIX: &str = "@unq.gbl.spaces";27
const ONE_TO_ONE_THREAD_SUFFIX: &str = "@unq.gbl.spaces";26
const DIRECT_REQUIRED_FEATURES: &str = "nonByPass";28
const DIRECT_REQUIRED_FEATURES: &str = "nonByPass";27
const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;29
const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;28
const ALLOWED_HOST_SUFFIXES: [&str; 2] =30
const TEAMS_HOSTS: [HostRule; 1] = [HostRule::Domain("teams.microsoft.com")];29
[".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];30
const BACKEND_SUFFIX: &str = ".skype.com";31
const BACKEND_SUFFIX: &str = ".skype.com";31
const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";32
const AUTHZ_SCOPE_NAME: &str = "authorization.readwrite";32
const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";33
const FLIGHTPROXY_EP: &str = "https://api.flightproxy.teams.microsoft.com/api/v2/ep";@@ -143,25 +144,32 @@ impl Conversation {143
}144
}144
}145
}145
146
146
fn host_of(url: &str) -> Result<&str> {147
fn plain_https(url: &str) -> Result<Url> {147
url.strip_prefix("https://")148
Url::parse(url)148
.and_then(|rest| rest.split(['/', '?']).next())149
.ok()149
.map(|authority| authority.split(':').next().unwrap_or(authority))150
.filter(|parsed| {150
.ok_or_else(|| Error::Signaling("link is not https".into()))151
parsed.scheme() == "https"152
&& parsed.username().is_empty()153
&& parsed.password().is_none()154
&& parsed.port().is_none()155
&& parsed.host_str().is_some()156
})157
.ok_or_else(|| Error::Signaling("link is not plain https".into()))151
}158
}152
159
153
/// Bearer requests only go to Teams hosts; links come from server answers.160
/// Bearer requests only go to Teams hosts; links come from server answers.154
pub fn ensure_teams_url(url: &str) -> Result<()> {161
pub fn ensure_teams_url(url: &str) -> Result<()> {155
let host = host_of(url)?;162
trusted_teams_url(url).map(|_| ())156
if ALLOWED_HOST_SUFFIXES163
}157
.iter()164
158
.any(|suffix| host.ends_with(suffix))165
fn trusted_teams_url(url: &str) -> Result<Url> {159
|| host == "teams.microsoft.com"166
trusted_https_url(url, &TEAMS_HOSTS).ok_or_else(|| {160
{167
let host = Url::parse(url)161
Ok(())168
.ok()162
} else {169
.and_then(|parsed| parsed.host_str().map(str::to_owned))163
Err(Error::Signaling(format!("refusing link to host {host}")))170
.unwrap_or_default();164
}171
Error::Signaling(format!("refusing link to host {host}"))172
})165
}173
}166
174
167
fn is_backend_host(host: &str) -> bool {175
fn is_backend_host(host: &str) -> bool {@@ -176,15 +184,12 @@ fn is_backend_host(host: &str) -> bool {176
184
177
/// Push links may name a backend host directly; the browser always reaches those through flightproxy.185
/// Push links may name a backend host directly; the browser always reaches those through flightproxy.178
pub fn routed_url(url: &str) -> Result<String> {186
pub fn routed_url(url: &str) -> Result<String> {179
let host = host_of(url)?;187
let parsed = plain_https(url)?;188
let host = parsed.host_str().unwrap_or_default();180
if !is_backend_host(host) {189
if !is_backend_host(host) {181
ensure_teams_url(url)?;190
return Ok(trusted_teams_url(url)?.into());182
return Ok(url.to_owned());183
}191
}184
let rest = &url["https://".len()..];192
let path = &parsed[Position::BeforePath..];185
let path = rest186
.find(['/', '?'])187
.map_or("", |position| &rest[position..]);188
Ok(format!("{FLIGHTPROXY_EP}/{host}{path}"))193
Ok(format!("{FLIGHTPROXY_EP}/{host}{path}"))189
}194
}190
195
@@ -797,8 +802,9 @@ impl Signaling {797
}802
}798
803
799
async fn bot_command(&self, command_url: &str, body: Value, label: &str) -> Result<u16> {804
async fn bot_command(&self, command_url: &str, body: Value, label: &str) -> Result<u16> {805
let command_url = trusted_teams_url(command_url)?;800
let arguments = json!({806
let arguments = json!({801
"url": command_url,807
"url": command_url.as_str(),802
"body": body,808
"body": body,803
"recorderResource": captions::RECORDER_RESOURCE,809
"recorderResource": captions::RECORDER_RESOURCE,804
"recorderScope": captions::RECORDER_SCOPE,810
"recorderScope": captions::RECORDER_SCOPE,@@ -1651,6 +1657,14 @@ mod tests {1651
assert!(ensure_teams_url("https://conv-euno-06-prod-aks.conv.skype.com/conv/1").is_err());1657
assert!(ensure_teams_url("https://conv-euno-06-prod-aks.conv.skype.com/conv/1").is_err());1652
assert!(ensure_teams_url("https://evil.example/?x=.teams.microsoft.com").is_err());1658
assert!(ensure_teams_url("https://evil.example/?x=.teams.microsoft.com").is_err());1653
assert!(ensure_teams_url("http://api.flightproxy.teams.microsoft.com/x").is_err());1659
assert!(ensure_teams_url("http://api.flightproxy.teams.microsoft.com/x").is_err());1660
for bypass in [1661
"https://evil.example\\.teams.microsoft.com/x",1662
"https://evil.example#.teams.microsoft.com/x",1663
"https://a.teams.microsoft.com:x@evil.example/",1664
] {1665
assert!(ensure_teams_url(bypass).is_err(), "{bypass}");1666
assert!(routed_url(bypass).is_err(), "{bypass}");1667
}1654
}1668
}1655
1669
1656
#[test]1670
#[test]@@ -1665,7 +1679,12 @@ mod tests {1665
"https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y"1679
"https://api.flightproxy.teams.microsoft.com/api/v2/ep/x/y"1666
);1680
);1667
assert!(routed_url("https://evil.skype.com.example/x").is_err());1681
assert!(routed_url("https://evil.skype.com.example/x").is_err());1668
assert!(routed_url("https://Evil.skype.com/x").is_err());1682
assert_eq!(1683
routed_url("https://CC.skype.com/x").unwrap(),1684
format!("{FLIGHTPROXY_EP}/cc.skype.com/x")1685
);1686
assert!(routed_url("https://cc.skype.com:x@evil.example/x").is_err());1687
assert!(routed_url("https://evil.example\\.cc.skype.com/x").is_err());1669
assert!(routed_url("https://user@cc.skype.com/x").is_err());1688
assert!(routed_url("https://user@cc.skype.com/x").is_err());1670
assert!(routed_url("http://cc.skype.com/x").is_err());1689
assert!(routed_url("http://cc.skype.com/x").is_err());1671
assert!(routed_url("https://.skype.com/x").is_err());1690
assert!(routed_url("https://.skype.com/x").is_err());@@ -306,6 +306,13 @@ impl LocalVideo {
306
306
.map_err(|error| Error::Webrtc(error.to_string()))
307
307
}
308
308
309
fn outgoing_mut(&mut self, source: SendSource) -> &mut Outgoing {
310
match source {
311
SendSource::Camera => &mut self.camera,
312
SendSource::Screen => &mut self.screen,
313
}
314
}
315
309
316
fn sender_of(&self, source: SendSource) -> Option<RtpSender> {
310
317
let lines = self.lines.as_ref()?;
311
318
match source {
@@ -324,6 +331,13 @@ impl LocalVideo {
324
331
SendSource::Screen => self.sharing(),
325
332
};
326
333
let Some(sender) = self.sender_of(source).filter(|_| sending) else {
334
// The controller often sends the limit before the source exists.
335
// Keep it. A repeat of the same limit is dropped by the filter,
336
// and refresh applies this copy once sending and a frame size exist.
337
self.outgoing_mut(source).requested = Some(RequestedLimits {
338
limits: limits.to_vec(),
339
applied_for: None,
340
});
327
341
return Ok(None);
328
342
};
329
343
let outgoing = match source {
@@ -404,6 +418,24 @@ impl LocalVideo {
404
418
refreshed
405
419
}
406
420
421
/// Applies a limit that was waiting for this source and writes it on the call report.
422
/// The drive loop only records a refresh it performs itself.
423
fn record_refreshed_send_limits(&mut self) {
424
let Some(timeline) = self.timeline.clone() else {
425
self.refresh_send_limits();
426
return;
427
};
428
for (source, refreshed) in self.refresh_send_limits() {
429
match refreshed {
430
Ok(Some(plans)) => {
431
timeline.record("send limits", format!("{source:?} {plans:?}"));
432
}
433
Ok(None) => {}
434
Err(error) => timeline.record("send limits failed", error.to_string()),
435
}
436
}
437
}
438
407
439
fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {
408
440
let mut parameters = sender.parameters();
409
441
for encoding in &mut parameters.encodings {
@@ -474,6 +506,19 @@ impl LocalVideo {
474
506
.filter(|model| !model.is_empty())
475
507
}
476
508
509
pub fn effects_label(&self) -> String {
510
let effects = self.blur.effects();
511
let flag = |on: bool| if on { "on" } else { "off" };
512
format!(
513
"blur={} standout={} framing={} brightness={} soft_focus={}",
514
flag(self.blur.enabled()),
515
flag(self.blur.standout()),
516
flag(effects.auto_framing),
517
flag(effects.adjust_brightness),
518
flag(effects.soft_focus)
519
)
520
}
521
477
522
pub fn has_lines(&self) -> bool {
478
523
self.lines.is_some()
479
524
}
@@ -724,6 +769,7 @@ impl LocalVideo {
724
769
}
725
770
Self::begin_sending_on(&lines.camera, &self.camera.track)?;
726
771
self.camera_preview = false;
772
self.record_refreshed_send_limits();
727
773
Ok(())
728
774
}
729
775
@@ -898,6 +944,7 @@ impl LocalVideo {
898
944
}
899
945
Self::begin_sending_on(&share, &self.screen.track)?;
900
946
let _ = self.tune_share(&share.sender());
947
self.record_refreshed_send_limits();
901
948
Ok(())
902
949
}
903
950
@@ -948,6 +995,77 @@ mod tests {
948
995
assert!(!video.camera_previewing() && !video.camera_on());
949
996
}
950
997
998
#[tokio::test]
999
async fn a_camera_limit_that_arrived_while_off_is_applied_when_the_camera_starts() {
1000
let factory = crate::devices::shared_factory();
1001
let peer = factory
1002
.create_peer_connection(RtcConfiguration::default())
1003
.expect("peer");
1004
let camera = peer
1005
.add_transceiver_for_media(
1006
MediaType::Video,
1007
RtpTransceiverInit {
1008
direction: RtpTransceiverDirection::SendRecv,
1009
stream_ids: vec!["camera".into()],
1010
send_encodings: Vec::new(),
1011
},
1012
)
1013
.expect("transceiver");
1014
let (updates, _) = tokio::sync::mpsc::unbounded_channel();
1015
let mut video = LocalVideo::new(
1016
&factory,
1017
VideoMode::Pattern,
1018
VideoHub::new(updates.clone()),
1019
updates,
1020
);
1021
video
1022
.set_lines(VideoLines {
1023
camera,
1024
share: None,
1025
})
1026
.expect("lines");
1027
let limit = |bitrate: u64| SendLimit {
1028
max_fs: Some(920),
1029
max_mbps: Some(13_800),
1030
max_fps: Some(15.0),
1031
max_bitrate: Some(bitrate),
1032
keyframe: false,
1033
rid: None,
1034
ssrc: None,
1035
};
1036
assert!(
1037
video
1038
.apply_send_limit(SendSource::Camera, &[limit(600_000)])
1039
.unwrap()
1040
.is_none()
1041
);
1042
assert!(
1043
video
1044
.apply_send_limit(SendSource::Camera, &[limit(100_000)])
1045
.unwrap()
1046
.is_none()
1047
);
1048
video
1049
.start_camera(&DeviceChoice::SystemDefault)
1050
.expect("camera");
1051
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
1052
let refreshed = video.refresh_send_limits();
1053
let bitrate = refreshed.iter().find_map(|(source, applied)| {
1054
(*source == SendSource::Camera)
1055
.then_some(applied)
1056
.and_then(|applied| {
1057
applied.as_ref().ok().and_then(|plans| {
1058
plans.as_ref().and_then(|plans| {
1059
plans.first().and_then(|plan| {
1060
plan.limits.as_ref().and_then(|limits| limits.max_bitrate)
1061
})
1062
})
1063
})
1064
})
1065
});
1066
assert_eq!(bitrate, Some(100_000));
1067
}
1068
951
1069
#[tokio::test]
952
1070
async fn clearing_a_sender_track_does_not_crash() {
953
1071
let factory = crate::devices::shared_factory();
@@ -306,6 +306,13 @@ impl LocalVideo {306
.map_err(|error| Error::Webrtc(error.to_string()))306
.map_err(|error| Error::Webrtc(error.to_string()))307
}307
}308
308
309
fn outgoing_mut(&mut self, source: SendSource) -> &mut Outgoing {310
match source {311
SendSource::Camera => &mut self.camera,312
SendSource::Screen => &mut self.screen,313
}314
}315
309
fn sender_of(&self, source: SendSource) -> Option<RtpSender> {316
fn sender_of(&self, source: SendSource) -> Option<RtpSender> {310
let lines = self.lines.as_ref()?;317
let lines = self.lines.as_ref()?;311
match source {318
match source {@@ -324,6 +331,13 @@ impl LocalVideo {324
SendSource::Screen => self.sharing(),331
SendSource::Screen => self.sharing(),325
};332
};326
let Some(sender) = self.sender_of(source).filter(|_| sending) else {333
let Some(sender) = self.sender_of(source).filter(|_| sending) else {334
// The controller often sends the limit before the source exists.335
// Keep it. A repeat of the same limit is dropped by the filter,336
// and refresh applies this copy once sending and a frame size exist.337
self.outgoing_mut(source).requested = Some(RequestedLimits {338
limits: limits.to_vec(),339
applied_for: None,340
});327
return Ok(None);341
return Ok(None);328
};342
};329
let outgoing = match source {343
let outgoing = match source {@@ -404,6 +418,24 @@ impl LocalVideo {404
refreshed418
refreshed405
}419
}406
420
421
/// Applies a limit that was waiting for this source and writes it on the call report.422
/// The drive loop only records a refresh it performs itself.423
fn record_refreshed_send_limits(&mut self) {424
let Some(timeline) = self.timeline.clone() else {425
self.refresh_send_limits();426
return;427
};428
for (source, refreshed) in self.refresh_send_limits() {429
match refreshed {430
Ok(Some(plans)) => {431
timeline.record("send limits", format!("{source:?} {plans:?}"));432
}433
Ok(None) => {}434
Err(error) => timeline.record("send limits failed", error.to_string()),435
}436
}437
}438
407
fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {439
fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {408
let mut parameters = sender.parameters();440
let mut parameters = sender.parameters();409
for encoding in &mut parameters.encodings {441
for encoding in &mut parameters.encodings {@@ -474,6 +506,19 @@ impl LocalVideo {474
.filter(|model| !model.is_empty())506
.filter(|model| !model.is_empty())475
}507
}476
508
509
pub fn effects_label(&self) -> String {510
let effects = self.blur.effects();511
let flag = |on: bool| if on { "on" } else { "off" };512
format!(513
"blur={} standout={} framing={} brightness={} soft_focus={}",514
flag(self.blur.enabled()),515
flag(self.blur.standout()),516
flag(effects.auto_framing),517
flag(effects.adjust_brightness),518
flag(effects.soft_focus)519
)520
}521
477
pub fn has_lines(&self) -> bool {522
pub fn has_lines(&self) -> bool {478
self.lines.is_some()523
self.lines.is_some()479
}524
}@@ -724,6 +769,7 @@ impl LocalVideo {724
}769
}725
Self::begin_sending_on(&lines.camera, &self.camera.track)?;770
Self::begin_sending_on(&lines.camera, &self.camera.track)?;726
self.camera_preview = false;771
self.camera_preview = false;772
self.record_refreshed_send_limits();727
Ok(())773
Ok(())728
}774
}729
775
@@ -898,6 +944,7 @@ impl LocalVideo {898
}944
}899
Self::begin_sending_on(&share, &self.screen.track)?;945
Self::begin_sending_on(&share, &self.screen.track)?;900
let _ = self.tune_share(&share.sender());946
let _ = self.tune_share(&share.sender());947
self.record_refreshed_send_limits();901
Ok(())948
Ok(())902
}949
}903
950
@@ -948,6 +995,77 @@ mod tests {948
assert!(!video.camera_previewing() && !video.camera_on());995
assert!(!video.camera_previewing() && !video.camera_on());949
}996
}950
997
998
#[tokio::test]999
async fn a_camera_limit_that_arrived_while_off_is_applied_when_the_camera_starts() {1000
let factory = crate::devices::shared_factory();1001
let peer = factory1002
.create_peer_connection(RtcConfiguration::default())1003
.expect("peer");1004
let camera = peer1005
.add_transceiver_for_media(1006
MediaType::Video,1007
RtpTransceiverInit {1008
direction: RtpTransceiverDirection::SendRecv,1009
stream_ids: vec!["camera".into()],1010
send_encodings: Vec::new(),1011
},1012
)1013
.expect("transceiver");1014
let (updates, _) = tokio::sync::mpsc::unbounded_channel();1015
let mut video = LocalVideo::new(1016
&factory,1017
VideoMode::Pattern,1018
VideoHub::new(updates.clone()),1019
updates,1020
);1021
video1022
.set_lines(VideoLines {1023
camera,1024
share: None,1025
})1026
.expect("lines");1027
let limit = |bitrate: u64| SendLimit {1028
max_fs: Some(920),1029
max_mbps: Some(13_800),1030
max_fps: Some(15.0),1031
max_bitrate: Some(bitrate),1032
keyframe: false,1033
rid: None,1034
ssrc: None,1035
};1036
assert!(1037
video1038
.apply_send_limit(SendSource::Camera, &[limit(600_000)])1039
.unwrap()1040
.is_none()1041
);1042
assert!(1043
video1044
.apply_send_limit(SendSource::Camera, &[limit(100_000)])1045
.unwrap()1046
.is_none()1047
);1048
video1049
.start_camera(&DeviceChoice::SystemDefault)1050
.expect("camera");1051
tokio::time::sleep(std::time::Duration::from_millis(200)).await;1052
let refreshed = video.refresh_send_limits();1053
let bitrate = refreshed.iter().find_map(|(source, applied)| {1054
(*source == SendSource::Camera)1055
.then_some(applied)1056
.and_then(|applied| {1057
applied.as_ref().ok().and_then(|plans| {1058
plans.as_ref().and_then(|plans| {1059
plans.first().and_then(|plan| {1060
plan.limits.as_ref().and_then(|limits| limits.max_bitrate)1061
})1062
})1063
})1064
})1065
});1066
assert_eq!(bitrate, Some(100_000));1067
}1068
951
#[tokio::test]1069
#[tokio::test]952
async fn clearing_a_sender_track_does_not_crash() {1070
async fn clearing_a_sender_track_does_not_crash() {953
let factory = crate::devices::shared_factory();1071
let factory = crate::devices::shared_factory();@@ -4,7 +4,7 @@ use serde_json::{Value, json};
4
4
use session::{App, Scope, Session};
5
5
6
6
use crate::error::{Error, Result};
7
use crate::links::{LinkImage, decoded_image};
7
use crate::links::{LinkImage, decoded_image, trusted_ams_image_url};
8
8
use crate::messages::ensure_success;
9
9
use crate::pins::transport::{CSA_RESOURCE, CSA_SCOPE, skype_fetch_answer};
10
10
@@ -87,13 +87,18 @@ impl Ams {
87
87
88
88
/// Reads an AMS image view such as `.../v1/objects/{id}/views/imgo` with the Skype token.
89
89
pub async fn download_image(&self, url: &str) -> Result<LinkImage> {
90
let Some(url) = trusted_ams_image_url(url) else {
91
return Err(Error::UnexpectedAnswer(format!(
92
"not an AMS image url: {url}"
93
)));
94
};
90
95
let answer = self
91
96
.session
92
97
.run_with_token(
93
98
App::Teams,
94
99
&Scope::new(CSA_RESOURCE, CSA_SCOPE),
95
100
DOWNLOAD_BODY,
96
&json!({ "url": url }),
101
&json!({ "url": url.as_str() }),
97
102
false,
98
103
)
99
104
.await?;
@@ -4,7 +4,7 @@ use serde_json::{Value, json};4
use session::{App, Scope, Session};4
use session::{App, Scope, Session};5
5
6
use crate::error::{Error, Result};6
use crate::error::{Error, Result};7
use crate::links::{LinkImage, decoded_image};7
use crate::links::{LinkImage, decoded_image, trusted_ams_image_url};8
use crate::messages::ensure_success;8
use crate::messages::ensure_success;9
use crate::pins::transport::{CSA_RESOURCE, CSA_SCOPE, skype_fetch_answer};9
use crate::pins::transport::{CSA_RESOURCE, CSA_SCOPE, skype_fetch_answer};10
10
@@ -87,13 +87,18 @@ impl Ams {87
87
88
/// Reads an AMS image view such as `.../v1/objects/{id}/views/imgo` with the Skype token.88
/// Reads an AMS image view such as `.../v1/objects/{id}/views/imgo` with the Skype token.89
pub async fn download_image(&self, url: &str) -> Result<LinkImage> {89
pub async fn download_image(&self, url: &str) -> Result<LinkImage> {90
let Some(url) = trusted_ams_image_url(url) else {91
return Err(Error::UnexpectedAnswer(format!(92
"not an AMS image url: {url}"93
)));94
};90
let answer = self95
let answer = self91
.session96
.session92
.run_with_token(97
.run_with_token(93
App::Teams,98
App::Teams,94
&Scope::new(CSA_RESOURCE, CSA_SCOPE),99
&Scope::new(CSA_RESOURCE, CSA_SCOPE),95
DOWNLOAD_BODY,100
DOWNLOAD_BODY,96
&json!({ "url": url }),101
&json!({ "url": url.as_str() }),97
false,102
false,98
)103
)99
.await?;104
.await?;@@ -9,7 +9,8 @@ mod write;
9
9
pub use loopback::{allocate_redirect_uri, wait_for_code};
10
10
pub use merge::{merge_calendar_events, normalize_join_url};
11
11
pub use oauth::{
12
AuthPending, GoogleOAuth, TokenBundle, client_id_from_env, exchange_code, refresh_access_token,
12
AuthPending, GoogleOAuth, TokenBundle, client_from_stored, client_id_from_env, exchange_code,
13
refresh_access_token,
13
14
};
14
15
pub use parse::{parse_calendar_list, parse_google_events};
15
16
pub use write::{
@@ -9,7 +9,8 @@ mod write;9
pub use loopback::{allocate_redirect_uri, wait_for_code};9
pub use loopback::{allocate_redirect_uri, wait_for_code};10
pub use merge::{merge_calendar_events, normalize_join_url};10
pub use merge::{merge_calendar_events, normalize_join_url};11
pub use oauth::{11
pub use oauth::{12
AuthPending, GoogleOAuth, TokenBundle, client_id_from_env, exchange_code, refresh_access_token,12
AuthPending, GoogleOAuth, TokenBundle, client_from_stored, client_id_from_env, exchange_code,13
refresh_access_token,13
};14
};14
pub use parse::{parse_calendar_list, parse_google_events};15
pub use parse::{parse_calendar_list, parse_google_events};15
pub use write::{16
pub use write::{@@ -39,9 +39,20 @@ pub struct TokenBundle {
39
39
}
40
40
41
41
/// Runtime env wins; otherwise the value baked in at compile time (`option_env!`).
42
/// Empty strings count as missing. Used by Connect and token refresh.
42
/// Empty strings count as missing. Used when Settings has no saved pair.
43
43
pub fn client_id_from_env() -> Option<GoogleOAuth> {
44
client_from_stored(None, None)
45
}
46
47
/// A saved id and secret win only together. Otherwise the same order as
48
/// [`client_id_from_env`]: runtime env, then the compiled client.
49
pub fn client_from_stored(
50
stored_id: Option<&str>,
51
stored_secret: Option<&str>,
52
) -> Option<GoogleOAuth> {
44
53
resolve_oauth(
54
stored_id,
55
stored_secret,
45
56
std::env::var(GOOGLE_CLIENT_ID_ENV).ok().as_deref(),
46
57
std::env::var(GOOGLE_CLIENT_SECRET_ENV).ok().as_deref(),
47
58
option_env!("TEAMS_GOOGLE_CLIENT_ID"),
@@ -50,11 +61,21 @@ pub fn client_id_from_env() -> Option<GoogleOAuth> {
50
61
}
51
62
52
63
fn resolve_oauth(
64
stored_id: Option<&str>,
65
stored_secret: Option<&str>,
53
66
runtime_id: Option<&str>,
54
67
runtime_secret: Option<&str>,
55
68
compile_id: Option<&str>,
56
69
compile_secret: Option<&str>,
57
70
) -> Option<GoogleOAuth> {
71
if let (Some(client_id), Some(client_secret)) =
72
(first_non_empty(stored_id), first_non_empty(stored_secret))
73
{
74
return Some(GoogleOAuth {
75
client_id,
76
client_secret,
77
});
78
}
58
79
let client_id = first_non_empty(runtime_id).or_else(|| first_non_empty(compile_id))?;
59
80
let client_secret = first_non_empty(runtime_secret)
60
81
.or_else(|| first_non_empty(compile_secret))
@@ -208,6 +229,8 @@ mod tests {
208
229
#[test]
209
230
fn resolve_prefers_runtime_over_compile() {
210
231
let oauth = resolve_oauth(
232
None,
233
None,
211
234
Some("runtime-id"),
212
235
Some("runtime-secret"),
213
236
Some("compile-id"),
@@ -220,22 +243,74 @@ mod tests {
220
243
221
244
#[test]
222
245
fn resolve_falls_back_to_compile_when_runtime_empty() {
223
let oauth =
224
resolve_oauth(Some(" "), None, Some("compile-id"), Some("compile-secret")).unwrap();
246
let oauth = resolve_oauth(
247
None,
248
None,
249
Some(" "),
250
None,
251
Some("compile-id"),
252
Some("compile-secret"),
253
)
254
.unwrap();
225
255
assert_eq!(oauth.client_id, "compile-id");
226
256
assert_eq!(oauth.client_secret, "compile-secret");
227
257
}
228
258
229
259
#[test]
230
260
fn resolve_returns_none_when_both_missing() {
231
assert!(resolve_oauth(None, None, None, None).is_none());
232
assert!(resolve_oauth(Some(""), None, Some(" "), None).is_none());
261
assert!(resolve_oauth(None, None, None, None, None, None).is_none());
262
assert!(resolve_oauth(None, None, Some(""), None, Some(" "), None).is_none());
233
263
}
234
264
235
265
#[test]
236
266
fn resolve_allows_missing_secret() {
237
let oauth = resolve_oauth(Some("cid"), None, None, None).unwrap();
267
let oauth = resolve_oauth(None, None, Some("cid"), None, None, None).unwrap();
238
268
assert_eq!(oauth.client_id, "cid");
239
269
assert!(oauth.client_secret.is_empty());
240
270
}
271
272
#[test]
273
fn stored_pair_wins_over_runtime_and_compile() {
274
let oauth = resolve_oauth(
275
Some(" stored-id "),
276
Some(" stored-secret "),
277
Some("runtime-id"),
278
Some("runtime-secret"),
279
Some("compile-id"),
280
Some("compile-secret"),
281
)
282
.unwrap();
283
assert_eq!(oauth.client_id, "stored-id");
284
assert_eq!(oauth.client_secret, "stored-secret");
285
}
286
287
#[test]
288
fn stored_id_without_secret_does_not_override() {
289
let oauth = resolve_oauth(
290
Some("stored-id"),
291
Some(" "),
292
Some("runtime-id"),
293
Some("runtime-secret"),
294
None,
295
None,
296
)
297
.unwrap();
298
assert_eq!(oauth.client_id, "runtime-id");
299
assert_eq!(oauth.client_secret, "runtime-secret");
300
}
301
302
#[test]
303
fn stored_secret_without_id_does_not_override() {
304
let oauth = resolve_oauth(
305
Some(""),
306
Some("stored-secret"),
307
None,
308
None,
309
Some("compile-id"),
310
Some("compile-secret"),
311
)
312
.unwrap();
313
assert_eq!(oauth.client_id, "compile-id");
314
assert_eq!(oauth.client_secret, "compile-secret");
315
}
241
316
}
@@ -39,9 +39,20 @@ pub struct TokenBundle {39
}39
}40
40
41
/// Runtime env wins; otherwise the value baked in at compile time (`option_env!`).41
/// Runtime env wins; otherwise the value baked in at compile time (`option_env!`).42
/// Empty strings count as missing. Used by Connect and token refresh.42
/// Empty strings count as missing. Used when Settings has no saved pair.43
pub fn client_id_from_env() -> Option<GoogleOAuth> {43
pub fn client_id_from_env() -> Option<GoogleOAuth> {44
client_from_stored(None, None)45
}46
47
/// A saved id and secret win only together. Otherwise the same order as48
/// [`client_id_from_env`]: runtime env, then the compiled client.49
pub fn client_from_stored(50
stored_id: Option<&str>,51
stored_secret: Option<&str>,52
) -> Option<GoogleOAuth> {44
resolve_oauth(53
resolve_oauth(54
stored_id,55
stored_secret,45
std::env::var(GOOGLE_CLIENT_ID_ENV).ok().as_deref(),56
std::env::var(GOOGLE_CLIENT_ID_ENV).ok().as_deref(),46
std::env::var(GOOGLE_CLIENT_SECRET_ENV).ok().as_deref(),57
std::env::var(GOOGLE_CLIENT_SECRET_ENV).ok().as_deref(),47
option_env!("TEAMS_GOOGLE_CLIENT_ID"),58
option_env!("TEAMS_GOOGLE_CLIENT_ID"),@@ -50,11 +61,21 @@ pub fn client_id_from_env() -> Option<GoogleOAuth> {50
}61
}51
62
52
fn resolve_oauth(63
fn resolve_oauth(64
stored_id: Option<&str>,65
stored_secret: Option<&str>,53
runtime_id: Option<&str>,66
runtime_id: Option<&str>,54
runtime_secret: Option<&str>,67
runtime_secret: Option<&str>,55
compile_id: Option<&str>,68
compile_id: Option<&str>,56
compile_secret: Option<&str>,69
compile_secret: Option<&str>,57
) -> Option<GoogleOAuth> {70
) -> Option<GoogleOAuth> {71
if let (Some(client_id), Some(client_secret)) =72
(first_non_empty(stored_id), first_non_empty(stored_secret))73
{74
return Some(GoogleOAuth {75
client_id,76
client_secret,77
});78
}58
let client_id = first_non_empty(runtime_id).or_else(|| first_non_empty(compile_id))?;79
let client_id = first_non_empty(runtime_id).or_else(|| first_non_empty(compile_id))?;59
let client_secret = first_non_empty(runtime_secret)80
let client_secret = first_non_empty(runtime_secret)60
.or_else(|| first_non_empty(compile_secret))81
.or_else(|| first_non_empty(compile_secret))@@ -208,6 +229,8 @@ mod tests {208
#[test]229
#[test]209
fn resolve_prefers_runtime_over_compile() {230
fn resolve_prefers_runtime_over_compile() {210
let oauth = resolve_oauth(231
let oauth = resolve_oauth(232
None,233
None,211
Some("runtime-id"),234
Some("runtime-id"),212
Some("runtime-secret"),235
Some("runtime-secret"),213
Some("compile-id"),236
Some("compile-id"),@@ -220,22 +243,74 @@ mod tests {220
243
221
#[test]244
#[test]222
fn resolve_falls_back_to_compile_when_runtime_empty() {245
fn resolve_falls_back_to_compile_when_runtime_empty() {223
let oauth =246
let oauth = resolve_oauth(224
resolve_oauth(Some(" "), None, Some("compile-id"), Some("compile-secret")).unwrap();247
None,248
None,249
Some(" "),250
None,251
Some("compile-id"),252
Some("compile-secret"),253
)254
.unwrap();225
assert_eq!(oauth.client_id, "compile-id");255
assert_eq!(oauth.client_id, "compile-id");226
assert_eq!(oauth.client_secret, "compile-secret");256
assert_eq!(oauth.client_secret, "compile-secret");227
}257
}228
258
229
#[test]259
#[test]230
fn resolve_returns_none_when_both_missing() {260
fn resolve_returns_none_when_both_missing() {231
assert!(resolve_oauth(None, None, None, None).is_none());261
assert!(resolve_oauth(None, None, None, None, None, None).is_none());232
assert!(resolve_oauth(Some(""), None, Some(" "), None).is_none());262
assert!(resolve_oauth(None, None, Some(""), None, Some(" "), None).is_none());233
}263
}234
264
235
#[test]265
#[test]236
fn resolve_allows_missing_secret() {266
fn resolve_allows_missing_secret() {237
let oauth = resolve_oauth(Some("cid"), None, None, None).unwrap();267
let oauth = resolve_oauth(None, None, Some("cid"), None, None, None).unwrap();238
assert_eq!(oauth.client_id, "cid");268
assert_eq!(oauth.client_id, "cid");239
assert!(oauth.client_secret.is_empty());269
assert!(oauth.client_secret.is_empty());240
}270
}271
272
#[test]273
fn stored_pair_wins_over_runtime_and_compile() {274
let oauth = resolve_oauth(275
Some(" stored-id "),276
Some(" stored-secret "),277
Some("runtime-id"),278
Some("runtime-secret"),279
Some("compile-id"),280
Some("compile-secret"),281
)282
.unwrap();283
assert_eq!(oauth.client_id, "stored-id");284
assert_eq!(oauth.client_secret, "stored-secret");285
}286
287
#[test]288
fn stored_id_without_secret_does_not_override() {289
let oauth = resolve_oauth(290
Some("stored-id"),291
Some(" "),292
Some("runtime-id"),293
Some("runtime-secret"),294
None,295
None,296
)297
.unwrap();298
assert_eq!(oauth.client_id, "runtime-id");299
assert_eq!(oauth.client_secret, "runtime-secret");300
}301
302
#[test]303
fn stored_secret_without_id_does_not_override() {304
let oauth = resolve_oauth(305
Some(""),306
Some("stored-secret"),307
None,308
None,309
Some("compile-id"),310
Some("compile-secret"),311
)312
.unwrap();313
assert_eq!(oauth.client_id, "compile-id");314
assert_eq!(oauth.client_secret, "compile-secret");315
}241
}316
}@@ -92,9 +92,9 @@ pub use custom_emojis::{CustomEmojis, OrgEmoji, OrgEmojiCatalog, custom_emoji_ht
92
92
pub use gifs::{Gif, Gifs};
93
93
pub use google_calendar::{
94
94
AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,
95
client_id_from_env, exchange_code, google_event_body, google_rsvp_query, google_rsvp_status,
96
parse_calendar_list, parse_google_events, refresh_access_token, rrule_for_repeat,
97
wait_for_code,
95
client_from_stored, client_id_from_env, exchange_code, google_event_body, google_rsvp_query,
96
google_rsvp_status, parse_calendar_list, parse_google_events, refresh_access_token,
97
rrule_for_repeat, wait_for_code,
98
98
};
99
99
pub use ical::{
100
100
CalDavEventDraft, build_vevent, exclude_occurrence_from_ics, expand_events, parse_calendar,
@@ -92,9 +92,9 @@ pub use custom_emojis::{CustomEmojis, OrgEmoji, OrgEmojiCatalog, custom_emoji_ht92
pub use gifs::{Gif, Gifs};92
pub use gifs::{Gif, Gifs};93
pub use google_calendar::{93
pub use google_calendar::{94
AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,94
AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,95
client_id_from_env, exchange_code, google_event_body, google_rsvp_query, google_rsvp_status,95
client_from_stored, client_id_from_env, exchange_code, google_event_body, google_rsvp_query,96
parse_calendar_list, parse_google_events, refresh_access_token, rrule_for_repeat,96
google_rsvp_status, parse_calendar_list, parse_google_events, refresh_access_token,97
wait_for_code,97
rrule_for_repeat, wait_for_code,98
};98
};99
pub use ical::{99
pub use ical::{100
CalDavEventDraft, build_vevent, exclude_occurrence_from_ics, expand_events, parse_calendar,100
CalDavEventDraft, build_vevent, exclude_occurrence_from_ics, expand_events, parse_calendar,@@ -1,7 +1,9 @@
1
1
use base64::Engine as _;
2
2
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
3
3
use serde_json::{Value, json};
4
use session::trusted_url::{HostRule, trusted_https_url};
4
5
use session::{Method, Request};
6
use url::Url;
5
7
6
8
use crate::error::{Error, Result};
7
9
use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};
@@ -11,7 +13,10 @@ pub const LINK_PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";
11
13
const LIST_VIEW: &str = "msnp24Equivalent";
12
14
const HOSTED_CONTENTS_SEGMENT: &str = "/hostedContents/";
13
15
const HOSTED_URL_KEY: &str = ",url=";
14
const AMS_HOST_SUFFIX: &str = ".asm.skype.com";
16
const LINK_PROXY_HOSTS: [HostRule; 1] = [HostRule::Domain("asyncgw.teams.microsoft.com")];
17
const AMS_HOSTS: [HostRule; 1] = [HostRule::Domain("asm.skype.com")];
18
const AMS_OBJECT_HOSTS: [HostRule; 2] = [AMS_HOSTS[0], LINK_PROXY_HOSTS[0]];
19
const OBJECTS_PATH: &str = "/v1/objects/";
15
20
const VIEWS_SEGMENT: &str = "/views/";
16
21
const FULL_SIZE_VIEW_PREFIX: &str = "imgpsh_fullsize";
17
22
/// The view Teams opens in its image viewer; `_anim` keeps animated GIFs moving.
@@ -41,15 +46,16 @@ pub struct LinkImage {
41
46
}
42
47
43
48
pub fn is_link_image_url(url: &str) -> bool {
44
url.strip_prefix("https://")
45
.and_then(|rest| rest.split(['/', '?', '#']).next())
46
.is_some_and(|host| host.ends_with(LINK_PROXY_HOST_SUFFIX))
49
trusted_https_url(url, &LINK_PROXY_HOSTS).is_some()
47
50
}
48
51
49
52
/// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`.
50
53
pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {
51
54
let (_, url) = hosted_content_fields(graph_url)?;
52
(is_link_image_url(&url) || is_ams_image_url(&url)).then_some(url)
55
(is_link_image_url(&url) || is_ams_image_url(&url))
56
.then(|| Url::parse(&url).ok())
57
.flatten()
58
.map(String::from)
53
59
}
54
60
55
61
/// The `id=` value from a Graph `hostedContents` link, used when `url=` is empty
@@ -99,11 +105,11 @@ pub(crate) fn object_id_from_ams_path(url: &str) -> Option<&str> {
99
105
100
106
/// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages.
101
107
pub fn is_ams_image_url(url: &str) -> bool {
102
url.strip_prefix("https://")
103
.and_then(|rest| rest.split_once('/'))
104
.is_some_and(|(host, path)| {
105
host.ends_with(AMS_HOST_SUFFIX) && path.starts_with("v1/objects/")
106
})
108
trusted_ams_image_url(url).is_some()
109
}
110
111
pub fn trusted_ams_image_url(url: &str) -> Option<Url> {
112
trusted_https_url(url, &AMS_HOSTS).filter(|parsed| parsed.path().starts_with(OBJECTS_PATH))
107
113
}
108
114
109
115
/// The full-resolution view of the AMS image at `url` (a plain AMS view or a Graph `hostedContents` link to one).
@@ -112,15 +118,9 @@ pub fn is_ams_image_url(url: &str) -> bool {
112
118
pub fn ams_full_size_url(url: &str) -> Option<String> {
113
119
let decoded = hosted_content_image_url(url);
114
120
let url = decoded.as_deref().unwrap_or(url);
115
let is_object = |host: &str, path: &str| {
116
path.starts_with("v1/objects/")
117
&& (host.ends_with(AMS_HOST_SUFFIX) || host.ends_with(LINK_PROXY_HOST_SUFFIX))
118
};
119
let (host, path) = url.strip_prefix("https://")?.split_once('/')?;
120
if !is_object(host, path) {
121
return None;
122
}
123
let (object, view) = url.rsplit_once(VIEWS_SEGMENT)?;
121
let parsed = trusted_https_url(url, &AMS_OBJECT_HOSTS)
122
.filter(|parsed| parsed.path().starts_with(OBJECTS_PATH))?;
123
let (object, view) = parsed.as_str().rsplit_once(VIEWS_SEGMENT)?;
124
124
let still_picture = view.starts_with("img") && !view.contains(['/', '?', '#']);
125
125
(still_picture && !view.starts_with(FULL_SIZE_VIEW_PREFIX))
126
126
.then(|| format!("{object}{VIEWS_SEGMENT}{FULL_SIZE_VIEW}"))
@@ -215,12 +215,15 @@ impl<T: MessageTransport> Messages<T> {
215
215
}
216
216
217
217
pub async fn link_image(&self, url: &str) -> Result<LinkImage> {
218
if !is_link_image_url(url) {
218
let Some(url) = trusted_https_url(url, &LINK_PROXY_HOSTS) else {
219
219
return Err(Error::UnexpectedAnswer(format!(
220
220
"not a link preview image url: {url}"
221
221
)));
222
}
223
let answer = self.transport.send(Request::binary_get(url)).await?;
222
};
223
let answer = self
224
.transport
225
.send(Request::binary_get(url.as_str()))
226
.await?;
224
227
ensure_success(&answer)?;
225
228
decoded_image(&answer.body)
226
229
}
@@ -412,5 +415,24 @@ mod tests {
412
415
assert!(!is_link_image_url(
413
416
"http://de-prod.asyncgw.teams.microsoft.com/x"
414
417
));
418
for bypass in [
419
"https://evil.example\\.asyncgw.teams.microsoft.com/x",
420
"https://de-prod.asyncgw.teams.microsoft.com:x@evil.example/",
421
] {
422
assert!(!is_link_image_url(bypass), "{bypass}");
423
}
424
}
425
426
#[test]
427
fn ams_checks_see_the_host_the_request_goes_to() {
428
for bypass in [
429
"https://evil.example#.asm.skype.com/v1/objects/a",
430
"https://evil.example?.asm.skype.com/v1/objects/a",
431
"https://evil.example\\.asm.skype.com/v1/objects/a",
432
"https://eu-api.asm.skype.com@evil.example/v1/objects/a",
433
] {
434
assert!(!is_ams_image_url(bypass), "{bypass}");
435
assert_eq!(ams_full_size_url(&format!("{bypass}/views/imgo")), None);
436
}
415
437
}
416
438
}
@@ -1,7 +1,9 @@1
use base64::Engine as _;1
use base64::Engine as _;2
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};2
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};3
use serde_json::{Value, json};3
use serde_json::{Value, json};4
use session::trusted_url::{HostRule, trusted_https_url};4
use session::{Method, Request};5
use session::{Method, Request};6
use url::Url;5
7
6
use crate::error::{Error, Result};8
use crate::error::{Error, Result};7
use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};9
use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};@@ -11,7 +13,10 @@ pub const LINK_PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";11
const LIST_VIEW: &str = "msnp24Equivalent";13
const LIST_VIEW: &str = "msnp24Equivalent";12
const HOSTED_CONTENTS_SEGMENT: &str = "/hostedContents/";14
const HOSTED_CONTENTS_SEGMENT: &str = "/hostedContents/";13
const HOSTED_URL_KEY: &str = ",url=";15
const HOSTED_URL_KEY: &str = ",url=";14
const AMS_HOST_SUFFIX: &str = ".asm.skype.com";16
const LINK_PROXY_HOSTS: [HostRule; 1] = [HostRule::Domain("asyncgw.teams.microsoft.com")];17
const AMS_HOSTS: [HostRule; 1] = [HostRule::Domain("asm.skype.com")];18
const AMS_OBJECT_HOSTS: [HostRule; 2] = [AMS_HOSTS[0], LINK_PROXY_HOSTS[0]];19
const OBJECTS_PATH: &str = "/v1/objects/";15
const VIEWS_SEGMENT: &str = "/views/";20
const VIEWS_SEGMENT: &str = "/views/";16
const FULL_SIZE_VIEW_PREFIX: &str = "imgpsh_fullsize";21
const FULL_SIZE_VIEW_PREFIX: &str = "imgpsh_fullsize";17
/// The view Teams opens in its image viewer; `_anim` keeps animated GIFs moving.22
/// The view Teams opens in its image viewer; `_anim` keeps animated GIFs moving.@@ -41,15 +46,16 @@ pub struct LinkImage {41
}46
}42
47
43
pub fn is_link_image_url(url: &str) -> bool {48
pub fn is_link_image_url(url: &str) -> bool {44
url.strip_prefix("https://")49
trusted_https_url(url, &LINK_PROXY_HOSTS).is_some()45
.and_then(|rest| rest.split(['/', '?', '#']).next())46
.is_some_and(|host| host.ends_with(LINK_PROXY_HOST_SUFFIX))47
}50
}48
51
49
/// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`.52
/// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`.50
pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {53
pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {51
let (_, url) = hosted_content_fields(graph_url)?;54
let (_, url) = hosted_content_fields(graph_url)?;52
(is_link_image_url(&url) || is_ams_image_url(&url)).then_some(url)55
(is_link_image_url(&url) || is_ams_image_url(&url))56
.then(|| Url::parse(&url).ok())57
.flatten()58
.map(String::from)53
}59
}54
60
55
/// The `id=` value from a Graph `hostedContents` link, used when `url=` is empty61
/// The `id=` value from a Graph `hostedContents` link, used when `url=` is empty@@ -99,11 +105,11 @@ pub(crate) fn object_id_from_ams_path(url: &str) -> Option<&str> {99
105
100
/// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages.106
/// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages.101
pub fn is_ams_image_url(url: &str) -> bool {107
pub fn is_ams_image_url(url: &str) -> bool {102
url.strip_prefix("https://")108
trusted_ams_image_url(url).is_some()103
.and_then(|rest| rest.split_once('/'))109
}104
.is_some_and(|(host, path)| {110
105
host.ends_with(AMS_HOST_SUFFIX) && path.starts_with("v1/objects/")111
pub fn trusted_ams_image_url(url: &str) -> Option<Url> {106
})112
trusted_https_url(url, &AMS_HOSTS).filter(|parsed| parsed.path().starts_with(OBJECTS_PATH))107
}113
}108
114
109
/// The full-resolution view of the AMS image at `url` (a plain AMS view or a Graph `hostedContents` link to one).115
/// The full-resolution view of the AMS image at `url` (a plain AMS view or a Graph `hostedContents` link to one).@@ -112,15 +118,9 @@ pub fn is_ams_image_url(url: &str) -> bool {112
pub fn ams_full_size_url(url: &str) -> Option<String> {118
pub fn ams_full_size_url(url: &str) -> Option<String> {113
let decoded = hosted_content_image_url(url);119
let decoded = hosted_content_image_url(url);114
let url = decoded.as_deref().unwrap_or(url);120
let url = decoded.as_deref().unwrap_or(url);115
let is_object = |host: &str, path: &str| {121
let parsed = trusted_https_url(url, &AMS_OBJECT_HOSTS)116
path.starts_with("v1/objects/")122
.filter(|parsed| parsed.path().starts_with(OBJECTS_PATH))?;117
&& (host.ends_with(AMS_HOST_SUFFIX) || host.ends_with(LINK_PROXY_HOST_SUFFIX))123
let (object, view) = parsed.as_str().rsplit_once(VIEWS_SEGMENT)?;118
};119
let (host, path) = url.strip_prefix("https://")?.split_once('/')?;120
if !is_object(host, path) {121
return None;122
}123
let (object, view) = url.rsplit_once(VIEWS_SEGMENT)?;124
let still_picture = view.starts_with("img") && !view.contains(['/', '?', '#']);124
let still_picture = view.starts_with("img") && !view.contains(['/', '?', '#']);125
(still_picture && !view.starts_with(FULL_SIZE_VIEW_PREFIX))125
(still_picture && !view.starts_with(FULL_SIZE_VIEW_PREFIX))126
.then(|| format!("{object}{VIEWS_SEGMENT}{FULL_SIZE_VIEW}"))126
.then(|| format!("{object}{VIEWS_SEGMENT}{FULL_SIZE_VIEW}"))@@ -215,12 +215,15 @@ impl<T: MessageTransport> Messages<T> {215
}215
}216
216
217
pub async fn link_image(&self, url: &str) -> Result<LinkImage> {217
pub async fn link_image(&self, url: &str) -> Result<LinkImage> {218
if !is_link_image_url(url) {218
let Some(url) = trusted_https_url(url, &LINK_PROXY_HOSTS) else {219
return Err(Error::UnexpectedAnswer(format!(219
return Err(Error::UnexpectedAnswer(format!(220
"not a link preview image url: {url}"220
"not a link preview image url: {url}"221
)));221
)));222
}222
};223
let answer = self.transport.send(Request::binary_get(url)).await?;223
let answer = self224
.transport225
.send(Request::binary_get(url.as_str()))226
.await?;224
ensure_success(&answer)?;227
ensure_success(&answer)?;225
decoded_image(&answer.body)228
decoded_image(&answer.body)226
}229
}@@ -412,5 +415,24 @@ mod tests {412
assert!(!is_link_image_url(415
assert!(!is_link_image_url(413
"http://de-prod.asyncgw.teams.microsoft.com/x"416
"http://de-prod.asyncgw.teams.microsoft.com/x"414
));417
));418
for bypass in [419
"https://evil.example\\.asyncgw.teams.microsoft.com/x",420
"https://de-prod.asyncgw.teams.microsoft.com:x@evil.example/",421
] {422
assert!(!is_link_image_url(bypass), "{bypass}");423
}424
}425
426
#[test]427
fn ams_checks_see_the_host_the_request_goes_to() {428
for bypass in [429
"https://evil.example#.asm.skype.com/v1/objects/a",430
"https://evil.example?.asm.skype.com/v1/objects/a",431
"https://evil.example\\.asm.skype.com/v1/objects/a",432
"https://eu-api.asm.skype.com@evil.example/v1/objects/a",433
] {434
assert!(!is_ams_image_url(bypass), "{bypass}");435
assert_eq!(ams_full_size_url(&format!("{bypass}/views/imgo")), None);436
}415
}437
}416
}438
}@@ -1,7 +1,8 @@
1
1
use serde_json::{Value, json};
2
use session::trusted_url::may_carry_credentials;
2
3
use session::{ApiResponse, App, Request, Scope, Session};
3
4
4
use crate::error::Result;
5
use crate::error::{Error, Result};
5
6
6
7
pub const CSA_RESOURCE: &str = "https://chatsvcagg.teams.microsoft.com";
7
8
pub const CSA_SCOPE: &str = "user_impersonation";
@@ -86,6 +87,12 @@ pub fn skype_fetch_answer(answer: Value) -> ApiResponse {
86
87
87
88
impl CsaTransport for SkypeTokenTransport {
88
89
async fn send(&self, request: Request) -> Result<ApiResponse> {
90
if !may_carry_credentials(&request.url) {
91
return Err(Error::UnexpectedAnswer(format!(
92
"refusing skype token request to {}",
93
request.url
94
)));
95
}
89
96
let answer = self
90
97
.session
91
98
.run_with_token(
@@ -1,7 +1,8 @@1
use serde_json::{Value, json};1
use serde_json::{Value, json};2
use session::trusted_url::may_carry_credentials;2
use session::{ApiResponse, App, Request, Scope, Session};3
use session::{ApiResponse, App, Request, Scope, Session};3
4
4
use crate::error::Result;5
use crate::error::{Error, Result};5
6
6
pub const CSA_RESOURCE: &str = "https://chatsvcagg.teams.microsoft.com";7
pub const CSA_RESOURCE: &str = "https://chatsvcagg.teams.microsoft.com";7
pub const CSA_SCOPE: &str = "user_impersonation";8
pub const CSA_SCOPE: &str = "user_impersonation";@@ -86,6 +87,12 @@ pub fn skype_fetch_answer(answer: Value) -> ApiResponse {86
87
87
impl CsaTransport for SkypeTokenTransport {88
impl CsaTransport for SkypeTokenTransport {88
async fn send(&self, request: Request) -> Result<ApiResponse> {89
async fn send(&self, request: Request) -> Result<ApiResponse> {90
if !may_carry_credentials(&request.url) {91
return Err(Error::UnexpectedAnswer(format!(92
"refusing skype token request to {}",93
request.url94
)));95
}89
let answer = self96
let answer = self90
.session97
.session91
.run_with_token(98
.run_with_token(@@ -40,6 +40,8 @@ pub struct RealtimeConfig {
40
40
pub ringable: bool,
41
41
pub initially_active: bool,
42
42
pub native: bool,
43
/// Wakes the native reconnect backoff early, e.g. from the banner's Retry action.
44
pub retry: Option<Arc<Notify>>,
43
45
}
44
46
45
47
/// Page globals of one Trouter client; a second client in the same tab needs its own names.
@@ -74,6 +76,7 @@ impl Default for RealtimeConfig {
74
76
ringable: false,
75
77
initially_active: false,
76
78
native: std::env::var_os("TEAMS_PAGE_TROUTER").is_none(),
79
retry: None,
77
80
}
78
81
}
79
82
}
@@ -40,6 +40,8 @@ pub struct RealtimeConfig {40
pub ringable: bool,40
pub ringable: bool,41
pub initially_active: bool,41
pub initially_active: bool,42
pub native: bool,42
pub native: bool,43
/// Wakes the native reconnect backoff early, e.g. from the banner's Retry action.44
pub retry: Option<Arc<Notify>>,43
}45
}44
46
45
/// Page globals of one Trouter client; a second client in the same tab needs its own names.47
/// Page globals of one Trouter client; a second client in the same tab needs its own names.@@ -74,6 +76,7 @@ impl Default for RealtimeConfig {74
ringable: false,76
ringable: false,75
initially_active: false,77
initially_active: false,76
native: std::env::var_os("TEAMS_PAGE_TROUTER").is_none(),78
native: std::env::var_os("TEAMS_PAGE_TROUTER").is_none(),79
retry: None,77
}80
}78
}81
}79
}82
}@@ -322,6 +322,7 @@ pub(super) struct NativeTrouter {
322
322
pub endpoint_id: String,
323
323
force_refresh: bool,
324
324
retry: u32,
325
retry_signal: Option<Arc<Notify>>,
325
326
ack_counter: u64,
326
327
surl: String,
327
328
registered_at: Option<Instant>,
@@ -353,6 +354,7 @@ impl NativeTrouter {
353
354
activity: watch::Receiver<bool>,
354
355
resend: Arc<Notify>,
355
356
) -> Self {
357
let retry_signal = config.retry.clone();
356
358
NativeTrouter {
357
359
session,
358
360
config,
@@ -364,6 +366,7 @@ impl NativeTrouter {
364
366
endpoint_id: uuid::Uuid::new_v4().to_string(),
365
367
force_refresh: false,
366
368
retry: 0,
369
retry_signal,
367
370
ack_counter: 0,
368
371
surl: String::new(),
369
372
registered_at: None,
@@ -389,6 +392,7 @@ impl NativeTrouter {
389
392
}
390
393
391
394
pub(super) async fn run(mut self, mut stop: oneshot::Receiver<oneshot::Sender<()>>) {
395
let retry_signal = self.retry_signal.clone();
392
396
loop {
393
397
let connected = tokio::select! {
394
398
connected = self.connect() => connected,
@@ -422,6 +426,12 @@ impl NativeTrouter {
422
426
}
423
427
return;
424
428
}
429
_ = async {
430
match &retry_signal {
431
Some(signal) => signal.notified().await,
432
None => std::future::pending().await,
433
}
434
} => self.retry = 0,
425
435
_ = self.output.closed() => return,
426
436
}
427
437
}
@@ -322,6 +322,7 @@ pub(super) struct NativeTrouter {322
pub endpoint_id: String,322
pub endpoint_id: String,323
force_refresh: bool,323
force_refresh: bool,324
retry: u32,324
retry: u32,325
retry_signal: Option<Arc<Notify>>,325
ack_counter: u64,326
ack_counter: u64,326
surl: String,327
surl: String,327
registered_at: Option<Instant>,328
registered_at: Option<Instant>,@@ -353,6 +354,7 @@ impl NativeTrouter {353
activity: watch::Receiver<bool>,354
activity: watch::Receiver<bool>,354
resend: Arc<Notify>,355
resend: Arc<Notify>,355
) -> Self {356
) -> Self {357
let retry_signal = config.retry.clone();356
NativeTrouter {358
NativeTrouter {357
session,359
session,358
config,360
config,@@ -364,6 +366,7 @@ impl NativeTrouter {364
endpoint_id: uuid::Uuid::new_v4().to_string(),366
endpoint_id: uuid::Uuid::new_v4().to_string(),365
force_refresh: false,367
force_refresh: false,366
retry: 0,368
retry: 0,369
retry_signal,367
ack_counter: 0,370
ack_counter: 0,368
surl: String::new(),371
surl: String::new(),369
registered_at: None,372
registered_at: None,@@ -389,6 +392,7 @@ impl NativeTrouter {389
}392
}390
393
391
pub(super) async fn run(mut self, mut stop: oneshot::Receiver<oneshot::Sender<()>>) {394
pub(super) async fn run(mut self, mut stop: oneshot::Receiver<oneshot::Sender<()>>) {395
let retry_signal = self.retry_signal.clone();392
loop {396
loop {393
let connected = tokio::select! {397
let connected = tokio::select! {394
connected = self.connect() => connected,398
connected = self.connect() => connected,@@ -422,6 +426,12 @@ impl NativeTrouter {422
}426
}423
return;427
return;424
}428
}429
_ = async {430
match &retry_signal {431
Some(signal) => signal.notified().await,432
None => std::future::pending().await,433
}434
} => self.retry = 0,425
_ = self.output.closed() => return,435
_ = self.output.closed() => return,426
}436
}427
}437
}@@ -193,6 +193,7 @@ impl Runner {
193
193
) {
194
194
let mut attached = Some(first);
195
195
let mut backoff = Duration::from_secs(1);
196
let retry_signal = self.config.retry.clone();
196
197
loop {
197
198
let current = match attached.take() {
198
199
Some(current) => current,
@@ -207,6 +208,12 @@ impl Runner {
207
208
_ = sleep(backoff) => {}
208
209
_ = &mut stop => return,
209
210
_ = self.output.closed() => return,
211
_ = async {
212
match &retry_signal {
213
Some(signal) => signal.notified().await,
214
None => std::future::pending().await,
215
}
216
} => backoff = Duration::from_millis(500),
210
217
}
211
218
backoff = (backoff * 2).min(self.config.max_reattach_backoff);
212
219
continue;
@@ -193,6 +193,7 @@ impl Runner {193
) {193
) {194
let mut attached = Some(first);194
let mut attached = Some(first);195
let mut backoff = Duration::from_secs(1);195
let mut backoff = Duration::from_secs(1);196
let retry_signal = self.config.retry.clone();196
loop {197
loop {197
let current = match attached.take() {198
let current = match attached.take() {198
Some(current) => current,199
Some(current) => current,@@ -207,6 +208,12 @@ impl Runner {207
_ = sleep(backoff) => {}208
_ = sleep(backoff) => {}208
_ = &mut stop => return,209
_ = &mut stop => return,209
_ = self.output.closed() => return,210
_ = self.output.closed() => return,211
_ = async {212
match &retry_signal {213
Some(signal) => signal.notified().await,214
None => std::future::pending().await,215
}216
} => backoff = Duration::from_millis(500),210
}217
}211
backoff = (backoff * 2).min(self.config.max_reattach_backoff);218
backoff = (backoff * 2).min(self.config.max_reattach_backoff);212
continue;219
continue;@@ -1,7 +1,7 @@
1
1
use std::collections::VecDeque;
2
2
use std::sync::Mutex;
3
3
4
use serde_json::{json, Value};
4
use serde_json::{Value, json};
5
5
use session::{ApiResponse, Method, Request};
6
6
7
7
use super::*;
@@ -1,7 +1,7 @@1
use std::collections::VecDeque;1
use std::collections::VecDeque;2
use std::sync::Mutex;2
use std::sync::Mutex;3
3
4
use serde_json::{json, Value};4
use serde_json::{Value, json};5
use session::{ApiResponse, Method, Request};5
use session::{ApiResponse, Method, Request};6
6
7
use super::*;7
use super::*;@@ -32,6 +32,7 @@ const ALLOWED_PATHS: &[(&str, &str)] = &[
32
32
("webview/", "WebView2 page hosts"),
33
33
("app-base/src/task_dialog/sdk.rs", "task dialog host origin"),
34
34
("core/src/links.rs", "link classification"),
35
("kvt-sleutels/src/session.rs", "KVT: sign-in hosts of the sleutels.kvt.nl session tab"),
35
36
("core/src/meeting_join.rs", "meeting join link parsing"),
36
37
("core/src/message_link.rs", "message link parsing"),
37
38
("core/src/call_event.rs", "recording link host check"),
@@ -32,6 +32,7 @@ const ALLOWED_PATHS: &[(&str, &str)] = &[32
("webview/", "WebView2 page hosts"),32
("webview/", "WebView2 page hosts"),33
("app-base/src/task_dialog/sdk.rs", "task dialog host origin"),33
("app-base/src/task_dialog/sdk.rs", "task dialog host origin"),34
("core/src/links.rs", "link classification"),34
("core/src/links.rs", "link classification"),35
("kvt-sleutels/src/session.rs", "KVT: sign-in hosts of the sleutels.kvt.nl session tab"),35
("core/src/meeting_join.rs", "meeting join link parsing"),36
("core/src/meeting_join.rs", "meeting join link parsing"),36
("core/src/message_link.rs", "message link parsing"),37
("core/src/message_link.rs", "message link parsing"),37
("core/src/call_event.rs", "recording link host check"),38
("core/src/call_event.rs", "recording link host check"),@@ -0,0 +1,120 @@
1
/// A code block language as Teams offers it: the id its `language-*` class carries and the name shown.
2
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3
pub struct CodeLanguage {
4
pub id: &'static str,
5
pub name: &'static str,
6
}
7
8
pub const PLAIN_LANGUAGE: &str = "plaintext";
9
10
const fn language(id: &'static str, name: &'static str) -> CodeLanguage {
11
CodeLanguage { id, name }
12
}
13
14
/// Teams' code block picker, in its order, from the class map of its code block editor
15
/// (Teams web). Its Shell row sends `language-bash` like Bash, so it is left out here.
16
/// A new language is one row here, and a grammar in the app's highlighter if it gets colours.
17
pub const CODE_LANGUAGES: &[CodeLanguage] = &[
18
language(PLAIN_LANGUAGE, "Plain Text"),
19
language("bash", "Bash"),
20
language("c", "C"),
21
language("cpp", "C++"),
22
language("csharp", "C#"),
23
language("css", "CSS"),
24
language("dart", "Dart"),
25
language("dockerFile", "DockerFile"),
26
language("dos", "DOS"),
27
language("go", "Go"),
28
language("graphql", "GraphQL"),
29
language("html", "HTML"),
30
language("http", "HTTP"),
31
language("java", "Java"),
32
language("javascript", "JavaScript"),
33
language("json", "JSON"),
34
language("jsp", "JSP"),
35
language("jsx", "JSX"),
36
language("kotlin", "Kotlin"),
37
language("kql", "KQL"),
38
language("latex", "LaTeX"),
39
language("lisp", "Lisp"),
40
language("markdown", "Markdown"),
41
language("objectivec", "Objective-C"),
42
language("octave", "Octave"),
43
language("perl", "Perl"),
44
language("php", "PHP"),
45
language("powershell", "PowerShell"),
46
language("python", "Python"),
47
language("r", "R"),
48
language("ruby", "Ruby"),
49
language("rust", "Rust"),
50
language("scala", "Scala"),
51
language("scss", "SCSS"),
52
language("sql", "SQL"),
53
language("swift", "Swift"),
54
language("typescript", "TypeScript"),
55
language("vbnet", "VB.NET"),
56
language("vbscript", "VBScript"),
57
language("verilog", "Verilog"),
58
language("vhdl", "VHDL"),
59
language("xml", "XML"),
60
language("yaml", "YAML"),
61
];
62
63
/// Short names people type after ``` that mean one of Teams' languages.
64
const ALIASES: &[(&str, &str)] = &[
65
("text", PLAIN_LANGUAGE),
66
("txt", PLAIN_LANGUAGE),
67
("sh", "bash"),
68
("shell", "bash"),
69
("zsh", "bash"),
70
("c++", "cpp"),
71
("cs", "csharp"),
72
("c#", "csharp"),
73
("docker", "dockerFile"),
74
("bat", "dos"),
75
("cmd", "dos"),
76
("golang", "go"),
77
("js", "javascript"),
78
("kt", "kotlin"),
79
("tex", "latex"),
80
("md", "markdown"),
81
("objc", "objectivec"),
82
("matlab", "octave"),
83
("ps1", "powershell"),
84
("py", "python"),
85
("rb", "ruby"),
86
("rs", "rust"),
87
("ts", "typescript"),
88
("tsx", "typescript"),
89
("vb", "vbnet"),
90
("svg", "xml"),
91
("yml", "yaml"),
92
];
93
94
/// Teams' language for an id or a common short name, in any case.
95
pub fn code_language(id: &str) -> Option<&'static CodeLanguage> {
96
let id = ALIASES
97
.iter()
98
.find(|(alias, _)| alias.eq_ignore_ascii_case(id))
99
.map_or(id, |(_, target)| target);
100
CODE_LANGUAGES
101
.iter()
102
.find(|language| language.id.eq_ignore_ascii_case(id))
103
}
104
105
#[cfg(test)]
106
mod tests {
107
use super::*;
108
109
#[test]
110
fn ids_names_and_short_names_find_teams_languages() {
111
assert_eq!(
112
code_language("dockerfile").map(|l| l.id),
113
Some("dockerFile")
114
);
115
assert_eq!(code_language("py").map(|l| l.name), Some("Python"));
116
assert_eq!(code_language("SHELL").map(|l| l.name), Some("Bash"));
117
assert_eq!(code_language("brainfuck"), None);
118
assert!(ALIASES.iter().all(|(_, id)| code_language(id).is_some()));
119
}
120
}
@@ -0,0 +1,120 @@1
/// A code block language as Teams offers it: the id its `language-*` class carries and the name shown.2
#[derive(Debug, Clone, Copy, PartialEq, Eq)]3
pub struct CodeLanguage {4
pub id: &'static str,5
pub name: &'static str,6
}7
8
pub const PLAIN_LANGUAGE: &str = "plaintext";9
10
const fn language(id: &'static str, name: &'static str) -> CodeLanguage {11
CodeLanguage { id, name }12
}13
14
/// Teams' code block picker, in its order, from the class map of its code block editor15
/// (Teams web). Its Shell row sends `language-bash` like Bash, so it is left out here.16
/// A new language is one row here, and a grammar in the app's highlighter if it gets colours.17
pub const CODE_LANGUAGES: &[CodeLanguage] = &[18
language(PLAIN_LANGUAGE, "Plain Text"),19
language("bash", "Bash"),20
language("c", "C"),21
language("cpp", "C++"),22
language("csharp", "C#"),23
language("css", "CSS"),24
language("dart", "Dart"),25
language("dockerFile", "DockerFile"),26
language("dos", "DOS"),27
language("go", "Go"),28
language("graphql", "GraphQL"),29
language("html", "HTML"),30
language("http", "HTTP"),31
language("java", "Java"),32
language("javascript", "JavaScript"),33
language("json", "JSON"),34
language("jsp", "JSP"),35
language("jsx", "JSX"),36
language("kotlin", "Kotlin"),37
language("kql", "KQL"),38
language("latex", "LaTeX"),39
language("lisp", "Lisp"),40
language("markdown", "Markdown"),41
language("objectivec", "Objective-C"),42
language("octave", "Octave"),43
language("perl", "Perl"),44
language("php", "PHP"),45
language("powershell", "PowerShell"),46
language("python", "Python"),47
language("r", "R"),48
language("ruby", "Ruby"),49
language("rust", "Rust"),50
language("scala", "Scala"),51
language("scss", "SCSS"),52
language("sql", "SQL"),53
language("swift", "Swift"),54
language("typescript", "TypeScript"),55
language("vbnet", "VB.NET"),56
language("vbscript", "VBScript"),57
language("verilog", "Verilog"),58
language("vhdl", "VHDL"),59
language("xml", "XML"),60
language("yaml", "YAML"),61
];62
63
/// Short names people type after ``` that mean one of Teams' languages.64
const ALIASES: &[(&str, &str)] = &[65
("text", PLAIN_LANGUAGE),66
("txt", PLAIN_LANGUAGE),67
("sh", "bash"),68
("shell", "bash"),69
("zsh", "bash"),70
("c++", "cpp"),71
("cs", "csharp"),72
("c#", "csharp"),73
("docker", "dockerFile"),74
("bat", "dos"),75
("cmd", "dos"),76
("golang", "go"),77
("js", "javascript"),78
("kt", "kotlin"),79
("tex", "latex"),80
("md", "markdown"),81
("objc", "objectivec"),82
("matlab", "octave"),83
("ps1", "powershell"),84
("py", "python"),85
("rb", "ruby"),86
("rs", "rust"),87
("ts", "typescript"),88
("tsx", "typescript"),89
("vb", "vbnet"),90
("svg", "xml"),91
("yml", "yaml"),92
];93
94
/// Teams' language for an id or a common short name, in any case.95
pub fn code_language(id: &str) -> Option<&'static CodeLanguage> {96
let id = ALIASES97
.iter()98
.find(|(alias, _)| alias.eq_ignore_ascii_case(id))99
.map_or(id, |(_, target)| target);100
CODE_LANGUAGES101
.iter()102
.find(|language| language.id.eq_ignore_ascii_case(id))103
}104
105
#[cfg(test)]106
mod tests {107
use super::*;108
109
#[test]110
fn ids_names_and_short_names_find_teams_languages() {111
assert_eq!(112
code_language("dockerfile").map(|l| l.id),113
Some("dockerFile")114
);115
assert_eq!(code_language("py").map(|l| l.name), Some("Python"));116
assert_eq!(code_language("SHELL").map(|l| l.name), Some("Bash"));117
assert_eq!(code_language("brainfuck"), None);118
assert!(ALIASES.iter().all(|(_, id)| code_language(id).is_some()));119
}120
}@@ -12,6 +12,8 @@ pub const MAX_DEPTH: u8 = 2;
12
12
pub const MAX_HEADING: u8 = 3;
13
13
pub const OBJECT_MARK: char = '\u{FFFC}';
14
14
pub const RULE_MARK: char = '\u{FFFA}';
15
/// The marker of a code block's first line: the composer shows the block's header there.
16
pub const CODE_HEADER_MARK: char = '\u{FFF9}';
15
17
pub const MAX_INDENT: u8 = 8;
16
18
pub const INDENT_PIXELS: u32 = 40;
17
19
pub const RULE_HTML: &str = "<hr>";
@@ -783,6 +785,20 @@ impl Draft {
783
785
return None;
784
786
}
785
787
let before = &self.text[content.start..cursor];
788
// Teams opens the block on the third backtick; undo gives back the fence for ```lang + Enter.
789
if self.lines[index] == LineKind::Text && before == FENCE && cursor == content.end {
790
self.splice(content.clone(), "", &[]);
791
let cursor = self.set_line_kind(index, LineKind::Code(None), None, content.start);
792
// A block of the same language right below joins this one under its header.
793
let cursor = self.repair(cursor);
794
return Some((
795
cursor,
796
TypingStyle {
797
at: cursor,
798
..TypingStyle::default()
799
},
800
));
801
}
786
802
if self.lines[index] == LineKind::Text
787
803
&& let Some((kind, number)) = line_shortcut(before)
788
804
{
@@ -880,7 +896,9 @@ impl Draft {
880
896
LineKind::Text => {
881
897
let language = fence_language(&self.text[content.clone()])?;
882
898
self.splice(content.clone(), "", &[]);
883
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))
899
let cursor =
900
self.set_line_kind(index, LineKind::Code(language), None, content.start);
901
Some(self.repair(cursor))
884
902
}
885
903
LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => None,
886
904
LineKind::Indent(_) if !shift => None,
@@ -900,10 +918,17 @@ impl Draft {
900
918
Some(cursor + 1)
901
919
}
902
920
LineKind::Code(_) => {
921
// The third Enter leaves: two empty lines end the block, one stays code.
903
922
let last_of_block = self.lines.get(index + 1) != Some(&kind);
904
let block_continues_above = index > 0 && self.lines[index - 1] == kind;
905
if content.is_empty() && last_of_block && block_continues_above && !shift {
906
return Some(self.set_line_kind(index, LineKind::Text, None, cursor));
923
let empty_line_above = index >= 2
924
&& self.lines[index - 1] == kind
925
&& self.lines[index - 2] == kind
926
&& self.content_range(index - 1).is_empty();
927
if content.is_empty() && last_of_block && empty_line_above && !shift {
928
let above = self.line_ranges()[index - 1].start;
929
self.splice(above..content.start, "", &[]);
930
let cursor = self.set_line_kind(index - 1, LineKind::Text, None, above);
931
return Some(self.repair(cursor));
907
932
}
908
933
self.splice(cursor..cursor, "\n", &[]);
909
934
Some(cursor + 1)
@@ -985,10 +1010,9 @@ impl Draft {
985
1010
match &kind {
986
1011
LineKind::Text | LineKind::Indent(_) | LineKind::Rule => None,
987
1012
LineKind::Code(_) => {
988
let first_of_block = index == 0 || self.lines[index - 1] != kind;
989
(cursor == line.start && first_of_block).then(|| {
990
self.lines[index] = LineKind::Text;
991
cursor
1013
(cursor <= content.start && self.first_of_block(index)).then(|| {
1014
let cursor = self.set_line_kind(index, LineKind::Text, None, cursor);
1015
self.repair(cursor)
992
1016
})
993
1017
}
994
1018
LineKind::Table(_) => None,
@@ -1153,6 +1177,36 @@ impl Draft {
1153
1177
self.repair(0);
1154
1178
}
1155
1179
1180
/// The lines of the code block at `cursor`: the run of code lines with one language.
1181
pub fn code_block_at(&self, cursor: usize) -> Option<Range<usize>> {
1182
let index = self.line_at(cursor);
1183
let kind = self.lines.get(index)?;
1184
if !matches!(kind, LineKind::Code(_)) {
1185
return None;
1186
}
1187
let start = self.lines[..index]
1188
.iter()
1189
.rposition(|other| other != kind)
1190
.map_or(0, |before| before + 1);
1191
let end = index
1192
+ self.lines[index..]
1193
.iter()
1194
.take_while(|other| *other == kind)
1195
.count();
1196
Some(start..end)
1197
}
1198
1199
/// Only the header marks change: a block that now matches the next one merges with it.
1200
pub fn set_code_language(&mut self, cursor: usize, language: Option<String>) {
1201
if let Some(block) = self.code_block_at(cursor) {
1202
self.journal = Journal::default();
1203
for kind in &mut self.lines[block] {
1204
*kind = LineKind::Code(language.clone());
1205
}
1206
self.repair(cursor);
1207
}
1208
}
1209
1156
1210
pub fn table(&self, index: usize) -> Option<&Table> {
1157
1211
match self.lines.get(index)? {
1158
1212
LineKind::Table(table) => Some(table),
@@ -1451,7 +1505,8 @@ impl Draft {
1451
1505
let language = language.as_deref().unwrap_or(PLAIN_LANGUAGE);
1452
1506
html.push_str(&format!(
1453
1507
"<pre class=\"language-{} skipProofing\" spellcheck=\"false\"><code>",
1454
escape_html(&language.to_ascii_lowercase())
1508
// Teams' ids are case-sensitive: `dockerFile`.
1509
escape_html(language)
1455
1510
));
1456
1511
let code = run
1457
1512
.iter()
@@ -1718,11 +1773,48 @@ impl Draft {
1718
1773
})
1719
1774
.unwrap_or(1),
1720
1775
},
1776
LineKind::Code(_) if self.first_of_block(index) => {
1777
return CODE_HEADER_MARK.to_string();
1778
}
1721
1779
_ => 1,
1722
1780
};
1723
1781
marker_text(kind, number)
1724
1782
}
1725
1783
1784
fn first_of_block(&self, index: usize) -> bool {
1785
index == 0 || self.lines[index - 1] != self.lines[index]
1786
}
1787
1788
/// Only the first line of a code block holds the header mark.
1789
fn repair_code_headers(&mut self, mut cursor: usize) -> usize {
1790
let stray: Vec<usize> = self
1791
.text
1792
.match_indices(CODE_HEADER_MARK)
1793
.map(|(at, _)| at)
1794
.filter(|at| {
1795
let index = self.line_at(*at);
1796
!matches!(self.lines[index], LineKind::Code(_))
1797
|| !self.first_of_block(index)
1798
|| self.line_ranges()[index].start != *at
1799
})
1800
.collect();
1801
for at in stray.into_iter().rev() {
1802
let mark = at..at + CODE_HEADER_MARK.len_utf8();
1803
self.splice(mark.clone(), "", &[]);
1804
if cursor > at {
1805
cursor -= (cursor - at).min(mark.len());
1806
}
1807
}
1808
for index in 0..self.lines.len() {
1809
if matches!(self.lines[index], LineKind::Code(_)) {
1810
let marker = self.marker_range(index);
1811
let expected = self.expected_marker(index, None);
1812
cursor = self.replace_marker(marker, &expected, cursor);
1813
}
1814
}
1815
cursor
1816
}
1817
1726
1818
fn set_line_kind(
1727
1819
&mut self,
1728
1820
index: usize,
@@ -1798,6 +1890,7 @@ impl Draft {
1798
1890
/// List items whose marker was edited away become text; numbered items are renumbered.
1799
1891
fn repair(&mut self, cursor: usize) -> usize {
1800
1892
let mut cursor = self.repair_objects(cursor);
1893
cursor = self.repair_code_headers(cursor);
1801
1894
for index in 0..self.lines.len() {
1802
1895
let kind = self.lines[index].clone();
1803
1896
if !kind.is_list() {
@@ -1858,6 +1951,7 @@ fn marker_len(kind: &LineKind, line: &str) -> usize {
1858
1951
}
1859
1952
}
1860
1953
LineKind::Numbered(_) => numbered_marker(line).map_or(0, |(length, _)| length),
1954
LineKind::Code(_) if line.starts_with(CODE_HEADER_MARK) => CODE_HEADER_MARK.len_utf8(),
1861
1955
_ => 0,
1862
1956
}
1863
1957
}
@@ -1892,7 +1986,14 @@ fn fence_language(line: &str) -> Option<Option<String>> {
1892
1986
let valid = info
1893
1987
.chars()
1894
1988
.all(|character| character.is_alphanumeric() || "+#-_.".contains(character));
1895
valid.then(|| (!info.is_empty()).then(|| info.to_lowercase()))
1989
valid.then(|| teams_language(info))
1990
}
1991
1992
/// The id Teams knows for a typed language, so ```py sends `language-python`; Plain Text is none.
1993
fn teams_language(info: &str) -> Option<String> {
1994
let id = crate::code_language(info)
1995
.map_or_else(|| info.to_lowercase(), |language| language.id.to_owned());
1996
(!info.is_empty() && id != crate::PLAIN_LANGUAGE).then_some(id)
1896
1997
}
1897
1998
1898
1999
fn valid_inner(inner: &str) -> bool {
@@ -3037,28 +3138,102 @@ mod tests {
3037
3138
3038
3139
#[test]
3039
3140
fn fence_and_enter_open_a_code_block_that_enter_continues() {
3040
let mut draft = typed_draft("```rust");
3141
let mut draft = Draft::plain("```rust");
3041
3142
let cursor = draft.break_line(draft.text().len(), false).unwrap();
3042
assert_eq!((draft.text(), cursor), ("", 0));
3143
assert_eq!((draft.text(), cursor), ("\u{FFF9}", 3));
3043
3144
assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);
3044
3145
typed(&mut draft, "fn x() {}");
3045
3146
let cursor = draft.break_line(draft.text().len(), false).unwrap();
3046
3147
assert_eq!(draft.lines().len(), 2);
3047
assert_eq!(draft.break_line(cursor, false), Some(cursor));
3148
let cursor = draft.break_line(cursor, false).unwrap();
3149
assert_eq!(draft.lines().len(), 3, "one empty line stays code");
3150
assert_eq!(draft.lines()[2], LineKind::Code(Some("rust".into())));
3151
let end = draft.break_line(cursor, false).unwrap();
3152
assert_eq!(
3153
draft.lines().len(),
3154
2,
3155
"the third Enter drops both empty lines"
3156
);
3048
3157
assert_eq!(draft.lines()[1], LineKind::Text);
3158
assert_eq!(end, draft.line_ranges()[1].start);
3049
3159
assert_eq!(
3050
3160
draft.to_html(),
3051
3161
"<pre class=\"language-rust skipProofing\" spellcheck=\"false\"><code>fn x() {}</code></pre>"
3052
3162
);
3053
3163
}
3054
3164
3165
#[test]
3166
fn a_fence_opens_a_code_block_only_alone_on_a_plain_line() {
3167
assert_eq!(typed_draft("a ```").lines(), [LineKind::Text]);
3168
assert_eq!(typed_draft("> ```").lines(), [LineKind::Quote]);
3169
let mut draft = Draft::plain("x");
3170
draft.apply_edit("```x", 3, None);
3171
assert!(draft.convert_typed(3).is_none());
3172
assert_eq!(draft.text(), "```x");
3173
}
3174
3175
#[test]
3176
fn a_language_goes_to_the_whole_code_block_at_the_cursor_only() {
3177
let mut draft = Draft::from_markdown("```\na\nb\n```\nx\n```\nc\n```");
3178
draft.set_code_language(0, Some("go".into()));
3179
assert_eq!(
3180
draft.lines(),
3181
[
3182
LineKind::Code(Some("go".into())),
3183
LineKind::Code(Some("go".into())),
3184
LineKind::Text,
3185
LineKind::Code(None),
3186
]
3187
);
3188
assert_eq!(
3189
draft.code_block_at(draft.text().find('b').unwrap()),
3190
Some(0..2)
3191
);
3192
assert_eq!(draft.code_block_at(draft.text().len() - 1), Some(3..4));
3193
draft.set_code_language(draft.text().find('x').unwrap(), Some("c".into()));
3194
assert_eq!(draft.lines()[2], LineKind::Text);
3195
assert!(draft.to_html().starts_with("<pre class=\"language-go "));
3196
}
3197
3198
#[test]
3199
fn the_block_keeps_its_first_line_when_enter_leaves_it() {
3200
let mut draft = typed_draft("```");
3201
let cursor = draft.break_line(draft.text().len(), false).unwrap();
3202
let cursor = draft.break_line(cursor, false).unwrap();
3203
draft.break_line(cursor, false).unwrap();
3204
assert_eq!(draft.lines(), [LineKind::Code(None), LineKind::Text]);
3205
}
3206
3207
#[test]
3208
fn a_fence_above_a_block_of_its_language_joins_it_under_one_header() {
3209
let mut draft = Draft::from_markdown("x\n```python\nb\n```");
3210
let fenced = format!("```python{}", &draft.text()[1..]);
3211
draft.apply_edit(&fenced, "```python".len(), None);
3212
draft.break_line("```python".len(), false).unwrap();
3213
assert_eq!(draft.text().matches(CODE_HEADER_MARK).count(), 1);
3214
assert!(draft.to_html().contains("language-python"));
3215
let docker = Draft::from_lines(&[DraftLine {
3216
kind: LineKind::Code(Some("dockerFile".into())),
3217
number: None,
3218
content: "FROM x".into(),
3219
marks: Vec::new(),
3220
}]);
3221
assert!(
3222
docker
3223
.to_html()
3224
.starts_with("<pre class=\"language-dockerFile ")
3225
);
3226
}
3227
3055
3228
#[test]
3056
3229
fn markdown_inside_code_stays_literal() {
3057
3230
let mut draft = typed_draft("```");
3058
let cursor = draft.break_line(3, false).unwrap();
3059
assert_eq!(cursor, 0);
3231
assert_eq!(
3232
(draft.text(), draft.lines()),
3233
("\u{FFF9}", &[LineKind::Code(None)][..])
3234
);
3060
3235
typed(&mut draft, "a **b**");
3061
assert_eq!(draft.text(), "a **b**");
3236
assert_eq!(draft.text(), "\u{FFF9}a **b**");
3062
3237
assert!(draft.marks().is_empty());
3063
3238
}
3064
3239
@@ -3142,7 +3317,7 @@ mod tests {
3142
3317
<blockquote>q1<br>q2</blockquote>\
3143
3318
<ul><li>a<ul><li>b</li></ul></li></ul>\
3144
3319
<ol><li>x</li><li>y</li></ol>\
3145
<pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>print(1)</code></pre>"
3320
<pre class=\"language-python skipProofing\" spellcheck=\"false\"><code>print(1)</code></pre>"
3146
3321
);
3147
3322
}
3148
3323
@@ -3346,7 +3521,7 @@ mod tests {
3346
3521
#[test]
3347
3522
fn code_lines_hold_only_their_content() {
3348
3523
let mut draft = Draft::from_markdown("```\nlet a = 1;\n\u{2003}b\n```");
3349
assert_eq!(draft.text(), "let a = 1;\n\u{2003}b");
3524
assert_eq!(draft.text(), "\u{FFF9}let a = 1;\n\u{2003}b");
3350
3525
assert_eq!(
3351
3526
draft.to_html(),
3352
3527
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>let a = 1;<br>\u{2003}b</code></pre>"
@@ -3367,7 +3542,7 @@ mod tests {
3367
3542
3368
3543
#[test]
3369
3544
fn code_indentation_is_kept_on_paste_split_and_send() {
3370
let mut draft = typed_draft("```py");
3545
let mut draft = Draft::plain("```py");
3371
3546
let cursor = draft.break_line(draft.text().len(), false).unwrap();
3372
3547
let pasted = "def f():\n return 1";
3373
3548
let mut next = draft.text().to_owned();
@@ -3375,10 +3550,10 @@ mod tests {
3375
3550
draft.apply_edit(&next, cursor + pasted.len(), None);
3376
3551
assert_eq!(
3377
3552
draft.to_html(),
3378
"<pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>def f():<br> return 1</code></pre>"
3553
"<pre class=\"language-python skipProofing\" spellcheck=\"false\"><code>def f():<br> return 1</code></pre>"
3379
3554
);
3380
3555
let mut split = Draft::from_markdown("```\n a b\n```");
3381
let after_a = " a".len();
3556
let after_a = "\u{FFF9} a".len();
3382
3557
split.break_line(after_a, false).unwrap();
3383
3558
assert_eq!(
3384
3559
split.to_html(),
@@ -12,6 +12,8 @@ pub const MAX_DEPTH: u8 = 2;12
pub const MAX_HEADING: u8 = 3;12
pub const MAX_HEADING: u8 = 3;13
pub const OBJECT_MARK: char = '\u{FFFC}';13
pub const OBJECT_MARK: char = '\u{FFFC}';14
pub const RULE_MARK: char = '\u{FFFA}';14
pub const RULE_MARK: char = '\u{FFFA}';15
/// The marker of a code block's first line: the composer shows the block's header there.16
pub const CODE_HEADER_MARK: char = '\u{FFF9}';15
pub const MAX_INDENT: u8 = 8;17
pub const MAX_INDENT: u8 = 8;16
pub const INDENT_PIXELS: u32 = 40;18
pub const INDENT_PIXELS: u32 = 40;17
pub const RULE_HTML: &str = "<hr>";19
pub const RULE_HTML: &str = "<hr>";@@ -783,6 +785,20 @@ impl Draft {783
return None;785
return None;784
}786
}785
let before = &self.text[content.start..cursor];787
let before = &self.text[content.start..cursor];788
// Teams opens the block on the third backtick; undo gives back the fence for ```lang + Enter.789
if self.lines[index] == LineKind::Text && before == FENCE && cursor == content.end {790
self.splice(content.clone(), "", &[]);791
let cursor = self.set_line_kind(index, LineKind::Code(None), None, content.start);792
// A block of the same language right below joins this one under its header.793
let cursor = self.repair(cursor);794
return Some((795
cursor,796
TypingStyle {797
at: cursor,798
..TypingStyle::default()799
},800
));801
}786
if self.lines[index] == LineKind::Text802
if self.lines[index] == LineKind::Text787
&& let Some((kind, number)) = line_shortcut(before)803
&& let Some((kind, number)) = line_shortcut(before)788
{804
{@@ -880,7 +896,9 @@ impl Draft {880
LineKind::Text => {896
LineKind::Text => {881
let language = fence_language(&self.text[content.clone()])?;897
let language = fence_language(&self.text[content.clone()])?;882
self.splice(content.clone(), "", &[]);898
self.splice(content.clone(), "", &[]);883
Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))899
let cursor =900
self.set_line_kind(index, LineKind::Code(language), None, content.start);901
Some(self.repair(cursor))884
}902
}885
LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => None,903
LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => None,886
LineKind::Indent(_) if !shift => None,904
LineKind::Indent(_) if !shift => None,@@ -900,10 +918,17 @@ impl Draft {900
Some(cursor + 1)918
Some(cursor + 1)901
}919
}902
LineKind::Code(_) => {920
LineKind::Code(_) => {921
// The third Enter leaves: two empty lines end the block, one stays code.903
let last_of_block = self.lines.get(index + 1) != Some(&kind);922
let last_of_block = self.lines.get(index + 1) != Some(&kind);904
let block_continues_above = index > 0 && self.lines[index - 1] == kind;923
let empty_line_above = index >= 2905
if content.is_empty() && last_of_block && block_continues_above && !shift {924
&& self.lines[index - 1] == kind906
return Some(self.set_line_kind(index, LineKind::Text, None, cursor));925
&& self.lines[index - 2] == kind926
&& self.content_range(index - 1).is_empty();927
if content.is_empty() && last_of_block && empty_line_above && !shift {928
let above = self.line_ranges()[index - 1].start;929
self.splice(above..content.start, "", &[]);930
let cursor = self.set_line_kind(index - 1, LineKind::Text, None, above);931
return Some(self.repair(cursor));907
}932
}908
self.splice(cursor..cursor, "\n", &[]);933
self.splice(cursor..cursor, "\n", &[]);909
Some(cursor + 1)934
Some(cursor + 1)@@ -985,10 +1010,9 @@ impl Draft {985
match &kind {1010
match &kind {986
LineKind::Text | LineKind::Indent(_) | LineKind::Rule => None,1011
LineKind::Text | LineKind::Indent(_) | LineKind::Rule => None,987
LineKind::Code(_) => {1012
LineKind::Code(_) => {988
let first_of_block = index == 0 || self.lines[index - 1] != kind;1013
(cursor <= content.start && self.first_of_block(index)).then(|| {989
(cursor == line.start && first_of_block).then(|| {1014
let cursor = self.set_line_kind(index, LineKind::Text, None, cursor);990
self.lines[index] = LineKind::Text;1015
self.repair(cursor)991
cursor992
})1016
})993
}1017
}994
LineKind::Table(_) => None,1018
LineKind::Table(_) => None,@@ -1153,6 +1177,36 @@ impl Draft {1153
self.repair(0);1177
self.repair(0);1154
}1178
}1155
1179
1180
/// The lines of the code block at `cursor`: the run of code lines with one language.1181
pub fn code_block_at(&self, cursor: usize) -> Option<Range<usize>> {1182
let index = self.line_at(cursor);1183
let kind = self.lines.get(index)?;1184
if !matches!(kind, LineKind::Code(_)) {1185
return None;1186
}1187
let start = self.lines[..index]1188
.iter()1189
.rposition(|other| other != kind)1190
.map_or(0, |before| before + 1);1191
let end = index1192
+ self.lines[index..]1193
.iter()1194
.take_while(|other| *other == kind)1195
.count();1196
Some(start..end)1197
}1198
1199
/// Only the header marks change: a block that now matches the next one merges with it.1200
pub fn set_code_language(&mut self, cursor: usize, language: Option<String>) {1201
if let Some(block) = self.code_block_at(cursor) {1202
self.journal = Journal::default();1203
for kind in &mut self.lines[block] {1204
*kind = LineKind::Code(language.clone());1205
}1206
self.repair(cursor);1207
}1208
}1209
1156
pub fn table(&self, index: usize) -> Option<&Table> {1210
pub fn table(&self, index: usize) -> Option<&Table> {1157
match self.lines.get(index)? {1211
match self.lines.get(index)? {1158
LineKind::Table(table) => Some(table),1212
LineKind::Table(table) => Some(table),@@ -1451,7 +1505,8 @@ impl Draft {1451
let language = language.as_deref().unwrap_or(PLAIN_LANGUAGE);1505
let language = language.as_deref().unwrap_or(PLAIN_LANGUAGE);1452
html.push_str(&format!(1506
html.push_str(&format!(1453
"<pre class=\"language-{} skipProofing\" spellcheck=\"false\"><code>",1507
"<pre class=\"language-{} skipProofing\" spellcheck=\"false\"><code>",1454
escape_html(&language.to_ascii_lowercase())1508
// Teams' ids are case-sensitive: `dockerFile`.1509
escape_html(language)1455
));1510
));1456
let code = run1511
let code = run1457
.iter()1512
.iter()@@ -1718,11 +1773,48 @@ impl Draft {1718
})1773
})1719
.unwrap_or(1),1774
.unwrap_or(1),1720
},1775
},1776
LineKind::Code(_) if self.first_of_block(index) => {1777
return CODE_HEADER_MARK.to_string();1778
}1721
_ => 1,1779
_ => 1,1722
};1780
};1723
marker_text(kind, number)1781
marker_text(kind, number)1724
}1782
}1725
1783
1784
fn first_of_block(&self, index: usize) -> bool {1785
index == 0 || self.lines[index - 1] != self.lines[index]1786
}1787
1788
/// Only the first line of a code block holds the header mark.1789
fn repair_code_headers(&mut self, mut cursor: usize) -> usize {1790
let stray: Vec<usize> = self1791
.text1792
.match_indices(CODE_HEADER_MARK)1793
.map(|(at, _)| at)1794
.filter(|at| {1795
let index = self.line_at(*at);1796
!matches!(self.lines[index], LineKind::Code(_))1797
|| !self.first_of_block(index)1798
|| self.line_ranges()[index].start != *at1799
})1800
.collect();1801
for at in stray.into_iter().rev() {1802
let mark = at..at + CODE_HEADER_MARK.len_utf8();1803
self.splice(mark.clone(), "", &[]);1804
if cursor > at {1805
cursor -= (cursor - at).min(mark.len());1806
}1807
}1808
for index in 0..self.lines.len() {1809
if matches!(self.lines[index], LineKind::Code(_)) {1810
let marker = self.marker_range(index);1811
let expected = self.expected_marker(index, None);1812
cursor = self.replace_marker(marker, &expected, cursor);1813
}1814
}1815
cursor1816
}1817
1726
fn set_line_kind(1818
fn set_line_kind(1727
&mut self,1819
&mut self,1728
index: usize,1820
index: usize,@@ -1798,6 +1890,7 @@ impl Draft {1798
/// List items whose marker was edited away become text; numbered items are renumbered.1890
/// List items whose marker was edited away become text; numbered items are renumbered.1799
fn repair(&mut self, cursor: usize) -> usize {1891
fn repair(&mut self, cursor: usize) -> usize {1800
let mut cursor = self.repair_objects(cursor);1892
let mut cursor = self.repair_objects(cursor);1893
cursor = self.repair_code_headers(cursor);1801
for index in 0..self.lines.len() {1894
for index in 0..self.lines.len() {1802
let kind = self.lines[index].clone();1895
let kind = self.lines[index].clone();1803
if !kind.is_list() {1896
if !kind.is_list() {@@ -1858,6 +1951,7 @@ fn marker_len(kind: &LineKind, line: &str) -> usize {1858
}1951
}1859
}1952
}1860
LineKind::Numbered(_) => numbered_marker(line).map_or(0, |(length, _)| length),1953
LineKind::Numbered(_) => numbered_marker(line).map_or(0, |(length, _)| length),1954
LineKind::Code(_) if line.starts_with(CODE_HEADER_MARK) => CODE_HEADER_MARK.len_utf8(),1861
_ => 0,1955
_ => 0,1862
}1956
}1863
}1957
}@@ -1892,7 +1986,14 @@ fn fence_language(line: &str) -> Option<Option<String>> {1892
let valid = info1986
let valid = info1893
.chars()1987
.chars()1894
.all(|character| character.is_alphanumeric() || "+#-_.".contains(character));1988
.all(|character| character.is_alphanumeric() || "+#-_.".contains(character));1895
valid.then(|| (!info.is_empty()).then(|| info.to_lowercase()))1989
valid.then(|| teams_language(info))1990
}1991
1992
/// The id Teams knows for a typed language, so ```py sends `language-python`; Plain Text is none.1993
fn teams_language(info: &str) -> Option<String> {1994
let id = crate::code_language(info)1995
.map_or_else(|| info.to_lowercase(), |language| language.id.to_owned());1996
(!info.is_empty() && id != crate::PLAIN_LANGUAGE).then_some(id)1896
}1997
}1897
1998
1898
fn valid_inner(inner: &str) -> bool {1999
fn valid_inner(inner: &str) -> bool {@@ -3037,28 +3138,102 @@ mod tests {3037
3138
3038
#[test]3139
#[test]3039
fn fence_and_enter_open_a_code_block_that_enter_continues() {3140
fn fence_and_enter_open_a_code_block_that_enter_continues() {3040
let mut draft = typed_draft("```rust");3141
let mut draft = Draft::plain("```rust");3041
let cursor = draft.break_line(draft.text().len(), false).unwrap();3142
let cursor = draft.break_line(draft.text().len(), false).unwrap();3042
assert_eq!((draft.text(), cursor), ("", 0));3143
assert_eq!((draft.text(), cursor), ("\u{FFF9}", 3));3043
assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);3144
assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);3044
typed(&mut draft, "fn x() {}");3145
typed(&mut draft, "fn x() {}");3045
let cursor = draft.break_line(draft.text().len(), false).unwrap();3146
let cursor = draft.break_line(draft.text().len(), false).unwrap();3046
assert_eq!(draft.lines().len(), 2);3147
assert_eq!(draft.lines().len(), 2);3047
assert_eq!(draft.break_line(cursor, false), Some(cursor));3148
let cursor = draft.break_line(cursor, false).unwrap();3149
assert_eq!(draft.lines().len(), 3, "one empty line stays code");3150
assert_eq!(draft.lines()[2], LineKind::Code(Some("rust".into())));3151
let end = draft.break_line(cursor, false).unwrap();3152
assert_eq!(3153
draft.lines().len(),3154
2,3155
"the third Enter drops both empty lines"3156
);3048
assert_eq!(draft.lines()[1], LineKind::Text);3157
assert_eq!(draft.lines()[1], LineKind::Text);3158
assert_eq!(end, draft.line_ranges()[1].start);3049
assert_eq!(3159
assert_eq!(3050
draft.to_html(),3160
draft.to_html(),3051
"<pre class=\"language-rust skipProofing\" spellcheck=\"false\"><code>fn x() {}</code></pre>"3161
"<pre class=\"language-rust skipProofing\" spellcheck=\"false\"><code>fn x() {}</code></pre>"3052
);3162
);3053
}3163
}3054
3164
3165
#[test]3166
fn a_fence_opens_a_code_block_only_alone_on_a_plain_line() {3167
assert_eq!(typed_draft("a ```").lines(), [LineKind::Text]);3168
assert_eq!(typed_draft("> ```").lines(), [LineKind::Quote]);3169
let mut draft = Draft::plain("x");3170
draft.apply_edit("```x", 3, None);3171
assert!(draft.convert_typed(3).is_none());3172
assert_eq!(draft.text(), "```x");3173
}3174
3175
#[test]3176
fn a_language_goes_to_the_whole_code_block_at_the_cursor_only() {3177
let mut draft = Draft::from_markdown("```\na\nb\n```\nx\n```\nc\n```");3178
draft.set_code_language(0, Some("go".into()));3179
assert_eq!(3180
draft.lines(),3181
[3182
LineKind::Code(Some("go".into())),3183
LineKind::Code(Some("go".into())),3184
LineKind::Text,3185
LineKind::Code(None),3186
]3187
);3188
assert_eq!(3189
draft.code_block_at(draft.text().find('b').unwrap()),3190
Some(0..2)3191
);3192
assert_eq!(draft.code_block_at(draft.text().len() - 1), Some(3..4));3193
draft.set_code_language(draft.text().find('x').unwrap(), Some("c".into()));3194
assert_eq!(draft.lines()[2], LineKind::Text);3195
assert!(draft.to_html().starts_with("<pre class=\"language-go "));3196
}3197
3198
#[test]3199
fn the_block_keeps_its_first_line_when_enter_leaves_it() {3200
let mut draft = typed_draft("```");3201
let cursor = draft.break_line(draft.text().len(), false).unwrap();3202
let cursor = draft.break_line(cursor, false).unwrap();3203
draft.break_line(cursor, false).unwrap();3204
assert_eq!(draft.lines(), [LineKind::Code(None), LineKind::Text]);3205
}3206
3207
#[test]3208
fn a_fence_above_a_block_of_its_language_joins_it_under_one_header() {3209
let mut draft = Draft::from_markdown("x\n```python\nb\n```");3210
let fenced = format!("```python{}", &draft.text()[1..]);3211
draft.apply_edit(&fenced, "```python".len(), None);3212
draft.break_line("```python".len(), false).unwrap();3213
assert_eq!(draft.text().matches(CODE_HEADER_MARK).count(), 1);3214
assert!(draft.to_html().contains("language-python"));3215
let docker = Draft::from_lines(&[DraftLine {3216
kind: LineKind::Code(Some("dockerFile".into())),3217
number: None,3218
content: "FROM x".into(),3219
marks: Vec::new(),3220
}]);3221
assert!(3222
docker3223
.to_html()3224
.starts_with("<pre class=\"language-dockerFile ")3225
);3226
}3227
3055
#[test]3228
#[test]3056
fn markdown_inside_code_stays_literal() {3229
fn markdown_inside_code_stays_literal() {3057
let mut draft = typed_draft("```");3230
let mut draft = typed_draft("```");3058
let cursor = draft.break_line(3, false).unwrap();3231
assert_eq!(3059
assert_eq!(cursor, 0);3232
(draft.text(), draft.lines()),3233
("\u{FFF9}", &[LineKind::Code(None)][..])3234
);3060
typed(&mut draft, "a **b**");3235
typed(&mut draft, "a **b**");3061
assert_eq!(draft.text(), "a **b**");3236
assert_eq!(draft.text(), "\u{FFF9}a **b**");3062
assert!(draft.marks().is_empty());3237
assert!(draft.marks().is_empty());3063
}3238
}3064
3239
@@ -3142,7 +3317,7 @@ mod tests {3142
<blockquote>q1<br>q2</blockquote>\3317
<blockquote>q1<br>q2</blockquote>\3143
<ul><li>a<ul><li>b</li></ul></li></ul>\3318
<ul><li>a<ul><li>b</li></ul></li></ul>\3144
<ol><li>x</li><li>y</li></ol>\3319
<ol><li>x</li><li>y</li></ol>\3145
<pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>print(1)</code></pre>"3320
<pre class=\"language-python skipProofing\" spellcheck=\"false\"><code>print(1)</code></pre>"3146
);3321
);3147
}3322
}3148
3323
@@ -3346,7 +3521,7 @@ mod tests {3346
#[test]3521
#[test]3347
fn code_lines_hold_only_their_content() {3522
fn code_lines_hold_only_their_content() {3348
let mut draft = Draft::from_markdown("```\nlet a = 1;\n\u{2003}b\n```");3523
let mut draft = Draft::from_markdown("```\nlet a = 1;\n\u{2003}b\n```");3349
assert_eq!(draft.text(), "let a = 1;\n\u{2003}b");3524
assert_eq!(draft.text(), "\u{FFF9}let a = 1;\n\u{2003}b");3350
assert_eq!(3525
assert_eq!(3351
draft.to_html(),3526
draft.to_html(),3352
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>let a = 1;<br>\u{2003}b</code></pre>"3527
"<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>let a = 1;<br>\u{2003}b</code></pre>"@@ -3367,7 +3542,7 @@ mod tests {3367
3542
3368
#[test]3543
#[test]3369
fn code_indentation_is_kept_on_paste_split_and_send() {3544
fn code_indentation_is_kept_on_paste_split_and_send() {3370
let mut draft = typed_draft("```py");3545
let mut draft = Draft::plain("```py");3371
let cursor = draft.break_line(draft.text().len(), false).unwrap();3546
let cursor = draft.break_line(draft.text().len(), false).unwrap();3372
let pasted = "def f():\n return 1";3547
let pasted = "def f():\n return 1";3373
let mut next = draft.text().to_owned();3548
let mut next = draft.text().to_owned();@@ -3375,10 +3550,10 @@ mod tests {3375
draft.apply_edit(&next, cursor + pasted.len(), None);3550
draft.apply_edit(&next, cursor + pasted.len(), None);3376
assert_eq!(3551
assert_eq!(3377
draft.to_html(),3552
draft.to_html(),3378
"<pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>def f():<br> return 1</code></pre>"3553
"<pre class=\"language-python skipProofing\" spellcheck=\"false\"><code>def f():<br> return 1</code></pre>"3379
);3554
);3380
let mut split = Draft::from_markdown("```\n a b\n```");3555
let mut split = Draft::from_markdown("```\n a b\n```");3381
let after_a = " a".len();3556
let after_a = "\u{FFF9} a".len();3382
split.break_line(after_a, false).unwrap();3557
split.break_line(after_a, false).unwrap();3383
assert_eq!(3558
assert_eq!(3384
split.to_html(),3559
split.to_html(),@@ -22,6 +22,7 @@ mod chat_paging;
22
22
mod chat_send;
23
23
mod chat_settings_sync;
24
24
mod cloud_files;
25
mod code_languages;
25
26
mod copilot;
26
27
mod default_reactions;
27
28
mod download;
@@ -138,15 +139,16 @@ pub use chatsvc::{
138
139
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,
139
140
parse_language_settings, target_patch,
140
141
};
142
pub use code_languages::{CODE_LANGUAGES, CodeLanguage, PLAIN_LANGUAGE, code_language};
141
143
pub use default_reactions::{
142
144
DEFAULT_REACTION_SLOTS, TEAMS_DEFAULT_REACTIONS, default_reactions,
143
145
store_account_default_reactions,
144
146
};
145
147
pub use download::LibraryFile;
146
148
pub use draft::{
147
Draft, DraftLine, Edit, FormatState, INDENT_PIXELS, LineKind, MAX_DEPTH, MAX_INDENT, Mark,
148
MarkKind, OBJECT_MARK, RULE_MARK, SizeStep, TypingStyle, changed_span, has_markdown, link_url,
149
map_offset, reverse_edits,
149
CODE_HEADER_MARK, Draft, DraftLine, Edit, FormatState, INDENT_PIXELS, LineKind, MAX_DEPTH,
150
MAX_INDENT, Mark, MarkKind, OBJECT_MARK, RULE_MARK, SizeStep, TypingStyle, changed_span,
151
has_markdown, link_url, map_offset, reverse_edits,
150
152
};
151
153
pub use emoticon_tags::{EmoticonTag, emoticon_tags};
152
154
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};
@@ -189,7 +191,7 @@ pub use receipts::{ReceiptReader, ReceiptState};
189
191
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
190
192
pub use scheduled::NOTES_CHAT_ID;
191
193
pub use skin_tone::{skin_tone, store_account_skin_tone};
192
pub use spans::{FontSize, Span, html_to_spans};
194
pub use spans::{CODE_BLOCK_ITEMTYPE, FontSize, Span, html_to_spans};
193
195
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
194
196
pub use stored::{
195
197
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,
@@ -22,6 +22,7 @@ mod chat_paging;22
mod chat_send;22
mod chat_send;23
mod chat_settings_sync;23
mod chat_settings_sync;24
mod cloud_files;24
mod cloud_files;25
mod code_languages;25
mod copilot;26
mod copilot;26
mod default_reactions;27
mod default_reactions;27
mod download;28
mod download;@@ -138,15 +139,16 @@ pub use chatsvc::{138
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,139
TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,139
parse_language_settings, target_patch,140
parse_language_settings, target_patch,140
};141
};142
pub use code_languages::{CODE_LANGUAGES, CodeLanguage, PLAIN_LANGUAGE, code_language};141
pub use default_reactions::{143
pub use default_reactions::{142
DEFAULT_REACTION_SLOTS, TEAMS_DEFAULT_REACTIONS, default_reactions,144
DEFAULT_REACTION_SLOTS, TEAMS_DEFAULT_REACTIONS, default_reactions,143
store_account_default_reactions,145
store_account_default_reactions,144
};146
};145
pub use download::LibraryFile;147
pub use download::LibraryFile;146
pub use draft::{148
pub use draft::{147
Draft, DraftLine, Edit, FormatState, INDENT_PIXELS, LineKind, MAX_DEPTH, MAX_INDENT, Mark,149
CODE_HEADER_MARK, Draft, DraftLine, Edit, FormatState, INDENT_PIXELS, LineKind, MAX_DEPTH,148
MarkKind, OBJECT_MARK, RULE_MARK, SizeStep, TypingStyle, changed_span, has_markdown, link_url,150
MAX_INDENT, Mark, MarkKind, OBJECT_MARK, RULE_MARK, SizeStep, TypingStyle, changed_span,149
map_offset, reverse_edits,151
has_markdown, link_url, map_offset, reverse_edits,150
};152
};151
pub use emoticon_tags::{EmoticonTag, emoticon_tags};153
pub use emoticon_tags::{EmoticonTag, emoticon_tags};152
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};154
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};@@ -189,7 +191,7 @@ pub use receipts::{ReceiptReader, ReceiptState};189
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};191
pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};190
pub use scheduled::NOTES_CHAT_ID;192
pub use scheduled::NOTES_CHAT_ID;191
pub use skin_tone::{skin_tone, store_account_skin_tone};193
pub use skin_tone::{skin_tone, store_account_skin_tone};192
pub use spans::{FontSize, Span, html_to_spans};194
pub use spans::{CODE_BLOCK_ITEMTYPE, FontSize, Span, html_to_spans};193
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};195
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};194
pub use stored::{196
pub use stored::{195
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,197
AttachmentInfo, FileCard, FileKind, ImageKind, ImageRef, MentionInfo, PROFILE_LINK_PREFIX,@@ -81,13 +81,14 @@ const LANGUAGE_PREFIX: &str = "language-";
81
81
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
82
82
const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";
83
83
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
84
pub const CODE_BLOCK_ITEMTYPE: &str = "http://schema.skype.com/CodeBlockEditor";
84
85
const MAX_HEADING_LEVEL: u8 = 3;
85
86
const MARK_BACKGROUND: u32 = 0xffff00;
86
87
const MAX_CONSECUTIVE_BREAKS: usize = 2;
87
88
const INDENTED_ELEMENTS: [&str; 8] = ["p", "div", "h1", "h2", "h3", "h4", "h5", "h6"];
88
89
const INDENT_STEP_PIXELS: f32 = 40.;
89
90
const MAX_INDENT_LEVEL: u8 = 8;
90
const PLAIN_LANGUAGE: &str = "plaintext";
91
use crate::code_languages::PLAIN_LANGUAGE;
91
92
92
93
pub fn html_to_spans(html: &str) -> Vec<Span> {
93
94
let fragment = Html::parse_fragment(html);
@@ -116,6 +117,12 @@ fn convert_children(element: ElementRef<'_>) -> Vec<Span> {
116
117
let Some(child_element) = ElementRef::wrap(child) else {
117
118
continue;
118
119
};
120
// The empty paragraph Teams puts before a code block only links it to its editor.
121
if child_element.value().attr("itemtype") == Some(CODE_BLOCK_ITEMTYPE)
122
&& raw_text(child_element).trim().is_empty()
123
{
124
continue;
125
}
119
126
let is_block = BLOCK_ELEMENTS.contains(&child_element.value().name());
120
127
if (is_block || break_pending) && !spans.is_empty() {
121
128
spans.push(Span::LineBreak);
@@ -408,8 +415,9 @@ fn language_of(element: ElementRef<'_>) -> Option<String> {
408
415
element
409
416
.value()
410
417
.classes()
411
.find_map(|class| class.strip_prefix(LANGUAGE_PREFIX))
412
.filter(|language| !language.is_empty())
418
.filter_map(|class| class.strip_prefix(LANGUAGE_PREFIX))
419
// Teams marks a language it guessed with this second class.
420
.find(|language| !language.is_empty() && *language != "was-auto-selected")
413
421
.map(str::to_owned)
414
422
}
415
423
@@ -81,13 +81,14 @@ const LANGUAGE_PREFIX: &str = "language-";81
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";81
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";82
const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";82
const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";83
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";83
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";84
pub const CODE_BLOCK_ITEMTYPE: &str = "http://schema.skype.com/CodeBlockEditor";84
const MAX_HEADING_LEVEL: u8 = 3;85
const MAX_HEADING_LEVEL: u8 = 3;85
const MARK_BACKGROUND: u32 = 0xffff00;86
const MARK_BACKGROUND: u32 = 0xffff00;86
const MAX_CONSECUTIVE_BREAKS: usize = 2;87
const MAX_CONSECUTIVE_BREAKS: usize = 2;87
const INDENTED_ELEMENTS: [&str; 8] = ["p", "div", "h1", "h2", "h3", "h4", "h5", "h6"];88
const INDENTED_ELEMENTS: [&str; 8] = ["p", "div", "h1", "h2", "h3", "h4", "h5", "h6"];88
const INDENT_STEP_PIXELS: f32 = 40.;89
const INDENT_STEP_PIXELS: f32 = 40.;89
const MAX_INDENT_LEVEL: u8 = 8;90
const MAX_INDENT_LEVEL: u8 = 8;90
const PLAIN_LANGUAGE: &str = "plaintext";91
use crate::code_languages::PLAIN_LANGUAGE;91
92
92
pub fn html_to_spans(html: &str) -> Vec<Span> {93
pub fn html_to_spans(html: &str) -> Vec<Span> {93
let fragment = Html::parse_fragment(html);94
let fragment = Html::parse_fragment(html);@@ -116,6 +117,12 @@ fn convert_children(element: ElementRef<'_>) -> Vec<Span> {116
let Some(child_element) = ElementRef::wrap(child) else {117
let Some(child_element) = ElementRef::wrap(child) else {117
continue;118
continue;118
};119
};120
// The empty paragraph Teams puts before a code block only links it to its editor.121
if child_element.value().attr("itemtype") == Some(CODE_BLOCK_ITEMTYPE)122
&& raw_text(child_element).trim().is_empty()123
{124
continue;125
}119
let is_block = BLOCK_ELEMENTS.contains(&child_element.value().name());126
let is_block = BLOCK_ELEMENTS.contains(&child_element.value().name());120
if (is_block || break_pending) && !spans.is_empty() {127
if (is_block || break_pending) && !spans.is_empty() {121
spans.push(Span::LineBreak);128
spans.push(Span::LineBreak);@@ -408,8 +415,9 @@ fn language_of(element: ElementRef<'_>) -> Option<String> {408
element415
element409
.value()416
.value()410
.classes()417
.classes()411
.find_map(|class| class.strip_prefix(LANGUAGE_PREFIX))418
.filter_map(|class| class.strip_prefix(LANGUAGE_PREFIX))412
.filter(|language| !language.is_empty())419
// Teams marks a language it guessed with this second class.420
.find(|language| !language.is_empty() && *language != "was-auto-selected")413
.map(str::to_owned)421
.map(str::to_owned)414
}422
}415
423
@@ -535,5 +535,5 @@ fn code_blocks_send_the_teams_pre_code_shape_and_read_back_line_breaks() {
535
535
);
536
536
let back = Draft::from_spans(&html_to_spans(&html));
537
537
assert_eq!(back.lines(), [LineKind::Code(None), LineKind::Code(None)]);
538
assert_eq!(back.text(), "a < b\n c");
538
assert_eq!(back.text(), "\u{FFF9}a < b\n c");
539
539
}
@@ -535,5 +535,5 @@ fn code_blocks_send_the_teams_pre_code_shape_and_read_back_line_breaks() {535
);535
);536
let back = Draft::from_spans(&html_to_spans(&html));536
let back = Draft::from_spans(&html_to_spans(&html));537
assert_eq!(back.lines(), [LineKind::Code(None), LineKind::Code(None)]);537
assert_eq!(back.lines(), [LineKind::Code(None), LineKind::Code(None)]);538
assert_eq!(back.text(), "a < b\n c");538
assert_eq!(back.text(), "\u{FFF9}a < b\n c");539
}539
}@@ -550,3 +550,32 @@ fn org_emoji_keep_their_image_and_name() {
550
550
}]
551
551
);
552
552
}
553
554
#[test]
555
fn the_teams_code_block_marker_adds_no_empty_line() {
556
let spans = html_to_spans(
557
"<p>before</p><p itemtype=\"http://schema.skype.com/CodeBlockEditor\" id=\"x_codeBlockEditor-1\"> </p><pre class=\"language-py\" itemid=\"codeBlockEditor-1\"><code>x</code></pre>",
558
);
559
assert_eq!(
560
spans,
561
[
562
Span::Text("before".into()),
563
Span::LineBreak,
564
Span::CodeBlock {
565
language: Some("py".into()),
566
code: "x".into()
567
}
568
]
569
);
570
}
571
572
#[test]
573
fn teams_auto_selected_code_keeps_its_language() {
574
let spans = html_to_spans(
575
"<pre class=\"language-python language-was-auto-selected\"><code><span class=\"hljs-keyword\">def</span> f</code></pre>",
576
);
577
assert!(
578
matches!(&spans[..], [Span::CodeBlock { language: Some(language), .. }] if language == "python"),
579
"{spans:?}"
580
);
581
}
@@ -550,3 +550,32 @@ fn org_emoji_keep_their_image_and_name() {550
}]550
}]551
);551
);552
}552
}553
554
#[test]555
fn the_teams_code_block_marker_adds_no_empty_line() {556
let spans = html_to_spans(557
"<p>before</p><p itemtype=\"http://schema.skype.com/CodeBlockEditor\" id=\"x_codeBlockEditor-1\"> </p><pre class=\"language-py\" itemid=\"codeBlockEditor-1\"><code>x</code></pre>",558
);559
assert_eq!(560
spans,561
[562
Span::Text("before".into()),563
Span::LineBreak,564
Span::CodeBlock {565
language: Some("py".into()),566
code: "x".into()567
}568
]569
);570
}571
572
#[test]573
fn teams_auto_selected_code_keeps_its_language() {574
let spans = html_to_spans(575
"<pre class=\"language-python language-was-auto-selected\"><code><span class=\"hljs-keyword\">def</span> f</code></pre>",576
);577
assert!(578
matches!(&spans[..], [Span::CodeBlock { language: Some(language), .. }] if language == "python"),579
"{spans:?}"580
);581
}@@ -19,39 +19,14 @@
19
19
else take(key, entry);
20
20
}
21
21
const plain = entries.length;
22
// Newer MSAL.js seals its localStorage cache: AES-GCM under a key from the msal.cache.encryption session cookie.
23
const unseal = async () => {
24
const cookie = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith('msal.cache.encryption='));
25
let sealing = null;
26
try { sealing = cookie && JSON.parse(decodeURIComponent(cookie.slice(cookie.indexOf('=') + 1))); } catch (error) {}
27
if (!sealing || !sealing.key || !sealing.id) return;
28
const bytes = (text) => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=')),
29
(character) => character.charCodeAt(0));
22
if (sealed.length) {
23
const unsealEntries = __UNSEAL__;
30
24
const memo = (window.__rustyTeamsUnsealed = window.__rustyTeamsUnsealed || new Map());
31
const base = await crypto.subtle.importKey('raw', bytes(sealing.key), 'HKDF', false, ['deriveKey']);
32
for (const [key, entry] of sealed) {
33
if (entry.id !== sealing.id) continue;
34
if (!memo.has(entry.nonce)) {
35
// MSAL binds an entry to the client id in its key, or to an empty context when the key has none.
36
const contexts = [...(key.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) || []), ''];
37
for (const context of new Set(contexts)) {
38
try {
39
const derived = await crypto.subtle.deriveKey(
40
{name: 'HKDF', salt: bytes(entry.nonce), hash: 'SHA-256', info: new TextEncoder().encode(context)},
41
base, {name: 'AES-GCM', length: 256}, false, ['decrypt']);
42
const data = await crypto.subtle.decrypt({name: 'AES-GCM', iv: new Uint8Array(12)}, derived, bytes(entry.data));
43
memo.set(entry.nonce, JSON.parse(new TextDecoder().decode(data)));
44
break;
45
} catch (error) {}
46
}
47
}
48
if (memo.has(entry.nonce)) {
49
take(key, memo.get(entry.nonce));
50
opened++;
51
}
25
for (const [key, entry] of await unsealEntries(sealed, memo)) {
26
take(key, entry);
27
opened++;
52
28
}
53
};
54
if (sealed.length) await unseal();
29
}
55
30
const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;
56
31
const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];
57
32
// Without a tenant the account's home tenant; a guest tenant is reached with the same account's refresh token.
@@ -19,39 +19,14 @@19
else take(key, entry);19
else take(key, entry);20
}20
}21
const plain = entries.length;21
const plain = entries.length;22
// Newer MSAL.js seals its localStorage cache: AES-GCM under a key from the msal.cache.encryption session cookie.22
if (sealed.length) {23
const unseal = async () => {23
const unsealEntries = __UNSEAL__;24
const cookie = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith('msal.cache.encryption='));25
let sealing = null;26
try { sealing = cookie && JSON.parse(decodeURIComponent(cookie.slice(cookie.indexOf('=') + 1))); } catch (error) {}27
if (!sealing || !sealing.key || !sealing.id) return;28
const bytes = (text) => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=')),29
(character) => character.charCodeAt(0));30
const memo = (window.__rustyTeamsUnsealed = window.__rustyTeamsUnsealed || new Map());24
const memo = (window.__rustyTeamsUnsealed = window.__rustyTeamsUnsealed || new Map());31
const base = await crypto.subtle.importKey('raw', bytes(sealing.key), 'HKDF', false, ['deriveKey']);25
for (const [key, entry] of await unsealEntries(sealed, memo)) {32
for (const [key, entry] of sealed) {26
take(key, entry);33
if (entry.id !== sealing.id) continue;27
opened++;34
if (!memo.has(entry.nonce)) {35
// MSAL binds an entry to the client id in its key, or to an empty context when the key has none.36
const contexts = [...(key.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) || []), ''];37
for (const context of new Set(contexts)) {38
try {39
const derived = await crypto.subtle.deriveKey(40
{name: 'HKDF', salt: bytes(entry.nonce), hash: 'SHA-256', info: new TextEncoder().encode(context)},41
base, {name: 'AES-GCM', length: 256}, false, ['decrypt']);42
const data = await crypto.subtle.decrypt({name: 'AES-GCM', iv: new Uint8Array(12)}, derived, bytes(entry.data));43
memo.set(entry.nonce, JSON.parse(new TextDecoder().decode(data)));44
break;45
} catch (error) {}46
}47
}48
if (memo.has(entry.nonce)) {49
take(key, memo.get(entry.nonce));50
opened++;51
}52
}28
}53
};29
}54
if (sealed.length) await unseal();55
const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;30
const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;56
const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];31
const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];57
// Without a tenant the account's home tenant; a guest tenant is reached with the same account's refresh token.32
// Without a tenant the account's home tenant; a guest tenant is reached with the same account's refresh token.@@ -0,0 +1,31 @@
1
// Newer MSAL.js seals its localStorage cache: AES-GCM under a key from the msal.cache.encryption session cookie.
2
// Answers [key, entry] for every sealed entry it could open. `memo` keeps opened entries by nonce.
3
async (sealed, memo) => {
4
const opened = [];
5
const cookie = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith('msal.cache.encryption='));
6
let sealing = null;
7
try { sealing = cookie && JSON.parse(decodeURIComponent(cookie.slice(cookie.indexOf('=') + 1))); } catch (error) {}
8
if (!sealing || !sealing.key || !sealing.id || !sealed.length) return opened;
9
const bytes = (text) => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=')),
10
(character) => character.charCodeAt(0));
11
const base = await crypto.subtle.importKey('raw', bytes(sealing.key), 'HKDF', false, ['deriveKey']);
12
for (const [key, entry] of sealed) {
13
if (entry.id !== sealing.id) continue;
14
if (!memo.has(entry.nonce)) {
15
// MSAL binds an entry to the client id in its key, or to an empty context when the key has none.
16
const contexts = [...(String(key).match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) || []), ''];
17
for (const context of new Set(contexts)) {
18
try {
19
const derived = await crypto.subtle.deriveKey(
20
{name: 'HKDF', salt: bytes(entry.nonce), hash: 'SHA-256', info: new TextEncoder().encode(context)},
21
base, {name: 'AES-GCM', length: 256}, false, ['decrypt']);
22
const data = await crypto.subtle.decrypt({name: 'AES-GCM', iv: new Uint8Array(12)}, derived, bytes(entry.data));
23
memo.set(entry.nonce, JSON.parse(new TextDecoder().decode(data)));
24
break;
25
} catch (error) {}
26
}
27
}
28
if (memo.has(entry.nonce)) opened.push([key, memo.get(entry.nonce)]);
29
}
30
return opened;
31
}
@@ -0,0 +1,31 @@1
// Newer MSAL.js seals its localStorage cache: AES-GCM under a key from the msal.cache.encryption session cookie.2
// Answers [key, entry] for every sealed entry it could open. `memo` keeps opened entries by nonce.3
async (sealed, memo) => {4
const opened = [];5
const cookie = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith('msal.cache.encryption='));6
let sealing = null;7
try { sealing = cookie && JSON.parse(decodeURIComponent(cookie.slice(cookie.indexOf('=') + 1))); } catch (error) {}8
if (!sealing || !sealing.key || !sealing.id || !sealed.length) return opened;9
const bytes = (text) => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=')),10
(character) => character.charCodeAt(0));11
const base = await crypto.subtle.importKey('raw', bytes(sealing.key), 'HKDF', false, ['deriveKey']);12
for (const [key, entry] of sealed) {13
if (entry.id !== sealing.id) continue;14
if (!memo.has(entry.nonce)) {15
// MSAL binds an entry to the client id in its key, or to an empty context when the key has none.16
const contexts = [...(String(key).match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) || []), ''];17
for (const context of new Set(contexts)) {18
try {19
const derived = await crypto.subtle.deriveKey(20
{name: 'HKDF', salt: bytes(entry.nonce), hash: 'SHA-256', info: new TextEncoder().encode(context)},21
base, {name: 'AES-GCM', length: 256}, false, ['decrypt']);22
const data = await crypto.subtle.decrypt({name: 'AES-GCM', iv: new Uint8Array(12)}, derived, bytes(entry.data));23
memo.set(entry.nonce, JSON.parse(new TextDecoder().decode(data)));24
break;25
} catch (error) {}26
}27
}28
if (memo.has(entry.nonce)) opened.push([key, memo.get(entry.nonce)]);29
}30
return opened;31
}@@ -1,5 +1,8 @@
1
1
use serde::Deserialize;
2
2
3
/// Defender for Cloud Apps (Conditional Access App Control) proxies the app on `<host>.mcas.ms`.
4
pub const MCAS_SUFFIX: &str = ".mcas.ms";
5
3
6
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4
7
pub enum App {
5
8
Teams,
@@ -17,22 +20,59 @@ impl App {
17
20
}
18
21
}
19
22
20
pub fn start_url(self) -> &'static str {
21
match self {
22
App::Teams => "https://teams.cloud.microsoft/",
23
/// With `mcas` the URL goes through the MCAS proxy, where the MSAL cache of a proxied
24
/// tenant lives.
25
pub fn start_url(self, mcas: bool) -> &'static str {
26
match (self, mcas) {
27
(App::Teams, false) => "https://teams.cloud.microsoft/",
28
(App::Teams, true) => "https://teams.cloud.microsoft.mcas.ms/",
23
29
}
24
30
}
25
31
26
32
/// A static page on the app origin: keeps the MSAL cache reachable without running the app.
27
pub fn park_url(self) -> &'static str {
28
match self {
29
App::Teams => "https://teams.cloud.microsoft/robots.txt",
33
pub fn park_url(self, mcas: bool) -> &'static str {
34
match (self, mcas) {
35
(App::Teams, false) => "https://teams.cloud.microsoft/robots.txt",
36
(App::Teams, true) => "https://teams.cloud.microsoft.mcas.ms/robots.txt",
30
37
}
31
38
}
32
39
40
/// The start URL on the same origin as `tab_url`, so waking a parked tab keeps its cache.
41
pub fn start_url_like(self, tab_url: &str) -> &'static str {
42
self.start_url(is_mcas_url(tab_url))
43
}
44
33
45
pub fn is_park_url(self, url: &str) -> bool {
34
url.starts_with(self.park_url())
46
// both origins count, a tab parked before the switch must still be seen as parked
47
[self.park_url(false), self.park_url(true)]
48
.iter()
49
.any(|park| url.starts_with(park))
35
50
}
51
52
/// True when `url` is an https page on one of the app hosts, directly or through the
53
/// MCAS proxy. The host must match exactly, a look-alike host is not the app.
54
pub fn is_app_url(self, url: &str) -> bool {
55
let Ok(parsed) = url::Url::parse(url) else {
56
return false;
57
};
58
let Some(host) = parsed.host_str().filter(|_| parsed.scheme() == "https") else {
59
return false;
60
};
61
let host = host.strip_suffix(MCAS_SUFFIX).unwrap_or(host);
62
self.origins()
63
.iter()
64
.any(|origin| origin.strip_prefix("https://") == Some(host))
65
}
66
}
67
68
/// True when `url` is an https page on a host behind the MCAS proxy.
69
pub fn is_mcas_url(url: &str) -> bool {
70
url::Url::parse(url).is_ok_and(|parsed| {
71
parsed.scheme() == "https"
72
&& parsed
73
.host_str()
74
.is_some_and(|host| host.len() > MCAS_SUFFIX.len() && host.ends_with(MCAS_SUFFIX))
75
})
36
76
}
37
77
38
78
impl std::fmt::Display for App {
@@ -60,17 +100,17 @@ pub struct Target {
60
100
61
101
pub fn find_app_tab(targets: &[Target], app: App) -> Option<&Target> {
62
102
targets.iter().find(|target| {
63
target.kind == "page"
64
&& target.websocket_url.is_some()
65
&& app
66
.origins()
67
.iter()
68
.any(|origin| target.url.starts_with(origin))
103
target.kind == "page" && target.websocket_url.is_some() && app.is_app_url(&target.url)
69
104
})
70
105
}
71
106
72
107
pub fn is_login_url(url: &str) -> bool {
73
LOGIN_ORIGINS.iter().any(|origin| url.starts_with(origin))
108
LOGIN_ORIGINS.iter().any(|origin| is_on_origin(url, origin))
109
}
110
111
pub(crate) fn is_on_origin(url: &str, origin: &str) -> bool {
112
url.strip_prefix(origin)
113
.is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?', '#']))
74
114
}
75
115
76
116
pub fn has_login_tab(targets: &[Target]) -> bool {
@@ -125,6 +165,68 @@ mod tests {
125
165
assert!(!App::Teams.is_park_url("https://teams.cloud.microsoft/v2/"));
126
166
}
127
167
168
#[test]
169
fn mcas_urls_go_through_the_proxy_and_both_park_urls_count() {
170
assert_eq!(
171
App::Teams.start_url(true),
172
"https://teams.cloud.microsoft.mcas.ms/"
173
);
174
assert_eq!(
175
App::Teams.park_url(true),
176
"https://teams.cloud.microsoft.mcas.ms/robots.txt"
177
);
178
assert_eq!(
179
App::Teams.start_url(false),
180
"https://teams.cloud.microsoft/"
181
);
182
assert_eq!(
183
App::Teams.start_url_like("https://teams.cloud.microsoft.mcas.ms/robots.txt"),
184
App::Teams.start_url(true)
185
);
186
assert_eq!(
187
App::Teams.start_url_like("https://teams.cloud.microsoft/robots.txt"),
188
App::Teams.start_url(false)
189
);
190
assert!(!is_mcas_url("http://teams.cloud.microsoft.mcas.ms/"));
191
assert!(!is_mcas_url("https://mcas.ms/"));
192
assert!(App::Teams.is_park_url("https://teams.cloud.microsoft.mcas.ms/robots.txt"));
193
assert!(App::Teams.is_park_url("https://teams.cloud.microsoft/robots.txt"));
194
assert!(!App::Teams.is_park_url("https://teams.cloud.microsoft.mcas.ms/v2/"));
195
}
196
197
#[test]
198
fn a_lookalike_host_is_not_the_login_page() {
199
assert!(is_login_url("https://login.live.com/oauth"));
200
assert!(!is_login_url("https://login.live.com.evil.example/"));
201
}
202
203
#[test]
204
fn app_urls_need_an_exact_host() {
205
for url in [
206
"https://teams.cloud.microsoft/v2/",
207
"https://teams.microsoft.com/v2/",
208
"https://teams.cloud.microsoft.mcas.ms/",
209
"https://teams.cloud.microsoft.mcas.ms/robots.txt",
210
] {
211
assert!(App::Teams.is_app_url(url), "{url}");
212
}
213
for url in [
214
"https://teams.cloud.microsoft.evil.example/",
215
"https://teams.cloud.microsoftevil.example/",
216
"https://evil.mcas.ms/",
217
"http://teams.cloud.microsoft/",
218
"https://login.microsoftonline.com/",
219
"about:blank",
220
] {
221
assert!(!App::Teams.is_app_url(url), "{url}");
222
}
223
let look_alike: Vec<Target> = serde_json::from_str(
224
r#"[{"type":"page","url":"https://teams.cloud.microsoft.evil.example/","webSocketDebuggerUrl":"ws://x/1"}]"#,
225
)
226
.unwrap();
227
assert!(find_app_tab(&look_alike, App::Teams).is_none());
228
}
229
128
230
#[test]
129
231
fn detects_login_tab() {
130
232
let mut targets = targets();
@@ -1,5 +1,8 @@1
use serde::Deserialize;1
use serde::Deserialize;2
2
3
/// Defender for Cloud Apps (Conditional Access App Control) proxies the app on `<host>.mcas.ms`.4
pub const MCAS_SUFFIX: &str = ".mcas.ms";5
3
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]6
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]4
pub enum App {7
pub enum App {5
Teams,8
Teams,@@ -17,22 +20,59 @@ impl App {17
}20
}18
}21
}19
22
20
pub fn start_url(self) -> &'static str {23
/// With `mcas` the URL goes through the MCAS proxy, where the MSAL cache of a proxied21
match self {24
/// tenant lives.22
App::Teams => "https://teams.cloud.microsoft/",25
pub fn start_url(self, mcas: bool) -> &'static str {26
match (self, mcas) {27
(App::Teams, false) => "https://teams.cloud.microsoft/",28
(App::Teams, true) => "https://teams.cloud.microsoft.mcas.ms/",23
}29
}24
}30
}25
31
26
/// A static page on the app origin: keeps the MSAL cache reachable without running the app.32
/// A static page on the app origin: keeps the MSAL cache reachable without running the app.27
pub fn park_url(self) -> &'static str {33
pub fn park_url(self, mcas: bool) -> &'static str {28
match self {34
match (self, mcas) {29
App::Teams => "https://teams.cloud.microsoft/robots.txt",35
(App::Teams, false) => "https://teams.cloud.microsoft/robots.txt",36
(App::Teams, true) => "https://teams.cloud.microsoft.mcas.ms/robots.txt",30
}37
}31
}38
}32
39
40
/// The start URL on the same origin as `tab_url`, so waking a parked tab keeps its cache.41
pub fn start_url_like(self, tab_url: &str) -> &'static str {42
self.start_url(is_mcas_url(tab_url))43
}44
33
pub fn is_park_url(self, url: &str) -> bool {45
pub fn is_park_url(self, url: &str) -> bool {34
url.starts_with(self.park_url())46
// both origins count, a tab parked before the switch must still be seen as parked47
[self.park_url(false), self.park_url(true)]48
.iter()49
.any(|park| url.starts_with(park))35
}50
}51
52
/// True when `url` is an https page on one of the app hosts, directly or through the53
/// MCAS proxy. The host must match exactly, a look-alike host is not the app.54
pub fn is_app_url(self, url: &str) -> bool {55
let Ok(parsed) = url::Url::parse(url) else {56
return false;57
};58
let Some(host) = parsed.host_str().filter(|_| parsed.scheme() == "https") else {59
return false;60
};61
let host = host.strip_suffix(MCAS_SUFFIX).unwrap_or(host);62
self.origins()63
.iter()64
.any(|origin| origin.strip_prefix("https://") == Some(host))65
}66
}67
68
/// True when `url` is an https page on a host behind the MCAS proxy.69
pub fn is_mcas_url(url: &str) -> bool {70
url::Url::parse(url).is_ok_and(|parsed| {71
parsed.scheme() == "https"72
&& parsed73
.host_str()74
.is_some_and(|host| host.len() > MCAS_SUFFIX.len() && host.ends_with(MCAS_SUFFIX))75
})36
}76
}37
77
38
impl std::fmt::Display for App {78
impl std::fmt::Display for App {@@ -60,17 +100,17 @@ pub struct Target {60
100
61
pub fn find_app_tab(targets: &[Target], app: App) -> Option<&Target> {101
pub fn find_app_tab(targets: &[Target], app: App) -> Option<&Target> {62
targets.iter().find(|target| {102
targets.iter().find(|target| {63
target.kind == "page"103
target.kind == "page" && target.websocket_url.is_some() && app.is_app_url(&target.url)64
&& target.websocket_url.is_some()65
&& app66
.origins()67
.iter()68
.any(|origin| target.url.starts_with(origin))69
})104
})70
}105
}71
106
72
pub fn is_login_url(url: &str) -> bool {107
pub fn is_login_url(url: &str) -> bool {73
LOGIN_ORIGINS.iter().any(|origin| url.starts_with(origin))108
LOGIN_ORIGINS.iter().any(|origin| is_on_origin(url, origin))109
}110
111
pub(crate) fn is_on_origin(url: &str, origin: &str) -> bool {112
url.strip_prefix(origin)113
.is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?', '#']))74
}114
}75
115
76
pub fn has_login_tab(targets: &[Target]) -> bool {116
pub fn has_login_tab(targets: &[Target]) -> bool {@@ -125,6 +165,68 @@ mod tests {125
assert!(!App::Teams.is_park_url("https://teams.cloud.microsoft/v2/"));165
assert!(!App::Teams.is_park_url("https://teams.cloud.microsoft/v2/"));126
}166
}127
167
168
#[test]169
fn mcas_urls_go_through_the_proxy_and_both_park_urls_count() {170
assert_eq!(171
App::Teams.start_url(true),172
"https://teams.cloud.microsoft.mcas.ms/"173
);174
assert_eq!(175
App::Teams.park_url(true),176
"https://teams.cloud.microsoft.mcas.ms/robots.txt"177
);178
assert_eq!(179
App::Teams.start_url(false),180
"https://teams.cloud.microsoft/"181
);182
assert_eq!(183
App::Teams.start_url_like("https://teams.cloud.microsoft.mcas.ms/robots.txt"),184
App::Teams.start_url(true)185
);186
assert_eq!(187
App::Teams.start_url_like("https://teams.cloud.microsoft/robots.txt"),188
App::Teams.start_url(false)189
);190
assert!(!is_mcas_url("http://teams.cloud.microsoft.mcas.ms/"));191
assert!(!is_mcas_url("https://mcas.ms/"));192
assert!(App::Teams.is_park_url("https://teams.cloud.microsoft.mcas.ms/robots.txt"));193
assert!(App::Teams.is_park_url("https://teams.cloud.microsoft/robots.txt"));194
assert!(!App::Teams.is_park_url("https://teams.cloud.microsoft.mcas.ms/v2/"));195
}196
197
#[test]198
fn a_lookalike_host_is_not_the_login_page() {199
assert!(is_login_url("https://login.live.com/oauth"));200
assert!(!is_login_url("https://login.live.com.evil.example/"));201
}202
203
#[test]204
fn app_urls_need_an_exact_host() {205
for url in [206
"https://teams.cloud.microsoft/v2/",207
"https://teams.microsoft.com/v2/",208
"https://teams.cloud.microsoft.mcas.ms/",209
"https://teams.cloud.microsoft.mcas.ms/robots.txt",210
] {211
assert!(App::Teams.is_app_url(url), "{url}");212
}213
for url in [214
"https://teams.cloud.microsoft.evil.example/",215
"https://teams.cloud.microsoftevil.example/",216
"https://evil.mcas.ms/",217
"http://teams.cloud.microsoft/",218
"https://login.microsoftonline.com/",219
"about:blank",220
] {221
assert!(!App::Teams.is_app_url(url), "{url}");222
}223
let look_alike: Vec<Target> = serde_json::from_str(224
r#"[{"type":"page","url":"https://teams.cloud.microsoft.evil.example/","webSocketDebuggerUrl":"ws://x/1"}]"#,225
)226
.unwrap();227
assert!(find_app_tab(&look_alike, App::Teams).is_none());228
}229
128
#[test]230
#[test]129
fn detects_login_tab() {231
fn detects_login_tab() {130
let mut targets = targets();232
let mut targets = targets();@@ -2,14 +2,16 @@ mod app;
2
2
mod error;
3
3
mod events;
4
4
mod http;
5
pub mod msal_key;
5
6
mod native;
6
7
mod page_script;
7
8
mod request;
8
9
mod scope;
9
10
mod session;
10
11
mod transport;
12
pub mod trusted_url;
11
13
12
pub use app::{App, Target, find_app_tab, has_login_tab, is_login_url};
14
pub use app::{App, MCAS_SUFFIX, Target, find_app_tab, has_login_tab, is_login_url, is_mcas_url};
13
15
pub use error::{Error, Result};
14
16
pub use events::{TabChannel, TabCommand, TabControl, TabEvent, TabEvents};
15
17
pub use native::ensure_crypto_provider;
@@ -18,5 +20,5 @@ pub use request::{
18
20
ApiResponse, AugloopExchange, AugloopStage, BodyToken, Method, Request, SignalrExchange,
19
21
};
20
22
pub use scope::{GRAPH, IC3, NestedApp, PRESENCE, SPACES, Scope};
21
pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig, TabHold};
23
pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig, TabHold, UNSEAL_SCRIPT};
22
24
pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};
@@ -2,14 +2,16 @@ mod app;2
mod error;2
mod error;3
mod events;3
mod events;4
mod http;4
mod http;5
pub mod msal_key;5
mod native;6
mod native;6
mod page_script;7
mod page_script;7
mod request;8
mod request;8
mod scope;9
mod scope;9
mod session;10
mod session;10
mod transport;11
mod transport;12
pub mod trusted_url;11
13
12
pub use app::{App, Target, find_app_tab, has_login_tab, is_login_url};14
pub use app::{App, MCAS_SUFFIX, Target, find_app_tab, has_login_tab, is_login_url, is_mcas_url};13
pub use error::{Error, Result};15
pub use error::{Error, Result};14
pub use events::{TabChannel, TabCommand, TabControl, TabEvent, TabEvents};16
pub use events::{TabChannel, TabCommand, TabControl, TabEvent, TabEvents};15
pub use native::ensure_crypto_provider;17
pub use native::ensure_crypto_provider;@@ -18,5 +20,5 @@ pub use request::{18
ApiResponse, AugloopExchange, AugloopStage, BodyToken, Method, Request, SignalrExchange,20
ApiResponse, AugloopExchange, AugloopStage, BodyToken, Method, Request, SignalrExchange,19
};21
};20
pub use scope::{GRAPH, IC3, NestedApp, PRESENCE, SPACES, Scope};22
pub use scope::{GRAPH, IC3, NestedApp, PRESENCE, SPACES, Scope};21
pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig, TabHold};23
pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig, TabHold, UNSEAL_SCRIPT};22
pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};24
pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};@@ -1,19 +1,21 @@
1
//! Keeps the key of the Teams token cache across browser restarts (issue #84).
1
//! Keeps the key of the Teams token cache across app restarts (issue #84).
2
2
//!
3
3
//! MSAL.js encrypts its localStorage cache with a key held in the session cookie
4
//! `msal.cache.encryption`. A session cookie dies with the process, so every restart (headless
5
//! hand-over, login window, hung renderer, app exit) made MSAL create a new key, drop the cache
6
//! and ask for sign-in again. Before Chromium stops, the cookie gets an expiry instead; the key
7
//! then sits in the profile next to the cache it protects, which the profile already holds.
4
//! `msal.cache.encryption`. A session cookie dies with the page, so every restart made MSAL create
5
//! a new key, drop the cache and ask for sign-in again. While the page is signed in, the cookie
6
//! gets an expiry instead; the key then sits in the profile next to the cache it protects, which
7
//! the profile already holds. The managed Chromium path also does this once more on a graceful
8
//! stop as a second chance.
8
9
//!
9
10
//! Trade-off: the key moves from a session cookie into the profile's cookie store, encrypted by
10
//! the OS keyring (or Chromium's fixed key where no keyring is available). The profile already
11
//! the OS keyring (or the browser's fixed key where no keyring is available). The profile already
11
12
//! holds the equally powerful ESTS cookies that keep the session alive, so this is a conscious
12
13
//! choice, not a new credential at rest.
13
14
14
use serde_json::{Map, Value, json};
15
15
use std::collections::HashSet;
16
16
17
use serde_json::{Map, Value, json};
18
17
19
/// The cookie MSAL.js reads its cache encryption key from; only its name and value matter to it.
18
20
const MSAL_KEY_COOKIE: &str = "msal.cache.encryption";
19
21
/// How long the key outlives the last stop; every stop renews the expiry. 90 days is the chosen
@@ -37,7 +39,7 @@ const CARRIED_FIELDS: [&str; 10] = [
37
39
/// `Storage.setCookies` parameters for the current MSAL key cookies. Duplicates by
38
40
/// `(domain, path, partitionKey)` are collapsed, preferring host-only cookies over stale domain
39
41
/// cookies that could otherwise shadow the active key.
40
pub(crate) fn persisted_key_cookies(get_cookies: &Value, now_secs: u64) -> Option<Value> {
42
pub fn persisted_key_cookies(get_cookies: &Value, now_secs: u64) -> Option<Value> {
41
43
let expires = now_secs + KEY_LIFETIME_SECS;
42
44
let mut candidates: Vec<&Value> = get_cookies["cookies"]
43
45
.as_array()?
@@ -1,19 +1,21 @@1
//! Keeps the key of the Teams token cache across browser restarts (issue #84).1
//! Keeps the key of the Teams token cache across app restarts (issue #84).2
//!2
//!3
//! MSAL.js encrypts its localStorage cache with a key held in the session cookie3
//! MSAL.js encrypts its localStorage cache with a key held in the session cookie4
//! `msal.cache.encryption`. A session cookie dies with the process, so every restart (headless4
//! `msal.cache.encryption`. A session cookie dies with the page, so every restart made MSAL create5
//! hand-over, login window, hung renderer, app exit) made MSAL create a new key, drop the cache5
//! a new key, drop the cache and ask for sign-in again. While the page is signed in, the cookie6
//! and ask for sign-in again. Before Chromium stops, the cookie gets an expiry instead; the key6
//! gets an expiry instead; the key then sits in the profile next to the cache it protects, which7
//! then sits in the profile next to the cache it protects, which the profile already holds.7
//! the profile already holds. The managed Chromium path also does this once more on a graceful8
//! stop as a second chance.8
//!9
//!9
//! Trade-off: the key moves from a session cookie into the profile's cookie store, encrypted by10
//! Trade-off: the key moves from a session cookie into the profile's cookie store, encrypted by10
//! the OS keyring (or Chromium's fixed key where no keyring is available). The profile already11
//! the OS keyring (or the browser's fixed key where no keyring is available). The profile already11
//! holds the equally powerful ESTS cookies that keep the session alive, so this is a conscious12
//! holds the equally powerful ESTS cookies that keep the session alive, so this is a conscious12
//! choice, not a new credential at rest.13
//! choice, not a new credential at rest.13
14
14
use serde_json::{Map, Value, json};15
use std::collections::HashSet;15
use std::collections::HashSet;16
16
17
use serde_json::{Map, Value, json};18
17
/// The cookie MSAL.js reads its cache encryption key from; only its name and value matter to it.19
/// The cookie MSAL.js reads its cache encryption key from; only its name and value matter to it.18
const MSAL_KEY_COOKIE: &str = "msal.cache.encryption";20
const MSAL_KEY_COOKIE: &str = "msal.cache.encryption";19
/// How long the key outlives the last stop; every stop renews the expiry. 90 days is the chosen21
/// How long the key outlives the last stop; every stop renews the expiry. 90 days is the chosen@@ -37,7 +39,7 @@ const CARRIED_FIELDS: [&str; 10] = [37
/// `Storage.setCookies` parameters for the current MSAL key cookies. Duplicates by39
/// `Storage.setCookies` parameters for the current MSAL key cookies. Duplicates by38
/// `(domain, path, partitionKey)` are collapsed, preferring host-only cookies over stale domain40
/// `(domain, path, partitionKey)` are collapsed, preferring host-only cookies over stale domain39
/// cookies that could otherwise shadow the active key.41
/// cookies that could otherwise shadow the active key.40
pub(crate) fn persisted_key_cookies(get_cookies: &Value, now_secs: u64) -> Option<Value> {42
pub fn persisted_key_cookies(get_cookies: &Value, now_secs: u64) -> Option<Value> {41
let expires = now_secs + KEY_LIFETIME_SECS;43
let expires = now_secs + KEY_LIFETIME_SECS;42
let mut candidates: Vec<&Value> = get_cookies["cookies"]44
let mut candidates: Vec<&Value> = get_cookies["cookies"]43
.as_array()?45
.as_array()?@@ -7,7 +7,7 @@ use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
7
7
use futures_util::future::join_all;
8
8
use serde_json::{Value, json};
9
9
10
use crate::app::App;
10
use crate::app::{App, is_on_origin};
11
11
use crate::request::{ApiResponse, Method, Request};
12
12
use crate::scope::Scope;
13
13
use crate::session::Session;
@@ -249,7 +249,7 @@ fn eligible(request: &Request) -> bool {
249
249
fn needs_page_cookies(url: &str) -> bool {
250
250
App::ALL.iter().any(|&app| {
251
251
app.origins().iter().any(|origin| {
252
same_origin(url, origin)
252
is_on_origin(url, origin)
253
253
&& !(app == App::Teams
254
254
&& TEAMS_BEARER_PATHS
255
255
.iter()
@@ -258,11 +258,6 @@ fn needs_page_cookies(url: &str) -> bool {
258
258
})
259
259
}
260
260
261
fn same_origin(url: &str, origin: &str) -> bool {
262
url.strip_prefix(origin)
263
.is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?', '#']))
264
}
265
266
261
fn method(method: Method) -> reqwest::Method {
267
262
match method {
268
263
Method::Get => reqwest::Method::GET,
@@ -7,7 +7,7 @@ use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};7
use futures_util::future::join_all;7
use futures_util::future::join_all;8
use serde_json::{Value, json};8
use serde_json::{Value, json};9
9
10
use crate::app::App;10
use crate::app::{App, is_on_origin};11
use crate::request::{ApiResponse, Method, Request};11
use crate::request::{ApiResponse, Method, Request};12
use crate::scope::Scope;12
use crate::scope::Scope;13
use crate::session::Session;13
use crate::session::Session;@@ -249,7 +249,7 @@ fn eligible(request: &Request) -> bool {249
fn needs_page_cookies(url: &str) -> bool {249
fn needs_page_cookies(url: &str) -> bool {250
App::ALL.iter().any(|&app| {250
App::ALL.iter().any(|&app| {251
app.origins().iter().any(|origin| {251
app.origins().iter().any(|origin| {252
same_origin(url, origin)252
is_on_origin(url, origin)253
&& !(app == App::Teams253
&& !(app == App::Teams254
&& TEAMS_BEARER_PATHS254
&& TEAMS_BEARER_PATHS255
.iter()255
.iter()@@ -258,11 +258,6 @@ fn needs_page_cookies(url: &str) -> bool {258
})258
})259
}259
}260
260
261
fn same_origin(url: &str, origin: &str) -> bool {262
url.strip_prefix(origin)263
.is_some_and(|rest| rest.is_empty() || rest.starts_with(['/', '?', '#']))264
}265
266
fn method(method: Method) -> reqwest::Method {261
fn method(method: Method) -> reqwest::Method {267
match method {262
match method {268
Method::Get => reqwest::Method::GET,263
Method::Get => reqwest::Method::GET,@@ -1,6 +1,6 @@
1
1
use std::collections::{HashMap, HashSet};
2
use std::sync::Arc;
3
2
use std::sync::atomic::{AtomicBool, Ordering};
3
use std::sync::{Arc, LazyLock};
4
4
use std::time::Duration;
5
5
6
6
use serde_json::{Value, json};
@@ -14,9 +14,12 @@ use crate::native::NativeHttp;
14
14
use crate::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult};
15
15
use crate::scope::Scope;
16
16
use crate::transport::{CdpTransport, Transport};
17
use crate::trusted_url::may_carry_credentials;
17
18
18
19
pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:9222";
19
pub(crate) const FETCH_SCRIPT: &str = include_str!("../assets/fetch.js");
20
pub const UNSEAL_SCRIPT: &str = include_str!("../assets/unseal.js");
21
pub(crate) static FETCH_SCRIPT: LazyLock<String> =
22
LazyLock::new(|| include_str!("../assets/fetch.js").replace("__UNSEAL__", UNSEAL_SCRIPT));
20
23
pub(crate) const NOT_GRANTED_PREFIX: &str = "the app is not granted";
21
24
const MAX_DOWNLOAD_BYTES: u64 = 60 * 1024 * 1024;
22
25
const DEFAULT_CONCURRENCY: usize = 6;
@@ -146,11 +149,22 @@ impl Session {
146
149
Ok(response)
147
150
}
148
151
152
/// Requests with credentials to a host outside [`crate::trusted_url::MICROSOFT_HOSTS`] answer status 0 and are never sent.
149
153
pub async fn batch(&self, requests: &[Request], scope: &Scope) -> Result<Vec<ApiResponse>> {
150
154
let mut results: Vec<Option<ApiResponse>> = vec![None; requests.len()];
151
let mut pending: Vec<usize> = (0..requests.len()).collect();
155
let mut pending: Vec<usize> = Vec::with_capacity(requests.len());
156
for (index, request) in requests.iter().enumerate() {
157
if request.anonymous || may_carry_credentials(&request.url) {
158
pending.push(index);
159
} else {
160
results[index] = Some(refused_untrusted_host());
161
}
162
}
152
163
let mut forced_here = false;
153
164
for attempt in 0..=self.config.max_throttle_retries {
165
if pending.is_empty() {
166
break;
167
}
154
168
let batch: Vec<&Request> = pending.iter().map(|&index| &requests[index]).collect();
155
169
let answers = match self.run_with_fresh_token(&batch, scope).await {
156
170
Ok(answers) => answers,
@@ -278,7 +292,7 @@ impl Session {
278
292
search: &mut TokenSearch,
279
293
) -> Result<Option<Vec<ApiResponse>>> {
280
294
let payload = self.payload(requests, scope);
281
let expression = format!("({FETCH_SCRIPT})({payload})");
295
let expression = format!("({})({payload})", FETCH_SCRIPT.as_str());
282
296
let has_write = requests.iter().any(|request| request.method != Method::Get);
283
297
for app in App::ALL {
284
298
let outcome = match self.evaluate_in(app, &expression).await {
@@ -332,6 +346,60 @@ impl Session {
332
346
.to_string()
333
347
}
334
348
349
/// Runs one CDP method in the app tab, opening the tab when needed.
350
pub(crate) async fn cdp_in(
351
&self,
352
app: App,
353
method: &str,
354
params: Value,
355
) -> Result<Option<Value>> {
356
let mut slot = self.tabs[&app].lock().await;
357
if slot.is_none() {
358
let Some((control, _)) = self.transport.open(app, false).await? else {
359
return Ok(None);
360
};
361
*slot = Some(control);
362
}
363
let control = slot.as_ref().expect("connection set above");
364
let outcome = control.call(method, params).await;
365
if outcome.is_err() {
366
*slot = None;
367
}
368
outcome.map(Some)
369
}
370
371
/// Whether [`Session::persist_msal_key`] can run on this transport.
372
pub fn can_persist_msal_key(&self) -> bool {
373
self.transport.supports_cdp()
374
}
375
376
/// Gives MSAL's session-cookie cache key an expiry so the next start can still read the token
377
/// cache. Works over CDP for WebView2 and for a managed Chrome session.
378
pub async fn persist_msal_key(&self) -> Result<bool> {
379
if !self.can_persist_msal_key() {
380
return Ok(false);
381
}
382
let now_secs = std::time::SystemTime::now()
383
.duration_since(std::time::UNIX_EPOCH)
384
.map_or(0, |elapsed| elapsed.as_secs());
385
let Some(cookies) = self
386
.cdp_in(App::Teams, "Storage.getCookies", json!({}))
387
.await?
388
else {
389
return Ok(false);
390
};
391
let Some(params) = crate::msal_key::persisted_key_cookies(&cookies, now_secs) else {
392
return Ok(false);
393
};
394
let Some(_) = self
395
.cdp_in(App::Teams, "Storage.setCookies", params)
396
.await?
397
else {
398
return Ok(false);
399
};
400
Ok(true)
401
}
402
335
403
pub(crate) async fn evaluate_in(&self, app: App, expression: &str) -> Result<Option<Value>> {
336
404
let mut slot = self.tabs[&app].lock().await;
337
405
if slot.is_none() {
@@ -378,6 +446,14 @@ impl Drop for TabHold {
378
446
}
379
447
}
380
448
449
fn refused_untrusted_host() -> ApiResponse {
450
ApiResponse {
451
status: 0,
452
body: Value::String("refused: credentials only go to Microsoft hosts over https".into()),
453
retry_after: None,
454
}
455
}
456
381
457
fn native_http(config: &SessionConfig) -> Option<Arc<NativeHttp>> {
382
458
config
383
459
.native_http
@@ -427,6 +503,24 @@ mod tests {
427
503
}
428
504
}
429
505
506
#[tokio::test]
507
async fn credentials_never_leave_for_a_foreign_host() {
508
let session =
509
Session::with_transport(Arc::new(HoldRecorder::default()), SessionConfig::default())
510
.await
511
.unwrap();
512
let answers = session
513
.batch(
514
&[Request::binary_get(
515
"https://evil.com\\.asyncgw.teams.microsoft.com/x",
516
)],
517
&Scope::graph("x"),
518
)
519
.await
520
.unwrap();
521
assert_eq!(answers[0].status, 0);
522
}
523
430
524
#[tokio::test]
431
525
async fn tab_hold_releases_the_tab_when_dropped() {
432
526
let recorder = Arc::new(HoldRecorder::default());
@@ -1,6 +1,6 @@1
use std::collections::{HashMap, HashSet};1
use std::collections::{HashMap, HashSet};2
use std::sync::Arc;3
use std::sync::atomic::{AtomicBool, Ordering};2
use std::sync::atomic::{AtomicBool, Ordering};3
use std::sync::{Arc, LazyLock};4
use std::time::Duration;4
use std::time::Duration;5
5
6
use serde_json::{Value, json};6
use serde_json::{Value, json};@@ -14,9 +14,12 @@ use crate::native::NativeHttp;14
use crate::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult};14
use crate::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult};15
use crate::scope::Scope;15
use crate::scope::Scope;16
use crate::transport::{CdpTransport, Transport};16
use crate::transport::{CdpTransport, Transport};17
use crate::trusted_url::may_carry_credentials;17
18
18
pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:9222";19
pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:9222";19
pub(crate) const FETCH_SCRIPT: &str = include_str!("../assets/fetch.js");20
pub const UNSEAL_SCRIPT: &str = include_str!("../assets/unseal.js");21
pub(crate) static FETCH_SCRIPT: LazyLock<String> =22
LazyLock::new(|| include_str!("../assets/fetch.js").replace("__UNSEAL__", UNSEAL_SCRIPT));20
pub(crate) const NOT_GRANTED_PREFIX: &str = "the app is not granted";23
pub(crate) const NOT_GRANTED_PREFIX: &str = "the app is not granted";21
const MAX_DOWNLOAD_BYTES: u64 = 60 * 1024 * 1024;24
const MAX_DOWNLOAD_BYTES: u64 = 60 * 1024 * 1024;22
const DEFAULT_CONCURRENCY: usize = 6;25
const DEFAULT_CONCURRENCY: usize = 6;@@ -146,11 +149,22 @@ impl Session {146
Ok(response)149
Ok(response)147
}150
}148
151
152
/// Requests with credentials to a host outside [`crate::trusted_url::MICROSOFT_HOSTS`] answer status 0 and are never sent.149
pub async fn batch(&self, requests: &[Request], scope: &Scope) -> Result<Vec<ApiResponse>> {153
pub async fn batch(&self, requests: &[Request], scope: &Scope) -> Result<Vec<ApiResponse>> {150
let mut results: Vec<Option<ApiResponse>> = vec![None; requests.len()];154
let mut results: Vec<Option<ApiResponse>> = vec![None; requests.len()];151
let mut pending: Vec<usize> = (0..requests.len()).collect();155
let mut pending: Vec<usize> = Vec::with_capacity(requests.len());156
for (index, request) in requests.iter().enumerate() {157
if request.anonymous || may_carry_credentials(&request.url) {158
pending.push(index);159
} else {160
results[index] = Some(refused_untrusted_host());161
}162
}152
let mut forced_here = false;163
let mut forced_here = false;153
for attempt in 0..=self.config.max_throttle_retries {164
for attempt in 0..=self.config.max_throttle_retries {165
if pending.is_empty() {166
break;167
}154
let batch: Vec<&Request> = pending.iter().map(|&index| &requests[index]).collect();168
let batch: Vec<&Request> = pending.iter().map(|&index| &requests[index]).collect();155
let answers = match self.run_with_fresh_token(&batch, scope).await {169
let answers = match self.run_with_fresh_token(&batch, scope).await {156
Ok(answers) => answers,170
Ok(answers) => answers,@@ -278,7 +292,7 @@ impl Session {278
search: &mut TokenSearch,292
search: &mut TokenSearch,279
) -> Result<Option<Vec<ApiResponse>>> {293
) -> Result<Option<Vec<ApiResponse>>> {280
let payload = self.payload(requests, scope);294
let payload = self.payload(requests, scope);281
let expression = format!("({FETCH_SCRIPT})({payload})");295
let expression = format!("({})({payload})", FETCH_SCRIPT.as_str());282
let has_write = requests.iter().any(|request| request.method != Method::Get);296
let has_write = requests.iter().any(|request| request.method != Method::Get);283
for app in App::ALL {297
for app in App::ALL {284
let outcome = match self.evaluate_in(app, &expression).await {298
let outcome = match self.evaluate_in(app, &expression).await {@@ -332,6 +346,60 @@ impl Session {332
.to_string()346
.to_string()333
}347
}334
348
349
/// Runs one CDP method in the app tab, opening the tab when needed.350
pub(crate) async fn cdp_in(351
&self,352
app: App,353
method: &str,354
params: Value,355
) -> Result<Option<Value>> {356
let mut slot = self.tabs[&app].lock().await;357
if slot.is_none() {358
let Some((control, _)) = self.transport.open(app, false).await? else {359
return Ok(None);360
};361
*slot = Some(control);362
}363
let control = slot.as_ref().expect("connection set above");364
let outcome = control.call(method, params).await;365
if outcome.is_err() {366
*slot = None;367
}368
outcome.map(Some)369
}370
371
/// Whether [`Session::persist_msal_key`] can run on this transport.372
pub fn can_persist_msal_key(&self) -> bool {373
self.transport.supports_cdp()374
}375
376
/// Gives MSAL's session-cookie cache key an expiry so the next start can still read the token377
/// cache. Works over CDP for WebView2 and for a managed Chrome session.378
pub async fn persist_msal_key(&self) -> Result<bool> {379
if !self.can_persist_msal_key() {380
return Ok(false);381
}382
let now_secs = std::time::SystemTime::now()383
.duration_since(std::time::UNIX_EPOCH)384
.map_or(0, |elapsed| elapsed.as_secs());385
let Some(cookies) = self386
.cdp_in(App::Teams, "Storage.getCookies", json!({}))387
.await?388
else {389
return Ok(false);390
};391
let Some(params) = crate::msal_key::persisted_key_cookies(&cookies, now_secs) else {392
return Ok(false);393
};394
let Some(_) = self395
.cdp_in(App::Teams, "Storage.setCookies", params)396
.await?397
else {398
return Ok(false);399
};400
Ok(true)401
}402
335
pub(crate) async fn evaluate_in(&self, app: App, expression: &str) -> Result<Option<Value>> {403
pub(crate) async fn evaluate_in(&self, app: App, expression: &str) -> Result<Option<Value>> {336
let mut slot = self.tabs[&app].lock().await;404
let mut slot = self.tabs[&app].lock().await;337
if slot.is_none() {405
if slot.is_none() {@@ -378,6 +446,14 @@ impl Drop for TabHold {378
}446
}379
}447
}380
448
449
fn refused_untrusted_host() -> ApiResponse {450
ApiResponse {451
status: 0,452
body: Value::String("refused: credentials only go to Microsoft hosts over https".into()),453
retry_after: None,454
}455
}456
381
fn native_http(config: &SessionConfig) -> Option<Arc<NativeHttp>> {457
fn native_http(config: &SessionConfig) -> Option<Arc<NativeHttp>> {382
config458
config383
.native_http459
.native_http@@ -427,6 +503,24 @@ mod tests {427
}503
}428
}504
}429
505
506
#[tokio::test]507
async fn credentials_never_leave_for_a_foreign_host() {508
let session =509
Session::with_transport(Arc::new(HoldRecorder::default()), SessionConfig::default())510
.await511
.unwrap();512
let answers = session513
.batch(514
&[Request::binary_get(515
"https://evil.com\\.asyncgw.teams.microsoft.com/x",516
)],517
&Scope::graph("x"),518
)519
.await520
.unwrap();521
assert_eq!(answers[0].status, 0);522
}523
430
#[tokio::test]524
#[tokio::test]431
async fn tab_hold_releases_the_tab_when_dropped() {525
async fn tab_hold_releases_the_tab_when_dropped() {432
let recorder = Arc::new(HoldRecorder::default());526
let recorder = Arc::new(HoldRecorder::default());@@ -29,6 +29,12 @@ pub trait Transport: Send + Sync {
29
29
30
30
fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>>;
31
31
32
/// Whether the transport accepts raw CDP methods. WebDriver BiDi does not, so session-level
33
/// CDP work such as the MSAL cookie must stay off it.
34
fn supports_cdp(&self) -> bool {
35
true
36
}
37
32
38
/// While held the host must not navigate the app on its own (no parking).
33
39
fn hold(&self, _app: App, _held: bool) {}
34
40
}
@@ -73,7 +79,10 @@ impl Transport for CdpTransport {
73
79
open(target.websocket_url.as_deref().unwrap_or_default(), false).await?;
74
80
if parked {
75
81
control
76
.call("Page.navigate", json!({"url": app.start_url()}))
82
.call(
83
"Page.navigate",
84
json!({"url": app.start_url_like(&target.url)}),
85
)
77
86
.await?;
78
87
} else {
79
88
control
@@ -29,6 +29,12 @@ pub trait Transport: Send + Sync {29
29
30
fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>>;30
fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>>;31
31
32
/// Whether the transport accepts raw CDP methods. WebDriver BiDi does not, so session-level33
/// CDP work such as the MSAL cookie must stay off it.34
fn supports_cdp(&self) -> bool {35
true36
}37
32
/// While held the host must not navigate the app on its own (no parking).38
/// While held the host must not navigate the app on its own (no parking).33
fn hold(&self, _app: App, _held: bool) {}39
fn hold(&self, _app: App, _held: bool) {}34
}40
}@@ -73,7 +79,10 @@ impl Transport for CdpTransport {73
open(target.websocket_url.as_deref().unwrap_or_default(), false).await?;79
open(target.websocket_url.as_deref().unwrap_or_default(), false).await?;74
if parked {80
if parked {75
control81
control76
.call("Page.navigate", json!({"url": app.start_url()}))82
.call(83
"Page.navigate",84
json!({"url": app.start_url_like(&target.url)}),85
)77
.await?;86
.await?;78
} else {87
} else {79
control88
control@@ -0,0 +1,145 @@
1
use url::Url;
2
3
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4
pub enum HostRule {
5
Exact(&'static str),
6
Domain(&'static str),
7
}
8
9
impl HostRule {
10
fn allows(self, host: &str) -> bool {
11
match self {
12
HostRule::Exact(name) => host == name,
13
HostRule::Domain(domain) => {
14
host == domain
15
|| host
16
.strip_suffix(domain)
17
.is_some_and(|prefix| prefix.len() > 1 && prefix.ends_with('.'))
18
}
19
}
20
}
21
}
22
23
pub const MICROSOFT_HOSTS: [HostRule; 12] = [
24
HostRule::Domain("microsoft.com"),
25
HostRule::Domain("cloud.microsoft"),
26
HostRule::Domain("microsoft365.com"),
27
HostRule::Domain("microsoftonline.com"),
28
HostRule::Domain("office.com"),
29
HostRule::Domain("office.net"),
30
HostRule::Domain("office365.com"),
31
HostRule::Domain("skype.com"),
32
HostRule::Domain("sharepoint.com"),
33
HostRule::Domain("onedrive.com"),
34
HostRule::Domain("live.com"),
35
HostRule::Domain("mcas.ms"),
36
];
37
38
/// The parsed URL when `raw` is plain HTTPS to a host one of `rules` allows: no user info, no explicit port.
39
/// Callers send the returned URL, never `raw`, so the host that was checked is the host that is contacted.
40
pub fn trusted_https_url(raw: &str, rules: &[HostRule]) -> Option<Url> {
41
let url = Url::parse(raw).ok()?;
42
let host = url.host_str()?;
43
let plain = url.scheme() == "https"
44
&& url.username().is_empty()
45
&& url.password().is_none()
46
&& url.port().is_none();
47
(plain && rules.iter().any(|rule| rule.allows(host))).then_some(url)
48
}
49
50
pub fn is_trusted_https_url(raw: &str, rules: &[HostRule]) -> bool {
51
trusted_https_url(raw, rules).is_some()
52
}
53
54
pub fn may_carry_credentials(raw: &str) -> bool {
55
is_trusted_https_url(raw, &MICROSOFT_HOSTS) || is_websocket_to(raw, &MICROSOFT_HOSTS)
56
}
57
58
fn is_websocket_to(raw: &str, rules: &[HostRule]) -> bool {
59
Url::parse(raw).ok().is_some_and(|url| {
60
url.scheme() == "wss"
61
&& url.username().is_empty()
62
&& url.password().is_none()
63
&& url.port().is_none()
64
&& url
65
.host_str()
66
.is_some_and(|host| rules.iter().any(|rule| rule.allows(host)))
67
})
68
}
69
70
#[cfg(test)]
71
mod tests {
72
use super::*;
73
74
const AMS: [HostRule; 1] = [HostRule::Domain("asm.skype.com")];
75
76
#[test]
77
fn plain_https_to_an_allowed_host_passes() {
78
let url = trusted_https_url("https://eu-api.asm.skype.com/v1/objects/a", &AMS).unwrap();
79
assert_eq!(url.host_str(), Some("eu-api.asm.skype.com"));
80
assert!(is_trusted_https_url("https://asm.skype.com/x", &AMS));
81
assert!(is_trusted_https_url("https://EU.ASM.Skype.com/x", &AMS));
82
}
83
84
#[test]
85
fn separator_tricks_do_not_pass() {
86
for raw in [
87
"https://evil.example\\.asm.skype.com/v1/objects/a",
88
"https://evil.example#.asm.skype.com/v1/objects/a",
89
"https://evil.example?.asm.skype.com/v1/objects/a",
90
"https://evil.example/.asm.skype.com/v1/objects/a",
91
"https://a.asm.skype.com:x@evil.example/",
92
"https://a.asm.skype.com@evil.example/",
93
"https://user@a.asm.skype.com/",
94
"https://a.asm.skype.com:8443/",
95
"https://evilasm.skype.com/",
96
"https://asm.skype.com.evil.example/",
97
"https://.asm.skype.com/",
98
"http://a.asm.skype.com/",
99
"//a.asm.skype.com/",
100
"javascript:alert(1)//a.asm.skype.com",
101
"not a url",
102
] {
103
assert!(!is_trusted_https_url(raw, &AMS), "{raw}");
104
}
105
}
106
107
#[test]
108
fn the_checked_host_is_the_host_that_gets_contacted() {
109
let url = trusted_https_url("https://a.asm.skype.com/x?y#z", &AMS).unwrap();
110
assert_eq!(url.as_str(), "https://a.asm.skype.com/x?y#z");
111
}
112
113
#[test]
114
fn exact_rules_match_only_that_host() {
115
let rules = [HostRule::Exact("teams.microsoft.com")];
116
assert!(is_trusted_https_url(
117
"https://teams.microsoft.com/x",
118
&rules
119
));
120
assert!(!is_trusted_https_url(
121
"https://a.teams.microsoft.com/x",
122
&rules
123
));
124
}
125
126
#[test]
127
fn credentials_go_only_to_microsoft_hosts() {
128
assert!(may_carry_credentials("https://graph.microsoft.com/v1.0/me"));
129
assert!(may_carry_credentials(
130
"https://teams.cloud.microsoft/api/mt/emea/beta/users"
131
));
132
assert!(may_carry_credentials("https://contoso.sharepoint.com/x"));
133
assert!(may_carry_credentials(
134
"wss://go.trouter.teams.microsoft.com/v4"
135
));
136
assert!(may_carry_credentials(
137
"https://teams.cloud.microsoft.mcas.ms/api/mt/emea/beta/users"
138
));
139
assert!(!may_carry_credentials("https://evil.com\\.microsoft.com/"));
140
assert!(!may_carry_credentials("https://microsoft.com.evil.com/"));
141
assert!(!may_carry_credentials("https://evil.com/"));
142
assert!(!may_carry_credentials("http://graph.microsoft.com/v1.0/me"));
143
assert!(!may_carry_credentials("wss://evil.com/"));
144
}
145
}
@@ -0,0 +1,145 @@1
use url::Url;2
3
#[derive(Debug, Clone, Copy, PartialEq, Eq)]4
pub enum HostRule {5
Exact(&'static str),6
Domain(&'static str),7
}8
9
impl HostRule {10
fn allows(self, host: &str) -> bool {11
match self {12
HostRule::Exact(name) => host == name,13
HostRule::Domain(domain) => {14
host == domain15
|| host16
.strip_suffix(domain)17
.is_some_and(|prefix| prefix.len() > 1 && prefix.ends_with('.'))18
}19
}20
}21
}22
23
pub const MICROSOFT_HOSTS: [HostRule; 12] = [24
HostRule::Domain("microsoft.com"),25
HostRule::Domain("cloud.microsoft"),26
HostRule::Domain("microsoft365.com"),27
HostRule::Domain("microsoftonline.com"),28
HostRule::Domain("office.com"),29
HostRule::Domain("office.net"),30
HostRule::Domain("office365.com"),31
HostRule::Domain("skype.com"),32
HostRule::Domain("sharepoint.com"),33
HostRule::Domain("onedrive.com"),34
HostRule::Domain("live.com"),35
HostRule::Domain("mcas.ms"),36
];37
38
/// The parsed URL when `raw` is plain HTTPS to a host one of `rules` allows: no user info, no explicit port.39
/// Callers send the returned URL, never `raw`, so the host that was checked is the host that is contacted.40
pub fn trusted_https_url(raw: &str, rules: &[HostRule]) -> Option<Url> {41
let url = Url::parse(raw).ok()?;42
let host = url.host_str()?;43
let plain = url.scheme() == "https"44
&& url.username().is_empty()45
&& url.password().is_none()46
&& url.port().is_none();47
(plain && rules.iter().any(|rule| rule.allows(host))).then_some(url)48
}49
50
pub fn is_trusted_https_url(raw: &str, rules: &[HostRule]) -> bool {51
trusted_https_url(raw, rules).is_some()52
}53
54
pub fn may_carry_credentials(raw: &str) -> bool {55
is_trusted_https_url(raw, &MICROSOFT_HOSTS) || is_websocket_to(raw, &MICROSOFT_HOSTS)56
}57
58
fn is_websocket_to(raw: &str, rules: &[HostRule]) -> bool {59
Url::parse(raw).ok().is_some_and(|url| {60
url.scheme() == "wss"61
&& url.username().is_empty()62
&& url.password().is_none()63
&& url.port().is_none()64
&& url65
.host_str()66
.is_some_and(|host| rules.iter().any(|rule| rule.allows(host)))67
})68
}69
70
#[cfg(test)]71
mod tests {72
use super::*;73
74
const AMS: [HostRule; 1] = [HostRule::Domain("asm.skype.com")];75
76
#[test]77
fn plain_https_to_an_allowed_host_passes() {78
let url = trusted_https_url("https://eu-api.asm.skype.com/v1/objects/a", &AMS).unwrap();79
assert_eq!(url.host_str(), Some("eu-api.asm.skype.com"));80
assert!(is_trusted_https_url("https://asm.skype.com/x", &AMS));81
assert!(is_trusted_https_url("https://EU.ASM.Skype.com/x", &AMS));82
}83
84
#[test]85
fn separator_tricks_do_not_pass() {86
for raw in [87
"https://evil.example\\.asm.skype.com/v1/objects/a",88
"https://evil.example#.asm.skype.com/v1/objects/a",89
"https://evil.example?.asm.skype.com/v1/objects/a",90
"https://evil.example/.asm.skype.com/v1/objects/a",91
"https://a.asm.skype.com:x@evil.example/",92
"https://a.asm.skype.com@evil.example/",93
"https://user@a.asm.skype.com/",94
"https://a.asm.skype.com:8443/",95
"https://evilasm.skype.com/",96
"https://asm.skype.com.evil.example/",97
"https://.asm.skype.com/",98
"http://a.asm.skype.com/",99
"//a.asm.skype.com/",100
"javascript:alert(1)//a.asm.skype.com",101
"not a url",102
] {103
assert!(!is_trusted_https_url(raw, &AMS), "{raw}");104
}105
}106
107
#[test]108
fn the_checked_host_is_the_host_that_gets_contacted() {109
let url = trusted_https_url("https://a.asm.skype.com/x?y#z", &AMS).unwrap();110
assert_eq!(url.as_str(), "https://a.asm.skype.com/x?y#z");111
}112
113
#[test]114
fn exact_rules_match_only_that_host() {115
let rules = [HostRule::Exact("teams.microsoft.com")];116
assert!(is_trusted_https_url(117
"https://teams.microsoft.com/x",118
&rules119
));120
assert!(!is_trusted_https_url(121
"https://a.teams.microsoft.com/x",122
&rules123
));124
}125
126
#[test]127
fn credentials_go_only_to_microsoft_hosts() {128
assert!(may_carry_credentials("https://graph.microsoft.com/v1.0/me"));129
assert!(may_carry_credentials(130
"https://teams.cloud.microsoft/api/mt/emea/beta/users"131
));132
assert!(may_carry_credentials("https://contoso.sharepoint.com/x"));133
assert!(may_carry_credentials(134
"wss://go.trouter.teams.microsoft.com/v4"135
));136
assert!(may_carry_credentials(137
"https://teams.cloud.microsoft.mcas.ms/api/mt/emea/beta/users"138
));139
assert!(!may_carry_credentials("https://evil.com\\.microsoft.com/"));140
assert!(!may_carry_credentials("https://microsoft.com.evil.com/"));141
assert!(!may_carry_credentials("https://evil.com/"));142
assert!(!may_carry_credentials("http://graph.microsoft.com/v1.0/me"));143
assert!(!may_carry_credentials("wss://evil.com/"));144
}145
}@@ -9,7 +9,7 @@ pub(crate) fn tab_state(app: App, url: &str) -> &'static str {
9
9
"parked"
10
10
} else if is_login_url(url) {
11
11
"login"
12
} else if app.origins().iter().any(|origin| url.starts_with(origin)) {
12
} else if app.is_app_url(url) {
13
13
"app"
14
14
} else if url.starts_with("about:") {
15
15
"about"
@@ -9,7 +9,7 @@ pub(crate) fn tab_state(app: App, url: &str) -> &'static str {9
"parked"9
"parked"10
} else if is_login_url(url) {10
} else if is_login_url(url) {11
"login"11
"login"12
} else if app.origins().iter().any(|origin| url.starts_with(origin)) {12
} else if app.is_app_url(url) {13
"app"13
"app"14
} else if url.starts_with("about:") {14
} else if url.starts_with("about:") {15
"about"15
"about"@@ -190,7 +190,7 @@ fn create_windows(title: &str) -> windows::core::Result<HashMap<App, HWND>> {
190
190
}
191
191
192
192
fn load(shared: &Rc<Shared>) {
193
match create_views(shared, |app| app.start_url()) {
193
match create_views(shared, |app| app.start_url(false)) {
194
194
Ok(()) => shared.state.send_modify(|state| {
195
195
state.ready = true;
196
196
state.failure = None;
@@ -333,7 +333,7 @@ fn watch_loads(webview: &ICoreWebView2, app: App) -> windows::core::Result<()> {
333
333
}
334
334
335
335
fn is_running_app(app: App, url: &str) -> bool {
336
app.origins().iter().any(|origin| url.starts_with(origin)) && !app.is_park_url(url)
336
app.is_app_url(url) && !app.is_park_url(url)
337
337
}
338
338
339
339
fn park(shared: &Shared, app: App) {
@@ -342,7 +342,7 @@ fn park(shared: &Shared, app: App) {
342
342
{
343
343
set_memory_level(&webview, COREWEBVIEW2_MEMORY_USAGE_TARGET_LEVEL_LOW);
344
344
unsafe {
345
let _ = webview.Navigate(&HSTRING::from(app.park_url()));
345
let _ = webview.Navigate(&HSTRING::from(app.park_url(false)));
346
346
}
347
347
}
348
348
}
@@ -443,7 +443,7 @@ fn source_of(webview: &ICoreWebView2) -> String {
443
443
fn on_source_changed(shared: &Shared, app: App, url: String) {
444
444
let window = shared.windows[&app];
445
445
let login = is_login_url(&url);
446
let on_app = app.origins().iter().any(|origin| url.starts_with(origin));
446
let on_app = app.is_app_url(&url);
447
447
shared.state.send_modify(|state| {
448
448
state.urls.insert(app, url);
449
449
});
@@ -593,7 +593,7 @@ fn wake(shared: &Rc<Shared>, app: App) {
593
593
let _ = if is_running_app(app, &url) {
594
594
webview.Reload()
595
595
} else {
596
webview.Navigate(&HSTRING::from(app.start_url()))
596
webview.Navigate(&HSTRING::from(app.start_url(false)))
597
597
};
598
598
}
599
599
}
@@ -715,9 +715,9 @@ fn wake_views(shared: &Rc<Shared>, full: Option<App>) {
715
715
});
716
716
let outcome = create_views(shared, |app| {
717
717
if Some(app) == full {
718
app.start_url()
718
app.start_url(false)
719
719
} else {
720
app.park_url()
720
app.park_url(false)
721
721
}
722
722
});
723
723
if let Err(reason) = outcome {
@@ -190,7 +190,7 @@ fn create_windows(title: &str) -> windows::core::Result<HashMap<App, HWND>> {190
}190
}191
191
192
fn load(shared: &Rc<Shared>) {192
fn load(shared: &Rc<Shared>) {193
match create_views(shared, |app| app.start_url()) {193
match create_views(shared, |app| app.start_url(false)) {194
Ok(()) => shared.state.send_modify(|state| {194
Ok(()) => shared.state.send_modify(|state| {195
state.ready = true;195
state.ready = true;196
state.failure = None;196
state.failure = None;@@ -333,7 +333,7 @@ fn watch_loads(webview: &ICoreWebView2, app: App) -> windows::core::Result<()> {333
}333
}334
334
335
fn is_running_app(app: App, url: &str) -> bool {335
fn is_running_app(app: App, url: &str) -> bool {336
app.origins().iter().any(|origin| url.starts_with(origin)) && !app.is_park_url(url)336
app.is_app_url(url) && !app.is_park_url(url)337
}337
}338
338
339
fn park(shared: &Shared, app: App) {339
fn park(shared: &Shared, app: App) {@@ -342,7 +342,7 @@ fn park(shared: &Shared, app: App) {342
{342
{343
set_memory_level(&webview, COREWEBVIEW2_MEMORY_USAGE_TARGET_LEVEL_LOW);343
set_memory_level(&webview, COREWEBVIEW2_MEMORY_USAGE_TARGET_LEVEL_LOW);344
unsafe {344
unsafe {345
let _ = webview.Navigate(&HSTRING::from(app.park_url()));345
let _ = webview.Navigate(&HSTRING::from(app.park_url(false)));346
}346
}347
}347
}348
}348
}@@ -443,7 +443,7 @@ fn source_of(webview: &ICoreWebView2) -> String {443
fn on_source_changed(shared: &Shared, app: App, url: String) {443
fn on_source_changed(shared: &Shared, app: App, url: String) {444
let window = shared.windows[&app];444
let window = shared.windows[&app];445
let login = is_login_url(&url);445
let login = is_login_url(&url);446
let on_app = app.origins().iter().any(|origin| url.starts_with(origin));446
let on_app = app.is_app_url(&url);447
shared.state.send_modify(|state| {447
shared.state.send_modify(|state| {448
state.urls.insert(app, url);448
state.urls.insert(app, url);449
});449
});@@ -593,7 +593,7 @@ fn wake(shared: &Rc<Shared>, app: App) {593
let _ = if is_running_app(app, &url) {593
let _ = if is_running_app(app, &url) {594
webview.Reload()594
webview.Reload()595
} else {595
} else {596
webview.Navigate(&HSTRING::from(app.start_url()))596
webview.Navigate(&HSTRING::from(app.start_url(false)))597
};597
};598
}598
}599
}599
}@@ -715,9 +715,9 @@ fn wake_views(shared: &Rc<Shared>, full: Option<App>) {715
});715
});716
let outcome = create_views(shared, |app| {716
let outcome = create_views(shared, |app| {717
if Some(app) == full {717
if Some(app) == full {718
app.start_url()718
app.start_url(false)719
} else {719
} else {720
app.park_url()720
app.park_url(false)721
}721
}722
});722
});723
if let Err(reason) = outcome {723
if let Err(reason) = outcome {@@ -449,7 +449,7 @@ fn shadow_calls(webview: &ICoreWebView2) -> windows::core::Result<()> {
449
449
}
450
450
}
451
451
452
fn block_app_launch(webview: &ICoreWebView2) -> windows::core::Result<()> {
452
pub(crate) fn block_app_launch(webview: &ICoreWebView2) -> windows::core::Result<()> {
453
453
let Ok(webview) = webview.cast::<ICoreWebView2_18>() else {
454
454
return Ok(());
455
455
};
@@ -449,7 +449,7 @@ fn shadow_calls(webview: &ICoreWebView2) -> windows::core::Result<()> {449
}449
}450
}450
}451
451
452
fn block_app_launch(webview: &ICoreWebView2) -> windows::core::Result<()> {452
pub(crate) fn block_app_launch(webview: &ICoreWebView2) -> windows::core::Result<()> {453
let Ok(webview) = webview.cast::<ICoreWebView2_18>() else {453
let Ok(webview) = webview.cast::<ICoreWebView2_18>() else {454
return Ok(());454
return Ok(());455
};455
};@@ -3,12 +3,13 @@ use std::path::PathBuf;
3
3
use std::rc::{Rc, Weak};
4
4
use std::sync::Once;
5
5
6
use session::trusted_url::{MICROSOFT_HOSTS, is_trusted_https_url};
6
7
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
7
8
use webview2_com::Microsoft::Web::WebView2::Win32::*;
8
9
use webview2_com::{
9
10
CreateCoreWebView2ControllerCompletedHandler, CreateCoreWebView2EnvironmentCompletedHandler,
10
NavigationCompletedEventHandler, NewWindowRequestedEventHandler, SourceChangedEventHandler,
11
take_pwstr,
11
NavigationCompletedEventHandler, NavigationStartingEventHandler,
12
NewWindowRequestedEventHandler, SourceChangedEventHandler, take_pwstr,
12
13
};
13
14
use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};
14
15
use windows::Win32::Graphics::Gdi::{
@@ -18,11 +19,12 @@ use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};
18
19
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
19
20
use windows::Win32::UI::Shell::{DefSubclassProc, SetWindowSubclass};
20
21
use windows::Win32::UI::WindowsAndMessaging::*;
21
use windows::core::{HRESULT, HSTRING, Interface, PCWSTR, PWSTR, w};
22
use windows::core::{BOOL, HRESULT, HSTRING, Interface, PCWSTR, PWSTR, w};
22
23
23
24
use crate::embed::{EmbedEvent, EmbedSpec};
24
25
use crate::geometry::{EmbedBounds, local_cutouts};
25
26
use crate::host::environment_options;
27
use crate::host_dialog::block_app_launch;
26
28
27
29
const CONTAINER_CLASS: PCWSTR = w!("RustyTeamsEmbedContainer");
28
30
const OWNER_SUBCLASS_ID: usize = 0x5254_4542;
@@ -243,6 +245,8 @@ fn attach(embed: &SharedEmbed, controller: ICoreWebView2Controller) -> windows::
243
245
})?;
244
246
webview.Settings()?.SetIsStatusBarEnabled(false)?;
245
247
}
248
keep_on_microsoft_hosts(&webview)?;
249
block_app_launch(&webview)?;
246
250
watch_source(&webview, events.clone())?;
247
251
watch_loaded(&webview, events.clone())?;
248
252
forward_new_windows(&webview, events)?;
@@ -441,6 +445,23 @@ fn watch_source(
441
445
unsafe { webview.add_SourceChanged(&handler, &mut token) }
442
446
}
443
447
448
/// The embed shares the Teams profile and its single sign-on, so it may only show Microsoft pages.
449
fn keep_on_microsoft_hosts(webview: &ICoreWebView2) -> windows::core::Result<()> {
450
let handler = NavigationStartingEventHandler::create(Box::new(|_, arguments| {
451
let Some(arguments) = arguments else {
452
return Ok(());
453
};
454
let mut target = PWSTR::null();
455
unsafe { arguments.Uri(&mut target) }?;
456
if !is_trusted_https_url(&take_pwstr(target), &MICROSOFT_HOSTS) {
457
unsafe { arguments.SetCancel(true) }?;
458
}
459
Ok(())
460
}));
461
let mut token = 0;
462
unsafe { webview.add_NavigationStarting(&handler, &mut token) }
463
}
464
444
465
fn watch_loaded(
445
466
webview: &ICoreWebView2,
446
467
events: UnboundedSender<EmbedEvent>,
@@ -462,11 +483,16 @@ fn forward_new_windows(
462
483
return Ok(());
463
484
};
464
485
let mut target = PWSTR::null();
486
let mut user_initiated = BOOL::default();
465
487
unsafe {
466
488
arguments.Uri(&mut target)?;
489
arguments.IsUserInitiated(&mut user_initiated)?;
467
490
arguments.SetHandled(true)?;
468
491
}
469
let _ = events.send(EmbedEvent::NewWindow(take_pwstr(target)));
492
let target = take_pwstr(target);
493
if user_initiated.as_bool() {
494
let _ = events.send(EmbedEvent::NewWindow(target));
495
}
470
496
Ok(())
471
497
}));
472
498
let mut token = 0;
@@ -3,12 +3,13 @@ use std::path::PathBuf;3
use std::rc::{Rc, Weak};3
use std::rc::{Rc, Weak};4
use std::sync::Once;4
use std::sync::Once;5
5
6
use session::trusted_url::{MICROSOFT_HOSTS, is_trusted_https_url};6
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};7
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};7
use webview2_com::Microsoft::Web::WebView2::Win32::*;8
use webview2_com::Microsoft::Web::WebView2::Win32::*;8
use webview2_com::{9
use webview2_com::{9
CreateCoreWebView2ControllerCompletedHandler, CreateCoreWebView2EnvironmentCompletedHandler,10
CreateCoreWebView2ControllerCompletedHandler, CreateCoreWebView2EnvironmentCompletedHandler,10
NavigationCompletedEventHandler, NewWindowRequestedEventHandler, SourceChangedEventHandler,11
NavigationCompletedEventHandler, NavigationStartingEventHandler,11
take_pwstr,12
NewWindowRequestedEventHandler, SourceChangedEventHandler, take_pwstr,12
};13
};13
use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};14
use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};14
use windows::Win32::Graphics::Gdi::{15
use windows::Win32::Graphics::Gdi::{@@ -18,11 +19,12 @@ use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};18
use windows::Win32::System::LibraryLoader::GetModuleHandleW;19
use windows::Win32::System::LibraryLoader::GetModuleHandleW;19
use windows::Win32::UI::Shell::{DefSubclassProc, SetWindowSubclass};20
use windows::Win32::UI::Shell::{DefSubclassProc, SetWindowSubclass};20
use windows::Win32::UI::WindowsAndMessaging::*;21
use windows::Win32::UI::WindowsAndMessaging::*;21
use windows::core::{HRESULT, HSTRING, Interface, PCWSTR, PWSTR, w};22
use windows::core::{BOOL, HRESULT, HSTRING, Interface, PCWSTR, PWSTR, w};22
23
23
use crate::embed::{EmbedEvent, EmbedSpec};24
use crate::embed::{EmbedEvent, EmbedSpec};24
use crate::geometry::{EmbedBounds, local_cutouts};25
use crate::geometry::{EmbedBounds, local_cutouts};25
use crate::host::environment_options;26
use crate::host::environment_options;27
use crate::host_dialog::block_app_launch;26
28
27
const CONTAINER_CLASS: PCWSTR = w!("RustyTeamsEmbedContainer");29
const CONTAINER_CLASS: PCWSTR = w!("RustyTeamsEmbedContainer");28
const OWNER_SUBCLASS_ID: usize = 0x5254_4542;30
const OWNER_SUBCLASS_ID: usize = 0x5254_4542;@@ -243,6 +245,8 @@ fn attach(embed: &SharedEmbed, controller: ICoreWebView2Controller) -> windows::243
})?;245
})?;244
webview.Settings()?.SetIsStatusBarEnabled(false)?;246
webview.Settings()?.SetIsStatusBarEnabled(false)?;245
}247
}248
keep_on_microsoft_hosts(&webview)?;249
block_app_launch(&webview)?;246
watch_source(&webview, events.clone())?;250
watch_source(&webview, events.clone())?;247
watch_loaded(&webview, events.clone())?;251
watch_loaded(&webview, events.clone())?;248
forward_new_windows(&webview, events)?;252
forward_new_windows(&webview, events)?;@@ -441,6 +445,23 @@ fn watch_source(441
unsafe { webview.add_SourceChanged(&handler, &mut token) }445
unsafe { webview.add_SourceChanged(&handler, &mut token) }442
}446
}443
447
448
/// The embed shares the Teams profile and its single sign-on, so it may only show Microsoft pages.449
fn keep_on_microsoft_hosts(webview: &ICoreWebView2) -> windows::core::Result<()> {450
let handler = NavigationStartingEventHandler::create(Box::new(|_, arguments| {451
let Some(arguments) = arguments else {452
return Ok(());453
};454
let mut target = PWSTR::null();455
unsafe { arguments.Uri(&mut target) }?;456
if !is_trusted_https_url(&take_pwstr(target), &MICROSOFT_HOSTS) {457
unsafe { arguments.SetCancel(true) }?;458
}459
Ok(())460
}));461
let mut token = 0;462
unsafe { webview.add_NavigationStarting(&handler, &mut token) }463
}464
444
fn watch_loaded(465
fn watch_loaded(445
webview: &ICoreWebView2,466
webview: &ICoreWebView2,446
events: UnboundedSender<EmbedEvent>,467
events: UnboundedSender<EmbedEvent>,@@ -462,11 +483,16 @@ fn forward_new_windows(462
return Ok(());483
return Ok(());463
};484
};464
let mut target = PWSTR::null();485
let mut target = PWSTR::null();486
let mut user_initiated = BOOL::default();465
unsafe {487
unsafe {466
arguments.Uri(&mut target)?;488
arguments.Uri(&mut target)?;489
arguments.IsUserInitiated(&mut user_initiated)?;467
arguments.SetHandled(true)?;490
arguments.SetHandled(true)?;468
}491
}469
let _ = events.send(EmbedEvent::NewWindow(take_pwstr(target)));492
let target = take_pwstr(target);493
if user_initiated.as_bool() {494
let _ = events.send(EmbedEvent::NewWindow(target));495
}470
Ok(())496
Ok(())471
}));497
}));472
let mut token = 0;498
let mut token = 0;@@ -15,9 +15,11 @@ Options were: env vars only, a settings field for the client id, or one project
15
15
16
16
Official release builds compile in the project Desktop client id (and optional secret) via `option_env!`. Runtime env vars still override for developers. Users only click Connect Google; tokens stay on the device (see ADR 0002). Release CI must supply the client id at compile time so Dock and Start Menu launches are not Outlook-only by accident.
17
17
18
A client id and secret saved in Settings override both the environment and this compiled client (ADR 0024). When those fields are empty, this decision still applies.
19
18
20
## Consequences
19
21
20
22
- Connect works from a Dock-started macOS `.app` and from Windows/Linux installers without a terminal.
21
23
- The project owns the Google Cloud consent screen and verification path for the sensitive `calendar` scope.
22
24
- Local `cargo run` without the secret stays Outlook-only unless the developer exports the env vars.
23
- The client id is visible in the binary; the secret must never appear in UI, logs, or the store.
25
- The client id is visible in the binary; the secret must never appear in UI, logs, or the store. A secret the user types is stored in the OS keyring (ADR 0024) and is not shown again after save.
@@ -15,9 +15,11 @@ Options were: env vars only, a settings field for the client id, or one project15
15
16
Official release builds compile in the project Desktop client id (and optional secret) via `option_env!`. Runtime env vars still override for developers. Users only click Connect Google; tokens stay on the device (see ADR 0002). Release CI must supply the client id at compile time so Dock and Start Menu launches are not Outlook-only by accident.16
Official release builds compile in the project Desktop client id (and optional secret) via `option_env!`. Runtime env vars still override for developers. Users only click Connect Google; tokens stay on the device (see ADR 0002). Release CI must supply the client id at compile time so Dock and Start Menu launches are not Outlook-only by accident.17
17
18
A client id and secret saved in Settings override both the environment and this compiled client (ADR 0024). When those fields are empty, this decision still applies.19
18
## Consequences20
## Consequences19
21
20
- Connect works from a Dock-started macOS `.app` and from Windows/Linux installers without a terminal.22
- Connect works from a Dock-started macOS `.app` and from Windows/Linux installers without a terminal.21
- The project owns the Google Cloud consent screen and verification path for the sensitive `calendar` scope.23
- The project owns the Google Cloud consent screen and verification path for the sensitive `calendar` scope.22
- Local `cargo run` without the secret stays Outlook-only unless the developer exports the env vars.24
- Local `cargo run` without the secret stays Outlook-only unless the developer exports the env vars.23
- The client id is visible in the binary; the secret must never appear in UI, logs, or the store.25
- The client id is visible in the binary; the secret must never appear in UI, logs, or the store. A secret the user types is stored in the OS keyring (ADR 0024) and is not shown again after save.@@ -0,0 +1,24 @@
1
---
2
status: proposed
3
date: 2026-11-27
4
superseded-by:
5
---
6
7
# ADR 0024: Google OAuth client in Settings
8
9
## Context
10
11
ADR 0009 compiles one Desktop client into release builds so Connect Google works from a Dock or Start Menu launch. That still leaves anyone who wants their own Google Cloud client rebuilding the app or exporting shell variables. A settings field was rejected in 0009 because it would have been the only path.
12
13
## Decision
14
15
Settings › Calendar accounts accepts a client id and client secret, with a short guide for a Desktop client. The pair is used for Connect and token refresh only when both are saved. The id is store metadata. The secret is in the OS keyring under `rusty-teams.google-oauth`, never in the calendar account document, never in logs, and never put back into the field. Clearing the id removes the pair.
16
17
Empty settings keep ADR 0009: runtime environment, then the compiled client. Release builds stay unchanged.
18
19
## Consequences
20
21
- A person can use their own Google Cloud project without a rebuild.
22
- Official builds still connect with one click when the fields are empty.
23
- Tokens issued for the previous client do not refresh after a switch. The save notice says to connect again; the app does not disconnect on its own.
24
- The compiled client id remains visible in release binaries, as in ADR 0009.
@@ -0,0 +1,24 @@1
---2
status: proposed3
date: 2026-11-274
superseded-by:5
---6
7
# ADR 0024: Google OAuth client in Settings8
9
## Context10
11
ADR 0009 compiles one Desktop client into release builds so Connect Google works from a Dock or Start Menu launch. That still leaves anyone who wants their own Google Cloud client rebuilding the app or exporting shell variables. A settings field was rejected in 0009 because it would have been the only path.12
13
## Decision14
15
Settings › Calendar accounts accepts a client id and client secret, with a short guide for a Desktop client. The pair is used for Connect and token refresh only when both are saved. The id is store metadata. The secret is in the OS keyring under `rusty-teams.google-oauth`, never in the calendar account document, never in logs, and never put back into the field. Clearing the id removes the pair.16
17
Empty settings keep ADR 0009: runtime environment, then the compiled client. Release builds stay unchanged.18
19
## Consequences20
21
- A person can use their own Google Cloud project without a rebuild.22
- Official builds still connect with one click when the fields are empty.23
- Tokens issued for the previous client do not refresh after a switch. The save notice says to connect again; the app does not disconnect on its own.24
- The compiled client id remains visible in release binaries, as in ADR 0009.@@ -3,7 +3,7 @@ status: proposed
3
3
date: 2026-11-28
4
4
---
5
5
6
# ADR 0024: KVT fork, Business Central cards through sleutels.kvt.nl
6
# ADR 0025: KVT fork, Business Central cards through sleutels.kvt.nl
7
7
8
8
This record belongs to the KVT fork (`KVT-FORK.md`), not to upstream.
9
9
@@ -3,7 +3,7 @@ status: proposed3
date: 2026-11-283
date: 2026-11-284
---4
---5
5
6
# ADR 0024: KVT fork, Business Central cards through sleutels.kvt.nl6
# ADR 0025: KVT fork, Business Central cards through sleutels.kvt.nl7
7
8
This record belongs to the KVT fork (`KVT-FORK.md`), not to upstream.8
This record belongs to the KVT fork (`KVT-FORK.md`), not to upstream.9
9
@@ -39,6 +39,7 @@ Statuses: `proposed`, `accepted`, `superseded`.
39
39
| [0021](0021-linux-packages.md) | Linux releases also ship an AppImage, a deb and an rpm |
40
40
| [0022](0022-linux-parks-the-idle-teams-tab.md) | Linux parks the idle Teams tab in a Chromium browser |
41
41
| [0023](0023-calendar-slot-selection-for-new-meetings.md) | Picking empty calendar slots for a new meeting |
42
| [0024](0024-kvt-cards-and-sleutels-link.md) | KVT fork: Business Central cards through sleutels.kvt.nl |
42
| [0024](0024-google-oauth-client-in-settings.md) | A saved Google OAuth client in Settings overrides the built-in client |
43
| [0025](0025-kvt-cards-and-sleutels-link.md) | KVT fork: Business Central cards through sleutels.kvt.nl |
43
44
44
Records `0001` to `0021` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
45
Records `0001` to `0021` are the decisions already shipped. `0024` and `0025` are proposed. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.
@@ -39,6 +39,7 @@ Statuses: `proposed`, `accepted`, `superseded`.39
| [0021](0021-linux-packages.md) | Linux releases also ship an AppImage, a deb and an rpm |39
| [0021](0021-linux-packages.md) | Linux releases also ship an AppImage, a deb and an rpm |40
| [0022](0022-linux-parks-the-idle-teams-tab.md) | Linux parks the idle Teams tab in a Chromium browser |40
| [0022](0022-linux-parks-the-idle-teams-tab.md) | Linux parks the idle Teams tab in a Chromium browser |41
| [0023](0023-calendar-slot-selection-for-new-meetings.md) | Picking empty calendar slots for a new meeting |41
| [0023](0023-calendar-slot-selection-for-new-meetings.md) | Picking empty calendar slots for a new meeting |42
| [0024](0024-kvt-cards-and-sleutels-link.md) | KVT fork: Business Central cards through sleutels.kvt.nl |42
| [0024](0024-google-oauth-client-in-settings.md) | A saved Google OAuth client in Settings overrides the built-in client |43
| [0025](0025-kvt-cards-and-sleutels-link.md) | KVT fork: Business Central cards through sleutels.kvt.nl |43
44
44
Records `0001` to `0021` are the decisions already shipped. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.45
Records `0001` to `0021` are the decisions already shipped. `0024` and `0025` are proposed. `0001` follows Daniel's call-window note in `GUARDRAILS.md`.@@ -16,6 +16,7 @@ Run on a real Mac (`.app` from `scripts/build-macos.sh` or a release zip). Unit
16
16
3. Pick a display or window: share banner shows; stop share leaves the call up.
17
17
4. Cancel the picker: no share, call stays connected, no error toast.
18
18
5. Prefer a second person for 1:1 ring / accept when available (ROADMAP still Partial without that).
19
6. Camera on, no blur, standout, auto framing, brightness, or soft focus, and no share, for one minute. The call report (`host load`, every two seconds) names the threads that used CPU, says those effects are off, and states thermal state `nominal`, `fair`, `serious`, or `critical`. The next capture change follows the hottest thread in that report. This minute is the gate; it is not a substitute for guessing a GPU path.
19
20
20
21
## Desktop integration
21
22
@@ -16,6 +16,7 @@ Run on a real Mac (`.app` from `scripts/build-macos.sh` or a release zip). Unit16
3. Pick a display or window: share banner shows; stop share leaves the call up.16
3. Pick a display or window: share banner shows; stop share leaves the call up.17
4. Cancel the picker: no share, call stays connected, no error toast.17
4. Cancel the picker: no share, call stays connected, no error toast.18
5. Prefer a second person for 1:1 ring / accept when available (ROADMAP still Partial without that).18
5. Prefer a second person for 1:1 ring / accept when available (ROADMAP still Partial without that).19
6. Camera on, no blur, standout, auto framing, brightness, or soft focus, and no share, for one minute. The call report (`host load`, every two seconds) names the threads that used CPU, says those effects are off, and states thermal state `nominal`, `fair`, `serious`, or `critical`. The next capture change follows the hottest thread in that report. This minute is the gate; it is not a substitute for guessing a GPU path.19
20
20
## Desktop integration21
## Desktop integration21
22
@@ -26,6 +26,7 @@ pkgbase = kvt-rusty-teams
26
26
depends = libxcb
27
27
depends = wayland
28
28
depends = alsa-lib
29
depends = libpulse
29
30
depends = libpipewire
30
31
depends = libva
31
32
depends = glib2
@@ -26,6 +26,7 @@ pkgbase = kvt-rusty-teams26
depends = libxcb26
depends = libxcb27
depends = wayland27
depends = wayland28
depends = alsa-lib28
depends = alsa-lib29
depends = libpulse29
depends = libpipewire30
depends = libpipewire30
depends = libva31
depends = libva31
depends = glib232
depends = glib2@@ -12,7 +12,7 @@ arch=('x86_64')
12
12
url='https://git.kvt.nl/ict/rusty-teams'
13
13
license=('MIT')
14
14
depends=('glibc' 'gcc-libs' 'fontconfig' 'freetype2' 'libxkbcommon' 'libxkbcommon-x11'
15
'libx11' 'libxcb' 'wayland' 'alsa-lib' 'libpipewire' 'libva' 'glib2' 'hicolor-icon-theme')
15
'libx11' 'libxcb' 'wayland' 'alsa-lib' 'libpulse' 'libpipewire' 'libva' 'glib2' 'hicolor-icon-theme')
16
16
makedepends=('cargo' 'clang' 'mold' 'git' 'pkgconf' 'python'
17
17
'libxext' 'libxfixes' 'libxdamage' 'libxrandr' 'libxcomposite')
18
18
options=('!lto' '!debug')
@@ -12,7 +12,7 @@ arch=('x86_64')12
url='https://git.kvt.nl/ict/rusty-teams'12
url='https://git.kvt.nl/ict/rusty-teams'13
license=('MIT')13
license=('MIT')14
depends=('glibc' 'gcc-libs' 'fontconfig' 'freetype2' 'libxkbcommon' 'libxkbcommon-x11'14
depends=('glibc' 'gcc-libs' 'fontconfig' 'freetype2' 'libxkbcommon' 'libxkbcommon-x11'15
'libx11' 'libxcb' 'wayland' 'alsa-lib' 'libpipewire' 'libva' 'glib2' 'hicolor-icon-theme')15
'libx11' 'libxcb' 'wayland' 'alsa-lib' 'libpulse' 'libpipewire' 'libva' 'glib2' 'hicolor-icon-theme')16
makedepends=('cargo' 'clang' 'mold' 'git' 'pkgconf' 'python'16
makedepends=('cargo' 'clang' 'mold' 'git' 'pkgconf' 'python'17
'libxext' 'libxfixes' 'libxdamage' 'libxrandr' 'libxcomposite')17
'libxext' 'libxfixes' 'libxdamage' 'libxrandr' 'libxcomposite')18
options=('!lto' '!debug')18
options=('!lto' '!debug')@@ -10,7 +10,7 @@ arch=('x86_64')
10
10
url='https://git.kvt.nl/ict/rusty-teams'
11
11
license=('MIT')
12
12
depends=('glibc' 'gcc-libs' 'fontconfig' 'freetype2' 'libxkbcommon' 'libxkbcommon-x11'
13
'libx11' 'libxcb' 'wayland' 'alsa-lib' 'libpipewire' 'libva' 'glib2' 'hicolor-icon-theme')
13
'libx11' 'libxcb' 'wayland' 'alsa-lib' 'libpulse' 'libpipewire' 'libva' 'glib2' 'hicolor-icon-theme')
14
14
provides=('rusty-teams')
15
15
conflicts=('rusty-teams' 'rusty-teams-bin' 'rusty-teams-git')
16
16
options=('!strip' '!debug')
@@ -10,7 +10,7 @@ arch=('x86_64')10
url='https://git.kvt.nl/ict/rusty-teams'10
url='https://git.kvt.nl/ict/rusty-teams'11
license=('MIT')11
license=('MIT')12
depends=('glibc' 'gcc-libs' 'fontconfig' 'freetype2' 'libxkbcommon' 'libxkbcommon-x11'12
depends=('glibc' 'gcc-libs' 'fontconfig' 'freetype2' 'libxkbcommon' 'libxkbcommon-x11'13
'libx11' 'libxcb' 'wayland' 'alsa-lib' 'libpipewire' 'libva' 'glib2' 'hicolor-icon-theme')13
'libx11' 'libxcb' 'wayland' 'alsa-lib' 'libpulse' 'libpipewire' 'libva' 'glib2' 'hicolor-icon-theme')14
provides=('rusty-teams')14
provides=('rusty-teams')15
conflicts=('rusty-teams' 'rusty-teams-bin' 'rusty-teams-git')15
conflicts=('rusty-teams' 'rusty-teams-bin' 'rusty-teams-git')16
options=('!strip' '!debug')16
options=('!strip' '!debug')@@ -21,7 +21,7 @@ apt-get install -y -qq --no-install-recommends \
21
21
ca-certificates curl git gnupg lsb-release wget \
22
22
build-essential binutils file python3 unzip xz-utils patch jq \
23
23
clang mold pkg-config libclang-dev \
24
libglib2.0-dev libfontconfig-dev libasound2-dev libva-dev \
24
libglib2.0-dev libfontconfig-dev libasound2-dev libpulse-dev libva-dev \
25
25
libxkbcommon-dev libxkbcommon-x11-dev \
26
26
libx11-dev libxcb1-dev libxext-dev libxfixes-dev libxdamage-dev \
27
27
libxrandr-dev libxcomposite-dev libwayland-dev libpipewire-0.3-dev \
@@ -21,7 +21,7 @@ apt-get install -y -qq --no-install-recommends \21
ca-certificates curl git gnupg lsb-release wget \21
ca-certificates curl git gnupg lsb-release wget \22
build-essential binutils file python3 unzip xz-utils patch jq \22
build-essential binutils file python3 unzip xz-utils patch jq \23
clang mold pkg-config libclang-dev \23
clang mold pkg-config libclang-dev \24
libglib2.0-dev libfontconfig-dev libasound2-dev libva-dev \24
libglib2.0-dev libfontconfig-dev libasound2-dev libpulse-dev libva-dev \25
libxkbcommon-dev libxkbcommon-x11-dev \25
libxkbcommon-dev libxkbcommon-x11-dev \26
libx11-dev libxcb1-dev libxext-dev libxfixes-dev libxdamage-dev \26
libx11-dev libxcb1-dev libxext-dev libxfixes-dev libxdamage-dev \27
libxrandr-dev libxcomposite-dev libwayland-dev libpipewire-0.3-dev \27
libxrandr-dev libxcomposite-dev libwayland-dev libpipewire-0.3-dev \@@ -27,12 +27,13 @@ conflicts:
27
27
- teams
28
28
29
29
# Linked directly (ELF NEEDED): glibc, libstdc++, libgcc_s, glib/gio/gobject, ALSA, fontconfig,
30
# freetype, xcb, xkbcommon and xkbcommon-x11. Loaded at runtime with dlopen, so the package
31
# tools can't see them: Wayland (libwayland-client) and X11 (libX11) for the window, Vulkan or
32
# EGL for wgpu. libwebrtc dlopens the rest only for calls (PulseAudio, PipeWire for Wayland
33
# screen sharing, VA-API/GBM/DRM for hardware video, the X11 extensions for X11 screen
34
# capture), so those are recommended rather than required. The Teams session runs in the
35
# user's own browser, suggested below.
30
# freetype, xcb, xkbcommon, xkbcommon-x11, libpulse and libpulse-simple. Call tones link Pulse
31
# at build time, so a host without those sonames cannot start the binary. Loaded at runtime
32
# with dlopen, so the package tools can't see them: Wayland (libwayland-client) and X11
33
# (libX11) for the window, Vulkan or EGL for wgpu. libwebrtc dlopens the rest only for calls
34
# (PipeWire for Wayland screen sharing, VA-API/GBM/DRM for hardware video, the X11 extensions
35
# for X11 screen capture), so those stay recommended. The Teams session runs in the user's
36
# own browser, suggested below.
36
37
overrides:
37
38
deb:
38
39
depends:
@@ -49,11 +50,11 @@ overrides:
49
50
- libwayland-client0
50
51
- libx11-6
51
52
- libvulkan1 | libegl1
53
- libpulse0
52
54
recommends:
53
55
- mesa-vulkan-drivers
54
56
- libegl1
55
57
- libwayland-egl1
56
- libpulse0
57
58
- libpipewire-0.3-0
58
59
- libva2
59
60
- libva-drm2
@@ -85,9 +86,10 @@ overrides:
85
86
- libwayland-client.so.0()(64bit)
86
87
- libX11.so.6()(64bit)
87
88
- (libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))
89
- libpulse.so.0()(64bit)
90
- libpulse-simple.so.0()(64bit)
88
91
recommends:
89
92
- mesa-vulkan-drivers
90
- libpulse.so.0()(64bit)
91
93
- libpipewire-0.3.so.0()(64bit)
92
94
- libva.so.2()(64bit)
93
95
- libgbm.so.1()(64bit)
@@ -106,9 +108,9 @@ overrides:
106
108
- libx11
107
109
- vulkan-icd-loader
108
110
- libglvnd
111
- libpulse
109
112
recommends:
110
113
- mesa
111
- libpulse
112
114
- pipewire
113
115
- libva
114
116
- xdg-desktop-portal
@@ -27,12 +27,13 @@ conflicts:27
- teams27
- teams28
28
29
# Linked directly (ELF NEEDED): glibc, libstdc++, libgcc_s, glib/gio/gobject, ALSA, fontconfig,29
# Linked directly (ELF NEEDED): glibc, libstdc++, libgcc_s, glib/gio/gobject, ALSA, fontconfig,30
# freetype, xcb, xkbcommon and xkbcommon-x11. Loaded at runtime with dlopen, so the package30
# freetype, xcb, xkbcommon, xkbcommon-x11, libpulse and libpulse-simple. Call tones link Pulse31
# tools can't see them: Wayland (libwayland-client) and X11 (libX11) for the window, Vulkan or31
# at build time, so a host without those sonames cannot start the binary. Loaded at runtime32
# EGL for wgpu. libwebrtc dlopens the rest only for calls (PulseAudio, PipeWire for Wayland32
# with dlopen, so the package tools can't see them: Wayland (libwayland-client) and X1133
# screen sharing, VA-API/GBM/DRM for hardware video, the X11 extensions for X11 screen33
# (libX11) for the window, Vulkan or EGL for wgpu. libwebrtc dlopens the rest only for calls34
# capture), so those are recommended rather than required. The Teams session runs in the34
# (PipeWire for Wayland screen sharing, VA-API/GBM/DRM for hardware video, the X11 extensions35
# user's own browser, suggested below.35
# for X11 screen capture), so those stay recommended. The Teams session runs in the user's36
# own browser, suggested below.36
overrides:37
overrides:37
deb:38
deb:38
depends:39
depends:@@ -49,11 +50,11 @@ overrides:49
- libwayland-client050
- libwayland-client050
- libx11-651
- libx11-651
- libvulkan1 | libegl152
- libvulkan1 | libegl153
- libpulse052
recommends:54
recommends:53
- mesa-vulkan-drivers55
- mesa-vulkan-drivers54
- libegl156
- libegl155
- libwayland-egl157
- libwayland-egl156
- libpulse057
- libpipewire-0.3-058
- libpipewire-0.3-058
- libva259
- libva259
- libva-drm260
- libva-drm2@@ -85,9 +86,10 @@ overrides:85
- libwayland-client.so.0()(64bit)86
- libwayland-client.so.0()(64bit)86
- libX11.so.6()(64bit)87
- libX11.so.6()(64bit)87
- (libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))88
- (libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))89
- libpulse.so.0()(64bit)90
- libpulse-simple.so.0()(64bit)88
recommends:91
recommends:89
- mesa-vulkan-drivers92
- mesa-vulkan-drivers90
- libpulse.so.0()(64bit)91
- libpipewire-0.3.so.0()(64bit)93
- libpipewire-0.3.so.0()(64bit)92
- libva.so.2()(64bit)94
- libva.so.2()(64bit)93
- libgbm.so.1()(64bit)95
- libgbm.so.1()(64bit)@@ -106,9 +108,9 @@ overrides:106
- libx11108
- libx11107
- vulkan-icd-loader109
- vulkan-icd-loader108
- libglvnd110
- libglvnd111
- libpulse109
recommends:112
recommends:110
- mesa113
- mesa111
- libpulse112
- pipewire114
- pipewire113
- libva115
- libva114
- xdg-desktop-portal116
- xdg-desktop-portal@@ -34,6 +34,8 @@ Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in
34
34
| `src/input/editor/display_map/text_wrapper.rs`, `wrap_map.rs`, `display_map.rs` | `set_line_height()`, wrap measures every scale piece at its own size, rows taller than the line height are stored in `LineItem.blocks`, `_update(.., row_heights)` | wrap width and row tops follow the real glyph sizes |
35
35
| `src/input/editor/display_map/inline_line.rs` | `InlineFragment.placement` (paint offset and height), `InputLine.inline_offset` | fragments of a scaled row paint on one baseline; atomic tokens sit on it too |
36
36
| `src/input/base/element.rs` | `scale_font()`, `push_text_fragments()`; `layout_lines` / `layout_token_lines` build `InputLine::inline` rows for rows with scaled pieces, `prepaint_tokens` adds `inline_offset`, prepaint sets the wrapper line height | rows without scaled pieces keep the single `ShapedLine` path |
37
| `src/input/base/inline_tokens.rs`, `src/input/editor/display_map/text_wrapper.rs`, `src/input/base/element.rs`, `src/input/base/token_presentation.rs` | `InlineToken::header()` / `is_header()` (a block token), `InlineMetric.opens_row`; a header at a line end gets an empty row after it; a header is placed without the line indent and is offered the width up to `RIGHT_MARGIN` | a code block's header row in the composer, with the caret on the row below it even when the line has no text yet |
38
| `src/input/base/state.rs`, `src/input/base/element.rs` | `set_line_labels(Vec<(offset, SharedString)>, color)`; `paint_line_labels()` paints each label right-aligned before its offset, on the row that shows it | code line numbers in the line indent, without characters in the text |
37
39
| `src/tooltip.rs` | `TooltipRequest::while_alive(Weak<()>)`; the overlay drops content whose trigger token is gone, checked on render and on the next frame | the trigger's element state is dropped only after a frame without it, so the check runs one frame later |
38
40
39
41
## Limits
@@ -34,6 +34,8 @@ Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in34
| `src/input/editor/display_map/text_wrapper.rs`, `wrap_map.rs`, `display_map.rs` | `set_line_height()`, wrap measures every scale piece at its own size, rows taller than the line height are stored in `LineItem.blocks`, `_update(.., row_heights)` | wrap width and row tops follow the real glyph sizes |34
| `src/input/editor/display_map/text_wrapper.rs`, `wrap_map.rs`, `display_map.rs` | `set_line_height()`, wrap measures every scale piece at its own size, rows taller than the line height are stored in `LineItem.blocks`, `_update(.., row_heights)` | wrap width and row tops follow the real glyph sizes |35
| `src/input/editor/display_map/inline_line.rs` | `InlineFragment.placement` (paint offset and height), `InputLine.inline_offset` | fragments of a scaled row paint on one baseline; atomic tokens sit on it too |35
| `src/input/editor/display_map/inline_line.rs` | `InlineFragment.placement` (paint offset and height), `InputLine.inline_offset` | fragments of a scaled row paint on one baseline; atomic tokens sit on it too |36
| `src/input/base/element.rs` | `scale_font()`, `push_text_fragments()`; `layout_lines` / `layout_token_lines` build `InputLine::inline` rows for rows with scaled pieces, `prepaint_tokens` adds `inline_offset`, prepaint sets the wrapper line height | rows without scaled pieces keep the single `ShapedLine` path |36
| `src/input/base/element.rs` | `scale_font()`, `push_text_fragments()`; `layout_lines` / `layout_token_lines` build `InputLine::inline` rows for rows with scaled pieces, `prepaint_tokens` adds `inline_offset`, prepaint sets the wrapper line height | rows without scaled pieces keep the single `ShapedLine` path |37
| `src/input/base/inline_tokens.rs`, `src/input/editor/display_map/text_wrapper.rs`, `src/input/base/element.rs`, `src/input/base/token_presentation.rs` | `InlineToken::header()` / `is_header()` (a block token), `InlineMetric.opens_row`; a header at a line end gets an empty row after it; a header is placed without the line indent and is offered the width up to `RIGHT_MARGIN` | a code block's header row in the composer, with the caret on the row below it even when the line has no text yet |38
| `src/input/base/state.rs`, `src/input/base/element.rs` | `set_line_labels(Vec<(offset, SharedString)>, color)`; `paint_line_labels()` paints each label right-aligned before its offset, on the row that shows it | code line numbers in the line indent, without characters in the text |37
| `src/tooltip.rs` | `TooltipRequest::while_alive(Weak<()>)`; the overlay drops content whose trigger token is gone, checked on render and on the next frame | the trigger's element state is dropped only after a frame without it, so the check runs one frame later |39
| `src/tooltip.rs` | `TooltipRequest::while_alive(Weak<()>)`; the overlay drops content whose trigger token is gone, checked on render and on the next frame | the trigger's element state is dropped only after a frame without it, so the check runs one frame later |38
40
39
## Limits41
## Limits@@ -1863,6 +1863,7 @@ impl<M: InputModeKind> TextElement<M> {
1863
1863
range: span.range(),
1864
1864
width: token_size.width,
1865
1865
height: span.token().is_block().then_some(token_size.height),
1866
opens_row: span.token().is_header(),
1866
1867
})
1867
1868
})
1868
1869
.collect();
@@ -2102,11 +2103,16 @@ impl<M: InputModeKind> TextElement<M> {
2102
2103
{
2103
2104
let baseline_offset =
2104
2105
layout.lines[ix].inline_offset_at(position.y, layout.line_height);
2106
let header_shift = if span.token().is_header() {
2107
state.display_map.line_indent(start)
2108
} else {
2109
px(0.)
2110
};
2105
2111
placements.push((
2106
2112
state.token_context(span, layout.line_height, width),
2107
2113
bounds.origin
2108
2114
+ position
2109
+ point(layout.line_number_width, y + baseline_offset),
2115
+ point(layout.line_number_width - header_shift, y + baseline_offset),
2110
2116
));
2111
2117
}
2112
2118
}
@@ -2144,6 +2150,60 @@ impl<M: InputModeKind> TextElement<M> {
2144
2150
out
2145
2151
}
2146
2152
2153
fn paint_line_labels(
2154
&self,
2155
line: &LineLayout,
2156
row: usize,
2157
origin: Point<Pixels>,
2158
layout: &LastLayout,
2159
window: &mut Window,
2160
cx: &mut App,
2161
) {
2162
const GAP: f32 = 8.;
2163
let state = self.state.read(cx);
2164
if state.line_labels.is_empty() {
2165
return;
2166
}
2167
let start = state.text.line_start_offset(row);
2168
let end = state.text.line_end_offset(row);
2169
let first = state
2170
.line_labels
2171
.partition_point(|(offset, _)| *offset < start);
2172
let style = window.text_style();
2173
let font_size = style.font_size.to_pixels(window.rem_size());
2174
let labels: Vec<_> = state.line_labels[first..]
2175
.iter()
2176
.take_while(|(offset, _)| *offset <= end)
2177
.cloned()
2178
.collect();
2179
let color = state.line_label_color;
2180
for (offset, label) in labels {
2181
let Some(position) = line.position_for_index(offset - start, layout, false) else {
2182
continue;
2183
};
2184
let run = TextRun {
2185
len: label.len(),
2186
font: style.font(),
2187
color,
2188
background_color: None,
2189
underline: None,
2190
strikethrough: None,
2191
};
2192
let shaped = window
2193
.text_system()
2194
.shape_line(label, font_size, &[run], None);
2195
let x = position.x - px(GAP) - shaped.width;
2196
_ = shaped.paint(
2197
origin + point(x, position.y),
2198
layout.line_height,
2199
TextAlign::Left,
2200
None,
2201
window,
2202
cx,
2203
);
2204
}
2205
}
2206
2147
2207
#[allow(clippy::too_many_arguments)]
2148
2208
fn layout_lines(
2149
2209
state: &InputBaseState<M>,
@@ -3409,6 +3469,7 @@ impl<M: InputModeKind> Element for TextElement<M> {
3409
3469
window,
3410
3470
cx,
3411
3471
);
3472
self.paint_line_labels(line, row, p, &prepaint.last_layout, window, cx);
3412
3473
offset_y += line.size(line_height).height;
3413
3474
3414
3475
if Some(row) == prepaint.current_row {
@@ -1863,6 +1863,7 @@ impl<M: InputModeKind> TextElement<M> {1863
range: span.range(),1863
range: span.range(),1864
width: token_size.width,1864
width: token_size.width,1865
height: span.token().is_block().then_some(token_size.height),1865
height: span.token().is_block().then_some(token_size.height),1866
opens_row: span.token().is_header(),1866
})1867
})1867
})1868
})1868
.collect();1869
.collect();@@ -2102,11 +2103,16 @@ impl<M: InputModeKind> TextElement<M> {2102
{2103
{2103
let baseline_offset =2104
let baseline_offset =2104
layout.lines[ix].inline_offset_at(position.y, layout.line_height);2105
layout.lines[ix].inline_offset_at(position.y, layout.line_height);2106
let header_shift = if span.token().is_header() {2107
state.display_map.line_indent(start)2108
} else {2109
px(0.)2110
};2105
placements.push((2111
placements.push((2106
state.token_context(span, layout.line_height, width),2112
state.token_context(span, layout.line_height, width),2107
bounds.origin2113
bounds.origin2108
+ position2114
+ position2109
+ point(layout.line_number_width, y + baseline_offset),2115
+ point(layout.line_number_width - header_shift, y + baseline_offset),2110
));2116
));2111
}2117
}2112
}2118
}@@ -2144,6 +2150,60 @@ impl<M: InputModeKind> TextElement<M> {2144
out2150
out2145
}2151
}2146
2152
2153
fn paint_line_labels(2154
&self,2155
line: &LineLayout,2156
row: usize,2157
origin: Point<Pixels>,2158
layout: &LastLayout,2159
window: &mut Window,2160
cx: &mut App,2161
) {2162
const GAP: f32 = 8.;2163
let state = self.state.read(cx);2164
if state.line_labels.is_empty() {2165
return;2166
}2167
let start = state.text.line_start_offset(row);2168
let end = state.text.line_end_offset(row);2169
let first = state2170
.line_labels2171
.partition_point(|(offset, _)| *offset < start);2172
let style = window.text_style();2173
let font_size = style.font_size.to_pixels(window.rem_size());2174
let labels: Vec<_> = state.line_labels[first..]2175
.iter()2176
.take_while(|(offset, _)| *offset <= end)2177
.cloned()2178
.collect();2179
let color = state.line_label_color;2180
for (offset, label) in labels {2181
let Some(position) = line.position_for_index(offset - start, layout, false) else {2182
continue;2183
};2184
let run = TextRun {2185
len: label.len(),2186
font: style.font(),2187
color,2188
background_color: None,2189
underline: None,2190
strikethrough: None,2191
};2192
let shaped = window2193
.text_system()2194
.shape_line(label, font_size, &[run], None);2195
let x = position.x - px(GAP) - shaped.width;2196
_ = shaped.paint(2197
origin + point(x, position.y),2198
layout.line_height,2199
TextAlign::Left,2200
None,2201
window,2202
cx,2203
);2204
}2205
}2206
2147
#[allow(clippy::too_many_arguments)]2207
#[allow(clippy::too_many_arguments)]2148
fn layout_lines(2208
fn layout_lines(2149
state: &InputBaseState<M>,2209
state: &InputBaseState<M>,@@ -3409,6 +3469,7 @@ impl<M: InputModeKind> Element for TextElement<M> {3409
window,3469
window,3410
cx,3470
cx,3411
);3471
);3472
self.paint_line_labels(line, row, p, &prepaint.last_layout, window, cx);3412
offset_y += line.size(line_height).height;3473
offset_y += line.size(line_height).height;3413
3474
3414
if Some(row) == prepaint.current_row {3475
if Some(row) == prepaint.current_row {@@ -14,6 +14,7 @@ pub struct InlineToken {
14
14
text: SharedString,
15
15
label: SharedString,
16
16
block: bool,
17
header: bool,
17
18
}
18
19
19
20
impl InlineToken {
@@ -24,6 +25,7 @@ impl InlineToken {
24
25
label: text.clone(),
25
26
text,
26
27
block: false,
28
header: false,
27
29
}
28
30
}
29
31
pub fn with_label(mut self, label: impl Into<SharedString>) -> Self {
@@ -38,6 +40,16 @@ impl InlineToken {
38
40
pub fn is_block(&self) -> bool {
39
41
self.block
40
42
}
43
/// A block token that heads its line: it spans the row without the line indent, and
44
/// the rest of the line starts on the next row, also when it is empty.
45
pub fn header(mut self) -> Self {
46
self.block = true;
47
self.header = true;
48
self
49
}
50
pub fn is_header(&self) -> bool {
51
self.header
52
}
41
53
pub fn id(&self) -> &SharedString {
42
54
&self.id
43
55
}
@@ -14,6 +14,7 @@ pub struct InlineToken {14
text: SharedString,14
text: SharedString,15
label: SharedString,15
label: SharedString,16
block: bool,16
block: bool,17
header: bool,17
}18
}18
19
19
impl InlineToken {20
impl InlineToken {@@ -24,6 +25,7 @@ impl InlineToken {24
label: text.clone(),25
label: text.clone(),25
text,26
text,26
block: false,27
block: false,28
header: false,27
}29
}28
}30
}29
pub fn with_label(mut self, label: impl Into<SharedString>) -> Self {31
pub fn with_label(mut self, label: impl Into<SharedString>) -> Self {@@ -38,6 +40,16 @@ impl InlineToken {38
pub fn is_block(&self) -> bool {40
pub fn is_block(&self) -> bool {39
self.block41
self.block40
}42
}43
/// A block token that heads its line: it spans the row without the line indent, and44
/// the rest of the line starts on the next row, also when it is empty.45
pub fn header(mut self) -> Self {46
self.block = true;47
self.header = true;48
self49
}50
pub fn is_header(&self) -> bool {51
self.header52
}41
pub fn id(&self) -> &SharedString {53
pub fn id(&self) -> &SharedString {42
&self.id54
&self.id43
}55
}@@ -365,6 +365,9 @@ pub struct InputBaseState<M: InputModeKind> {
365
365
/// Real per-frame bounds of the placed token elements, keyed by token
366
366
/// start offset; used for hover payloads and stale-hover reconciliation.
367
367
pub(super) token_bounds: std::collections::HashMap<usize, Bounds<Pixels>>,
368
/// Text painted right-aligned in the indent before a byte offset, e.g. line numbers.
369
pub(super) line_labels: Vec<(usize, SharedString)>,
370
pub(super) line_label_color: gpui::Hsla,
368
371
/// The currently hovered token: its entered span, last measured bounds,
369
372
/// and UTF-16 range as of entry. Retained so hover exit can still be
370
373
/// delivered when the token is removed, replaced, scrolled out, or
@@ -733,6 +736,8 @@ impl<M: InputModeKind> InputBaseState<M> {
733
736
document_revision: 0,
734
737
token_presentation: Default::default(),
735
738
token_bounds: Default::default(),
739
line_labels: Vec::new(),
740
line_label_color: gpui::Hsla::default(),
736
741
hovered_token: None,
737
742
pending_token_hover_exits: Vec::new(),
738
743
token_layout_cache: None,
@@ -11206,6 +11211,23 @@ impl<M: crate::input::MultiLineMode> InputBaseState<M> {
11206
11211
cx.notify();
11207
11212
}
11208
11213
11214
/// Each label is painted right-aligned before its byte offset, in `color`, on the row
11215
/// that shows the offset; meant for the line indent. Set them again on change.
11216
pub fn set_line_labels(
11217
&mut self,
11218
mut labels: Vec<(usize, SharedString)>,
11219
color: gpui::Hsla,
11220
cx: &mut Context<Self>,
11221
) {
11222
labels.retain(|(offset, _)| *offset <= self.text.len());
11223
labels.sort_by_key(|(offset, _)| *offset);
11224
if labels != self.line_labels || color != self.line_label_color {
11225
self.line_labels = labels;
11226
self.line_label_color = color;
11227
cx.notify();
11228
}
11229
}
11230
11209
11231
/// Every row of the line starting at each byte offset starts `indent` further right,
11210
11232
/// and wraps that much earlier. Combines with a hanging indent on the same line.
11211
11233
/// Entries for offsets that are not line starts are ignored; set them again on change.
@@ -365,6 +365,9 @@ pub struct InputBaseState<M: InputModeKind> {365
/// Real per-frame bounds of the placed token elements, keyed by token365
/// Real per-frame bounds of the placed token elements, keyed by token366
/// start offset; used for hover payloads and stale-hover reconciliation.366
/// start offset; used for hover payloads and stale-hover reconciliation.367
pub(super) token_bounds: std::collections::HashMap<usize, Bounds<Pixels>>,367
pub(super) token_bounds: std::collections::HashMap<usize, Bounds<Pixels>>,368
/// Text painted right-aligned in the indent before a byte offset, e.g. line numbers.369
pub(super) line_labels: Vec<(usize, SharedString)>,370
pub(super) line_label_color: gpui::Hsla,368
/// The currently hovered token: its entered span, last measured bounds,371
/// The currently hovered token: its entered span, last measured bounds,369
/// and UTF-16 range as of entry. Retained so hover exit can still be372
/// and UTF-16 range as of entry. Retained so hover exit can still be370
/// delivered when the token is removed, replaced, scrolled out, or373
/// delivered when the token is removed, replaced, scrolled out, or@@ -733,6 +736,8 @@ impl<M: InputModeKind> InputBaseState<M> {733
document_revision: 0,736
document_revision: 0,734
token_presentation: Default::default(),737
token_presentation: Default::default(),735
token_bounds: Default::default(),738
token_bounds: Default::default(),739
line_labels: Vec::new(),740
line_label_color: gpui::Hsla::default(),736
hovered_token: None,741
hovered_token: None,737
pending_token_hover_exits: Vec::new(),742
pending_token_hover_exits: Vec::new(),738
token_layout_cache: None,743
token_layout_cache: None,@@ -11206,6 +11211,23 @@ impl<M: crate::input::MultiLineMode> InputBaseState<M> {11206
cx.notify();11211
cx.notify();11207
}11212
}11208
11213
11214
/// Each label is painted right-aligned before its byte offset, in `color`, on the row11215
/// that shows the offset; meant for the line indent. Set them again on change.11216
pub fn set_line_labels(11217
&mut self,11218
mut labels: Vec<(usize, SharedString)>,11219
color: gpui::Hsla,11220
cx: &mut Context<Self>,11221
) {11222
labels.retain(|(offset, _)| *offset <= self.text.len());11223
labels.sort_by_key(|(offset, _)| *offset);11224
if labels != self.line_labels || color != self.line_label_color {11225
self.line_labels = labels;11226
self.line_label_color = color;11227
cx.notify();11228
}11229
}11230
11209
/// Every row of the line starting at each byte offset starts `indent` further right,11231
/// Every row of the line starting at each byte offset starts `indent` further right,11210
/// and wraps that much earlier. Combines with a hanging indent on the same line.11232
/// and wraps that much earlier. Combines with a hanging indent on the same line.11211
/// Entries for offsets that are not line starts are ignored; set them again on change.11233
/// Entries for offsets that are not line starts are ignored; set them again on change.@@ -235,7 +235,12 @@ impl<M: InputModeKind> InputBaseState<M> {
235
235
disabled: self.disabled,
236
236
readonly: self.readonly,
237
237
line_height,
238
available_width: width,
238
// A header spans its row up to where block decorations end.
239
available_width: if span.token().is_header() {
240
width + super::element::RIGHT_MARGIN
241
} else {
242
width
243
},
239
244
}
240
245
}
241
246
/// The token starting at `start`, paired with the listener that opens it.
@@ -235,7 +235,12 @@ impl<M: InputModeKind> InputBaseState<M> {235
disabled: self.disabled,235
disabled: self.disabled,236
readonly: self.readonly,236
readonly: self.readonly,237
line_height,237
line_height,238
available_width: width,238
// A header spans its row up to where block decorations end.239
available_width: if span.token().is_header() {240
width + super::element::RIGHT_MARGIN241
} else {242
width243
},239
}244
}240
}245
}241
/// The token starting at `start`, paired with the listener that opens it.246
/// The token starting at `start`, paired with the listener that opens it.@@ -205,6 +205,8 @@ pub(crate) struct InlineMetric {
205
205
pub(crate) range: Range<usize>,
206
206
pub(crate) width: Pixels,
207
207
pub(crate) height: Option<Pixels>,
208
/// A header token: what follows it on its line starts a row, even when nothing does.
209
pub(crate) opens_row: bool,
208
210
}
209
211
210
212
fn block_rows_of(
@@ -737,7 +739,10 @@ impl TextWrapper {
737
739
let wrap_width =
738
740
(wrap_width - line_indent_at(&line_indents, line_start)).max(px(1.));
739
741
let line_indented = line_indent_at(&line_indents, line_start) > px(0.);
740
measured_wrap_boundaries(
742
let header_ends_line = tokens
743
.iter()
744
.any(|token| token.opens_row && token.range.end == line_str.len());
745
let mut boundaries = measured_wrap_boundaries(
741
746
line_str,
742
747
wrap_width,
743
748
wrapping_indent,
@@ -756,7 +761,14 @@ impl TextWrapper {
756
761
}
757
762
width + shape(offset..range.end)
758
763
},
759
)
764
);
765
if header_ends_line && boundaries.last().is_none_or(|last| last.ix < line_str.len()) {
766
boundaries.push(gpui::Boundary {
767
ix: line_str.len(),
768
next_indent: 0,
769
});
770
}
771
boundaries
760
772
},
761
773
&mut |line_start, rows| {
762
774
if !has_scaled {
@@ -1014,10 +1026,8 @@ impl TextWrapper {
1014
1026
}
1015
1027
}
1016
1028
1017
// Reset of the line
1018
if prev_boundary_ix < line.len() || prev_boundary_ix == 0 {
1019
wrapped_lines.push(prev_boundary_ix..line.len());
1020
}
1029
// Reset of the line; a boundary at the end (after a header token) opens an empty row.
1030
wrapped_lines.push(prev_boundary_ix..line.len());
1021
1031
1022
1032
let mut blocks =
1023
1033
block_rows_of(&self.inline_metrics, line_start, line.len(), &wrapped_lines);
@@ -1736,6 +1746,7 @@ mod tests {
1736
1746
range: token.clone(),
1737
1747
width: px(32.),
1738
1748
height: None,
1749
opens_row: false,
1739
1750
}]),
1740
1751
cx,
1741
1752
);
@@ -205,6 +205,8 @@ pub(crate) struct InlineMetric {205
pub(crate) range: Range<usize>,205
pub(crate) range: Range<usize>,206
pub(crate) width: Pixels,206
pub(crate) width: Pixels,207
pub(crate) height: Option<Pixels>,207
pub(crate) height: Option<Pixels>,208
/// A header token: what follows it on its line starts a row, even when nothing does.209
pub(crate) opens_row: bool,208
}210
}209
211
210
fn block_rows_of(212
fn block_rows_of(@@ -737,7 +739,10 @@ impl TextWrapper {737
let wrap_width =739
let wrap_width =738
(wrap_width - line_indent_at(&line_indents, line_start)).max(px(1.));740
(wrap_width - line_indent_at(&line_indents, line_start)).max(px(1.));739
let line_indented = line_indent_at(&line_indents, line_start) > px(0.);741
let line_indented = line_indent_at(&line_indents, line_start) > px(0.);740
measured_wrap_boundaries(742
let header_ends_line = tokens743
.iter()744
.any(|token| token.opens_row && token.range.end == line_str.len());745
let mut boundaries = measured_wrap_boundaries(741
line_str,746
line_str,742
wrap_width,747
wrap_width,743
wrapping_indent,748
wrapping_indent,@@ -756,7 +761,14 @@ impl TextWrapper {756
}761
}757
width + shape(offset..range.end)762
width + shape(offset..range.end)758
},763
},759
)764
);765
if header_ends_line && boundaries.last().is_none_or(|last| last.ix < line_str.len()) {766
boundaries.push(gpui::Boundary {767
ix: line_str.len(),768
next_indent: 0,769
});770
}771
boundaries760
},772
},761
&mut |line_start, rows| {773
&mut |line_start, rows| {762
if !has_scaled {774
if !has_scaled {@@ -1014,10 +1026,8 @@ impl TextWrapper {1014
}1026
}1015
}1027
}1016
1028
1017
// Reset of the line1029
// Reset of the line; a boundary at the end (after a header token) opens an empty row.1018
if prev_boundary_ix < line.len() || prev_boundary_ix == 0 {1030
wrapped_lines.push(prev_boundary_ix..line.len());1019
wrapped_lines.push(prev_boundary_ix..line.len());1020
}1021
1031
1022
let mut blocks =1032
let mut blocks =1023
block_rows_of(&self.inline_metrics, line_start, line.len(), &wrapped_lines);1033
block_rows_of(&self.inline_metrics, line_start, line.len(), &wrapped_lines);@@ -1736,6 +1746,7 @@ mod tests {1736
range: token.clone(),1746
range: token.clone(),1737
width: px(32.),1747
width: px(32.),1738
height: None,1748
height: None,1749
opens_row: false,1739
}]),1750
}]),1740
cx,1751
cx,1741
);1752
);