BlueGit

ict rusty-teams

fix(channels): embedded website tabs run on the main thread and never cover menus

| Before | After |
|---|---|
| WebView2 created on the dialog host thread as a child of the app window (input queues attached: a stall freezes both) | Created and driven on the GPUI main thread, callback-driven, no blocking waits |
| Native page drew over menus, dialogs and panels | Page shows only while nothing outside it holds focus (menus, dialogs, panels, switcher take focus) |

- Own container child window per embed, with region support for cut-outs; toasts are separate topmost windows and need none.
- Same WebView2 user data folder and options as the dialog host.
- New hidden probe `crates/webview/examples/embed_probe.rs`: creates, navigates, resizes, toggles, clips and closes an embed on one thread; passed 3/3 on Windows without showing a window.
- scripts/build-windows.sh builds examples too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-10 · 7 weeks ago

Hash
880d3673a8dbbdf304cfc52a5b4dfaaae687cc7d
Parent
9c8b7dc3
20 files changed +973 −368
crates/app/src/embedded_web.rs +68 −13
@@ -16,6 +16,8 @@ mod native_stub;
16 16 #[cfg(not(windows))]
17 17 use native_stub as native;
18 18
19 #[cfg(windows)]
20 pub use native::configure;
19 21 pub use native::{Native, NativeEvent, available};
20 22
21 23 const BAR_HEIGHT: f32 = 28.;
@@ -25,7 +27,6 @@ const OPEN_LABEL: &str = "Open in browser \u{2197}";
25 27 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
26 28 pub struct Overlays {
27 29 pub panels: bool,
28 pub tab_menu: bool,
29 30 }
30 31
31 32 impl Global for Overlays {}
@@ -42,20 +43,37 @@ impl Overlays {
42 43 cx.set_global(next);
43 44 }
44 45 }
46 }
45 47
46 pub fn any(self) -> bool {
47 self.panels || self.tab_menu
48 }
48 pub struct RootFocus(pub FocusHandle);
49
50 impl Global for RootFocus {}
51
52 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
53 pub enum FocusSpot {
54 Nowhere,
55 Page,
56 Elsewhere,
49 57 }
50 58
51 59 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
52 60 pub struct Visibility {
53 61 pub overlays: Overlays,
54 62 pub has_area: bool,
63 pub focus: FocusSpot,
55 64 }
56 65
57 66 pub fn embed_visible(visibility: Visibility) -> bool {
58 visibility.has_area && !visibility.overlays.any()
67 visibility.has_area && !visibility.overlays.panels && visibility.focus != FocusSpot::Elsewhere
68 }
69
70 pub fn focus_spot<T: PartialEq>(focused: Option<T>, inside_pane: bool, page: &[T]) -> FocusSpot {
71 match focused {
72 None => FocusSpot::Nowhere,
73 Some(_) if inside_pane => FocusSpot::Page,
74 Some(handle) if page.contains(&handle) => FocusSpot::Page,
75 Some(_) => FocusSpot::Elsewhere,
76 }
59 77 }
60 78
61 79 pub fn url_bar_text(url: &str) -> String {
@@ -72,6 +90,8 @@ pub struct EmbeddedWeb {
72 90 start_url: String,
73 91 url: String,
74 92 native: Native,
93 focus_handle: FocusHandle,
94 container_focus: FocusHandle,
75 95 _events: Task<()>,
76 96 }
77 97
@@ -83,6 +103,7 @@ impl EmbeddedWeb {
83 103 start_url: String,
84 104 native: Native,
85 105 mut events: UnboundedReceiver<NativeEvent>,
106 container_focus: FocusHandle,
86 107 cx: &mut Context<Self>,
87 108 ) -> Self {
88 109 let task = cx.spawn(async move |this, cx| {
@@ -98,6 +119,8 @@ impl EmbeddedWeb {
98 119 url: start_url.clone(),
99 120 start_url,
100 121 native,
122 focus_handle: cx.focus_handle(),
123 container_focus,
101 124 _events: task,
102 125 }
103 126 }
@@ -113,6 +136,7 @@ impl EmbeddedWeb {
113 136 cx.notify();
114 137 }
115 138 NativeEvent::NewWindow(url) => cx.open_url(&url),
139 NativeEvent::Loaded => {}
116 140 NativeEvent::Closed => cx.emit(EmbeddedWebEvent::Closed {
117 141 start_url: self.start_url.clone(),
118 142 }),
@@ -129,9 +153,12 @@ impl Drop for EmbeddedWeb {
129 153 impl Render for EmbeddedWeb {
130 154 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
131 155 let native = self.native.clone();
156 let pane_focus = self.focus_handle.clone();
157 let container_focus = self.container_focus.clone();
132 158 let open_url = self.url.clone();
133 159 v_flex()
134 160 .size_full()
161 .track_focus(&self.focus_handle)
135 162 .child(
136 163 h_flex()
137 164 .h(px(BAR_HEIGHT))
@@ -170,10 +197,19 @@ impl Render for EmbeddedWeb {
170 197 .child(
171 198 canvas(
172 199 move |bounds, window, cx| {
200 let mut page = vec![container_focus.clone()];
201 page.extend(
202 cx.try_global::<RootFocus>().map(|root| root.0.clone()),
203 );
173 204 let visible = embed_visible(Visibility {
174 205 overlays: Overlays::read(cx),
175 206 has_area: bounds.size.width > px(0.)
176 207 && bounds.size.height > px(0.),
208 focus: focus_spot(
209 window.focused(cx),
210 pane_focus.contains_focused(window, cx),
211 &page,
212 ),
177 213 });
178 214 native.place(bounds, window.scale_factor(), visible);
179 215 },
@@ -187,21 +223,40 @@ impl Render for EmbeddedWeb {
187 223
188 224 #[cfg(test)]
189 225 mod tests {
190 use super::{Overlays, Visibility, embed_visible, url_bar_text};
226 use super::{FocusSpot, Overlays, Visibility, embed_visible, focus_spot, url_bar_text};
191 227
192 fn visibility(panels: bool, tab_menu: bool, has_area: bool) -> Visibility {
228 fn visibility(panels: bool, focus: FocusSpot, has_area: bool) -> Visibility {
193 229 Visibility {
194 overlays: Overlays { panels, tab_menu },
230 overlays: Overlays { panels },
195 231 has_area,
232 focus,
196 233 }
197 234 }
198 235
199 236 #[test]
200 fn the_page_shows_only_without_overlays_and_with_room() {
201 assert!(embed_visible(visibility(false, false, true)));
202 assert!(!embed_visible(visibility(true, false, true)));
203 assert!(!embed_visible(visibility(false, true, true)));
204 assert!(!embed_visible(visibility(false, false, false)));
237 fn the_page_shows_only_with_room_and_no_panel() {
238 assert!(embed_visible(visibility(false, FocusSpot::Page, true)));
239 assert!(!embed_visible(visibility(true, FocusSpot::Page, true)));
240 assert!(!embed_visible(visibility(false, FocusSpot::Page, false)));
241 }
242
243 #[test]
244 fn focus_outside_the_page_hides_it() {
245 assert!(!embed_visible(visibility(
246 false,
247 FocusSpot::Elsewhere,
248 true
249 )));
250 assert!(embed_visible(visibility(false, FocusSpot::Nowhere, true)));
251 }
252
253 #[test]
254 fn focus_is_classified_against_the_page_handles() {
255 assert_eq!(focus_spot(None, false, &[1, 2]), FocusSpot::Nowhere);
256 assert_eq!(focus_spot(Some(2), false, &[1, 2]), FocusSpot::Page);
257 assert_eq!(focus_spot(Some(9), true, &[1, 2]), FocusSpot::Page);
258 assert_eq!(focus_spot(Some(9), false, &[1, 2]), FocusSpot::Elsewhere);
259 assert_eq!(focus_spot(Some(9), false, &[]), FocusSpot::Elsewhere);
205 260 }
206 261
207 262 #[test]
@@ -16,6 +16,8 @@ mod native_stub;
16#[cfg(not(windows))]
16#[cfg(not(windows))]
17use native_stub as native;
17use native_stub as native;
18
18
19#[cfg(windows)]
20pub use native::configure;
19pub use native::{Native, NativeEvent, available};
21pub use native::{Native, NativeEvent, available};
20
22
21const BAR_HEIGHT: f32 = 28.;
23const BAR_HEIGHT: f32 = 28.;
@@ -25,7 +27,6 @@ const OPEN_LABEL: &str = "Open in browser \u{2197}";
25#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
27#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
26pub struct Overlays {
28pub struct Overlays {
27 pub panels: bool,
29 pub panels: bool,
28 pub tab_menu: bool,
29}
30}
30
31
31impl Global for Overlays {}
32impl Global for Overlays {}
@@ -42,20 +43,37 @@ impl Overlays {
42 cx.set_global(next);
43 cx.set_global(next);
43 }
44 }
44 }
45 }
46}
45
47
46 pub fn any(self) -> bool {
48pub struct RootFocus(pub FocusHandle);
47 self.panels || self.tab_menu
49
48 }
50impl Global for RootFocus {}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum FocusSpot {
54 Nowhere,
55 Page,
56 Elsewhere,
49}
57}
50
58
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct Visibility {
60pub struct Visibility {
53 pub overlays: Overlays,
61 pub overlays: Overlays,
54 pub has_area: bool,
62 pub has_area: bool,
63 pub focus: FocusSpot,
55}
64}
56
65
57pub fn embed_visible(visibility: Visibility) -> bool {
66pub fn embed_visible(visibility: Visibility) -> bool {
58 visibility.has_area && !visibility.overlays.any()
67 visibility.has_area && !visibility.overlays.panels && visibility.focus != FocusSpot::Elsewhere
68}
69
70pub fn focus_spot<T: PartialEq>(focused: Option<T>, inside_pane: bool, page: &[T]) -> FocusSpot {
71 match focused {
72 None => FocusSpot::Nowhere,
73 Some(_) if inside_pane => FocusSpot::Page,
74 Some(handle) if page.contains(&handle) => FocusSpot::Page,
75 Some(_) => FocusSpot::Elsewhere,
76 }
59}
77}
60
78
61pub fn url_bar_text(url: &str) -> String {
79pub fn url_bar_text(url: &str) -> String {
@@ -72,6 +90,8 @@ pub struct EmbeddedWeb {
72 start_url: String,
90 start_url: String,
73 url: String,
91 url: String,
74 native: Native,
92 native: Native,
93 focus_handle: FocusHandle,
94 container_focus: FocusHandle,
75 _events: Task<()>,
95 _events: Task<()>,
76}
96}
77
97
@@ -83,6 +103,7 @@ impl EmbeddedWeb {
83 start_url: String,
103 start_url: String,
84 native: Native,
104 native: Native,
85 mut events: UnboundedReceiver<NativeEvent>,
105 mut events: UnboundedReceiver<NativeEvent>,
106 container_focus: FocusHandle,
86 cx: &mut Context<Self>,
107 cx: &mut Context<Self>,
87 ) -> Self {
108 ) -> Self {
88 let task = cx.spawn(async move |this, cx| {
109 let task = cx.spawn(async move |this, cx| {
@@ -98,6 +119,8 @@ impl EmbeddedWeb {
98 url: start_url.clone(),
119 url: start_url.clone(),
99 start_url,
120 start_url,
100 native,
121 native,
122 focus_handle: cx.focus_handle(),
123 container_focus,
101 _events: task,
124 _events: task,
102 }
125 }
103 }
126 }
@@ -113,6 +136,7 @@ impl EmbeddedWeb {
113 cx.notify();
136 cx.notify();
114 }
137 }
115 NativeEvent::NewWindow(url) => cx.open_url(&url),
138 NativeEvent::NewWindow(url) => cx.open_url(&url),
139 NativeEvent::Loaded => {}
116 NativeEvent::Closed => cx.emit(EmbeddedWebEvent::Closed {
140 NativeEvent::Closed => cx.emit(EmbeddedWebEvent::Closed {
117 start_url: self.start_url.clone(),
141 start_url: self.start_url.clone(),
118 }),
142 }),
@@ -129,9 +153,12 @@ impl Drop for EmbeddedWeb {
129impl Render for EmbeddedWeb {
153impl Render for EmbeddedWeb {
130 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
154 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
131 let native = self.native.clone();
155 let native = self.native.clone();
156 let pane_focus = self.focus_handle.clone();
157 let container_focus = self.container_focus.clone();
132 let open_url = self.url.clone();
158 let open_url = self.url.clone();
133 v_flex()
159 v_flex()
134 .size_full()
160 .size_full()
161 .track_focus(&self.focus_handle)
135 .child(
162 .child(
136 h_flex()
163 h_flex()
137 .h(px(BAR_HEIGHT))
164 .h(px(BAR_HEIGHT))
@@ -170,10 +197,19 @@ impl Render for EmbeddedWeb {
170 .child(
197 .child(
171 canvas(
198 canvas(
172 move |bounds, window, cx| {
199 move |bounds, window, cx| {
200 let mut page = vec![container_focus.clone()];
201 page.extend(
202 cx.try_global::<RootFocus>().map(|root| root.0.clone()),
203 );
173 let visible = embed_visible(Visibility {
204 let visible = embed_visible(Visibility {
174 overlays: Overlays::read(cx),
205 overlays: Overlays::read(cx),
175 has_area: bounds.size.width > px(0.)
206 has_area: bounds.size.width > px(0.)
176 && bounds.size.height > px(0.),
207 && bounds.size.height > px(0.),
208 focus: focus_spot(
209 window.focused(cx),
210 pane_focus.contains_focused(window, cx),
211 &page,
212 ),
177 });
213 });
178 native.place(bounds, window.scale_factor(), visible);
214 native.place(bounds, window.scale_factor(), visible);
179 },
215 },
@@ -187,21 +223,40 @@ impl Render for EmbeddedWeb {
187
223
188#[cfg(test)]
224#[cfg(test)]
189mod tests {
225mod tests {
190 use super::{Overlays, Visibility, embed_visible, url_bar_text};
226 use super::{FocusSpot, Overlays, Visibility, embed_visible, focus_spot, url_bar_text};
191
227
192 fn visibility(panels: bool, tab_menu: bool, has_area: bool) -> Visibility {
228 fn visibility(panels: bool, focus: FocusSpot, has_area: bool) -> Visibility {
193 Visibility {
229 Visibility {
194 overlays: Overlays { panels, tab_menu },
230 overlays: Overlays { panels },
195 has_area,
231 has_area,
232 focus,
196 }
233 }
197 }
234 }
198
235
199 #[test]
236 #[test]
200 fn the_page_shows_only_without_overlays_and_with_room() {
237 fn the_page_shows_only_with_room_and_no_panel() {
201 assert!(embed_visible(visibility(false, false, true)));
238 assert!(embed_visible(visibility(false, FocusSpot::Page, true)));
202 assert!(!embed_visible(visibility(true, false, true)));
239 assert!(!embed_visible(visibility(true, FocusSpot::Page, true)));
203 assert!(!embed_visible(visibility(false, true, true)));
240 assert!(!embed_visible(visibility(false, FocusSpot::Page, false)));
204 assert!(!embed_visible(visibility(false, false, false)));
241 }
242
243 #[test]
244 fn focus_outside_the_page_hides_it() {
245 assert!(!embed_visible(visibility(
246 false,
247 FocusSpot::Elsewhere,
248 true
249 )));
250 assert!(embed_visible(visibility(false, FocusSpot::Nowhere, true)));
251 }
252
253 #[test]
254 fn focus_is_classified_against_the_page_handles() {
255 assert_eq!(focus_spot(None, false, &[1, 2]), FocusSpot::Nowhere);
256 assert_eq!(focus_spot(Some(2), false, &[1, 2]), FocusSpot::Page);
257 assert_eq!(focus_spot(Some(9), true, &[1, 2]), FocusSpot::Page);
258 assert_eq!(focus_spot(Some(9), false, &[1, 2]), FocusSpot::Elsewhere);
259 assert_eq!(focus_spot(Some(9), false, &[]), FocusSpot::Elsewhere);
205 }
260 }
206
261
207 #[test]
262 #[test]
crates/app/src/embedded_web/native_stub.rs +1 −0
@@ -6,6 +6,7 @@ use tokio::sync::mpsc::UnboundedReceiver;
6 6 pub enum NativeEvent {
7 7 Navigated(String),
8 8 NewWindow(String),
9 Loaded,
9 10 Closed,
10 11 }
11 12
@@ -6,6 +6,7 @@ use tokio::sync::mpsc::UnboundedReceiver;
6pub enum NativeEvent {
6pub enum NativeEvent {
7 Navigated(String),
7 Navigated(String),
8 NewWindow(String),
8 NewWindow(String),
9 Loaded,
9 Closed,
10 Closed,
10}
11}
11
12
crates/app/src/embedded_web/native_windows.rs +34 −19
@@ -1,60 +1,75 @@
1 use std::cell::Cell;
1 use std::cell::{Cell, OnceCell};
2 use std::path::PathBuf;
2 3 use std::rc::Rc;
4 use std::sync::OnceLock;
3 5
4 6 use gpui_kit::*;
5 7 use tokio::sync::mpsc::UnboundedReceiver;
6 use webview::{EmbedBounds, EmbedHandle, EmbedSpec};
8 use webview::{EmbedBounds, EmbedHost, EmbedSpec, MainEmbed};
7 9
8 use crate::{notify, task_dialog, theme};
10 use crate::{notify, theme};
9 11
10 12 pub use webview::EmbedEvent as NativeEvent;
11 13
14 static USER_DATA_FOLDER: OnceLock<PathBuf> = OnceLock::new();
15
16 thread_local! {
17 static HOST: OnceCell<EmbedHost> = const { OnceCell::new() };
18 }
19
20 pub fn configure(user_data_folder: PathBuf) {
21 let _ = USER_DATA_FOLDER.set(user_data_folder);
22 }
23
12 24 pub fn available() -> bool {
13 task_dialog::host().is_some()
25 USER_DATA_FOLDER.get().is_some()
26 }
27
28 fn host() -> Option<EmbedHost> {
29 let folder = USER_DATA_FOLDER.get()?;
30 Some(HOST.with(|host| host.get_or_init(|| EmbedHost::new(folder.clone())).clone()))
14 31 }
15 32
16 33 #[derive(Clone)]
17 34 pub struct Native {
18 handle: EmbedHandle,
35 embed: MainEmbed,
19 36 placed: Rc<Cell<Option<(EmbedBounds, bool)>>>,
20 37 }
21 38
22 39 impl Native {
23 40 pub fn open(url: &str, window: &Window) -> Option<(Native, UnboundedReceiver<NativeEvent>)> {
24 let host = task_dialog::host()?;
25 41 let parent = notify::native_handle(window)?;
26 let (handle, events) = host.open_embed(EmbedSpec {
42 let (embed, events) = host()?.open(EmbedSpec {
27 43 parent,
28 44 url: url.to_owned(),
29 45 background: theme::BACKGROUND,
30 });
46 })?;
31 47 let native = Native {
32 handle,
48 embed,
33 49 placed: Rc::new(Cell::new(None)),
34 50 };
35 51 Some((native, events))
36 52 }
37 53
38 54 pub fn place(&self, bounds: Bounds<Pixels>, scale: f32, visible: bool) {
39 let physical = |value: Pixels| (f32::from(value) * scale).round() as i32;
40 55 let placement = (
41 EmbedBounds {
42 x: physical(bounds.origin.x),
43 y: physical(bounds.origin.y),
44 width: physical(bounds.size.width),
45 height: physical(bounds.size.height),
46 },
56 EmbedBounds::from_logical(
57 f32::from(bounds.origin.x),
58 f32::from(bounds.origin.y),
59 f32::from(bounds.size.width),
60 f32::from(bounds.size.height),
61 scale,
62 ),
47 63 visible,
48 64 );
49 65 if self.placed.get() == Some(placement) {
50 66 return;
51 67 }
52 68 self.placed.set(Some(placement));
53 self.handle.set_bounds(placement.0);
54 self.handle.set_visible(placement.1);
69 self.embed.place(placement.0, placement.1);
55 70 }
56 71
57 72 pub fn close(&self) {
58 self.handle.close();
73 self.embed.close();
59 74 }
60 75 }
@@ -1,60 +1,75 @@
1use std::cell::Cell;
1use std::cell::{Cell, OnceCell};
2use std::path::PathBuf;
2use std::rc::Rc;
3use std::rc::Rc;
4use std::sync::OnceLock;
3
5
4use gpui_kit::*;
6use gpui_kit::*;
5use tokio::sync::mpsc::UnboundedReceiver;
7use tokio::sync::mpsc::UnboundedReceiver;
6use webview::{EmbedBounds, EmbedHandle, EmbedSpec};
8use webview::{EmbedBounds, EmbedHost, EmbedSpec, MainEmbed};
7
9
8use crate::{notify, task_dialog, theme};
10use crate::{notify, theme};
9
11
10pub use webview::EmbedEvent as NativeEvent;
12pub use webview::EmbedEvent as NativeEvent;
11
13
14static USER_DATA_FOLDER: OnceLock<PathBuf> = OnceLock::new();
15
16thread_local! {
17 static HOST: OnceCell<EmbedHost> = const { OnceCell::new() };
18}
19
20pub fn configure(user_data_folder: PathBuf) {
21 let _ = USER_DATA_FOLDER.set(user_data_folder);
22}
23
12pub fn available() -> bool {
24pub fn available() -> bool {
13 task_dialog::host().is_some()
25 USER_DATA_FOLDER.get().is_some()
26}
27
28fn host() -> Option<EmbedHost> {
29 let folder = USER_DATA_FOLDER.get()?;
30 Some(HOST.with(|host| host.get_or_init(|| EmbedHost::new(folder.clone())).clone()))
14}
31}
15
32
16#[derive(Clone)]
33#[derive(Clone)]
17pub struct Native {
34pub struct Native {
18 handle: EmbedHandle,
35 embed: MainEmbed,
19 placed: Rc<Cell<Option<(EmbedBounds, bool)>>>,
36 placed: Rc<Cell<Option<(EmbedBounds, bool)>>>,
20}
37}
21
38
22impl Native {
39impl Native {
23 pub fn open(url: &str, window: &Window) -> Option<(Native, UnboundedReceiver<NativeEvent>)> {
40 pub fn open(url: &str, window: &Window) -> Option<(Native, UnboundedReceiver<NativeEvent>)> {
24 let host = task_dialog::host()?;
25 let parent = notify::native_handle(window)?;
41 let parent = notify::native_handle(window)?;
26 let (handle, events) = host.open_embed(EmbedSpec {
42 let (embed, events) = host()?.open(EmbedSpec {
27 parent,
43 parent,
28 url: url.to_owned(),
44 url: url.to_owned(),
29 background: theme::BACKGROUND,
45 background: theme::BACKGROUND,
30 });
46 })?;
31 let native = Native {
47 let native = Native {
32 handle,
48 embed,
33 placed: Rc::new(Cell::new(None)),
49 placed: Rc::new(Cell::new(None)),
34 };
50 };
35 Some((native, events))
51 Some((native, events))
36 }
52 }
37
53
38 pub fn place(&self, bounds: Bounds<Pixels>, scale: f32, visible: bool) {
54 pub fn place(&self, bounds: Bounds<Pixels>, scale: f32, visible: bool) {
39 let physical = |value: Pixels| (f32::from(value) * scale).round() as i32;
40 let placement = (
55 let placement = (
41 EmbedBounds {
56 EmbedBounds::from_logical(
42 x: physical(bounds.origin.x),
57 f32::from(bounds.origin.x),
43 y: physical(bounds.origin.y),
58 f32::from(bounds.origin.y),
44 width: physical(bounds.size.width),
59 f32::from(bounds.size.width),
45 height: physical(bounds.size.height),
60 f32::from(bounds.size.height),
46 },
61 scale,
62 ),
47 visible,
63 visible,
48 );
64 );
49 if self.placed.get() == Some(placement) {
65 if self.placed.get() == Some(placement) {
50 return;
66 return;
51 }
67 }
52 self.placed.set(Some(placement));
68 self.placed.set(Some(placement));
53 self.handle.set_bounds(placement.0);
69 self.embed.place(placement.0, placement.1);
54 self.handle.set_visible(placement.1);
55 }
70 }
56
71
57 pub fn close(&self) {
72 pub fn close(&self) {
58 self.handle.close();
73 self.embed.close();
59 }
74 }
60}
75}
crates/app/src/main.rs +1 −0
@@ -149,6 +149,7 @@ fn transport(endpoint: Option<&str>, database: Option<&std::path::Path>) -> Arc<
149 149 Some(directory) => directory.join(WEBVIEW_FOLDER),
150 150 None => data_path(WEBVIEW_FOLDER),
151 151 };
152 embedded_web::configure(user_data_folder.clone());
152 153 let transport = webview::start(webview::HostConfig {
153 154 user_data_folder,
154 155 window_title: format!("{APP_NAME} - Sign in"),
@@ -149,6 +149,7 @@ fn transport(endpoint: Option<&str>, database: Option<&std::path::Path>) -> Arc<
149 Some(directory) => directory.join(WEBVIEW_FOLDER),
149 Some(directory) => directory.join(WEBVIEW_FOLDER),
150 None => data_path(WEBVIEW_FOLDER),
150 None => data_path(WEBVIEW_FOLDER),
151 };
151 };
152 embedded_web::configure(user_data_folder.clone());
152 let transport = webview::start(webview::HostConfig {
153 let transport = webview::start(webview::HostConfig {
153 user_data_folder,
154 user_data_folder,
154 window_title: format!("{APP_NAME} - Sign in"),
155 window_title: format!("{APP_NAME} - Sign in"),
crates/app/src/task_dialog.rs +1 −1
@@ -11,7 +11,7 @@ mod hosted;
11 11 mod sdk;
12 12
13 13 #[cfg(windows)]
14 pub use hosted::{host, install_host};
14 pub use hosted::install_host;
15 15
16 16 #[cfg_attr(not(windows), allow(dead_code))]
17 17 #[derive(Debug, Clone, PartialEq)]
@@ -11,7 +11,7 @@ mod hosted;
11mod sdk;
11mod sdk;
12
12
13#[cfg(windows)]
13#[cfg(windows)]
14pub use hosted::{host, install_host};
14pub use hosted::install_host;
15
15
16#[cfg_attr(not(windows), allow(dead_code))]
16#[cfg_attr(not(windows), allow(dead_code))]
17#[derive(Debug, Clone, PartialEq)]
17#[derive(Debug, Clone, PartialEq)]
crates/app/src/task_dialog/hosted.rs +0 −4
@@ -17,10 +17,6 @@ pub fn install_host(transport: Arc<WebViewTransport>) {
17 17 let _ = HOST.set(transport);
18 18 }
19 19
20 pub fn host() -> Option<Arc<WebViewTransport>> {
21 HOST.get().cloned()
22 }
23
24 20 pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {
25 21 let Some(host) = HOST.get().cloned() else {
26 22 cx.open_url(&dialog.fallback_url);
@@ -17,10 +17,6 @@ pub fn install_host(transport: Arc<WebViewTransport>) {
17 let _ = HOST.set(transport);
17 let _ = HOST.set(transport);
18}
18}
19
19
20pub fn host() -> Option<Arc<WebViewTransport>> {
21 HOST.get().cloned()
22}
23
24pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {
20pub fn open(dialog: UrlDialog, engine: Option<Arc<Engine>>, cx: &mut App) {
25 let Some(host) = HOST.get().cloned() else {
21 let Some(host) = HOST.get().cloned() else {
26 cx.open_url(&dialog.fallback_url);
22 cx.open_url(&dialog.fallback_url);
crates/app/src/views/channel_tabs.rs +0 −4
@@ -33,13 +33,11 @@ pub enum ChannelPane {
33 33
34 34 pub type SelectPane = Rc<dyn Fn(ChannelPane, &mut App)>;
35 35 pub type OpenTab = Rc<dyn Fn(usize, &mut Window, &mut App)>;
36 pub type MenuToggled = Rc<dyn Fn(bool, &mut Window, &mut App)>;
37 36
38 37 #[derive(Clone)]
39 38 pub struct TabBarActions {
40 39 pub select: SelectPane,
41 40 pub open: OpenTab,
42 pub menu_toggled: MenuToggled,
43 41 }
44 42
45 43 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -137,7 +135,6 @@ fn overflow_button(
137 135 ) -> impl IntoElement {
138 136 let entries = hidden.to_vec();
139 137 let open = actions.open.clone();
140 let menu_toggled = actions.menu_toggled.clone();
141 138 Button::new("channel-tab-overflow")
142 139 .ghost()
143 140 .compact()
@@ -156,7 +153,6 @@ fn overflow_button(
156 153 )
157 154 })
158 155 })
159 .on_open_change(move |open, window, cx| menu_toggled(*open, window, cx))
160 156 }
161 157
162 158 pub fn render_tab_bar(
@@ -33,13 +33,11 @@ pub enum ChannelPane {
33
33
34pub type SelectPane = Rc<dyn Fn(ChannelPane, &mut App)>;
34pub type SelectPane = Rc<dyn Fn(ChannelPane, &mut App)>;
35pub type OpenTab = Rc<dyn Fn(usize, &mut Window, &mut App)>;
35pub type OpenTab = Rc<dyn Fn(usize, &mut Window, &mut App)>;
36pub type MenuToggled = Rc<dyn Fn(bool, &mut Window, &mut App)>;
37
36
38#[derive(Clone)]
37#[derive(Clone)]
39pub struct TabBarActions {
38pub struct TabBarActions {
40 pub select: SelectPane,
39 pub select: SelectPane,
41 pub open: OpenTab,
40 pub open: OpenTab,
42 pub menu_toggled: MenuToggled,
43}
41}
44
42
45#[derive(Debug, Clone, PartialEq, Eq)]
43#[derive(Debug, Clone, PartialEq, Eq)]
@@ -137,7 +135,6 @@ fn overflow_button(
137) -> impl IntoElement {
135) -> impl IntoElement {
138 let entries = hidden.to_vec();
136 let entries = hidden.to_vec();
139 let open = actions.open.clone();
137 let open = actions.open.clone();
140 let menu_toggled = actions.menu_toggled.clone();
141 Button::new("channel-tab-overflow")
138 Button::new("channel-tab-overflow")
142 .ghost()
139 .ghost()
143 .compact()
140 .compact()
@@ -156,7 +153,6 @@ fn overflow_button(
156 )
153 )
157 })
154 })
158 })
155 })
159 .on_open_change(move |open, window, cx| menu_toggled(*open, window, cx))
160}
156}
161
157
162pub fn render_tab_bar(
158pub fn render_tab_bar(
crates/app/src/views/conversation.rs +8 −1
@@ -180,6 +180,7 @@ pub struct ConversationView {
180 180 channel_tabs: Vec<ChannelTabRecord>,
181 181 tab_links: HashMap<String, String>,
182 182 web: Option<Entity<EmbeddedWeb>>,
183 focus_handle: FocusHandle,
183 184 web_subscription: Option<Subscription>,
184 185 shared: SharedState,
185 186 demo_library: DemoLibrary,
@@ -450,6 +451,7 @@ impl ConversationView {
450 451 channel_tabs: Vec::new(),
451 452 tab_links: HashMap::new(),
452 453 web: None,
454 focus_handle: cx.focus_handle(),
453 455 web_subscription: None,
454 456 shared: SharedState::default(),
455 457 demo_library: DemoLibrary::default(),
@@ -2980,7 +2982,12 @@ impl Render for ConversationView {
2980 2982 self.close_web();
2981 2983 }
2982 2984 let background = theme::background();
2983 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
2985 let mut root = v_flex()
2986 .flex_1()
2987 .min_w_0()
2988 .h_full()
2989 .bg(background)
2990 .track_focus(&self.focus_handle);
2984 2991 let drafting = self.draft_active;
2985 2992 if self.current.is_none() && !drafting {
2986 2993 return root
@@ -180,6 +180,7 @@ pub struct ConversationView {
180 channel_tabs: Vec<ChannelTabRecord>,
180 channel_tabs: Vec<ChannelTabRecord>,
181 tab_links: HashMap<String, String>,
181 tab_links: HashMap<String, String>,
182 web: Option<Entity<EmbeddedWeb>>,
182 web: Option<Entity<EmbeddedWeb>>,
183 focus_handle: FocusHandle,
183 web_subscription: Option<Subscription>,
184 web_subscription: Option<Subscription>,
184 shared: SharedState,
185 shared: SharedState,
185 demo_library: DemoLibrary,
186 demo_library: DemoLibrary,
@@ -450,6 +451,7 @@ impl ConversationView {
450 channel_tabs: Vec::new(),
451 channel_tabs: Vec::new(),
451 tab_links: HashMap::new(),
452 tab_links: HashMap::new(),
452 web: None,
453 web: None,
454 focus_handle: cx.focus_handle(),
453 web_subscription: None,
455 web_subscription: None,
454 shared: SharedState::default(),
456 shared: SharedState::default(),
455 demo_library: DemoLibrary::default(),
457 demo_library: DemoLibrary::default(),
@@ -2980,7 +2982,12 @@ impl Render for ConversationView {
2980 self.close_web();
2982 self.close_web();
2981 }
2983 }
2982 let background = theme::background();
2984 let background = theme::background();
2983 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
2985 let mut root = v_flex()
2986 .flex_1()
2987 .min_w_0()
2988 .h_full()
2989 .bg(background)
2990 .track_focus(&self.focus_handle);
2984 let drafting = self.draft_active;
2991 let drafting = self.draft_active;
2985 if self.current.is_none() && !drafting {
2992 if self.current.is_none() && !drafting {
2986 return root
2993 return root
crates/app/src/views/conversation/shared.rs +4 −7
@@ -14,7 +14,7 @@ use crate::channel_files::{
14 14 library_file, shared_items, sorted_entries,
15 15 };
16 16 use crate::downloads::DownloadKey;
17 use crate::embedded_web::{self, EmbeddedWeb, EmbeddedWebEvent, Overlays};
17 use crate::embedded_web::{self, EmbeddedWeb, EmbeddedWebEvent};
18 18 use crate::notice::short_error;
19 19 use crate::runtime;
20 20 use crate::views::attachment_tray::{display_name, read_attachment};
@@ -121,10 +121,6 @@ impl ConversationView {
121 121 .ok();
122 122 })
123 123 };
124 let menu_toggled = Rc::new(move |open: bool, window: &mut Window, cx: &mut App| {
125 Overlays::update(cx, |overlays| overlays.tab_menu = open);
126 window.refresh();
127 });
128 124 let active_tab_id = self
129 125 .web
130 126 .as_ref()
@@ -139,7 +135,6 @@ impl ConversationView {
139 135 &TabBarActions {
140 136 select,
141 137 open,
142 menu_toggled,
143 138 },
144 139 ))
145 140 }
@@ -178,7 +173,9 @@ impl ConversationView {
178 173 cx.open_url(&url);
179 174 return;
180 175 };
181 let web = cx.new(|cx| EmbeddedWeb::new(tab_id, url, native, events, cx));
176 let web = cx.new(|cx| {
177 EmbeddedWeb::new(tab_id, url, native, events, self.focus_handle.clone(), cx)
178 });
182 179 self.web_subscription =
183 180 Some(cx.subscribe(&web, |this, _, event: &EmbeddedWebEvent, cx| {
184 181 let EmbeddedWebEvent::Closed { start_url } = event;
@@ -14,7 +14,7 @@ use crate::channel_files::{
14 library_file, shared_items, sorted_entries,
14 library_file, shared_items, sorted_entries,
15};
15};
16use crate::downloads::DownloadKey;
16use crate::downloads::DownloadKey;
17use crate::embedded_web::{self, EmbeddedWeb, EmbeddedWebEvent, Overlays};
17use crate::embedded_web::{self, EmbeddedWeb, EmbeddedWebEvent};
18use crate::notice::short_error;
18use crate::notice::short_error;
19use crate::runtime;
19use crate::runtime;
20use crate::views::attachment_tray::{display_name, read_attachment};
20use crate::views::attachment_tray::{display_name, read_attachment};
@@ -121,10 +121,6 @@ impl ConversationView {
121 .ok();
121 .ok();
122 })
122 })
123 };
123 };
124 let menu_toggled = Rc::new(move |open: bool, window: &mut Window, cx: &mut App| {
125 Overlays::update(cx, |overlays| overlays.tab_menu = open);
126 window.refresh();
127 });
128 let active_tab_id = self
124 let active_tab_id = self
129 .web
125 .web
130 .as_ref()
126 .as_ref()
@@ -139,7 +135,6 @@ impl ConversationView {
139 &TabBarActions {
135 &TabBarActions {
140 select,
136 select,
141 open,
137 open,
142 menu_toggled,
143 },
138 },
144 ))
139 ))
145 }
140 }
@@ -178,7 +173,9 @@ impl ConversationView {
178 cx.open_url(&url);
173 cx.open_url(&url);
179 return;
174 return;
180 };
175 };
181 let web = cx.new(|cx| EmbeddedWeb::new(tab_id, url, native, events, cx));
176 let web = cx.new(|cx| {
177 EmbeddedWeb::new(tab_id, url, native, events, self.focus_handle.clone(), cx)
178 });
182 self.web_subscription =
179 self.web_subscription =
183 Some(cx.subscribe(&web, |this, _, event: &EmbeddedWebEvent, cx| {
180 Some(cx.subscribe(&web, |this, _, event: &EmbeddedWebEvent, cx| {
184 let EmbeddedWebEvent::Closed { start_url } = event;
181 let EmbeddedWebEvent::Closed { start_url } = event;
crates/app/src/views/shell.rs +2 −1
@@ -15,7 +15,7 @@ use super::switcher::{Switcher, SwitcherEvent, candidates_from};
15 15 use super::title_bar::render_title_bar;
16 16 use crate::activity::ActivityCenter;
17 17 use crate::app_state::{AppEvent, AppState, Selection};
18 use crate::embedded_web::Overlays;
18 use crate::embedded_web::{Overlays, RootFocus};
19 19 use crate::notice::NoticeAction;
20 20 use crate::notify::{NotificationCenter, selection_for};
21 21 use crate::theme;
@@ -100,6 +100,7 @@ impl AppShell {
100 100 });
101 101 let focus_handle = cx.focus_handle();
102 102 window.focus(&focus_handle, cx);
103 cx.set_global(RootFocus(focus_handle.clone()));
103 104 let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
104 105 let activity = cx.new(|cx| ActivityCenter::new(state.clone(), window, cx));
105 106 let activity_observation = cx.observe(&activity, |_, _, cx| cx.notify());
@@ -15,7 +15,7 @@ use super::switcher::{Switcher, SwitcherEvent, candidates_from};
15use super::title_bar::render_title_bar;
15use super::title_bar::render_title_bar;
16use crate::activity::ActivityCenter;
16use crate::activity::ActivityCenter;
17use crate::app_state::{AppEvent, AppState, Selection};
17use crate::app_state::{AppEvent, AppState, Selection};
18use crate::embedded_web::Overlays;
18use crate::embedded_web::{Overlays, RootFocus};
19use crate::notice::NoticeAction;
19use crate::notice::NoticeAction;
20use crate::notify::{NotificationCenter, selection_for};
20use crate::notify::{NotificationCenter, selection_for};
21use crate::theme;
21use crate::theme;
@@ -100,6 +100,7 @@ impl AppShell {
100 });
100 });
101 let focus_handle = cx.focus_handle();
101 let focus_handle = cx.focus_handle();
102 window.focus(&focus_handle, cx);
102 window.focus(&focus_handle, cx);
103 cx.set_global(RootFocus(focus_handle.clone()));
103 let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
104 let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
104 let activity = cx.new(|cx| ActivityCenter::new(state.clone(), window, cx));
105 let activity = cx.new(|cx| ActivityCenter::new(state.clone(), window, cx));
105 let activity_observation = cx.observe(&activity, |_, _, cx| cx.notify());
106 let activity_observation = cx.observe(&activity, |_, _, cx| cx.notify());
crates/webview/examples/embed_probe.rs added +253 −0
@@ -0,0 +1,253 @@
1 #[cfg(not(windows))]
2 fn main() {
3 eprintln!("embed_probe runs on Windows only");
4 std::process::exit(2);
5 }
6
7 #[cfg(windows)]
8 fn main() {
9 probe::run();
10 }
11
12 #[cfg(windows)]
13 mod probe {
14 use std::time::{Duration, Instant};
15
16 use tokio::sync::mpsc::UnboundedReceiver;
17 use webview::{EmbedBounds, EmbedEvent, EmbedHost, EmbedSpec, MainEmbed};
18 use windows::Win32::Foundation::{HINSTANCE, HWND, RECT};
19 use windows::Win32::Graphics::Gdi::{CreateRectRgn, DeleteObject, GetWindowRgn, HGDIOBJ};
20 use windows::Win32::System::LibraryLoader::GetModuleHandleW;
21 use windows::Win32::UI::WindowsAndMessaging::*;
22 use windows::core::{PCWSTR, w};
23
24 const GLOBAL_TIMEOUT: Duration = Duration::from_secs(20);
25 const STEP_TIMEOUT: Duration = Duration::from_secs(15);
26 const PAGE_URL: &str = "data:text/html,%3Ctitle%3Eprobe%3C%2Ftitle%3E%3Ch1%3Eprobe%3C%2Fh1%3E";
27 const PARENT_CLASS: PCWSTR = w!("EmbedProbeParent");
28 const CONTAINER_CLASS: PCWSTR = w!("RustyTeamsEmbedContainer");
29 const ERROR_REGION: i32 = 0;
30 const COMPLEX_REGION: i32 = 3;
31
32 struct Probe {
33 started: Instant,
34 events: UnboundedReceiver<EmbedEvent>,
35 seen: Vec<EmbedEvent>,
36 }
37
38 impl Probe {
39 fn wait_for(
40 &mut self,
41 label: &str,
42 mut done: impl FnMut(&[EmbedEvent]) -> bool,
43 ) -> Result<Duration, String> {
44 let step_start = Instant::now();
45 let deadline = step_start + STEP_TIMEOUT;
46 loop {
47 pump_messages();
48 while let Ok(event) = self.events.try_recv() {
49 self.seen.push(event);
50 }
51 if self.seen.contains(&EmbedEvent::Closed) {
52 return Err(format!("{label}: embed closed itself"));
53 }
54 if done(&self.seen) {
55 return Ok(step_start.elapsed());
56 }
57 if self.started.elapsed() > GLOBAL_TIMEOUT || Instant::now() > deadline {
58 return Err(format!("{label}: timed out"));
59 }
60 std::thread::sleep(Duration::from_millis(5));
61 }
62 }
63
64 fn settle(&mut self, label: &str, duration: Duration) -> Result<(), String> {
65 let end = Instant::now() + duration;
66 self.wait_for(label, |_| Instant::now() >= end).map(|_| ())
67 }
68 }
69
70 pub fn run() {
71 let started = Instant::now();
72 let outcome = execute(started);
73 match outcome {
74 Ok(()) => {
75 println!("PASS total={:?}", started.elapsed());
76 std::process::exit(0);
77 }
78 Err(reason) => {
79 println!("FAIL {reason} total={:?}", started.elapsed());
80 std::process::exit(1);
81 }
82 }
83 }
84
85 fn execute(started: Instant) -> Result<(), String> {
86 let parent = create_hidden_parent().map_err(|error| format!("parent window: {error}"))?;
87 let folder = std::env::temp_dir().join("rusty-teams-embed-probe-data");
88 let host = EmbedHost::new(folder);
89 let (embed, events) = host
90 .open(EmbedSpec {
91 parent: parent.0 as isize,
92 url: PAGE_URL.to_owned(),
93 background: 0x1f1f1f,
94 })
95 .ok_or("open returned no embed")?;
96 let mut probe = Probe {
97 started,
98 events,
99 seen: Vec::new(),
100 };
101 let container = find_container(parent).ok_or("container window missing after open")?;
102 embed.place(bounds(0, 0, 640, 480), true);
103 let loaded = probe.wait_for("navigation", |seen| seen.contains(&EmbedEvent::Loaded))?;
104 println!("navigation_completed after {loaded:?}");
105
106 embed.place(bounds(10, 20, 800, 600), true);
107 probe.settle("resize settle", Duration::from_millis(200))?;
108 let rect = window_rect(container);
109 expect(
110 (rect.right - rect.left, rect.bottom - rect.top) == (800, 600),
111 format!(
112 "resize: container is {}x{}",
113 rect.right - rect.left,
114 rect.bottom - rect.top
115 ),
116 )?;
117 println!("resize ok 800x600");
118
119 embed.place(bounds(10, 20, 800, 600), false);
120 probe.settle("hide settle", Duration::from_millis(100))?;
121 expect(
122 !style_visible(container),
123 "visibility: container still shown after hide".into(),
124 )?;
125 embed.place(bounds(10, 20, 800, 600), true);
126 probe.settle("show settle", Duration::from_millis(100))?;
127 expect(
128 style_visible(container),
129 "visibility: container hidden after show".into(),
130 )?;
131 println!("visibility toggle ok");
132
133 embed.set_cutouts(vec![bounds(500, 400, 300, 200)]);
134 expect(
135 region_kind(container) == COMPLEX_REGION,
136 format!(
137 "region: expected complex region, got {}",
138 region_kind(container)
139 ),
140 )?;
141 embed.set_cutouts(Vec::new());
142 expect(
143 region_kind(container) == ERROR_REGION,
144 format!(
145 "region: expected cleared region, got {}",
146 region_kind(container)
147 ),
148 )?;
149 println!("region apply/clear ok");
150
151 close(&embed, &mut probe, parent)?;
152 println!("close ok");
153 unsafe {
154 let _ = DestroyWindow(parent);
155 }
156 Ok(())
157 }
158
159 fn close(embed: &MainEmbed, probe: &mut Probe, parent: HWND) -> Result<(), String> {
160 embed.close();
161 probe.settle("close settle", Duration::from_millis(100))?;
162 expect(
163 find_container(parent).is_none(),
164 "close: container still exists".into(),
165 )
166 }
167
168 fn expect(condition: bool, failure: String) -> Result<(), String> {
169 condition.then_some(()).ok_or(failure)
170 }
171
172 fn bounds(x: i32, y: i32, width: i32, height: i32) -> EmbedBounds {
173 EmbedBounds {
174 x,
175 y,
176 width,
177 height,
178 }
179 }
180
181 fn pump_messages() {
182 let mut message = MSG::default();
183 while unsafe { PeekMessageW(&mut message, None, 0, 0, PM_REMOVE) }.as_bool() {
184 unsafe {
185 let _ = TranslateMessage(&message);
186 DispatchMessageW(&message);
187 }
188 }
189 }
190
191 fn create_hidden_parent() -> windows::core::Result<HWND> {
192 let instance = HINSTANCE(unsafe { GetModuleHandleW(None) }?.0);
193 let class = WNDCLASSW {
194 lpfnWndProc: Some(parent_procedure),
195 hInstance: instance,
196 lpszClassName: PARENT_CLASS,
197 ..Default::default()
198 };
199 unsafe { RegisterClassW(&class) };
200 unsafe {
201 CreateWindowExW(
202 WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE,
203 PARENT_CLASS,
204 w!("embed probe"),
205 WS_OVERLAPPEDWINDOW,
206 -32000,
207 -32000,
208 1000,
209 800,
210 None,
211 None,
212 Some(instance),
213 None,
214 )
215 }
216 }
217
218 extern "system" fn parent_procedure(
219 window: HWND,
220 message: u32,
221 wparam: windows::Win32::Foundation::WPARAM,
222 lparam: windows::Win32::Foundation::LPARAM,
223 ) -> windows::Win32::Foundation::LRESULT {
224 unsafe { DefWindowProcW(window, message, wparam, lparam) }
225 }
226
227 fn find_container(parent: HWND) -> Option<HWND> {
228 unsafe { FindWindowExW(Some(parent), None, CONTAINER_CLASS, PCWSTR::null()) }
229 .ok()
230 .filter(|window| !window.is_invalid())
231 }
232
233 fn window_rect(window: HWND) -> RECT {
234 let mut rect = RECT::default();
235 unsafe {
236 let _ = GetWindowRect(window, &mut rect);
237 }
238 rect
239 }
240
241 fn style_visible(window: HWND) -> bool {
242 unsafe { GetWindowLongPtrW(window, GWL_STYLE) as u32 & WS_VISIBLE.0 != 0 }
243 }
244
245 fn region_kind(window: HWND) -> i32 {
246 unsafe {
247 let probe_region = CreateRectRgn(0, 0, 0, 0);
248 let kind = GetWindowRgn(window, probe_region);
249 let _ = DeleteObject(HGDIOBJ(probe_region.0));
250 kind.0
251 }
252 }
253 }
@@ -0,0 +1,253 @@
1#[cfg(not(windows))]
2fn main() {
3 eprintln!("embed_probe runs on Windows only");
4 std::process::exit(2);
5}
6
7#[cfg(windows)]
8fn main() {
9 probe::run();
10}
11
12#[cfg(windows)]
13mod probe {
14 use std::time::{Duration, Instant};
15
16 use tokio::sync::mpsc::UnboundedReceiver;
17 use webview::{EmbedBounds, EmbedEvent, EmbedHost, EmbedSpec, MainEmbed};
18 use windows::Win32::Foundation::{HINSTANCE, HWND, RECT};
19 use windows::Win32::Graphics::Gdi::{CreateRectRgn, DeleteObject, GetWindowRgn, HGDIOBJ};
20 use windows::Win32::System::LibraryLoader::GetModuleHandleW;
21 use windows::Win32::UI::WindowsAndMessaging::*;
22 use windows::core::{PCWSTR, w};
23
24 const GLOBAL_TIMEOUT: Duration = Duration::from_secs(20);
25 const STEP_TIMEOUT: Duration = Duration::from_secs(15);
26 const PAGE_URL: &str = "data:text/html,%3Ctitle%3Eprobe%3C%2Ftitle%3E%3Ch1%3Eprobe%3C%2Fh1%3E";
27 const PARENT_CLASS: PCWSTR = w!("EmbedProbeParent");
28 const CONTAINER_CLASS: PCWSTR = w!("RustyTeamsEmbedContainer");
29 const ERROR_REGION: i32 = 0;
30 const COMPLEX_REGION: i32 = 3;
31
32 struct Probe {
33 started: Instant,
34 events: UnboundedReceiver<EmbedEvent>,
35 seen: Vec<EmbedEvent>,
36 }
37
38 impl Probe {
39 fn wait_for(
40 &mut self,
41 label: &str,
42 mut done: impl FnMut(&[EmbedEvent]) -> bool,
43 ) -> Result<Duration, String> {
44 let step_start = Instant::now();
45 let deadline = step_start + STEP_TIMEOUT;
46 loop {
47 pump_messages();
48 while let Ok(event) = self.events.try_recv() {
49 self.seen.push(event);
50 }
51 if self.seen.contains(&EmbedEvent::Closed) {
52 return Err(format!("{label}: embed closed itself"));
53 }
54 if done(&self.seen) {
55 return Ok(step_start.elapsed());
56 }
57 if self.started.elapsed() > GLOBAL_TIMEOUT || Instant::now() > deadline {
58 return Err(format!("{label}: timed out"));
59 }
60 std::thread::sleep(Duration::from_millis(5));
61 }
62 }
63
64 fn settle(&mut self, label: &str, duration: Duration) -> Result<(), String> {
65 let end = Instant::now() + duration;
66 self.wait_for(label, |_| Instant::now() >= end).map(|_| ())
67 }
68 }
69
70 pub fn run() {
71 let started = Instant::now();
72 let outcome = execute(started);
73 match outcome {
74 Ok(()) => {
75 println!("PASS total={:?}", started.elapsed());
76 std::process::exit(0);
77 }
78 Err(reason) => {
79 println!("FAIL {reason} total={:?}", started.elapsed());
80 std::process::exit(1);
81 }
82 }
83 }
84
85 fn execute(started: Instant) -> Result<(), String> {
86 let parent = create_hidden_parent().map_err(|error| format!("parent window: {error}"))?;
87 let folder = std::env::temp_dir().join("rusty-teams-embed-probe-data");
88 let host = EmbedHost::new(folder);
89 let (embed, events) = host
90 .open(EmbedSpec {
91 parent: parent.0 as isize,
92 url: PAGE_URL.to_owned(),
93 background: 0x1f1f1f,
94 })
95 .ok_or("open returned no embed")?;
96 let mut probe = Probe {
97 started,
98 events,
99 seen: Vec::new(),
100 };
101 let container = find_container(parent).ok_or("container window missing after open")?;
102 embed.place(bounds(0, 0, 640, 480), true);
103 let loaded = probe.wait_for("navigation", |seen| seen.contains(&EmbedEvent::Loaded))?;
104 println!("navigation_completed after {loaded:?}");
105
106 embed.place(bounds(10, 20, 800, 600), true);
107 probe.settle("resize settle", Duration::from_millis(200))?;
108 let rect = window_rect(container);
109 expect(
110 (rect.right - rect.left, rect.bottom - rect.top) == (800, 600),
111 format!(
112 "resize: container is {}x{}",
113 rect.right - rect.left,
114 rect.bottom - rect.top
115 ),
116 )?;
117 println!("resize ok 800x600");
118
119 embed.place(bounds(10, 20, 800, 600), false);
120 probe.settle("hide settle", Duration::from_millis(100))?;
121 expect(
122 !style_visible(container),
123 "visibility: container still shown after hide".into(),
124 )?;
125 embed.place(bounds(10, 20, 800, 600), true);
126 probe.settle("show settle", Duration::from_millis(100))?;
127 expect(
128 style_visible(container),
129 "visibility: container hidden after show".into(),
130 )?;
131 println!("visibility toggle ok");
132
133 embed.set_cutouts(vec![bounds(500, 400, 300, 200)]);
134 expect(
135 region_kind(container) == COMPLEX_REGION,
136 format!(
137 "region: expected complex region, got {}",
138 region_kind(container)
139 ),
140 )?;
141 embed.set_cutouts(Vec::new());
142 expect(
143 region_kind(container) == ERROR_REGION,
144 format!(
145 "region: expected cleared region, got {}",
146 region_kind(container)
147 ),
148 )?;
149 println!("region apply/clear ok");
150
151 close(&embed, &mut probe, parent)?;
152 println!("close ok");
153 unsafe {
154 let _ = DestroyWindow(parent);
155 }
156 Ok(())
157 }
158
159 fn close(embed: &MainEmbed, probe: &mut Probe, parent: HWND) -> Result<(), String> {
160 embed.close();
161 probe.settle("close settle", Duration::from_millis(100))?;
162 expect(
163 find_container(parent).is_none(),
164 "close: container still exists".into(),
165 )
166 }
167
168 fn expect(condition: bool, failure: String) -> Result<(), String> {
169 condition.then_some(()).ok_or(failure)
170 }
171
172 fn bounds(x: i32, y: i32, width: i32, height: i32) -> EmbedBounds {
173 EmbedBounds {
174 x,
175 y,
176 width,
177 height,
178 }
179 }
180
181 fn pump_messages() {
182 let mut message = MSG::default();
183 while unsafe { PeekMessageW(&mut message, None, 0, 0, PM_REMOVE) }.as_bool() {
184 unsafe {
185 let _ = TranslateMessage(&message);
186 DispatchMessageW(&message);
187 }
188 }
189 }
190
191 fn create_hidden_parent() -> windows::core::Result<HWND> {
192 let instance = HINSTANCE(unsafe { GetModuleHandleW(None) }?.0);
193 let class = WNDCLASSW {
194 lpfnWndProc: Some(parent_procedure),
195 hInstance: instance,
196 lpszClassName: PARENT_CLASS,
197 ..Default::default()
198 };
199 unsafe { RegisterClassW(&class) };
200 unsafe {
201 CreateWindowExW(
202 WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE,
203 PARENT_CLASS,
204 w!("embed probe"),
205 WS_OVERLAPPEDWINDOW,
206 -32000,
207 -32000,
208 1000,
209 800,
210 None,
211 None,
212 Some(instance),
213 None,
214 )
215 }
216 }
217
218 extern "system" fn parent_procedure(
219 window: HWND,
220 message: u32,
221 wparam: windows::Win32::Foundation::WPARAM,
222 lparam: windows::Win32::Foundation::LPARAM,
223 ) -> windows::Win32::Foundation::LRESULT {
224 unsafe { DefWindowProcW(window, message, wparam, lparam) }
225 }
226
227 fn find_container(parent: HWND) -> Option<HWND> {
228 unsafe { FindWindowExW(Some(parent), None, CONTAINER_CLASS, PCWSTR::null()) }
229 .ok()
230 .filter(|window| !window.is_invalid())
231 }
232
233 fn window_rect(window: HWND) -> RECT {
234 let mut rect = RECT::default();
235 unsafe {
236 let _ = GetWindowRect(window, &mut rect);
237 }
238 rect
239 }
240
241 fn style_visible(window: HWND) -> bool {
242 unsafe { GetWindowLongPtrW(window, GWL_STYLE) as u32 & WS_VISIBLE.0 != 0 }
243 }
244
245 fn region_kind(window: HWND) -> i32 {
246 unsafe {
247 let probe_region = CreateRectRgn(0, 0, 0, 0);
248 let kind = GetWindowRgn(window, probe_region);
249 let _ = DeleteObject(HGDIOBJ(probe_region.0));
250 kind.0
251 }
252 }
253}
crates/webview/examples/probe.rs +12 −0
@@ -1,8 +1,18 @@
1 #[cfg(not(windows))]
2 fn main() {
3 eprintln!("probe runs on Windows only");
4 std::process::exit(2);
5 }
6
7 #[cfg(windows)]
1 8 use std::path::PathBuf;
9 #[cfg(windows)]
2 10 use std::time::{Duration, Instant};
3 11
12 #[cfg(windows)]
4 13 use session::{App, Method, Scope, Session, SessionConfig};
5 14
15 #[cfg(windows)]
6 16 #[tokio::main]
7 17 async fn main() {
8 18 let folder = std::env::args().nth(1).map(PathBuf::from).expect("usage: probe <user-data-folder> [hold-seconds]");
@@ -32,6 +42,7 @@ async fn main() {
32 42 presence_call(&session, "after hold").await;
33 43 }
34 44
45 #[cfg(windows)]
35 46 async fn presence_call(session: &Session, phase: &str) {
36 47 let me = match session.request(Method::Get, "https://graph.microsoft.com/v1.0/me?$select=id", &Scope::graph("User.Read"), None).await {
37 48 Ok(response) => response.body["id"].as_str().unwrap_or_default().to_owned(),
@@ -51,6 +62,7 @@ async fn presence_call(session: &Session, phase: &str) {
51 62 }
52 63 }
53 64
65 #[cfg(windows)]
54 66 async fn graph_calls(session: &Session, phase: &str) {
55 67 for (label, url, scope) in [
56 68 ("graph me", "https://graph.microsoft.com/v1.0/me?$select=id", Scope::graph("User.Read")),
@@ -1,8 +1,18 @@
1#[cfg(not(windows))]
2fn main() {
3 eprintln!("probe runs on Windows only");
4 std::process::exit(2);
5}
6
7#[cfg(windows)]
1use std::path::PathBuf;
8use std::path::PathBuf;
9#[cfg(windows)]
2use std::time::{Duration, Instant};
10use std::time::{Duration, Instant};
3
11
12#[cfg(windows)]
4use session::{App, Method, Scope, Session, SessionConfig};
13use session::{App, Method, Scope, Session, SessionConfig};
5
14
15#[cfg(windows)]
6#[tokio::main]
16#[tokio::main]
7async fn main() {
17async fn main() {
8 let folder = std::env::args().nth(1).map(PathBuf::from).expect("usage: probe <user-data-folder> [hold-seconds]");
18 let folder = std::env::args().nth(1).map(PathBuf::from).expect("usage: probe <user-data-folder> [hold-seconds]");
@@ -32,6 +42,7 @@ async fn main() {
32 presence_call(&session, "after hold").await;
42 presence_call(&session, "after hold").await;
33}
43}
34
44
45#[cfg(windows)]
35async fn presence_call(session: &Session, phase: &str) {
46async fn presence_call(session: &Session, phase: &str) {
36 let me = match session.request(Method::Get, "https://graph.microsoft.com/v1.0/me?$select=id", &Scope::graph("User.Read"), None).await {
47 let me = match session.request(Method::Get, "https://graph.microsoft.com/v1.0/me?$select=id", &Scope::graph("User.Read"), None).await {
37 Ok(response) => response.body["id"].as_str().unwrap_or_default().to_owned(),
48 Ok(response) => response.body["id"].as_str().unwrap_or_default().to_owned(),
@@ -51,6 +62,7 @@ async fn presence_call(session: &Session, phase: &str) {
51 }
62 }
52}
63}
53
64
65#[cfg(windows)]
54async fn graph_calls(session: &Session, phase: &str) {
66async fn graph_calls(session: &Session, phase: &str) {
55 for (label, url, scope) in [
67 for (label, url, scope) in [
56 ("graph me", "https://graph.microsoft.com/v1.0/me?$select=id", Scope::graph("User.Read")),
68 ("graph me", "https://graph.microsoft.com/v1.0/me?$select=id", Scope::graph("User.Read")),
crates/webview/src/embed.rs +1 −55
@@ -1,7 +1,3 @@
1 use std::sync::{Arc, mpsc};
2
3 use crate::transport::UiRequest;
4
5 1 #[derive(Debug, Clone)]
6 2 pub struct EmbedSpec {
7 3 pub parent: isize,
@@ -9,60 +5,10 @@ pub struct EmbedSpec {
9 5 pub background: u32,
10 6 }
11 7
12 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
13 pub struct EmbedBounds {
14 pub x: i32,
15 pub y: i32,
16 pub width: i32,
17 pub height: i32,
18 }
19
20 8 #[derive(Debug, Clone, PartialEq, Eq)]
21 9 pub enum EmbedEvent {
22 10 Navigated(String),
23 11 NewWindow(String),
12 Loaded,
24 13 Closed,
25 14 }
26
27 #[derive(Debug)]
28 pub(crate) enum EmbedCommand {
29 Bounds(EmbedBounds),
30 Visible(bool),
31 Navigate(String),
32 Close,
33 }
34
35 #[derive(Clone)]
36 pub struct EmbedHandle {
37 pub(crate) id: u64,
38 pub(crate) requests: mpsc::Sender<UiRequest>,
39 pub(crate) waker: Arc<dyn Fn() + Send + Sync>,
40 }
41
42 impl EmbedHandle {
43 pub fn set_bounds(&self, bounds: EmbedBounds) {
44 self.send(EmbedCommand::Bounds(bounds));
45 }
46
47 pub fn set_visible(&self, visible: bool) {
48 self.send(EmbedCommand::Visible(visible));
49 }
50
51 pub fn navigate(&self, url: String) {
52 self.send(EmbedCommand::Navigate(url));
53 }
54
55 pub fn close(&self) {
56 self.send(EmbedCommand::Close);
57 }
58
59 fn send(&self, command: EmbedCommand) {
60 let request = UiRequest::Embed {
61 id: self.id,
62 command,
63 };
64 if self.requests.send(request).is_ok() {
65 (self.waker)();
66 }
67 }
68 }
@@ -1,7 +1,3 @@
1use std::sync::{Arc, mpsc};
2
3use crate::transport::UiRequest;
4
5#[derive(Debug, Clone)]
1#[derive(Debug, Clone)]
6pub struct EmbedSpec {
2pub struct EmbedSpec {
7 pub parent: isize,
3 pub parent: isize,
@@ -9,60 +5,10 @@ pub struct EmbedSpec {
9 pub background: u32,
5 pub background: u32,
10}
6}
11
7
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct EmbedBounds {
14 pub x: i32,
15 pub y: i32,
16 pub width: i32,
17 pub height: i32,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
8#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum EmbedEvent {
9pub enum EmbedEvent {
22 Navigated(String),
10 Navigated(String),
23 NewWindow(String),
11 NewWindow(String),
12 Loaded,
24 Closed,
13 Closed,
25}
14}
26
27#[derive(Debug)]
28pub(crate) enum EmbedCommand {
29 Bounds(EmbedBounds),
30 Visible(bool),
31 Navigate(String),
32 Close,
33}
34
35#[derive(Clone)]
36pub struct EmbedHandle {
37 pub(crate) id: u64,
38 pub(crate) requests: mpsc::Sender<UiRequest>,
39 pub(crate) waker: Arc<dyn Fn() + Send + Sync>,
40}
41
42impl EmbedHandle {
43 pub fn set_bounds(&self, bounds: EmbedBounds) {
44 self.send(EmbedCommand::Bounds(bounds));
45 }
46
47 pub fn set_visible(&self, visible: bool) {
48 self.send(EmbedCommand::Visible(visible));
49 }
50
51 pub fn navigate(&self, url: String) {
52 self.send(EmbedCommand::Navigate(url));
53 }
54
55 pub fn close(&self) {
56 self.send(EmbedCommand::Close);
57 }
58
59 fn send(&self, command: EmbedCommand) {
60 let request = UiRequest::Embed {
61 id: self.id,
62 command,
63 };
64 if self.requests.send(request).is_ok() {
65 (self.waker)();
66 }
67 }
68}
crates/webview/src/geometry.rs added +131 −0
@@ -0,0 +1,131 @@
1 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2 pub struct EmbedBounds {
3 pub x: i32,
4 pub y: i32,
5 pub width: i32,
6 pub height: i32,
7 }
8
9 impl EmbedBounds {
10 pub fn from_logical(x: f32, y: f32, width: f32, height: f32, scale: f32) -> Self {
11 let physical = |value: f32| (value * scale).round() as i32;
12 EmbedBounds {
13 x: physical(x),
14 y: physical(y),
15 width: physical(width),
16 height: physical(height),
17 }
18 }
19
20 pub fn has_area(self) -> bool {
21 self.width > 0 && self.height > 0
22 }
23
24 fn right(self) -> i32 {
25 self.x + self.width
26 }
27
28 fn bottom(self) -> i32 {
29 self.y + self.height
30 }
31
32 fn within(self, outer: EmbedBounds) -> Option<EmbedBounds> {
33 let left = self.x.max(outer.x);
34 let top = self.y.max(outer.y);
35 let right = self.right().min(outer.right());
36 let bottom = self.bottom().min(outer.bottom());
37 (right > left && bottom > top).then_some(EmbedBounds {
38 x: left,
39 y: top,
40 width: right - left,
41 height: bottom - top,
42 })
43 }
44 }
45
46 /// Cutouts clipped to the content rectangle, relative to its top-left corner.
47 pub fn local_cutouts(content: EmbedBounds, cutouts: &[EmbedBounds]) -> Vec<EmbedBounds> {
48 cutouts
49 .iter()
50 .filter_map(|cutout| cutout.within(content))
51 .map(|clipped| EmbedBounds {
52 x: clipped.x - content.x,
53 y: clipped.y - content.y,
54 ..clipped
55 })
56 .collect()
57 }
58
59 #[cfg(test)]
60 mod tests {
61 use super::{EmbedBounds, local_cutouts};
62
63 fn bounds(x: i32, y: i32, width: i32, height: i32) -> EmbedBounds {
64 EmbedBounds {
65 x,
66 y,
67 width,
68 height,
69 }
70 }
71
72 #[test]
73 fn logical_bounds_scale_to_physical_pixels() {
74 assert_eq!(
75 EmbedBounds::from_logical(10., 20.5, 100., 50., 1.5),
76 bounds(15, 31, 150, 75)
77 );
78 assert_eq!(
79 EmbedBounds::from_logical(10., 20., 100., 50., 1.),
80 bounds(10, 20, 100, 50)
81 );
82 }
83
84 #[test]
85 fn a_cutout_inside_the_content_becomes_content_relative() {
86 let content = bounds(100, 50, 800, 600);
87 assert_eq!(
88 local_cutouts(content, &[bounds(500, 400, 200, 100)]),
89 vec![bounds(400, 350, 200, 100)]
90 );
91 }
92
93 #[test]
94 fn a_cutout_sticking_out_is_clipped_to_the_content() {
95 let content = bounds(100, 50, 800, 600);
96 assert_eq!(
97 local_cutouts(content, &[bounds(850, 600, 200, 200)]),
98 vec![bounds(750, 550, 50, 50)]
99 );
100 assert_eq!(
101 local_cutouts(content, &[bounds(0, 0, 150, 100)]),
102 vec![bounds(0, 0, 50, 50)]
103 );
104 }
105
106 #[test]
107 fn cutouts_outside_or_empty_are_dropped() {
108 let content = bounds(100, 50, 800, 600);
109 assert!(local_cutouts(content, &[bounds(0, 0, 50, 50)]).is_empty());
110 assert!(local_cutouts(content, &[bounds(100, 650, 100, 20)]).is_empty());
111 assert!(local_cutouts(content, &[bounds(200, 200, 0, 40)]).is_empty());
112 }
113
114 #[test]
115 fn scaled_cutouts_line_up_with_scaled_content() {
116 let scale = 1.25;
117 let content = EmbedBounds::from_logical(240., 80., 600., 400., scale);
118 let toast = EmbedBounds::from_logical(660., 380., 180., 100., scale);
119 assert_eq!(
120 local_cutouts(content, &[toast]),
121 vec![bounds(525, 375, 225, 125)]
122 );
123 }
124
125 #[test]
126 fn has_area_needs_both_sides() {
127 assert!(bounds(0, 0, 1, 1).has_area());
128 assert!(!bounds(0, 0, 0, 10).has_area());
129 assert!(!bounds(0, 0, 10, 0).has_area());
130 }
131 }
@@ -0,0 +1,131 @@
1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2pub struct EmbedBounds {
3 pub x: i32,
4 pub y: i32,
5 pub width: i32,
6 pub height: i32,
7}
8
9impl EmbedBounds {
10 pub fn from_logical(x: f32, y: f32, width: f32, height: f32, scale: f32) -> Self {
11 let physical = |value: f32| (value * scale).round() as i32;
12 EmbedBounds {
13 x: physical(x),
14 y: physical(y),
15 width: physical(width),
16 height: physical(height),
17 }
18 }
19
20 pub fn has_area(self) -> bool {
21 self.width > 0 && self.height > 0
22 }
23
24 fn right(self) -> i32 {
25 self.x + self.width
26 }
27
28 fn bottom(self) -> i32 {
29 self.y + self.height
30 }
31
32 fn within(self, outer: EmbedBounds) -> Option<EmbedBounds> {
33 let left = self.x.max(outer.x);
34 let top = self.y.max(outer.y);
35 let right = self.right().min(outer.right());
36 let bottom = self.bottom().min(outer.bottom());
37 (right > left && bottom > top).then_some(EmbedBounds {
38 x: left,
39 y: top,
40 width: right - left,
41 height: bottom - top,
42 })
43 }
44}
45
46/// Cutouts clipped to the content rectangle, relative to its top-left corner.
47pub fn local_cutouts(content: EmbedBounds, cutouts: &[EmbedBounds]) -> Vec<EmbedBounds> {
48 cutouts
49 .iter()
50 .filter_map(|cutout| cutout.within(content))
51 .map(|clipped| EmbedBounds {
52 x: clipped.x - content.x,
53 y: clipped.y - content.y,
54 ..clipped
55 })
56 .collect()
57}
58
59#[cfg(test)]
60mod tests {
61 use super::{EmbedBounds, local_cutouts};
62
63 fn bounds(x: i32, y: i32, width: i32, height: i32) -> EmbedBounds {
64 EmbedBounds {
65 x,
66 y,
67 width,
68 height,
69 }
70 }
71
72 #[test]
73 fn logical_bounds_scale_to_physical_pixels() {
74 assert_eq!(
75 EmbedBounds::from_logical(10., 20.5, 100., 50., 1.5),
76 bounds(15, 31, 150, 75)
77 );
78 assert_eq!(
79 EmbedBounds::from_logical(10., 20., 100., 50., 1.),
80 bounds(10, 20, 100, 50)
81 );
82 }
83
84 #[test]
85 fn a_cutout_inside_the_content_becomes_content_relative() {
86 let content = bounds(100, 50, 800, 600);
87 assert_eq!(
88 local_cutouts(content, &[bounds(500, 400, 200, 100)]),
89 vec![bounds(400, 350, 200, 100)]
90 );
91 }
92
93 #[test]
94 fn a_cutout_sticking_out_is_clipped_to_the_content() {
95 let content = bounds(100, 50, 800, 600);
96 assert_eq!(
97 local_cutouts(content, &[bounds(850, 600, 200, 200)]),
98 vec![bounds(750, 550, 50, 50)]
99 );
100 assert_eq!(
101 local_cutouts(content, &[bounds(0, 0, 150, 100)]),
102 vec![bounds(0, 0, 50, 50)]
103 );
104 }
105
106 #[test]
107 fn cutouts_outside_or_empty_are_dropped() {
108 let content = bounds(100, 50, 800, 600);
109 assert!(local_cutouts(content, &[bounds(0, 0, 50, 50)]).is_empty());
110 assert!(local_cutouts(content, &[bounds(100, 650, 100, 20)]).is_empty());
111 assert!(local_cutouts(content, &[bounds(200, 200, 0, 40)]).is_empty());
112 }
113
114 #[test]
115 fn scaled_cutouts_line_up_with_scaled_content() {
116 let scale = 1.25;
117 let content = EmbedBounds::from_logical(240., 80., 600., 400., scale);
118 let toast = EmbedBounds::from_logical(660., 380., 180., 100., scale);
119 assert_eq!(
120 local_cutouts(content, &[toast]),
121 vec![bounds(525, 375, 225, 125)]
122 );
123 }
124
125 #[test]
126 fn has_area_needs_both_sides() {
127 assert!(bounds(0, 0, 1, 1).has_area());
128 assert!(!bounds(0, 0, 0, 10).has_area());
129 assert!(!bounds(0, 0, 10, 0).has_area());
130 }
131}
crates/webview/src/host.rs +8 −10
@@ -23,7 +23,6 @@ use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};
23 23
24 24 use crate::fanout::Subscribers;
25 25 use crate::host_dialog::{self, Dialog};
26 use crate::host_embed::{self, Embed};
27 26 use crate::transport::{HostState, UiRequest, WebViewTransport};
28 27 use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};
29 28
@@ -55,7 +54,6 @@ pub(crate) struct Shared {
55 54 views: RefCell<HashMap<App, View>>,
56 55 pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,
57 56 pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,
58 pub(crate) embeds: RefCell<HashMap<u64, Embed>>,
59 57 subscribers: RefCell<Subscribers>,
60 58 state: watch::Sender<HostState>,
61 59 requests: mpsc::Receiver<UiRequest>,
@@ -116,7 +114,6 @@ fn run(
116 114 views: RefCell::new(HashMap::new()),
117 115 environment: RefCell::new(None),
118 116 dialogs: RefCell::new(HashMap::new()),
119 embeds: RefCell::new(HashMap::new()),
120 117 subscribers: RefCell::new(Subscribers::default()),
121 118 state,
122 119 requests,
@@ -191,15 +188,19 @@ fn create_views(shared: &Rc<Shared>) -> std::result::Result<(), String> {
191 188 Ok(())
192 189 }
193 190
194 fn create_environment(
195 user_data_folder: &std::path::Path,
196 ) -> std::result::Result<ICoreWebView2Environment, String> {
191 pub(crate) fn environment_options() -> ICoreWebView2EnvironmentOptions {
197 192 let options = CoreWebView2EnvironmentOptions::default();
198 193 unsafe {
199 194 options.set_additional_browser_arguments(BROWSER_ARGUMENTS.to_owned());
200 195 options.set_allow_single_sign_on_using_os_primary_account(true);
201 196 }
202 let options: ICoreWebView2EnvironmentOptions = options.into();
197 options.into()
198 }
199
200 fn create_environment(
201 user_data_folder: &std::path::Path,
202 ) -> std::result::Result<ICoreWebView2Environment, String> {
203 let options = environment_options();
203 204 let folder = HSTRING::from(user_data_folder.as_os_str());
204 205 let (sender, receiver) = mpsc::channel();
205 206 CreateCoreWebView2EnvironmentCompletedHandler::wait_for_async_operation(
@@ -434,8 +435,6 @@ fn drain(shared: &Rc<Shared>) {
434 435 host_dialog::open(shared, id, spec, events)
435 436 }
436 437 UiRequest::Dialog { id, command } => host_dialog::run(shared, id, command),
437 UiRequest::OpenEmbed { id, spec, events } => host_embed::open(shared, id, spec, events),
438 UiRequest::Embed { id, command } => host_embed::run(shared, id, command),
439 438 }
440 439 }
441 440 }
@@ -525,7 +524,6 @@ fn restart(shared: &Rc<Shared>) {
525 524 shared.state.send_modify(|state| state.ready = false);
526 525 shared.subscribers.borrow_mut().clear();
527 526 host_dialog::close_all(shared);
528 host_embed::close_all(shared);
529 527 let views: Vec<View> = shared
530 528 .views
531 529 .borrow_mut()
@@ -23,7 +23,6 @@ use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};
23
23
24use crate::fanout::Subscribers;
24use crate::fanout::Subscribers;
25use crate::host_dialog::{self, Dialog};
25use crate::host_dialog::{self, Dialog};
26use crate::host_embed::{self, Embed};
27use crate::transport::{HostState, UiRequest, WebViewTransport};
26use crate::transport::{HostState, UiRequest, WebViewTransport};
28use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};
27use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};
29
28
@@ -55,7 +54,6 @@ pub(crate) struct Shared {
55 views: RefCell<HashMap<App, View>>,
54 views: RefCell<HashMap<App, View>>,
56 pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,
55 pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,
57 pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,
56 pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,
58 pub(crate) embeds: RefCell<HashMap<u64, Embed>>,
59 subscribers: RefCell<Subscribers>,
57 subscribers: RefCell<Subscribers>,
60 state: watch::Sender<HostState>,
58 state: watch::Sender<HostState>,
61 requests: mpsc::Receiver<UiRequest>,
59 requests: mpsc::Receiver<UiRequest>,
@@ -116,7 +114,6 @@ fn run(
116 views: RefCell::new(HashMap::new()),
114 views: RefCell::new(HashMap::new()),
117 environment: RefCell::new(None),
115 environment: RefCell::new(None),
118 dialogs: RefCell::new(HashMap::new()),
116 dialogs: RefCell::new(HashMap::new()),
119 embeds: RefCell::new(HashMap::new()),
120 subscribers: RefCell::new(Subscribers::default()),
117 subscribers: RefCell::new(Subscribers::default()),
121 state,
118 state,
122 requests,
119 requests,
@@ -191,15 +188,19 @@ fn create_views(shared: &Rc<Shared>) -> std::result::Result<(), String> {
191 Ok(())
188 Ok(())
192}
189}
193
190
194fn create_environment(
191pub(crate) fn environment_options() -> ICoreWebView2EnvironmentOptions {
195 user_data_folder: &std::path::Path,
196) -> std::result::Result<ICoreWebView2Environment, String> {
197 let options = CoreWebView2EnvironmentOptions::default();
192 let options = CoreWebView2EnvironmentOptions::default();
198 unsafe {
193 unsafe {
199 options.set_additional_browser_arguments(BROWSER_ARGUMENTS.to_owned());
194 options.set_additional_browser_arguments(BROWSER_ARGUMENTS.to_owned());
200 options.set_allow_single_sign_on_using_os_primary_account(true);
195 options.set_allow_single_sign_on_using_os_primary_account(true);
201 }
196 }
202 let options: ICoreWebView2EnvironmentOptions = options.into();
197 options.into()
198}
199
200fn create_environment(
201 user_data_folder: &std::path::Path,
202) -> std::result::Result<ICoreWebView2Environment, String> {
203 let options = environment_options();
203 let folder = HSTRING::from(user_data_folder.as_os_str());
204 let folder = HSTRING::from(user_data_folder.as_os_str());
204 let (sender, receiver) = mpsc::channel();
205 let (sender, receiver) = mpsc::channel();
205 CreateCoreWebView2EnvironmentCompletedHandler::wait_for_async_operation(
206 CreateCoreWebView2EnvironmentCompletedHandler::wait_for_async_operation(
@@ -434,8 +435,6 @@ fn drain(shared: &Rc<Shared>) {
434 host_dialog::open(shared, id, spec, events)
435 host_dialog::open(shared, id, spec, events)
435 }
436 }
436 UiRequest::Dialog { id, command } => host_dialog::run(shared, id, command),
437 UiRequest::Dialog { id, command } => host_dialog::run(shared, id, command),
437 UiRequest::OpenEmbed { id, spec, events } => host_embed::open(shared, id, spec, events),
438 UiRequest::Embed { id, command } => host_embed::run(shared, id, command),
439 }
438 }
440 }
439 }
441}
440}
@@ -525,7 +524,6 @@ fn restart(shared: &Rc<Shared>) {
525 shared.state.send_modify(|state| state.ready = false);
524 shared.state.send_modify(|state| state.ready = false);
526 shared.subscribers.borrow_mut().clear();
525 shared.subscribers.borrow_mut().clear();
527 host_dialog::close_all(shared);
526 host_dialog::close_all(shared);
528 host_embed::close_all(shared);
529 let views: Vec<View> = shared
527 let views: Vec<View> = shared
530 .views
528 .views
531 .borrow_mut()
529 .borrow_mut()
crates/webview/src/host_embed.rs deleted +0 −222
@@ -1,222 +0,0 @@
1 use std::rc::Rc;
2
3 use tokio::sync::mpsc::UnboundedSender;
4 use webview2_com::Microsoft::Web::WebView2::Win32::*;
5 use webview2_com::{
6 CreateCoreWebView2ControllerCompletedHandler, NewWindowRequestedEventHandler,
7 SourceChangedEventHandler, take_pwstr,
8 };
9 use windows::Win32::Foundation::{HWND, RECT};
10 use windows::core::{HSTRING, Interface, PWSTR};
11
12 use crate::embed::{EmbedBounds, EmbedCommand, EmbedEvent, EmbedSpec};
13 use crate::host::{Shared, shared as running_host};
14
15 struct EmbedView {
16 controller: ICoreWebView2Controller,
17 webview: ICoreWebView2,
18 }
19
20 pub(crate) struct Embed {
21 view: Option<EmbedView>,
22 bounds: Option<EmbedBounds>,
23 visible: bool,
24 events: UnboundedSender<EmbedEvent>,
25 }
26
27 pub(crate) fn open(
28 shared: &Rc<Shared>,
29 id: u64,
30 spec: EmbedSpec,
31 events: UnboundedSender<EmbedEvent>,
32 ) {
33 let Some(environment) = shared.environment.borrow().clone() else {
34 let _ = events.send(EmbedEvent::Closed);
35 return;
36 };
37 shared.embeds.borrow_mut().insert(
38 id,
39 Embed {
40 view: None,
41 bounds: None,
42 visible: false,
43 events,
44 },
45 );
46 let parent = HWND(spec.parent as *mut _);
47 let handler =
48 CreateCoreWebView2ControllerCompletedHandler::create(Box::new(move |code, controller| {
49 let Some(shared) = running_host() else {
50 return Ok(());
51 };
52 let attached = code
53 .and_then(|()| {
54 controller.ok_or_else(|| windows::core::Error::from(windows::core::HRESULT(-1)))
55 })
56 .and_then(|controller| attach(&shared, id, controller, &spec));
57 if attached.is_err() {
58 close(&shared, id);
59 }
60 Ok(())
61 }));
62 if unsafe { environment.CreateCoreWebView2Controller(parent, &handler) }.is_err() {
63 close(shared, id);
64 }
65 }
66
67 pub(crate) fn run(shared: &Rc<Shared>, id: u64, command: EmbedCommand) {
68 match command {
69 EmbedCommand::Bounds(bounds) => {
70 let controller = update(shared, id, |embed| embed.bounds = Some(bounds));
71 if let Some(controller) = controller {
72 apply_bounds(&controller, bounds);
73 }
74 }
75 EmbedCommand::Visible(visible) => {
76 let controller = update(shared, id, |embed| embed.visible = visible);
77 if let Some(controller) = controller {
78 unsafe {
79 let _ = controller.SetIsVisible(visible);
80 }
81 }
82 }
83 EmbedCommand::Navigate(url) => {
84 let webview = shared
85 .embeds
86 .borrow()
87 .get(&id)
88 .and_then(|embed| embed.view.as_ref().map(|view| view.webview.clone()));
89 if let Some(webview) = webview {
90 unsafe {
91 let _ = webview.Navigate(&HSTRING::from(url));
92 }
93 }
94 }
95 EmbedCommand::Close => close(shared, id),
96 }
97 }
98
99 pub(crate) fn close(shared: &Rc<Shared>, id: u64) {
100 let Some(embed) = shared.embeds.borrow_mut().remove(&id) else {
101 return;
102 };
103 if let Some(view) = &embed.view {
104 unsafe {
105 let _ = view.controller.Close();
106 }
107 }
108 let _ = embed.events.send(EmbedEvent::Closed);
109 }
110
111 pub(crate) fn close_all(shared: &Rc<Shared>) {
112 let ids: Vec<u64> = shared.embeds.borrow().keys().copied().collect();
113 for id in ids {
114 close(shared, id);
115 }
116 }
117
118 fn update(
119 shared: &Shared,
120 id: u64,
121 change: impl FnOnce(&mut Embed),
122 ) -> Option<ICoreWebView2Controller> {
123 let mut embeds = shared.embeds.borrow_mut();
124 let embed = embeds.get_mut(&id)?;
125 change(embed);
126 embed.view.as_ref().map(|view| view.controller.clone())
127 }
128
129 fn emit(id: u64, event: EmbedEvent) {
130 if let Some(shared) = running_host()
131 && let Some(embed) = shared.embeds.borrow().get(&id)
132 {
133 let _ = embed.events.send(event);
134 }
135 }
136
137 fn apply_bounds(controller: &ICoreWebView2Controller, bounds: EmbedBounds) {
138 unsafe {
139 let _ = controller.SetBounds(RECT {
140 left: bounds.x,
141 top: bounds.y,
142 right: bounds.x + bounds.width,
143 bottom: bounds.y + bounds.height,
144 });
145 }
146 }
147
148 fn attach(
149 shared: &Rc<Shared>,
150 id: u64,
151 controller: ICoreWebView2Controller,
152 spec: &EmbedSpec,
153 ) -> windows::core::Result<()> {
154 let Some((bounds, visible)) = shared
155 .embeds
156 .borrow()
157 .get(&id)
158 .map(|embed| (embed.bounds, embed.visible))
159 else {
160 unsafe { controller.Close() }?;
161 return Ok(());
162 };
163 let webview = unsafe { controller.CoreWebView2() }?;
164 unsafe {
165 controller
166 .cast::<ICoreWebView2Controller2>()?
167 .SetDefaultBackgroundColor(COREWEBVIEW2_COLOR {
168 A: 255,
169 R: (spec.background >> 16) as u8,
170 G: (spec.background >> 8) as u8,
171 B: spec.background as u8,
172 })?;
173 webview.Settings()?.SetIsStatusBarEnabled(false)?;
174 }
175 if let Some(bounds) = bounds {
176 apply_bounds(&controller, bounds);
177 }
178 watch_source(&webview, id)?;
179 forward_new_windows(&webview, id)?;
180 unsafe {
181 controller.SetIsVisible(visible)?;
182 webview.Navigate(&HSTRING::from(spec.url.as_str()))?;
183 }
184 if let Some(embed) = shared.embeds.borrow_mut().get_mut(&id) {
185 embed.view = Some(EmbedView {
186 controller,
187 webview,
188 });
189 }
190 Ok(())
191 }
192
193 fn watch_source(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {
194 let handler = SourceChangedEventHandler::create(Box::new(move |sender, _| {
195 if let Some(sender) = sender {
196 let mut source = PWSTR::null();
197 if unsafe { sender.Source(&mut source) }.is_ok() {
198 emit(id, EmbedEvent::Navigated(take_pwstr(source)));
199 }
200 }
201 Ok(())
202 }));
203 let mut token = 0;
204 unsafe { webview.add_SourceChanged(&handler, &mut token) }
205 }
206
207 fn forward_new_windows(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {
208 let handler = NewWindowRequestedEventHandler::create(Box::new(move |_, arguments| {
209 let Some(arguments) = arguments else {
210 return Ok(());
211 };
212 let mut target = PWSTR::null();
213 unsafe {
214 arguments.Uri(&mut target)?;
215 arguments.SetHandled(true)?;
216 }
217 emit(id, EmbedEvent::NewWindow(take_pwstr(target)));
218 Ok(())
219 }));
220 let mut token = 0;
221 unsafe { webview.add_NewWindowRequested(&handler, &mut token) }
222 }
@@ -1,222 +0,0 @@
1use std::rc::Rc;
2
3use tokio::sync::mpsc::UnboundedSender;
4use webview2_com::Microsoft::Web::WebView2::Win32::*;
5use webview2_com::{
6 CreateCoreWebView2ControllerCompletedHandler, NewWindowRequestedEventHandler,
7 SourceChangedEventHandler, take_pwstr,
8};
9use windows::Win32::Foundation::{HWND, RECT};
10use windows::core::{HSTRING, Interface, PWSTR};
11
12use crate::embed::{EmbedBounds, EmbedCommand, EmbedEvent, EmbedSpec};
13use crate::host::{Shared, shared as running_host};
14
15struct EmbedView {
16 controller: ICoreWebView2Controller,
17 webview: ICoreWebView2,
18}
19
20pub(crate) struct Embed {
21 view: Option<EmbedView>,
22 bounds: Option<EmbedBounds>,
23 visible: bool,
24 events: UnboundedSender<EmbedEvent>,
25}
26
27pub(crate) fn open(
28 shared: &Rc<Shared>,
29 id: u64,
30 spec: EmbedSpec,
31 events: UnboundedSender<EmbedEvent>,
32) {
33 let Some(environment) = shared.environment.borrow().clone() else {
34 let _ = events.send(EmbedEvent::Closed);
35 return;
36 };
37 shared.embeds.borrow_mut().insert(
38 id,
39 Embed {
40 view: None,
41 bounds: None,
42 visible: false,
43 events,
44 },
45 );
46 let parent = HWND(spec.parent as *mut _);
47 let handler =
48 CreateCoreWebView2ControllerCompletedHandler::create(Box::new(move |code, controller| {
49 let Some(shared) = running_host() else {
50 return Ok(());
51 };
52 let attached = code
53 .and_then(|()| {
54 controller.ok_or_else(|| windows::core::Error::from(windows::core::HRESULT(-1)))
55 })
56 .and_then(|controller| attach(&shared, id, controller, &spec));
57 if attached.is_err() {
58 close(&shared, id);
59 }
60 Ok(())
61 }));
62 if unsafe { environment.CreateCoreWebView2Controller(parent, &handler) }.is_err() {
63 close(shared, id);
64 }
65}
66
67pub(crate) fn run(shared: &Rc<Shared>, id: u64, command: EmbedCommand) {
68 match command {
69 EmbedCommand::Bounds(bounds) => {
70 let controller = update(shared, id, |embed| embed.bounds = Some(bounds));
71 if let Some(controller) = controller {
72 apply_bounds(&controller, bounds);
73 }
74 }
75 EmbedCommand::Visible(visible) => {
76 let controller = update(shared, id, |embed| embed.visible = visible);
77 if let Some(controller) = controller {
78 unsafe {
79 let _ = controller.SetIsVisible(visible);
80 }
81 }
82 }
83 EmbedCommand::Navigate(url) => {
84 let webview = shared
85 .embeds
86 .borrow()
87 .get(&id)
88 .and_then(|embed| embed.view.as_ref().map(|view| view.webview.clone()));
89 if let Some(webview) = webview {
90 unsafe {
91 let _ = webview.Navigate(&HSTRING::from(url));
92 }
93 }
94 }
95 EmbedCommand::Close => close(shared, id),
96 }
97}
98
99pub(crate) fn close(shared: &Rc<Shared>, id: u64) {
100 let Some(embed) = shared.embeds.borrow_mut().remove(&id) else {
101 return;
102 };
103 if let Some(view) = &embed.view {
104 unsafe {
105 let _ = view.controller.Close();
106 }
107 }
108 let _ = embed.events.send(EmbedEvent::Closed);
109}
110
111pub(crate) fn close_all(shared: &Rc<Shared>) {
112 let ids: Vec<u64> = shared.embeds.borrow().keys().copied().collect();
113 for id in ids {
114 close(shared, id);
115 }
116}
117
118fn update(
119 shared: &Shared,
120 id: u64,
121 change: impl FnOnce(&mut Embed),
122) -> Option<ICoreWebView2Controller> {
123 let mut embeds = shared.embeds.borrow_mut();
124 let embed = embeds.get_mut(&id)?;
125 change(embed);
126 embed.view.as_ref().map(|view| view.controller.clone())
127}
128
129fn emit(id: u64, event: EmbedEvent) {
130 if let Some(shared) = running_host()
131 && let Some(embed) = shared.embeds.borrow().get(&id)
132 {
133 let _ = embed.events.send(event);
134 }
135}
136
137fn apply_bounds(controller: &ICoreWebView2Controller, bounds: EmbedBounds) {
138 unsafe {
139 let _ = controller.SetBounds(RECT {
140 left: bounds.x,
141 top: bounds.y,
142 right: bounds.x + bounds.width,
143 bottom: bounds.y + bounds.height,
144 });
145 }
146}
147
148fn attach(
149 shared: &Rc<Shared>,
150 id: u64,
151 controller: ICoreWebView2Controller,
152 spec: &EmbedSpec,
153) -> windows::core::Result<()> {
154 let Some((bounds, visible)) = shared
155 .embeds
156 .borrow()
157 .get(&id)
158 .map(|embed| (embed.bounds, embed.visible))
159 else {
160 unsafe { controller.Close() }?;
161 return Ok(());
162 };
163 let webview = unsafe { controller.CoreWebView2() }?;
164 unsafe {
165 controller
166 .cast::<ICoreWebView2Controller2>()?
167 .SetDefaultBackgroundColor(COREWEBVIEW2_COLOR {
168 A: 255,
169 R: (spec.background >> 16) as u8,
170 G: (spec.background >> 8) as u8,
171 B: spec.background as u8,
172 })?;
173 webview.Settings()?.SetIsStatusBarEnabled(false)?;
174 }
175 if let Some(bounds) = bounds {
176 apply_bounds(&controller, bounds);
177 }
178 watch_source(&webview, id)?;
179 forward_new_windows(&webview, id)?;
180 unsafe {
181 controller.SetIsVisible(visible)?;
182 webview.Navigate(&HSTRING::from(spec.url.as_str()))?;
183 }
184 if let Some(embed) = shared.embeds.borrow_mut().get_mut(&id) {
185 embed.view = Some(EmbedView {
186 controller,
187 webview,
188 });
189 }
190 Ok(())
191}
192
193fn watch_source(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {
194 let handler = SourceChangedEventHandler::create(Box::new(move |sender, _| {
195 if let Some(sender) = sender {
196 let mut source = PWSTR::null();
197 if unsafe { sender.Source(&mut source) }.is_ok() {
198 emit(id, EmbedEvent::Navigated(take_pwstr(source)));
199 }
200 }
201 Ok(())
202 }));
203 let mut token = 0;
204 unsafe { webview.add_SourceChanged(&handler, &mut token) }
205}
206
207fn forward_new_windows(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {
208 let handler = NewWindowRequestedEventHandler::create(Box::new(move |_, arguments| {
209 let Some(arguments) = arguments else {
210 return Ok(());
211 };
212 let mut target = PWSTR::null();
213 unsafe {
214 arguments.Uri(&mut target)?;
215 arguments.SetHandled(true)?;
216 }
217 emit(id, EmbedEvent::NewWindow(take_pwstr(target)));
218 Ok(())
219 }));
220 let mut token = 0;
221 unsafe { webview.add_NewWindowRequested(&handler, &mut token) }
222}
crates/webview/src/lib.rs +19 −4
@@ -1,20 +1,35 @@
1 #![cfg(windows)]
2
1 #[cfg(windows)]
3 2 mod dialog;
3 #[cfg(windows)]
4 4 mod embed;
5 #[cfg(windows)]
5 6 mod fanout;
7 mod geometry;
8 #[cfg(windows)]
6 9 mod host;
10 #[cfg(windows)]
7 11 mod host_dialog;
8 mod host_embed;
12 #[cfg(windows)]
13 mod main_embed;
14 #[cfg(windows)]
9 15 mod transport;
10 16
17 #[cfg(windows)]
11 18 pub use dialog::{DialogEvent, DialogHandle, DialogSpec};
12 pub use embed::{EmbedBounds, EmbedEvent, EmbedHandle, EmbedSpec};
19 #[cfg(windows)]
20 pub use embed::{EmbedEvent, EmbedSpec};
21 pub use geometry::{EmbedBounds, local_cutouts};
22 #[cfg(windows)]
13 23 pub use host::{HostConfig, start};
24 #[cfg(windows)]
25 pub use main_embed::{EmbedHost, MainEmbed};
26 #[cfg(windows)]
14 27 pub use transport::{HostState, WebViewTransport};
15 28
29 #[cfg(windows)]
16 30 pub(crate) const FORWARDED_EVENTS: [&str; 2] = ["Runtime.bindingCalled", "Page.frameNavigated"];
17 31
32 #[cfg(windows)]
18 33 // A hidden window counts as occluded, so Chromium would otherwise throttle the Trouter keep-alive timers.
19 34 pub(crate) const BROWSER_ARGUMENTS: &str = concat!(
20 35 "--disable-features=Translate,MediaRouter,OptimizationHints ",
@@ -1,20 +1,35 @@
1#![cfg(windows)]
1#[cfg(windows)]
2
3mod dialog;
2mod dialog;
3#[cfg(windows)]
4mod embed;
4mod embed;
5#[cfg(windows)]
5mod fanout;
6mod fanout;
7mod geometry;
8#[cfg(windows)]
6mod host;
9mod host;
10#[cfg(windows)]
7mod host_dialog;
11mod host_dialog;
8mod host_embed;
12#[cfg(windows)]
13mod main_embed;
14#[cfg(windows)]
9mod transport;
15mod transport;
10
16
17#[cfg(windows)]
11pub use dialog::{DialogEvent, DialogHandle, DialogSpec};
18pub use dialog::{DialogEvent, DialogHandle, DialogSpec};
12pub use embed::{EmbedBounds, EmbedEvent, EmbedHandle, EmbedSpec};
19#[cfg(windows)]
20pub use embed::{EmbedEvent, EmbedSpec};
21pub use geometry::{EmbedBounds, local_cutouts};
22#[cfg(windows)]
13pub use host::{HostConfig, start};
23pub use host::{HostConfig, start};
24#[cfg(windows)]
25pub use main_embed::{EmbedHost, MainEmbed};
26#[cfg(windows)]
14pub use transport::{HostState, WebViewTransport};
27pub use transport::{HostState, WebViewTransport};
15
28
29#[cfg(windows)]
16pub(crate) const FORWARDED_EVENTS: [&str; 2] = ["Runtime.bindingCalled", "Page.frameNavigated"];
30pub(crate) const FORWARDED_EVENTS: [&str; 2] = ["Runtime.bindingCalled", "Page.frameNavigated"];
17
31
32#[cfg(windows)]
18// A hidden window counts as occluded, so Chromium would otherwise throttle the Trouter keep-alive timers.
33// A hidden window counts as occluded, so Chromium would otherwise throttle the Trouter keep-alive timers.
19pub(crate) const BROWSER_ARGUMENTS: &str = concat!(
34pub(crate) const BROWSER_ARGUMENTS: &str = concat!(
20 "--disable-features=Translate,MediaRouter,OptimizationHints ",
35 "--disable-features=Translate,MediaRouter,OptimizationHints ",
crates/webview/src/main_embed.rs added +421 −0
@@ -0,0 +1,421 @@
1 use std::cell::RefCell;
2 use std::path::PathBuf;
3 use std::rc::Rc;
4 use std::sync::Once;
5
6 use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
7 use webview2_com::Microsoft::Web::WebView2::Win32::*;
8 use webview2_com::{
9 CreateCoreWebView2ControllerCompletedHandler, CreateCoreWebView2EnvironmentCompletedHandler,
10 NavigationCompletedEventHandler, NewWindowRequestedEventHandler, SourceChangedEventHandler,
11 take_pwstr,
12 };
13 use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM};
14 use windows::Win32::Graphics::Gdi::{
15 CombineRgn, CreateRectRgn, DeleteObject, HGDIOBJ, RGN_DIFF, SetWindowRgn,
16 };
17 use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};
18 use windows::Win32::System::LibraryLoader::GetModuleHandleW;
19 use windows::Win32::UI::WindowsAndMessaging::*;
20 use windows::core::{HRESULT, HSTRING, Interface, PCWSTR, PWSTR, w};
21
22 use crate::embed::{EmbedEvent, EmbedSpec};
23 use crate::geometry::{EmbedBounds, local_cutouts};
24 use crate::host::environment_options;
25
26 const CONTAINER_CLASS: PCWSTR = w!("RustyTeamsEmbedContainer");
27 static REGISTER_CONTAINER_CLASS: Once = Once::new();
28
29 enum Environment {
30 Idle,
31 Creating(Vec<SharedEmbed>),
32 Ready(ICoreWebView2Environment),
33 }
34
35 struct HostInner {
36 user_data_folder: PathBuf,
37 environment: RefCell<Environment>,
38 }
39
40 struct EmbedView {
41 controller: ICoreWebView2Controller,
42 webview: ICoreWebView2,
43 }
44
45 struct EmbedState {
46 spec: EmbedSpec,
47 container: HWND,
48 view: Option<EmbedView>,
49 bounds: Option<EmbedBounds>,
50 visible: bool,
51 cutouts: Vec<EmbedBounds>,
52 closed: bool,
53 events: UnboundedSender<EmbedEvent>,
54 }
55
56 type SharedEmbed = Rc<RefCell<EmbedState>>;
57
58 /// Creates embedded WebView2 views on the calling thread, which must pump Win32 messages.
59 #[derive(Clone)]
60 pub struct EmbedHost {
61 inner: Rc<HostInner>,
62 }
63
64 #[derive(Clone)]
65 pub struct MainEmbed {
66 state: SharedEmbed,
67 }
68
69 impl EmbedHost {
70 pub fn new(user_data_folder: PathBuf) -> Self {
71 unsafe {
72 let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
73 }
74 EmbedHost {
75 inner: Rc::new(HostInner {
76 user_data_folder,
77 environment: RefCell::new(Environment::Idle),
78 }),
79 }
80 }
81
82 pub fn open(&self, spec: EmbedSpec) -> Option<(MainEmbed, UnboundedReceiver<EmbedEvent>)> {
83 let container = create_container(HWND(spec.parent as *mut _)).ok()?;
84 let (events, receiver) = unbounded_channel();
85 let state = Rc::new(RefCell::new(EmbedState {
86 spec,
87 container,
88 view: None,
89 bounds: None,
90 visible: false,
91 cutouts: Vec::new(),
92 closed: false,
93 events,
94 }));
95 self.request_controller(&state);
96 Some((MainEmbed { state }, receiver))
97 }
98
99 fn request_controller(&self, embed: &SharedEmbed) {
100 let ready = match &mut *self.inner.environment.borrow_mut() {
101 Environment::Ready(environment) => Some(environment.clone()),
102 Environment::Creating(waiting) => {
103 waiting.push(embed.clone());
104 return;
105 }
106 environment @ Environment::Idle => {
107 *environment = Environment::Creating(vec![embed.clone()]);
108 None
109 }
110 };
111 match ready {
112 Some(environment) => create_controller(&environment, embed),
113 None => start_environment(&self.inner),
114 }
115 }
116 }
117
118 impl MainEmbed {
119 pub fn place(&self, bounds: EmbedBounds, visible: bool) {
120 {
121 let mut state = self.state.borrow_mut();
122 state.bounds = Some(bounds);
123 state.visible = visible;
124 }
125 layout(&self.state);
126 }
127
128 pub fn set_cutouts(&self, cutouts: Vec<EmbedBounds>) {
129 self.state.borrow_mut().cutouts = cutouts;
130 layout(&self.state);
131 }
132
133 pub fn navigate(&self, url: String) {
134 let webview = {
135 let mut state = self.state.borrow_mut();
136 match &state.view {
137 Some(view) => Some((view.webview.clone(), url)),
138 None => {
139 state.spec.url = url;
140 None
141 }
142 }
143 };
144 if let Some((webview, url)) = webview {
145 unsafe {
146 let _ = webview.Navigate(&HSTRING::from(url));
147 }
148 }
149 }
150
151 pub fn close(&self) {
152 teardown(&self.state);
153 }
154 }
155
156 fn start_environment(host: &Rc<HostInner>) {
157 let completed = host.clone();
158 let handler = CreateCoreWebView2EnvironmentCompletedHandler::create(Box::new(
159 move |code, environment| {
160 environment_ready(&completed, code.ok().and(environment));
161 Ok(())
162 },
163 ));
164 let folder = HSTRING::from(host.user_data_folder.as_os_str());
165 let options = environment_options();
166 let started = unsafe {
167 CreateCoreWebView2EnvironmentWithOptions(PCWSTR::null(), &folder, &options, &handler)
168 };
169 if started.is_err() {
170 environment_ready(host, None);
171 }
172 }
173
174 fn environment_ready(host: &Rc<HostInner>, environment: Option<ICoreWebView2Environment>) {
175 let next = match &environment {
176 Some(environment) => Environment::Ready(environment.clone()),
177 None => Environment::Idle,
178 };
179 let Environment::Creating(waiting) = host.environment.replace(next) else {
180 return;
181 };
182 for embed in waiting {
183 match &environment {
184 Some(environment) => create_controller(environment, &embed),
185 None => fail(&embed),
186 }
187 }
188 }
189
190 fn create_controller(environment: &ICoreWebView2Environment, embed: &SharedEmbed) {
191 let container = embed.borrow().container;
192 let target = embed.clone();
193 let handler =
194 CreateCoreWebView2ControllerCompletedHandler::create(Box::new(move |code, controller| {
195 let attached = code
196 .and_then(|()| controller.ok_or_else(|| windows::core::Error::from(HRESULT(-1))))
197 .and_then(|controller| {
198 attach(&target, controller.clone()).inspect_err(|_| unsafe {
199 let _ = controller.Close();
200 })
201 });
202 if attached.is_err() {
203 fail(&target);
204 }
205 Ok(())
206 }));
207 if unsafe { environment.CreateCoreWebView2Controller(container, &handler) }.is_err() {
208 fail(embed);
209 }
210 }
211
212 fn attach(embed: &SharedEmbed, controller: ICoreWebView2Controller) -> windows::core::Result<()> {
213 let (spec, events, closed) = {
214 let state = embed.borrow();
215 (state.spec.clone(), state.events.clone(), state.closed)
216 };
217 if closed {
218 unsafe { controller.Close() }?;
219 return Ok(());
220 }
221 let webview = unsafe { controller.CoreWebView2() }?;
222 unsafe {
223 controller
224 .cast::<ICoreWebView2Controller2>()?
225 .SetDefaultBackgroundColor(COREWEBVIEW2_COLOR {
226 A: 255,
227 R: (spec.background >> 16) as u8,
228 G: (spec.background >> 8) as u8,
229 B: spec.background as u8,
230 })?;
231 webview.Settings()?.SetIsStatusBarEnabled(false)?;
232 }
233 watch_source(&webview, events.clone())?;
234 watch_loaded(&webview, events.clone())?;
235 forward_new_windows(&webview, events)?;
236 embed.borrow_mut().view = Some(EmbedView {
237 controller,
238 webview: webview.clone(),
239 });
240 layout(embed);
241 unsafe { webview.Navigate(&HSTRING::from(spec.url.as_str())) }
242 }
243
244 fn fail(embed: &SharedEmbed) {
245 let events = embed.borrow().events.clone();
246 if teardown(embed) {
247 let _ = events.send(EmbedEvent::Closed);
248 }
249 }
250
251 fn teardown(embed: &SharedEmbed) -> bool {
252 let (controller, container) = {
253 let mut state = embed.borrow_mut();
254 if state.closed {
255 return false;
256 }
257 state.closed = true;
258 (
259 state.view.take().map(|view| view.controller),
260 state.container,
261 )
262 };
263 unsafe {
264 if let Some(controller) = controller {
265 let _ = controller.Close();
266 }
267 let _ = DestroyWindow(container);
268 }
269 true
270 }
271
272 fn layout(embed: &SharedEmbed) {
273 let (container, bounds, visible, cutouts, controller) = {
274 let state = embed.borrow();
275 if state.closed {
276 return;
277 }
278 (
279 state.container,
280 state.bounds,
281 state.visible,
282 state.cutouts.clone(),
283 state.view.as_ref().map(|view| view.controller.clone()),
284 )
285 };
286 let Some(bounds) = bounds else {
287 return;
288 };
289 let shown = visible && bounds.has_area();
290 unsafe {
291 let _ = SetWindowPos(
292 container,
293 None,
294 bounds.x,
295 bounds.y,
296 bounds.width,
297 bounds.height,
298 SWP_NOZORDER | SWP_NOACTIVATE,
299 );
300 apply_region(container, bounds, &cutouts);
301 let _ = ShowWindow(container, if shown { SW_SHOWNA } else { SW_HIDE });
302 if let Some(controller) = controller {
303 let _ = controller.SetBounds(RECT {
304 left: 0,
305 top: 0,
306 right: bounds.width,
307 bottom: bounds.height,
308 });
309 let _ = controller.SetIsVisible(shown);
310 }
311 }
312 }
313
314 unsafe fn apply_region(container: HWND, content: EmbedBounds, cutouts: &[EmbedBounds]) {
315 let local = local_cutouts(content, cutouts);
316 if local.is_empty() {
317 unsafe { SetWindowRgn(container, None, true) };
318 return;
319 }
320 unsafe {
321 let region = CreateRectRgn(0, 0, content.width, content.height);
322 for cutout in local {
323 let hole = CreateRectRgn(
324 cutout.x,
325 cutout.y,
326 cutout.x + cutout.width,
327 cutout.y + cutout.height,
328 );
329 CombineRgn(Some(region), Some(region), Some(hole), RGN_DIFF);
330 let _ = DeleteObject(HGDIOBJ(hole.0));
331 }
332 SetWindowRgn(container, Some(region), true);
333 }
334 }
335
336 fn create_container(parent: HWND) -> windows::core::Result<HWND> {
337 let instance = HINSTANCE(unsafe { GetModuleHandleW(None) }?.0);
338 REGISTER_CONTAINER_CLASS.call_once(|| {
339 let class = WNDCLASSW {
340 lpfnWndProc: Some(container_procedure),
341 hInstance: instance,
342 lpszClassName: CONTAINER_CLASS,
343 ..Default::default()
344 };
345 unsafe { RegisterClassW(&class) };
346 });
347 unsafe {
348 CreateWindowExW(
349 WINDOW_EX_STYLE::default(),
350 CONTAINER_CLASS,
351 w!(""),
352 WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
353 0,
354 0,
355 0,
356 0,
357 Some(parent),
358 None,
359 Some(instance),
360 None,
361 )
362 }
363 }
364
365 extern "system" fn container_procedure(
366 window: HWND,
367 message: u32,
368 wparam: WPARAM,
369 lparam: LPARAM,
370 ) -> LRESULT {
371 unsafe { DefWindowProcW(window, message, wparam, lparam) }
372 }
373
374 fn watch_source(
375 webview: &ICoreWebView2,
376 events: UnboundedSender<EmbedEvent>,
377 ) -> windows::core::Result<()> {
378 let handler = SourceChangedEventHandler::create(Box::new(move |sender, _| {
379 if let Some(sender) = sender {
380 let mut source = PWSTR::null();
381 if unsafe { sender.Source(&mut source) }.is_ok() {
382 let _ = events.send(EmbedEvent::Navigated(take_pwstr(source)));
383 }
384 }
385 Ok(())
386 }));
387 let mut token = 0;
388 unsafe { webview.add_SourceChanged(&handler, &mut token) }
389 }
390
391 fn watch_loaded(
392 webview: &ICoreWebView2,
393 events: UnboundedSender<EmbedEvent>,
394 ) -> windows::core::Result<()> {
395 let handler = NavigationCompletedEventHandler::create(Box::new(move |_, _| {
396 let _ = events.send(EmbedEvent::Loaded);
397 Ok(())
398 }));
399 let mut token = 0;
400 unsafe { webview.add_NavigationCompleted(&handler, &mut token) }
401 }
402
403 fn forward_new_windows(
404 webview: &ICoreWebView2,
405 events: UnboundedSender<EmbedEvent>,
406 ) -> windows::core::Result<()> {
407 let handler = NewWindowRequestedEventHandler::create(Box::new(move |_, arguments| {
408 let Some(arguments) = arguments else {
409 return Ok(());
410 };
411 let mut target = PWSTR::null();
412 unsafe {
413 arguments.Uri(&mut target)?;
414 arguments.SetHandled(true)?;
415 }
416 let _ = events.send(EmbedEvent::NewWindow(take_pwstr(target)));
417 Ok(())
418 }));
419 let mut token = 0;
420 unsafe { webview.add_NewWindowRequested(&handler, &mut token) }
421 }
@@ -0,0 +1,421 @@
1use std::cell::RefCell;
2use std::path::PathBuf;
3use std::rc::Rc;
4use std::sync::Once;
5
6use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
7use webview2_com::Microsoft::Web::WebView2::Win32::*;
8use webview2_com::{
9 CreateCoreWebView2ControllerCompletedHandler, CreateCoreWebView2EnvironmentCompletedHandler,
10 NavigationCompletedEventHandler, NewWindowRequestedEventHandler, SourceChangedEventHandler,
11 take_pwstr,
12};
13use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM};
14use windows::Win32::Graphics::Gdi::{
15 CombineRgn, CreateRectRgn, DeleteObject, HGDIOBJ, RGN_DIFF, SetWindowRgn,
16};
17use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};
18use windows::Win32::System::LibraryLoader::GetModuleHandleW;
19use windows::Win32::UI::WindowsAndMessaging::*;
20use windows::core::{HRESULT, HSTRING, Interface, PCWSTR, PWSTR, w};
21
22use crate::embed::{EmbedEvent, EmbedSpec};
23use crate::geometry::{EmbedBounds, local_cutouts};
24use crate::host::environment_options;
25
26const CONTAINER_CLASS: PCWSTR = w!("RustyTeamsEmbedContainer");
27static REGISTER_CONTAINER_CLASS: Once = Once::new();
28
29enum Environment {
30 Idle,
31 Creating(Vec<SharedEmbed>),
32 Ready(ICoreWebView2Environment),
33}
34
35struct HostInner {
36 user_data_folder: PathBuf,
37 environment: RefCell<Environment>,
38}
39
40struct EmbedView {
41 controller: ICoreWebView2Controller,
42 webview: ICoreWebView2,
43}
44
45struct EmbedState {
46 spec: EmbedSpec,
47 container: HWND,
48 view: Option<EmbedView>,
49 bounds: Option<EmbedBounds>,
50 visible: bool,
51 cutouts: Vec<EmbedBounds>,
52 closed: bool,
53 events: UnboundedSender<EmbedEvent>,
54}
55
56type SharedEmbed = Rc<RefCell<EmbedState>>;
57
58/// Creates embedded WebView2 views on the calling thread, which must pump Win32 messages.
59#[derive(Clone)]
60pub struct EmbedHost {
61 inner: Rc<HostInner>,
62}
63
64#[derive(Clone)]
65pub struct MainEmbed {
66 state: SharedEmbed,
67}
68
69impl EmbedHost {
70 pub fn new(user_data_folder: PathBuf) -> Self {
71 unsafe {
72 let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
73 }
74 EmbedHost {
75 inner: Rc::new(HostInner {
76 user_data_folder,
77 environment: RefCell::new(Environment::Idle),
78 }),
79 }
80 }
81
82 pub fn open(&self, spec: EmbedSpec) -> Option<(MainEmbed, UnboundedReceiver<EmbedEvent>)> {
83 let container = create_container(HWND(spec.parent as *mut _)).ok()?;
84 let (events, receiver) = unbounded_channel();
85 let state = Rc::new(RefCell::new(EmbedState {
86 spec,
87 container,
88 view: None,
89 bounds: None,
90 visible: false,
91 cutouts: Vec::new(),
92 closed: false,
93 events,
94 }));
95 self.request_controller(&state);
96 Some((MainEmbed { state }, receiver))
97 }
98
99 fn request_controller(&self, embed: &SharedEmbed) {
100 let ready = match &mut *self.inner.environment.borrow_mut() {
101 Environment::Ready(environment) => Some(environment.clone()),
102 Environment::Creating(waiting) => {
103 waiting.push(embed.clone());
104 return;
105 }
106 environment @ Environment::Idle => {
107 *environment = Environment::Creating(vec![embed.clone()]);
108 None
109 }
110 };
111 match ready {
112 Some(environment) => create_controller(&environment, embed),
113 None => start_environment(&self.inner),
114 }
115 }
116}
117
118impl MainEmbed {
119 pub fn place(&self, bounds: EmbedBounds, visible: bool) {
120 {
121 let mut state = self.state.borrow_mut();
122 state.bounds = Some(bounds);
123 state.visible = visible;
124 }
125 layout(&self.state);
126 }
127
128 pub fn set_cutouts(&self, cutouts: Vec<EmbedBounds>) {
129 self.state.borrow_mut().cutouts = cutouts;
130 layout(&self.state);
131 }
132
133 pub fn navigate(&self, url: String) {
134 let webview = {
135 let mut state = self.state.borrow_mut();
136 match &state.view {
137 Some(view) => Some((view.webview.clone(), url)),
138 None => {
139 state.spec.url = url;
140 None
141 }
142 }
143 };
144 if let Some((webview, url)) = webview {
145 unsafe {
146 let _ = webview.Navigate(&HSTRING::from(url));
147 }
148 }
149 }
150
151 pub fn close(&self) {
152 teardown(&self.state);
153 }
154}
155
156fn start_environment(host: &Rc<HostInner>) {
157 let completed = host.clone();
158 let handler = CreateCoreWebView2EnvironmentCompletedHandler::create(Box::new(
159 move |code, environment| {
160 environment_ready(&completed, code.ok().and(environment));
161 Ok(())
162 },
163 ));
164 let folder = HSTRING::from(host.user_data_folder.as_os_str());
165 let options = environment_options();
166 let started = unsafe {
167 CreateCoreWebView2EnvironmentWithOptions(PCWSTR::null(), &folder, &options, &handler)
168 };
169 if started.is_err() {
170 environment_ready(host, None);
171 }
172}
173
174fn environment_ready(host: &Rc<HostInner>, environment: Option<ICoreWebView2Environment>) {
175 let next = match &environment {
176 Some(environment) => Environment::Ready(environment.clone()),
177 None => Environment::Idle,
178 };
179 let Environment::Creating(waiting) = host.environment.replace(next) else {
180 return;
181 };
182 for embed in waiting {
183 match &environment {
184 Some(environment) => create_controller(environment, &embed),
185 None => fail(&embed),
186 }
187 }
188}
189
190fn create_controller(environment: &ICoreWebView2Environment, embed: &SharedEmbed) {
191 let container = embed.borrow().container;
192 let target = embed.clone();
193 let handler =
194 CreateCoreWebView2ControllerCompletedHandler::create(Box::new(move |code, controller| {
195 let attached = code
196 .and_then(|()| controller.ok_or_else(|| windows::core::Error::from(HRESULT(-1))))
197 .and_then(|controller| {
198 attach(&target, controller.clone()).inspect_err(|_| unsafe {
199 let _ = controller.Close();
200 })
201 });
202 if attached.is_err() {
203 fail(&target);
204 }
205 Ok(())
206 }));
207 if unsafe { environment.CreateCoreWebView2Controller(container, &handler) }.is_err() {
208 fail(embed);
209 }
210}
211
212fn attach(embed: &SharedEmbed, controller: ICoreWebView2Controller) -> windows::core::Result<()> {
213 let (spec, events, closed) = {
214 let state = embed.borrow();
215 (state.spec.clone(), state.events.clone(), state.closed)
216 };
217 if closed {
218 unsafe { controller.Close() }?;
219 return Ok(());
220 }
221 let webview = unsafe { controller.CoreWebView2() }?;
222 unsafe {
223 controller
224 .cast::<ICoreWebView2Controller2>()?
225 .SetDefaultBackgroundColor(COREWEBVIEW2_COLOR {
226 A: 255,
227 R: (spec.background >> 16) as u8,
228 G: (spec.background >> 8) as u8,
229 B: spec.background as u8,
230 })?;
231 webview.Settings()?.SetIsStatusBarEnabled(false)?;
232 }
233 watch_source(&webview, events.clone())?;
234 watch_loaded(&webview, events.clone())?;
235 forward_new_windows(&webview, events)?;
236 embed.borrow_mut().view = Some(EmbedView {
237 controller,
238 webview: webview.clone(),
239 });
240 layout(embed);
241 unsafe { webview.Navigate(&HSTRING::from(spec.url.as_str())) }
242}
243
244fn fail(embed: &SharedEmbed) {
245 let events = embed.borrow().events.clone();
246 if teardown(embed) {
247 let _ = events.send(EmbedEvent::Closed);
248 }
249}
250
251fn teardown(embed: &SharedEmbed) -> bool {
252 let (controller, container) = {
253 let mut state = embed.borrow_mut();
254 if state.closed {
255 return false;
256 }
257 state.closed = true;
258 (
259 state.view.take().map(|view| view.controller),
260 state.container,
261 )
262 };
263 unsafe {
264 if let Some(controller) = controller {
265 let _ = controller.Close();
266 }
267 let _ = DestroyWindow(container);
268 }
269 true
270}
271
272fn layout(embed: &SharedEmbed) {
273 let (container, bounds, visible, cutouts, controller) = {
274 let state = embed.borrow();
275 if state.closed {
276 return;
277 }
278 (
279 state.container,
280 state.bounds,
281 state.visible,
282 state.cutouts.clone(),
283 state.view.as_ref().map(|view| view.controller.clone()),
284 )
285 };
286 let Some(bounds) = bounds else {
287 return;
288 };
289 let shown = visible && bounds.has_area();
290 unsafe {
291 let _ = SetWindowPos(
292 container,
293 None,
294 bounds.x,
295 bounds.y,
296 bounds.width,
297 bounds.height,
298 SWP_NOZORDER | SWP_NOACTIVATE,
299 );
300 apply_region(container, bounds, &cutouts);
301 let _ = ShowWindow(container, if shown { SW_SHOWNA } else { SW_HIDE });
302 if let Some(controller) = controller {
303 let _ = controller.SetBounds(RECT {
304 left: 0,
305 top: 0,
306 right: bounds.width,
307 bottom: bounds.height,
308 });
309 let _ = controller.SetIsVisible(shown);
310 }
311 }
312}
313
314unsafe fn apply_region(container: HWND, content: EmbedBounds, cutouts: &[EmbedBounds]) {
315 let local = local_cutouts(content, cutouts);
316 if local.is_empty() {
317 unsafe { SetWindowRgn(container, None, true) };
318 return;
319 }
320 unsafe {
321 let region = CreateRectRgn(0, 0, content.width, content.height);
322 for cutout in local {
323 let hole = CreateRectRgn(
324 cutout.x,
325 cutout.y,
326 cutout.x + cutout.width,
327 cutout.y + cutout.height,
328 );
329 CombineRgn(Some(region), Some(region), Some(hole), RGN_DIFF);
330 let _ = DeleteObject(HGDIOBJ(hole.0));
331 }
332 SetWindowRgn(container, Some(region), true);
333 }
334}
335
336fn create_container(parent: HWND) -> windows::core::Result<HWND> {
337 let instance = HINSTANCE(unsafe { GetModuleHandleW(None) }?.0);
338 REGISTER_CONTAINER_CLASS.call_once(|| {
339 let class = WNDCLASSW {
340 lpfnWndProc: Some(container_procedure),
341 hInstance: instance,
342 lpszClassName: CONTAINER_CLASS,
343 ..Default::default()
344 };
345 unsafe { RegisterClassW(&class) };
346 });
347 unsafe {
348 CreateWindowExW(
349 WINDOW_EX_STYLE::default(),
350 CONTAINER_CLASS,
351 w!(""),
352 WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
353 0,
354 0,
355 0,
356 0,
357 Some(parent),
358 None,
359 Some(instance),
360 None,
361 )
362 }
363}
364
365extern "system" fn container_procedure(
366 window: HWND,
367 message: u32,
368 wparam: WPARAM,
369 lparam: LPARAM,
370) -> LRESULT {
371 unsafe { DefWindowProcW(window, message, wparam, lparam) }
372}
373
374fn watch_source(
375 webview: &ICoreWebView2,
376 events: UnboundedSender<EmbedEvent>,
377) -> windows::core::Result<()> {
378 let handler = SourceChangedEventHandler::create(Box::new(move |sender, _| {
379 if let Some(sender) = sender {
380 let mut source = PWSTR::null();
381 if unsafe { sender.Source(&mut source) }.is_ok() {
382 let _ = events.send(EmbedEvent::Navigated(take_pwstr(source)));
383 }
384 }
385 Ok(())
386 }));
387 let mut token = 0;
388 unsafe { webview.add_SourceChanged(&handler, &mut token) }
389}
390
391fn watch_loaded(
392 webview: &ICoreWebView2,
393 events: UnboundedSender<EmbedEvent>,
394) -> windows::core::Result<()> {
395 let handler = NavigationCompletedEventHandler::create(Box::new(move |_, _| {
396 let _ = events.send(EmbedEvent::Loaded);
397 Ok(())
398 }));
399 let mut token = 0;
400 unsafe { webview.add_NavigationCompleted(&handler, &mut token) }
401}
402
403fn forward_new_windows(
404 webview: &ICoreWebView2,
405 events: UnboundedSender<EmbedEvent>,
406) -> windows::core::Result<()> {
407 let handler = NewWindowRequestedEventHandler::create(Box::new(move |_, arguments| {
408 let Some(arguments) = arguments else {
409 return Ok(());
410 };
411 let mut target = PWSTR::null();
412 unsafe {
413 arguments.Uri(&mut target)?;
414 arguments.SetHandled(true)?;
415 }
416 let _ = events.send(EmbedEvent::NewWindow(take_pwstr(target)));
417 Ok(())
418 }));
419 let mut token = 0;
420 unsafe { webview.add_NewWindowRequested(&handler, &mut token) }
421}
crates/webview/src/transport.rs +0 −24
@@ -13,7 +13,6 @@ use tokio::sync::{
13 13 };
14 14
15 15 use crate::dialog::{DialogCommand, DialogEvent, DialogHandle, DialogSpec};
16 use crate::embed::{EmbedCommand, EmbedEvent, EmbedHandle, EmbedSpec};
17 16
18 17 const ENDPOINT_NAME: &str = "WebView2";
19 18 const READY_WAIT: Duration = Duration::from_secs(30);
@@ -40,15 +39,6 @@ pub(crate) enum UiRequest {
40 39 id: u64,
41 40 command: DialogCommand,
42 41 },
43 OpenEmbed {
44 id: u64,
45 spec: EmbedSpec,
46 events: UnboundedSender<EmbedEvent>,
47 },
48 Embed {
49 id: u64,
50 command: EmbedCommand,
51 },
52 42 }
53 43
54 44 #[derive(Debug, Clone, Default)]
@@ -64,7 +54,6 @@ pub struct WebViewTransport {
64 54 state: watch::Receiver<HostState>,
65 55 ready_wait: Duration,
66 56 next_dialog: AtomicU64,
67 next_embed: AtomicU64,
68 57 }
69 58
70 59 impl WebViewTransport {
@@ -79,7 +68,6 @@ impl WebViewTransport {
79 68 state,
80 69 ready_wait: READY_WAIT,
81 70 next_dialog: AtomicU64::new(1),
82 next_embed: AtomicU64::new(1),
83 71 }
84 72 }
85 73
@@ -95,18 +83,6 @@ impl WebViewTransport {
95 83 (handle, receiver)
96 84 }
97 85
98 pub fn open_embed(&self, spec: EmbedSpec) -> (EmbedHandle, UnboundedReceiver<EmbedEvent>) {
99 let id = self.next_embed.fetch_add(1, Ordering::Relaxed);
100 let (events, receiver) = unbounded_channel();
101 let handle = EmbedHandle {
102 id,
103 requests: self.requests.clone(),
104 waker: self.waker.clone(),
105 };
106 let _ = self.send(UiRequest::OpenEmbed { id, spec, events });
107 (handle, receiver)
108 }
109
110 86 fn send(&self, request: UiRequest) -> Result<()> {
111 87 self.requests
112 88 .send(request)
@@ -13,7 +13,6 @@ use tokio::sync::{
13};
13};
14
14
15use crate::dialog::{DialogCommand, DialogEvent, DialogHandle, DialogSpec};
15use crate::dialog::{DialogCommand, DialogEvent, DialogHandle, DialogSpec};
16use crate::embed::{EmbedCommand, EmbedEvent, EmbedHandle, EmbedSpec};
17
16
18const ENDPOINT_NAME: &str = "WebView2";
17const ENDPOINT_NAME: &str = "WebView2";
19const READY_WAIT: Duration = Duration::from_secs(30);
18const READY_WAIT: Duration = Duration::from_secs(30);
@@ -40,15 +39,6 @@ pub(crate) enum UiRequest {
40 id: u64,
39 id: u64,
41 command: DialogCommand,
40 command: DialogCommand,
42 },
41 },
43 OpenEmbed {
44 id: u64,
45 spec: EmbedSpec,
46 events: UnboundedSender<EmbedEvent>,
47 },
48 Embed {
49 id: u64,
50 command: EmbedCommand,
51 },
52}
42}
53
43
54#[derive(Debug, Clone, Default)]
44#[derive(Debug, Clone, Default)]
@@ -64,7 +54,6 @@ pub struct WebViewTransport {
64 state: watch::Receiver<HostState>,
54 state: watch::Receiver<HostState>,
65 ready_wait: Duration,
55 ready_wait: Duration,
66 next_dialog: AtomicU64,
56 next_dialog: AtomicU64,
67 next_embed: AtomicU64,
68}
57}
69
58
70impl WebViewTransport {
59impl WebViewTransport {
@@ -79,7 +68,6 @@ impl WebViewTransport {
79 state,
68 state,
80 ready_wait: READY_WAIT,
69 ready_wait: READY_WAIT,
81 next_dialog: AtomicU64::new(1),
70 next_dialog: AtomicU64::new(1),
82 next_embed: AtomicU64::new(1),
83 }
71 }
84 }
72 }
85
73
@@ -95,18 +83,6 @@ impl WebViewTransport {
95 (handle, receiver)
83 (handle, receiver)
96 }
84 }
97
85
98 pub fn open_embed(&self, spec: EmbedSpec) -> (EmbedHandle, UnboundedReceiver<EmbedEvent>) {
99 let id = self.next_embed.fetch_add(1, Ordering::Relaxed);
100 let (events, receiver) = unbounded_channel();
101 let handle = EmbedHandle {
102 id,
103 requests: self.requests.clone(),
104 waker: self.waker.clone(),
105 };
106 let _ = self.send(UiRequest::OpenEmbed { id, spec, events });
107 (handle, receiver)
108 }
109
110 fn send(&self, request: UiRequest) -> Result<()> {
86 fn send(&self, request: UiRequest) -> Result<()> {
111 self.requests
87 self.requests
112 .send(request)
88 .send(request)
scripts/build-windows.sh +9 −3
@@ -1,6 +1,6 @@
1 1 #!/usr/bin/env bash
2 2 # Cross-build a GPUI crate to a Windows .exe from WSL/Linux. No admin, no Visual Studio.
3 # Usage: scripts/build-windows.sh [crate-dir, default spikes/gpui-list] [binary-name, default: the crate's only binary]
3 # Usage: scripts/build-windows.sh [crate-dir, default spikes/gpui-list] [binary-or-example-name, default: the crate's only binary]
4 4 set -euo pipefail
5 5 repoRoot="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
6 6 crateDir="$(realpath "${1:-$repoRoot/spikes/gpui-list}")"
@@ -40,7 +40,13 @@ PY
40 40
41 41 cd "$crateDir"
42 42 binaryArguments=()
43 [ -n "$binaryName" ] && binaryArguments=(--bin "$binaryName")
43 outputDir="$CARGO_TARGET_DIR/$targetName/release"
44 if [ -n "$binaryName" ] && [ -f "$crateDir/examples/$binaryName.rs" ]; then
45 binaryArguments=(--example "$binaryName")
46 outputDir="$outputDir/examples"
47 elif [ -n "$binaryName" ]; then
48 binaryArguments=(--bin "$binaryName")
49 fi
44 50 cargo xwin build --release --target "$targetName" "${binaryArguments[@]}" \
45 51 --config "patch.crates-io.gpui-pre-windows.path=\"$patchedDir\""
46 ls -la "$CARGO_TARGET_DIR/$targetName/release/"*.exe
52 ls -la "$outputDir/"*.exe
@@ -1,6 +1,6 @@
1#!/usr/bin/env bash
1#!/usr/bin/env bash
2# Cross-build a GPUI crate to a Windows .exe from WSL/Linux. No admin, no Visual Studio.
2# Cross-build a GPUI crate to a Windows .exe from WSL/Linux. No admin, no Visual Studio.
3# Usage: scripts/build-windows.sh [crate-dir, default spikes/gpui-list] [binary-name, default: the crate's only binary]
3# Usage: scripts/build-windows.sh [crate-dir, default spikes/gpui-list] [binary-or-example-name, default: the crate's only binary]
4set -euo pipefail
4set -euo pipefail
5repoRoot="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
5repoRoot="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
6crateDir="$(realpath "${1:-$repoRoot/spikes/gpui-list}")"
6crateDir="$(realpath "${1:-$repoRoot/spikes/gpui-list}")"
@@ -40,7 +40,13 @@ PY
40
40
41cd "$crateDir"
41cd "$crateDir"
42binaryArguments=()
42binaryArguments=()
43[ -n "$binaryName" ] && binaryArguments=(--bin "$binaryName")
43outputDir="$CARGO_TARGET_DIR/$targetName/release"
44if [ -n "$binaryName" ] && [ -f "$crateDir/examples/$binaryName.rs" ]; then
45 binaryArguments=(--example "$binaryName")
46 outputDir="$outputDir/examples"
47elif [ -n "$binaryName" ]; then
48 binaryArguments=(--bin "$binaryName")
49fi
44cargo xwin build --release --target "$targetName" "${binaryArguments[@]}" \
50cargo xwin build --release --target "$targetName" "${binaryArguments[@]}" \
45 --config "patch.crates-io.gpui-pre-windows.path=\"$patchedDir\""
51 --config "patch.crates-io.gpui-pre-windows.path=\"$patchedDir\""
46ls -la "$CARGO_TARGET_DIR/$targetName/release/"*.exe
52ls -la "$outputDir/"*.exe