| 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 | } |