BlueGit

ict rusty-teams

Files

rusty-teams / crates / webview / src / host_dialog.rs

host_dialog.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
host_dialog.rs 17.6 KiB Download Raw
1use std::rc::Rc;
2
3use tokio::sync::mpsc::UnboundedSender;
4use webview2_com::Microsoft::Web::WebView2::Win32::*;
5use webview2_com::{
6 AcceleratorKeyPressedEventHandler, AddScriptToExecuteOnDocumentCreatedCompletedHandler,
7 CreateCoreWebView2ControllerCompletedHandler, LaunchingExternalUriSchemeEventHandler,
8 NewWindowRequestedEventHandler, PermissionRequestedEventHandler,
9 WebMessageReceivedEventHandler, WebResourceRequestedEventHandler, take_pwstr,
10};
11use windows::Win32::Foundation::{COLORREF, HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM};
12use windows::Win32::Graphics::Gdi::{
13 CreateSolidBrush, GetMonitorInfoW, MONITOR_DEFAULTTONEAREST, MONITOR_DEFAULTTOPRIMARY,
14 MONITOR_FROM_FLAGS, MONITORINFO, MonitorFromWindow,
15};
16use windows::Win32::System::LibraryLoader::GetModuleHandleW;
17use windows::Win32::UI::HiDpi::{AdjustWindowRectExForDpi, GetDpiForWindow};
18use windows::Win32::UI::Shell::SHCreateMemStream;
19use windows::Win32::UI::WindowsAndMessaging::*;
20use windows::core::{HSTRING, Interface, PWSTR, w};
21
22use crate::dialog::{DialogCommand, DialogEvent, DialogMode, DialogSpec, NEW_WINDOW_KIND};
23use crate::host::{Shared, fit, shared as running_host};
24
25const DIALOG_CLASS: windows::core::PCWSTR = w!("RustyTeamsDialog");
26const DIALOG_STYLE: WINDOW_STYLE = WINDOW_STYLE(WS_CAPTION.0 | WS_SYSMENU.0);
27const CALL_STYLE: WINDOW_STYLE = WS_OVERLAPPEDWINDOW;
28const MEDIA_ORIGINS: [&str; 3] = [
29 "https://teams.microsoft.com/",
30 "https://teams.cloud.microsoft/",
31 "https://teams.live.com/",
32];
33const BASE_DPI: u32 = 96;
34const VIRTUAL_KEY_ESCAPE: u32 = 0x1B;
35const PAGE_HEADERS: windows::core::PCWSTR =
36 w!("Content-Type: text/html; charset=utf-8\r\nCache-Control: no-store");
37const CALL_SHADOW_SCRIPT: &str = include_str!("call_shadow.js");
38
39struct DialogView {
40 controller: ICoreWebView2Controller,
41 webview: ICoreWebView2,
42}
43
44pub(crate) struct Dialog {
45 window: HWND,
46 view: Option<DialogView>,
47 events: UnboundedSender<DialogEvent>,
48}
49
50struct HostPage {
51 mode: DialogMode,
52 url: String,
53 html: String,
54}
55
56pub(crate) fn open(
57 shared: &Rc<Shared>,
58 id: u64,
59 spec: DialogSpec,
60 events: UnboundedSender<DialogEvent>,
61) {
62 let Some(environment) = shared.environment.borrow().clone() else {
63 let _ = events.send(DialogEvent::Closed);
64 return;
65 };
66 let Ok(window) = create_window(&spec) else {
67 let _ = events.send(DialogEvent::Closed);
68 return;
69 };
70 shared.dialogs.borrow_mut().insert(
71 id,
72 Dialog {
73 window,
74 view: None,
75 events,
76 },
77 );
78 unsafe {
79 let _ = ShowWindow(window, SW_SHOW);
80 let _ = SetForegroundWindow(window);
81 }
82 let page = HostPage {
83 mode: spec.mode,
84 url: spec.page_url,
85 html: spec.page_html,
86 };
87 let creator = environment.clone();
88 let handler =
89 CreateCoreWebView2ControllerCompletedHandler::create(Box::new(move |code, controller| {
90 let Some(shared) = running_host() else {
91 return Ok(());
92 };
93 let attached = code
94 .and_then(|()| {
95 controller.ok_or_else(|| windows::core::Error::from(windows::core::HRESULT(-1)))
96 })
97 .and_then(|controller| {
98 attach(&shared, id, &environment, controller, page, spec.background)
99 });
100 if attached.is_err() {
101 close(&shared, id);
102 }
103 Ok(())
104 }));
105 if unsafe { creator.CreateCoreWebView2Controller(window, &handler) }.is_err() {
106 close(shared, id);
107 }
108}
109
110pub(crate) fn run(shared: &Rc<Shared>, id: u64, command: DialogCommand) {
111 match command {
112 DialogCommand::Post(json) => {
113 let webview = shared
114 .dialogs
115 .borrow()
116 .get(&id)
117 .and_then(|dialog| dialog.view.as_ref().map(|view| view.webview.clone()));
118 if let Some(webview) = webview {
119 unsafe {
120 let _ = webview.PostWebMessageAsJson(&HSTRING::from(json));
121 }
122 }
123 }
124 DialogCommand::Resize { width, height } => resize(shared, id, width, height),
125 DialogCommand::Close => close(shared, id),
126 }
127}
128
129pub(crate) fn close(shared: &Rc<Shared>, id: u64) {
130 let Some(dialog) = shared.dialogs.borrow_mut().remove(&id) else {
131 return;
132 };
133 unsafe {
134 if let Some(view) = &dialog.view {
135 let _ = view.controller.Close();
136 }
137 let _ = DestroyWindow(dialog.window);
138 }
139 let _ = dialog.events.send(DialogEvent::Closed);
140}
141
142pub(crate) fn close_all(shared: &Rc<Shared>) {
143 let ids: Vec<u64> = shared.dialogs.borrow().keys().copied().collect();
144 for id in ids {
145 close(shared, id);
146 }
147}
148
149fn id_of(shared: &Shared, window: HWND) -> Option<u64> {
150 shared
151 .dialogs
152 .borrow()
153 .iter()
154 .find_map(|(&id, dialog)| (dialog.window == window).then_some(id))
155}
156
157fn emit(id: u64, event: DialogEvent) {
158 if let Some(shared) = running_host()
159 && let Some(dialog) = shared.dialogs.borrow().get(&id)
160 {
161 let _ = dialog.events.send(event);
162 }
163}
164
165fn work_area(window: HWND, flags: MONITOR_FROM_FLAGS) -> RECT {
166 let mut info = MONITORINFO {
167 cbSize: std::mem::size_of::<MONITORINFO>() as u32,
168 ..Default::default()
169 };
170 unsafe {
171 let monitor = MonitorFromWindow(window, flags);
172 let _ = GetMonitorInfoW(monitor, &mut info);
173 }
174 info.rcWork
175}
176
177fn outer_size(client_width: i32, client_height: i32, dpi: u32, work: RECT) -> (i32, i32) {
178 let mut frame = RECT {
179 left: 0,
180 top: 0,
181 right: client_width,
182 bottom: client_height,
183 };
184 unsafe {
185 let _ = AdjustWindowRectExForDpi(
186 &mut frame,
187 DIALOG_STYLE,
188 false,
189 WINDOW_EX_STYLE::default(),
190 dpi,
191 );
192 }
193 (
194 (frame.right - frame.left).min(work.right - work.left),
195 (frame.bottom - frame.top).min(work.bottom - work.top),
196 )
197}
198
199fn scaled(logical: u32, dpi: u32) -> i32 {
200 (logical as u64 * dpi as u64 / BASE_DPI as u64) as i32
201}
202
203fn create_window(spec: &DialogSpec) -> windows::core::Result<HWND> {
204 let instance = HINSTANCE(unsafe { GetModuleHandleW(None) }?.0);
205 let blue_green_red =
206 (spec.background & 0xff) << 16 | (spec.background & 0xff00) | (spec.background >> 16);
207 let class = WNDCLASSW {
208 lpfnWndProc: Some(dialog_procedure),
209 hInstance: instance,
210 lpszClassName: DIALOG_CLASS,
211 hbrBackground: unsafe { CreateSolidBrush(COLORREF(blue_green_red)) },
212 ..Default::default()
213 };
214 unsafe { RegisterClassW(&class) };
215 let owner = spec.owner.map(|raw| HWND(raw as *mut _));
216 let (dpi, work, owner_bounds) = match owner {
217 Some(owner) => {
218 let mut bounds = RECT::default();
219 unsafe {
220 let _ = GetWindowRect(owner, &mut bounds);
221 }
222 let dpi = unsafe { GetDpiForWindow(owner) }.max(BASE_DPI);
223 (
224 dpi,
225 work_area(owner, MONITOR_DEFAULTTONEAREST),
226 Some(bounds),
227 )
228 }
229 None => (
230 BASE_DPI,
231 work_area(HWND::default(), MONITOR_DEFAULTTOPRIMARY),
232 None,
233 ),
234 };
235 let (width, height) = outer_size(scaled(spec.width, dpi), scaled(spec.height, dpi), dpi, work);
236 let anchor = owner_bounds.unwrap_or(work);
237 let left = (anchor.left + (anchor.right - anchor.left - width) / 2)
238 .clamp(work.left, (work.right - width).max(work.left));
239 let top = (anchor.top + (anchor.bottom - anchor.top - height) / 2)
240 .clamp(work.top, (work.bottom - height).max(work.top));
241 unsafe {
242 CreateWindowExW(
243 WINDOW_EX_STYLE::default(),
244 DIALOG_CLASS,
245 &HSTRING::from(spec.title.as_str()),
246 match spec.mode {
247 DialogMode::Hosted => DIALOG_STYLE,
248 DialogMode::Call => CALL_STYLE,
249 },
250 left,
251 top,
252 width,
253 height,
254 owner,
255 None,
256 Some(instance),
257 None,
258 )
259 }
260}
261
262fn resize(shared: &Rc<Shared>, id: u64, width: Option<u32>, height: Option<u32>) {
263 let Some(window) = shared.dialogs.borrow().get(&id).map(|dialog| dialog.window) else {
264 return;
265 };
266 let dpi = unsafe { GetDpiForWindow(window) }.max(BASE_DPI);
267 let mut client = RECT::default();
268 unsafe {
269 let _ = GetClientRect(window, &mut client);
270 }
271 let client_width = width.map_or(client.right - client.left, |width| scaled(width, dpi));
272 let client_height = height.map_or(client.bottom - client.top, |height| scaled(height, dpi));
273 let (outer_width, outer_height) = outer_size(
274 client_width,
275 client_height,
276 dpi,
277 work_area(window, MONITOR_DEFAULTTONEAREST),
278 );
279 unsafe {
280 let _ = SetWindowPos(
281 window,
282 None,
283 0,
284 0,
285 outer_width,
286 outer_height,
287 SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE,
288 );
289 }
290}
291
292fn attach(
293 shared: &Rc<Shared>,
294 id: u64,
295 environment: &ICoreWebView2Environment,
296 controller: ICoreWebView2Controller,
297 page: HostPage,
298 background: u32,
299) -> windows::core::Result<()> {
300 let Some(window) = shared.dialogs.borrow().get(&id).map(|dialog| dialog.window) else {
301 unsafe { controller.Close() }?;
302 return Ok(());
303 };
304 let webview = unsafe { controller.CoreWebView2() }?;
305 fit(window, &controller);
306 unsafe {
307 controller
308 .cast::<ICoreWebView2Controller2>()?
309 .SetDefaultBackgroundColor(COREWEBVIEW2_COLOR {
310 A: 255,
311 R: (background >> 16) as u8,
312 G: (background >> 8) as u8,
313 B: background as u8,
314 })?;
315 webview.Settings()?.SetIsStatusBarEnabled(false)?;
316 }
317 match page.mode {
318 DialogMode::Hosted => {
319 serve_host_page(&webview, environment, &page)?;
320 let page_url = page.url.clone();
321 forward_messages(&webview, id, move |source| source == page_url)?;
322 close_on_escape(&controller, window)?;
323 }
324 DialogMode::Call => {
325 allow_teams_media(&webview)?;
326 shadow_calls(&webview)?;
327 block_app_launch(&webview)?;
328 forward_messages(&webview, id, is_media_origin)?;
329 }
330 }
331 forward_new_windows(&webview, id)?;
332 unsafe {
333 controller.SetIsVisible(true)?;
334 webview.Navigate(&HSTRING::from(page.url.as_str()))?;
335 }
336 if let Some(dialog) = shared.dialogs.borrow_mut().get_mut(&id) {
337 dialog.view = Some(DialogView {
338 controller,
339 webview,
340 });
341 }
342 Ok(())
343}
344
345fn serve_host_page(
346 webview: &ICoreWebView2,
347 environment: &ICoreWebView2Environment,
348 page: &HostPage,
349) -> windows::core::Result<()> {
350 let filter = HSTRING::from(page.url.as_str());
351 unsafe {
352 match webview.cast::<ICoreWebView2_22>() {
353 Ok(webview) => webview.AddWebResourceRequestedFilterWithRequestSourceKinds(
354 &filter,
355 COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT,
356 COREWEBVIEW2_WEB_RESOURCE_REQUEST_SOURCE_KINDS_ALL,
357 )?,
358 Err(_) => webview.AddWebResourceRequestedFilter(
359 &filter,
360 COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT,
361 )?,
362 }
363 }
364 let environment = environment.clone();
365 let (url, html) = (page.url.clone(), page.html.clone());
366 let handler = WebResourceRequestedEventHandler::create(Box::new(move |_, arguments| {
367 let Some(arguments) = arguments else {
368 return Ok(());
369 };
370 let request = unsafe { arguments.Request() }?;
371 let mut requested = PWSTR::null();
372 unsafe { request.Uri(&mut requested) }?;
373 if take_pwstr(requested) != url {
374 return Ok(());
375 }
376 let stream = unsafe { SHCreateMemStream(Some(html.as_bytes())) }
377 .ok_or_else(|| windows::core::Error::from(windows::core::HRESULT(-1)))?;
378 let response =
379 unsafe { environment.CreateWebResourceResponse(&stream, 200, w!("OK"), PAGE_HEADERS) }?;
380 unsafe { arguments.SetResponse(&response) }
381 }));
382 let mut token = 0;
383 unsafe { webview.add_WebResourceRequested(&handler, &mut token) }
384}
385
386fn forward_messages(
387 webview: &ICoreWebView2,
388 id: u64,
389 accepts: impl Fn(&str) -> bool + 'static,
390) -> windows::core::Result<()> {
391 let handler = WebMessageReceivedEventHandler::create(Box::new(move |_, arguments| {
392 let Some(arguments) = arguments else {
393 return Ok(());
394 };
395 let mut source = PWSTR::null();
396 unsafe { arguments.Source(&mut source) }?;
397 if !accepts(&take_pwstr(source)) {
398 return Ok(());
399 }
400 let mut message = PWSTR::null();
401 if unsafe { arguments.TryGetWebMessageAsString(&mut message) }.is_ok() {
402 emit(id, DialogEvent::Message(take_pwstr(message)));
403 }
404 Ok(())
405 }));
406 let mut token = 0;
407 unsafe { webview.add_WebMessageReceived(&handler, &mut token) }
408}
409
410fn allow_teams_media(webview: &ICoreWebView2) -> windows::core::Result<()> {
411 let handler = PermissionRequestedEventHandler::create(Box::new(move |_, arguments| {
412 let Some(arguments) = arguments else {
413 return Ok(());
414 };
415 let mut origin = PWSTR::null();
416 let mut kind = COREWEBVIEW2_PERMISSION_KIND::default();
417 unsafe {
418 arguments.Uri(&mut origin)?;
419 arguments.PermissionKind(&mut kind)?;
420 }
421 let origin = take_pwstr(origin);
422 let media = kind == COREWEBVIEW2_PERMISSION_KIND_MICROPHONE
423 || kind == COREWEBVIEW2_PERMISSION_KIND_CAMERA;
424 if media && is_media_origin(&origin) {
425 unsafe { arguments.SetState(COREWEBVIEW2_PERMISSION_STATE_ALLOW) }?;
426 }
427 Ok(())
428 }));
429 let mut token = 0;
430 unsafe { webview.add_PermissionRequested(&handler, &mut token) }
431}
432
433fn is_media_origin(origin: &str) -> bool {
434 MEDIA_ORIGINS
435 .iter()
436 .any(|allowed| origin.starts_with(allowed))
437}
438
439fn shadow_calls(webview: &ICoreWebView2) -> windows::core::Result<()> {
440 let handler =
441 AddScriptToExecuteOnDocumentCreatedCompletedHandler::create(Box::new(|_, _| Ok(())));
442 unsafe {
443 webview.AddScriptToExecuteOnDocumentCreated(&HSTRING::from(CALL_SHADOW_SCRIPT), &handler)
444 }
445}
446
447fn block_app_launch(webview: &ICoreWebView2) -> windows::core::Result<()> {
448 let Ok(webview) = webview.cast::<ICoreWebView2_18>() else {
449 return Ok(());
450 };
451 let handler = LaunchingExternalUriSchemeEventHandler::create(Box::new(|_, arguments| {
452 if let Some(arguments) = arguments {
453 unsafe { arguments.SetCancel(true) }?;
454 }
455 Ok(())
456 }));
457 let mut token = 0;
458 unsafe { webview.add_LaunchingExternalUriScheme(&handler, &mut token) }
459}
460
461fn forward_new_windows(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {
462 let handler = NewWindowRequestedEventHandler::create(Box::new(move |_, arguments| {
463 let Some(arguments) = arguments else {
464 return Ok(());
465 };
466 let mut target = PWSTR::null();
467 unsafe {
468 arguments.Uri(&mut target)?;
469 arguments.SetHandled(true)?;
470 }
471 let message = serde_json::json!({"kind": NEW_WINDOW_KIND, "url": take_pwstr(target)});
472 emit(id, DialogEvent::Message(message.to_string()));
473 Ok(())
474 }));
475 let mut token = 0;
476 unsafe { webview.add_NewWindowRequested(&handler, &mut token) }
477}
478
479fn close_on_escape(
480 controller: &ICoreWebView2Controller,
481 window: HWND,
482) -> windows::core::Result<()> {
483 let handler = AcceleratorKeyPressedEventHandler::create(Box::new(move |_, arguments| {
484 let Some(arguments) = arguments else {
485 return Ok(());
486 };
487 let mut kind = COREWEBVIEW2_KEY_EVENT_KIND::default();
488 let mut key = 0;
489 unsafe {
490 arguments.KeyEventKind(&mut kind)?;
491 arguments.VirtualKey(&mut key)?;
492 }
493 if kind == COREWEBVIEW2_KEY_EVENT_KIND_KEY_DOWN && key == VIRTUAL_KEY_ESCAPE {
494 unsafe {
495 arguments.SetHandled(true)?;
496 PostMessageW(Some(window), WM_CLOSE, WPARAM(0), LPARAM(0))?;
497 }
498 }
499 Ok(())
500 }));
501 let mut token = 0;
502 unsafe { controller.add_AcceleratorKeyPressed(&handler, &mut token) }
503}
504
505extern "system" fn dialog_procedure(
506 window: HWND,
507 message: u32,
508 wparam: WPARAM,
509 lparam: LPARAM,
510) -> LRESULT {
511 let Some(shared) = running_host() else {
512 return unsafe { DefWindowProcW(window, message, wparam, lparam) };
513 };
514 match message {
515 WM_SIZE => {
516 let id = id_of(&shared, window);
517 let controller = id.and_then(|id| {
518 shared
519 .dialogs
520 .borrow()
521 .get(&id)
522 .and_then(|dialog| dialog.view.as_ref().map(|view| view.controller.clone()))
523 });
524 if let Some(controller) = controller {
525 fit(window, &controller);
526 }
527 LRESULT(0)
528 }
529 WM_CLOSE | WM_DESTROY => {
530 if let Some(id) = id_of(&shared, window) {
531 close(&shared, id);
532 }
533 if message == WM_CLOSE {
534 LRESULT(0)
535 } else {
536 unsafe { DefWindowProcW(window, message, wparam, lparam) }
537 }
538 }
539 _ => unsafe { DefWindowProcW(window, message, wparam, lparam) },
540 }
541}