1use crate::window_modifiers::WindowModifiers;
2use glutin::context::GlProfile;
3use vizia_core::context::TreeProps;
4use vizia_window::{AnchorTarget, WindowDescription};
5#[cfg(target_os = "windows")]
6use winit::platform::windows::WindowExtWindows;
7#[cfg(target_os = "windows")]
8use winit::{platform::windows::WindowAttributesExtWindows, raw_window_handle::RawWindowHandle};
9
10use crate::convert::cursor_icon_to_cursor_icon;
11use hashbrown::HashMap;
12use std::error::Error;
13use std::num::NonZeroU32;
14use std::{ffi::CString, sync::Arc};
15use winit::raw_window_handle::HasWindowHandle;
16
17use gl_rs as gl;
18use glutin::config::Config;
19use glutin_winit::DisplayBuilder;
20
21use gl::types::*;
22
23use glutin::{
24 config::ConfigTemplateBuilder,
25 context::{ContextApi, ContextAttributesBuilder},
26 display::GetGlDisplay,
27 prelude::*,
28 surface::{SurfaceAttributesBuilder, WindowSurface},
29};
30
31use skia_safe::{
32 ColorSpace, ColorType, PixelGeometry, Surface, SurfaceProps, SurfacePropsFlags,
33 gpu::{
34 self, ContextOptions, SurfaceOrigin, backend_render_targets, ganesh::context_options,
35 gl::FramebufferInfo,
36 },
37};
38
39use vizia_core::prelude::*;
40use winit::event_loop::ActiveEventLoop;
41use winit::window::{CursorGrabMode, CursorIcon, CustomCursor, WindowAttributes, WindowLevel};
42use winit::{dpi::*, window::WindowId};
43
44pub struct WinState {
45 pub entity: Entity,
46 pub id: WindowId,
47 pub surface: skia_safe::Surface,
48 pub dirty_surface: skia_safe::Surface,
49 pub gr_context: skia_safe::gpu::DirectContext,
50 pub gl_surface: glutin::surface::Surface<glutin::surface::WindowSurface>,
51 gl_context: glutin::context::PossiblyCurrentContext,
52 gl_config: Config,
53 pub window: Arc<winit::window::Window>,
54 pub should_close: bool,
55 #[cfg(target_os = "windows")]
56 pub is_initially_cloaked: bool,
57}
58
59impl Drop for WinState {
60 fn drop(&mut self) {
61 let _ = self.gl_context.make_current(&self.gl_surface);
62 }
63}
64
65impl WinState {
66 pub fn new(
67 event_loop: &ActiveEventLoop,
68 entity: Entity,
69 #[allow(unused_mut)] mut window_attributes: WindowAttributes,
70 skia_resource_cache_limit: usize,
71 #[allow(unused_variables)] owner: Option<Arc<winit::window::Window>>,
72 ) -> Result<Self, Box<dyn Error>> {
73 #[cfg(target_os = "windows")]
74 let (window, gl_config) = {
75 if let Some(owner) = owner {
76 let RawWindowHandle::Win32(handle) = owner.window_handle().unwrap().as_raw() else {
77 unreachable!();
78 };
79 window_attributes = window_attributes.with_owner_window(handle.hwnd.get());
80 }
81
82 let window_attributes = window_attributes.with_visible(false);
85
86 let (window, config) = build_window(event_loop, window_attributes);
87
88 let window = window.expect("Could not create window with OpenGL context");
89 set_cloak(&window, true);
94
95 (window, config)
96 };
97
98 #[cfg(not(target_os = "windows"))]
99 let (window, gl_config) = {
100 let (window, config) = build_window(event_loop, window_attributes);
101 let window = window.expect("Could not create window with OpenGL context");
102 (window, config)
103 };
104
105 window.set_ime_allowed(true);
106
107 let raw_window_handle = window.window_handle().unwrap().as_raw();
108
109 let gl_display = gl_config.display();
110
111 let context_attributes = ContextAttributesBuilder::new()
112 .with_profile(GlProfile::Core)
113 .with_context_api(ContextApi::OpenGl(None))
114 .build(Some(raw_window_handle));
115
116 let fallback_context_attributes = ContextAttributesBuilder::new()
117 .with_profile(GlProfile::Core)
118 .with_context_api(ContextApi::Gles(None))
119 .build(Some(raw_window_handle));
120
121 let not_current_gl_context = unsafe {
122 gl_display.create_context(&gl_config, &context_attributes).unwrap_or_else(|_| {
123 gl_display
124 .create_context(&gl_config, &fallback_context_attributes)
125 .expect("failed to create context")
126 })
127 };
128
129 let inner_size = window.inner_size();
130 let (width, height): (u32, u32) = inner_size.into();
131
132 let attrs = SurfaceAttributesBuilder::<WindowSurface>::new().with_srgb(Some(true)).build(
133 raw_window_handle,
134 NonZeroU32::new(width.max(1)).unwrap(),
135 NonZeroU32::new(height.max(1)).unwrap(),
136 );
137
138 let gl_surface =
139 unsafe { gl_config.display().create_window_surface(&gl_config, &attrs).unwrap() };
140
141 let gl_context = not_current_gl_context.make_current(&gl_surface).unwrap();
142
143 gl::load_with(|s| {
151 gl_config.display().get_proc_address(CString::new(s).unwrap().as_c_str())
152 });
153
154 let interface = skia_safe::gpu::gl::Interface::new_load_with(|name| {
155 if name == "eglGetCurrentDisplay" {
156 return std::ptr::null();
157 }
158 gl_config.display().get_proc_address(CString::new(name).unwrap().as_c_str())
159 })
160 .expect("Could not create interface");
161
162 let mut context_options = ContextOptions::new();
164 context_options.skip_gl_error_checks = context_options::Enable::Yes;
165
166 let mut gr_context = skia_safe::gpu::direct_contexts::make_gl(interface, &context_options)
167 .expect("Could not create direct context");
168 gr_context.set_resource_cache_limit(skia_resource_cache_limit);
169
170 let fb_info = {
171 let mut fboid: GLint = 0;
172 unsafe { gl::GetIntegerv(gl::FRAMEBUFFER_BINDING, &mut fboid) };
173
174 FramebufferInfo {
175 fboid: fboid.try_into().unwrap(),
176 format: skia_safe::gpu::gl::Format::RGBA8.into(),
177 ..Default::default()
178 }
179 };
180
181 let num_samples = gl_config.num_samples() as usize;
182 let stencil_size = gl_config.stencil_size() as usize;
183
184 let mut surface =
185 create_surface(inner_size, fb_info, &mut gr_context, num_samples, stencil_size);
186
187 let dirty_surface = surface
188 .new_surface_with_dimensions((inner_size.width as i32, inner_size.height as i32))
189 .unwrap();
190
191 Ok(WinState {
193 entity,
194 gl_config,
195 gl_context,
196 id: window.id(),
197 gr_context,
198 gl_surface,
199 window: Arc::new(window),
200 surface,
201 dirty_surface,
202 should_close: false,
203 #[cfg(target_os = "windows")]
204 is_initially_cloaked: true,
205 })
206 }
207
208 pub fn window(&self) -> &winit::window::Window {
210 &self.window
211 }
212
213 pub fn make_current(&mut self) {
214 self.gl_context.make_current(&self.gl_surface).unwrap();
215 }
216
217 pub fn resize(&mut self, size: PhysicalSize<u32>) -> bool {
222 self.gl_context.make_current(&self.gl_surface).unwrap();
223
224 let targets = resize_targets(
225 size,
226 |width, height| self.gl_surface.resize(&self.gl_context, width, height),
227 |size| {
228 let fb_info = {
229 let mut fboid: GLint = 0;
230 unsafe { gl::GetIntegerv(gl::FRAMEBUFFER_BINDING, &mut fboid) };
231
232 FramebufferInfo {
233 fboid: fboid.try_into().unwrap(),
234 format: skia_safe::gpu::gl::Format::RGBA8.into(),
235 ..Default::default()
236 }
237 };
238
239 let mut surface = create_surface(
240 size,
241 fb_info,
242 &mut self.gr_context,
243 self.gl_config.num_samples() as usize,
244 self.gl_config.stencil_size() as usize,
245 );
246
247 let dirty_surface = surface
248 .new_surface_with_dimensions((size.width as i32, size.height as i32))
249 .unwrap();
250
251 (surface, dirty_surface)
252 },
253 );
254
255 match targets {
256 Some((surface, dirty_surface)) => {
257 self.surface = surface;
258 self.dirty_surface = dirty_surface;
259 true
260 }
261 None => false,
262 }
263 }
264
265 pub fn swap_buffers(&mut self) {
266 self.gr_context.flush_and_submit().expect("Failed to flush and submit GPU commands");
267 self.gl_surface.swap_buffers(&self.gl_context).expect("Failed to swap buffers");
268 }
269}
270
271pub(crate) fn resize_targets<T>(
276 size: PhysicalSize<u32>,
277 resize_gl: impl FnOnce(NonZeroU32, NonZeroU32),
278 construct_targets: impl FnOnce(PhysicalSize<u32>) -> T,
279) -> Option<T> {
280 let width = NonZeroU32::new(size.width)?;
281 let height = NonZeroU32::new(size.height)?;
282 let targets = construct_targets(size);
283 resize_gl(width, height);
284 Some(targets)
285}
286
287fn build_window(
288 event_loop: &ActiveEventLoop,
289 window_attributes: WindowAttributes,
290) -> (Option<winit::window::Window>, Config) {
291 let template = ConfigTemplateBuilder::new().with_alpha_size(8).with_transparency(true);
292 let display_builder = DisplayBuilder::new().with_window_attributes(Some(window_attributes));
293
294 display_builder
295 .build(event_loop, template, |configs| {
296 configs
299 .reduce(|accum, config| {
300 let transparency_check = config.supports_transparency().unwrap_or(false)
301 & !accum.supports_transparency().unwrap_or(false);
302
303 if transparency_check || config.num_samples() < accum.num_samples() {
304 config
305 } else {
306 accum
307 }
308 })
309 .unwrap()
310 })
311 .unwrap()
312}
313
314#[cfg(target_os = "windows")]
319pub fn set_cloak(window: &winit::window::Window, state: bool) -> bool {
320 use windows_sys::{
321 Win32::{
322 Foundation::{FALSE, HWND, TRUE},
323 Graphics::Dwm::{DWMWA_CLOAK, DwmSetWindowAttribute},
324 },
325 core::BOOL,
326 };
327
328 let RawWindowHandle::Win32(handle) = window.window_handle().unwrap().as_raw() else {
329 unreachable!();
330 };
331
332 let value = if state { TRUE } else { FALSE };
333
334 let result = unsafe {
335 DwmSetWindowAttribute(
336 handle.hwnd.get() as HWND,
337 DWMWA_CLOAK as u32,
338 std::ptr::from_ref(&value).cast(),
339 std::mem::size_of::<BOOL>() as u32,
340 )
341 };
342
343 result == 0 }
345
346pub fn create_surface(
347 size: PhysicalSize<u32>,
348 fb_info: FramebufferInfo,
349 gr_context: &mut skia_safe::gpu::DirectContext,
350 num_samples: usize,
351 stencil_size: usize,
352) -> Surface {
353 let size = (
354 size.width.try_into().expect("Could not convert width"),
355 size.height.try_into().expect("Could not convert height"),
356 );
357
358 let backend_render_target =
359 backend_render_targets::make_gl(size, num_samples, stencil_size, fb_info);
360
361 let surface_props = SurfaceProps::new_with_text_properties(
362 SurfacePropsFlags::default(),
363 PixelGeometry::default(),
364 0.5,
365 0.0,
366 );
367
368 gpu::surfaces::wrap_backend_render_target(
369 gr_context,
370 &backend_render_target,
371 SurfaceOrigin::BottomLeft,
372 ColorType::RGBA8888,
373 ColorSpace::new_srgb(),
374 Some(surface_props).as_ref(),
375 )
377 .expect("Could not create skia surface")
378}
379
380type WindowCallback = Option<Box<dyn Fn(&mut EventContext)>>;
381
382pub struct Window {
383 pub window: Option<Arc<winit::window::Window>>,
384 pub on_close: WindowCallback,
385 pub on_create: WindowCallback,
386 pub should_close: bool,
387 pub(crate) custom_cursors: Arc<HashMap<CursorIcon, CustomCursor>>,
388}
389
390impl Window {
391 fn window(&self) -> &winit::window::Window {
392 self.window.as_ref().unwrap()
393 }
394
395 pub fn new(cx: &mut Context, content: impl 'static + Fn(&mut Context)) -> Handle<Self> {
396 Self {
397 window: None,
398 on_close: None,
399 on_create: None,
400 should_close: false,
401 custom_cursors: Default::default(),
402 }
403 .build(cx, |cx| {
404 cx.windows.insert(
405 cx.current(),
406 WindowState {
407 content: Some(Arc::new(content)),
408 window_description: WindowDescription::new(),
409 ..Default::default()
410 },
411 );
412 cx.tree.set_window(cx.current(), true);
413 })
414 .position_type(PositionType::Absolute)
415 .anchor_target(AnchorTarget::Window)
416 }
417
418 pub fn popup(
419 cx: &mut Context,
420 is_modal: bool,
421 content: impl 'static + Fn(&mut Context),
422 ) -> Handle<Self> {
423 Self {
424 window: None,
425 on_close: None,
426 on_create: None,
427 should_close: false,
428 custom_cursors: Default::default(),
429 }
430 .build(cx, |cx| {
431 let parent_window = cx.parent_window();
432 if is_modal {
433 cx.emit_to(parent_window, WindowEvent::SetEnabled(false));
434 }
435
436 cx.windows.insert(
437 cx.current(),
438 WindowState {
439 owner: Some(parent_window),
440 is_modal: true,
441 content: Some(Arc::new(content)),
442 window_description: WindowDescription::new(),
443 ..Default::default()
444 },
445 );
446 cx.tree.set_window(cx.current(), true);
447 })
448 .position_type(PositionType::Absolute)
449 .anchor_target(AnchorTarget::Window)
450 .lock_focus_to_within()
451 }
452}
453
454impl View for Window {
455 fn element(&self) -> Option<&'static str> {
456 Some("window")
457 }
458
459 fn event(&mut self, cx: &mut EventContext, event: &mut Event) {
460 event.map(|window_event, meta| match window_event {
461 WindowEvent::Destroyed => {
462 let parent_window = cx.parent_window();
463 cx.emit_to(parent_window, WindowEvent::SetEnabled(true));
464 }
465
466 WindowEvent::GrabCursor(flag) => {
467 let grab_mode = if *flag { CursorGrabMode::Locked } else { CursorGrabMode::None };
468 self.window().set_cursor_grab(grab_mode).expect("Failed to set cursor grab");
469 }
470
471 WindowEvent::SetCursorPosition(x, y) => {
472 self.window()
473 .set_cursor_position(winit::dpi::Position::Physical(PhysicalPosition::new(
474 *x as i32, *y as i32,
475 )))
476 .expect("Failed to set cursor position");
477 }
478
479 WindowEvent::SetCursor(cursor) => {
480 let Some(icon) = cursor_icon_to_cursor_icon(*cursor) else {
481 self.window().set_cursor_visible(false);
482 return;
483 };
484
485 if let Some(custom_icon) = self.custom_cursors.get(&icon) {
486 self.window().set_cursor(custom_icon.clone());
487 } else {
488 self.window().set_cursor(icon);
489 }
490
491 self.window().set_cursor_visible(true);
492 }
493
494 WindowEvent::SetTitle(title) => {
495 if let Some(window_state) = cx.windows.get_mut(&cx.current()) {
496 window_state.window_description.title = title.clone();
497 }
498
499 if let Some(window) = &self.window {
500 window.set_title(title);
501 }
502 }
503
504 WindowEvent::SetSize(size) => {
505 let _ = self.window().request_inner_size(LogicalSize::new(size.width, size.height));
506 }
507
508 WindowEvent::SetMinSize(size) => {
509 self.window()
510 .set_min_inner_size(size.map(|size| LogicalSize::new(size.width, size.height)));
511 }
512
513 WindowEvent::SetMaxSize(size) => {
514 self.window()
515 .set_max_inner_size(size.map(|size| LogicalSize::new(size.width, size.height)));
516 }
517
518 WindowEvent::SetPosition(pos) => {
519 self.window().set_outer_position(LogicalPosition::new(pos.x, pos.y));
520 meta.consume();
521 }
522
523 WindowEvent::SetResizable(flag) => {
524 self.window().set_resizable(*flag);
525 }
526
527 WindowEvent::SetMinimized(flag) => {
528 self.window().set_minimized(*flag);
529 }
530
531 WindowEvent::SetMaximized(flag) => {
532 self.window().set_maximized(*flag);
533 }
534
535 WindowEvent::SetVisible(flag) => {
536 self.window().set_visible(*flag);
537
538 meta.consume();
539 }
540
541 WindowEvent::SetDecorations(flag) => {
542 self.window().set_decorations(*flag);
543 }
544
545 WindowEvent::ReloadStyles => {
546 cx.reload_styles().unwrap();
547 }
548
549 WindowEvent::WindowClose => {
550 self.should_close = true;
551
552 cx.close_window();
553
554 if let Some(callback) = &self.on_close {
555 callback(cx);
556 }
557
558 meta.consume();
559 }
560
561 WindowEvent::FocusNext => {
562 cx.focus_next();
563 }
564
565 WindowEvent::FocusPrev => {
566 cx.focus_prev();
567 }
568
569 WindowEvent::Redraw => {
570 self.window().request_redraw();
571 }
572
573 #[allow(unused_variables)]
574 WindowEvent::SetEnabled(flag) => {
575 #[cfg(target_os = "windows")]
576 self.window().set_enable(*flag);
577
578 self.window().focus_window();
579 }
580
581 WindowEvent::DragWindow => {
582 self.window().drag_window().expect("Failed to init drag window");
583 meta.consume();
584 }
585
586 WindowEvent::SetAlwaysOnTop(flag) => {
587 self.window().set_window_level(if *flag {
588 WindowLevel::AlwaysOnTop
589 } else {
590 WindowLevel::Normal
591 });
592 }
593
594 WindowEvent::SetImeCursorArea(position, size) => {
595 let position = PhysicalPosition::new(position.0 as i32, position.1 as i32);
596 let size = PhysicalSize::new(size.0, size.1);
597 self.window().set_ime_cursor_area(position, size);
598 }
599
600 _ => {}
601 })
602 }
603}
604
605impl WindowModifiers for Handle<'_, Window> {
606 fn on_close(self, callback: impl Fn(&mut EventContext) + 'static) -> Self {
607 self.modify(|window| window.on_close = Some(Box::new(callback)))
608 }
609
610 fn on_create(self, callback: impl Fn(&mut EventContext) + 'static) -> Self {
611 self.modify(|window| window.on_create = Some(Box::new(callback)))
612 }
613
614 fn title<T: ToStringLocalized>(mut self, title: impl Res<T> + Clone + 'static) -> Self {
615 let entity = self.entity();
616 let initial_title = title.get_value(&self).to_string_local(&self);
617 if let Some(win_state) = self.context().windows.get_mut(&entity) {
618 win_state.window_description.title = initial_title;
619 }
620
621 let getter_for_locale = title.clone();
622
623 self.context().with_current(entity, |cx| {
624 title.set_or_bind(cx, move |cx, val| {
625 let title_str = val.get_value(cx).to_string_local(cx);
626 cx.emit(WindowEvent::SetTitle(title_str));
627 });
628
629 let locale = cx.environment().locale;
630 locale.set_or_bind(cx, move |cx, _| {
631 let title = getter_for_locale.get_value(cx).to_string_local(cx);
632 cx.emit(WindowEvent::SetTitle(title));
633 });
634 });
635
636 self
637 }
638
639 fn inner_size<S: Into<WindowSize>>(mut self, size: impl Res<S>) -> Self {
640 let entity = self.entity();
641 let size = size.get_value(&self).into();
642 if let Some(win_state) = self.context().windows.get_mut(&entity) {
643 win_state.window_description.inner_size = size;
644 }
645
646 self
647 }
648
649 fn min_inner_size<S: Into<WindowSize>>(mut self, size: impl Res<Option<S>>) -> Self {
650 let entity = self.entity();
651 let size = size.get_value(&self).map(|size| size.into());
652 if let Some(win_state) = self.context().windows.get_mut(&entity) {
653 win_state.window_description.min_inner_size = size;
654 }
655
656 self
657 }
658
659 fn max_inner_size<S: Into<WindowSize>>(mut self, size: impl Res<Option<S>>) -> Self {
660 let entity = self.entity();
661 let size = size.get_value(&self).map(|size| size.into());
662 if let Some(win_state) = self.context().windows.get_mut(&entity) {
663 win_state.window_description.max_inner_size = size;
664 }
665
666 self
667 }
668
669 fn position<P: Into<vizia_window::WindowPosition>>(mut self, position: impl Res<P>) -> Self {
670 let entity = self.entity();
671 let pos = Some(position.get_value(&self).into());
672 if let Some(win_state) = self.context().windows.get_mut(&entity) {
673 win_state.window_description.position = pos;
674 }
675
676 self
677 }
678
679 fn offset<P: Into<vizia_window::WindowPosition>>(mut self, offset: impl Res<P>) -> Self {
680 let entity = self.entity();
681 let offset = Some(offset.get_value(&self).into());
682 if let Some(win_state) = self.context().windows.get_mut(&entity) {
683 win_state.window_description.offset = offset;
684 }
685
686 self
687 }
688
689 fn anchor<P: Into<vizia_window::Anchor>>(mut self, anchor: impl Res<P>) -> Self {
690 let entity = self.entity();
691 let anchor = Some(anchor.get_value(&self).into());
692 if let Some(win_state) = self.context().windows.get_mut(&entity) {
693 win_state.window_description.anchor = anchor;
694 }
695
696 self
697 }
698
699 fn anchor_target<P: Into<vizia_window::AnchorTarget>>(
700 mut self,
701 anchor_target: impl Res<P>,
702 ) -> Self {
703 let entity = self.entity();
704 let anchor_target = Some(anchor_target.get_value(&self).into());
705 if let Some(win_state) = self.context().windows.get_mut(&entity) {
706 win_state.window_description.anchor_target = anchor_target;
707 }
708
709 self
710 }
711
712 fn parent_anchor<P: Into<Anchor>>(mut self, parent_anchor: impl Res<P>) -> Self {
713 let entity = self.entity();
714 let parent_anchor = Some(parent_anchor.get_value(&self).into());
715 if let Some(win_state) = self.context().windows.get_mut(&entity) {
716 win_state.window_description.parent_anchor = parent_anchor;
717 }
718
719 self
720 }
721
722 fn resizable(mut self, flag: impl Res<bool>) -> Self {
723 let entity = self.entity();
724 let flag = flag.get_value(&self);
725 if let Some(win_state) = self.context().windows.get_mut(&entity) {
726 win_state.window_description.resizable = flag;
727 }
728
729 self
730 }
731
732 fn minimized(mut self, flag: impl Res<bool>) -> Self {
733 let entity = self.entity();
734 let flag = flag.get_value(&self);
735 if let Some(win_state) = self.context().windows.get_mut(&entity) {
736 win_state.window_description.minimized = flag;
737 }
738
739 self
740 }
741
742 fn maximized(mut self, flag: impl Res<bool>) -> Self {
743 let entity = self.entity();
744 let flag = flag.get_value(&self);
745 if let Some(win_state) = self.context().windows.get_mut(&entity) {
746 win_state.window_description.maximized = flag;
747 }
748
749 self
750 }
751
752 fn visible(mut self, flag: impl Res<bool>) -> Self {
753 let entity = self.entity();
754 let flag = flag.get_value(&self);
755 if let Some(win_state) = self.context().windows.get_mut(&entity) {
756 win_state.window_description.visible = flag
757 }
758
759 self
760 }
761
762 fn transparent(mut self, flag: bool) -> Self {
763 let entity = self.entity();
764 if let Some(win_state) = self.context().windows.get_mut(&entity) {
765 win_state.window_description.transparent = flag
766 }
767
768 self
769 }
770
771 fn decorations(mut self, flag: bool) -> Self {
772 let entity = self.entity();
773 if let Some(win_state) = self.context().windows.get_mut(&entity) {
774 win_state.window_description.decorations = flag
775 }
776
777 self
778 }
779
780 fn always_on_top(mut self, flag: bool) -> Self {
781 let entity = self.entity();
782 if let Some(win_state) = self.context().windows.get_mut(&entity) {
783 win_state.window_description.always_on_top = flag
784 }
785
786 self
787 }
788
789 fn vsync(mut self, flag: bool) -> Self {
790 let entity = self.entity();
791 if let Some(win_state) = self.context().windows.get_mut(&entity) {
792 win_state.window_description.vsync = flag
793 }
794
795 self
796 }
797
798 fn skia_resource_cache_limit(mut self, limit: usize) -> Self {
799 let entity = self.entity();
800 if let Some(win_state) = self.context().windows.get_mut(&entity) {
801 win_state.window_description.skia_resource_cache_limit = limit;
802 }
803
804 self
805 }
806
807 fn icon(mut self, width: u32, height: u32, image: Vec<u8>) -> Self {
808 let entity = self.entity();
809 if let Some(win_state) = self.context().windows.get_mut(&entity) {
810 win_state.window_description.icon = Some(image);
811 win_state.window_description.icon_width = width;
812 win_state.window_description.icon_height = height;
813 }
814
815 self
816 }
817
818 fn enabled_window_buttons(mut self, window_buttons: WindowButtons) -> Self {
819 let entity = self.entity();
820 if let Some(win_state) = self.context().windows.get_mut(&entity) {
821 win_state.window_description.enabled_window_buttons = window_buttons;
822 }
823
824 self
825 }
826}
827
828#[cfg(test)]
829mod tests {
830 use super::*;
831
832 #[test]
833 fn resize_uses_confirmed_extent_for_gl_and_targets() {
834 for (width, height) in [(2320, 1480), (1450, 925), (1080, 700), (1, 1)] {
835 let extent = PhysicalSize::new(width, height);
836 let operations = std::cell::RefCell::new(Vec::new());
837 let targets = resize_targets(
838 extent,
839 |width, height| operations.borrow_mut().push(("gl", width.get(), height.get())),
840 |size| {
841 operations.borrow_mut().push(("targets", size.width, size.height));
842 size
843 },
844 );
845 assert_eq!(targets, Some(extent));
846 let mut operations = operations.into_inner();
847 operations.sort();
848 assert_eq!(operations, vec![("gl", width, height), ("targets", width, height)]);
849 }
850 }
851
852 #[test]
853 fn resize_retains_targets_for_zero_extent() {
854 for extent in
855 [PhysicalSize::new(0, 1480), PhysicalSize::new(2320, 0), PhysicalSize::new(0, 0)]
856 {
857 let operations = std::cell::Cell::new(0);
858 let targets = resize_targets(
859 extent,
860 |_, _| operations.set(operations.get() + 1),
861 |_| {
862 operations.set(operations.get() + 1);
863 },
864 );
865 assert_eq!(targets, None);
866 assert_eq!(operations.get(), 0);
867 }
868 }
869}