1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
use super::*;
/// Releases all owned COM interfaces and DXGI waitable handles when `Win32D3d11SwapChain` is dropped.
impl Drop for Win32D3d11SwapChain {
/// Releases D3D11/DXGI COM resources in reverse dependency order and closes any waitable handle.
///
/// # Arguments
///
/// - `&Self` - Mutable swapchain being destroyed.
fn drop(&mut self) {
let Self { scene, .. } = self;
if let Some(scene_pipe) = scene.take() {
win32_d3d11_release_scene_pipeline(&scene_pipe);
}
win32_close_handle(self.get_waitable_handle());
win32_com_release(self.get_external_srv());
win32_com_release(self.get_external_tex());
win32_com_release(self.get_image_srv());
win32_com_release(self.get_image_tex());
win32_com_release(self.get_glyph_rgba8_srv());
win32_com_release(self.get_glyph_rgba8_tex());
win32_com_release(self.get_glyph_r8_srv());
win32_com_release(self.get_glyph_r8_tex());
win32_com_release(self.get_sampler_state());
win32_com_release(self.get_rasterizer_state());
win32_com_release(self.get_opaque_blend_state());
win32_com_release(self.get_blend_state());
win32_com_release(self.get_instance_srv());
win32_com_release(self.get_instance_buffer());
win32_com_release(self.get_constant_buffer());
win32_com_release(self.get_pixel_shader());
win32_com_release(self.get_vertex_shader());
win32_com_release(self.get_rtv());
win32_com_release(self.get_swap_chain2());
win32_com_release(self.get_swap_chain());
win32_com_release(self.get_context());
win32_com_release(self.get_device());
}
}
/// Default initialization for `WindowsPlatform`.
impl Default for WindowsPlatform {
/// Creates an empty Windows Win32 platform backend.
///
/// # Returns
///
/// - `Self` - Initialized Windows platform.
fn default() -> Self {
Self {
next_id: 1,
class_registered: false,
windows: HashMap::new(),
pending_events: Vec::new(),
clipboard_cache: None,
pump_paused: false,
wake_event: win32_create_wake_event(),
}
}
}
/// Win32 system event injection and GPU/GDI presentation telemetry helpers for `WindowsPlatform`.
impl WindowsPlatform {
/// Enqueues a normalized Windows `SystemEvent` to be drained on the next `poll_events()` tick.
///
/// # Arguments
///
/// - `&Self` - Mutable Windows platform backend.
/// - `SystemEvent` - System event to enqueue.
pub fn push_system_event(&mut self, event: SystemEvent) {
self.get_mut_pending_events()
.push(WindowEvent::System(event));
}
/// Selects the canonical Windows presentation path (`GpuDirect` when DXGI swapchain is available and mode is not `Software`; `SoftwareGdi` otherwise).
///
/// # Arguments
///
/// - `RenderMode` - Requested render pipeline mode.
/// - `bool` - Whether native DXGI/D3D11/D3D12 swapchain is available.
///
/// # Returns
///
/// - `WindowsPresentationPath` - Selected presentation path (`GpuDirect` has `cpu_mirror_active = false`).
#[must_use]
pub fn select_presentation_path(
render_mode: RenderMode,
dxgi_ready: bool,
) -> WindowsPresentationPath {
if dxgi_ready && render_mode != RenderMode::Software {
WindowsPresentationPath::GpuDirect
} else {
WindowsPresentationPath::SoftwareGdi
}
}
/// Returns whether a CPU software framebuffer mirror is currently active on Windows window `id`.
///
/// # Arguments
///
/// - `WindowId` - Target Windows window identifier.
///
/// # Returns
///
/// - `bool` - `false` on native DXGI swapchain `GpuDirect`; `true` on GDI software fallback.
#[must_use]
pub fn cpu_mirror_active(&self, id: WindowId) -> bool {
self.get_windows()
.get(&id)
.map(WindowsWindowRecord::get_cpu_mirror_active)
.unwrap_or(true)
}
/// Returns the most recent Windows presentation telemetry snapshot for window `id`.
///
/// # Arguments
///
/// - `WindowId` - Target Windows window identifier.
///
/// # Returns
///
/// - `Option<WindowsPresentTelemetry>` - Latest presentation telemetry, if the window exists.
#[must_use]
pub fn last_present_telemetry(&self, id: WindowId) -> Option<WindowsPresentTelemetry> {
self.get_windows()
.get(&id)
.map(WindowsWindowRecord::get_last_telemetry)
}
/// Signals the Win32 kernel wakeup event so a thread blocked in `MsgWaitForMultipleObjects` resumes immediately.
///
/// # Arguments
///
/// - `&Self` - Windows platform reference.
///
/// # Returns
///
/// - `bool` - `true` when the wakeup event was signaled.
pub fn wake_event_loop(&self) -> bool {
win32_signal_wake_event(self.get_wake_event())
}
/// Presents a compiled `DirectGpuFrameBatch` directly via dynamically loaded D3D11 (`DrawInstanced`) and DXGI 1.6 waitable swapchain.
///
/// # Arguments
///
/// - `&Self` - Mutable Windows platform backend.
/// - `WindowId` - Target Windows window identifier.
/// - `&DirectGpuFrameBatch` - Compiled 64-byte `GpuPrimitiveInstance` batch and atlas updates.
///
/// # Returns
///
/// - `Result<WindowsPresentTelemetry, PlatformError>` - Direct GPU telemetry (`cpu_mirror_active = false`) on success, or `Err` so caller falls back cleanly to 1:1 `SetDIBitsToDevice`.
pub fn present_direct_gpu_batch(
&mut self,
id: WindowId,
batch: &DirectGpuFrameBatch,
) -> Result<WindowsPresentTelemetry, PlatformError> {
let (hwnd, dxgi_cfg, existing_sc): (
usize,
Win32DxgiSwapChainConfig,
Option<Arc<Mutex<Win32D3d11SwapChain>>>,
) = {
let rec: &WindowsWindowRecord = self
.get_windows()
.get(&id)
.ok_or(PlatformError::WindowNotFound(id.get_value()))?;
let WindowsWindowRecord { d3d11, .. } = rec;
(rec.get_hwnd(), rec.get_dxgi_config(), d3d11.clone())
};
let swapchain_arc: Arc<Mutex<Win32D3d11SwapChain>> = match existing_sc {
Some(sc) => sc,
None => {
let created: Win32D3d11SwapChain = win32_d3d11_create_swapchain(
hwnd,
batch.get_viewport_width(),
batch.get_viewport_height(),
dxgi_cfg,
)
.ok_or_else(|| PlatformError::SurfaceError(ERR_WIN32_D3D11_PRESENT.to_string()))?;
let wrapped: Arc<Mutex<Win32D3d11SwapChain>> = Arc::new(Mutex::new(created));
if let Some(rec) = self.get_mut_windows().get_mut(&id) {
let WindowsWindowRecord { d3d11, .. } = rec;
*d3d11 = Some(wrapped.clone());
}
wrapped
}
};
let (sync_qpc_time, present_count): (u64, u32) = {
let mut guard: MutexGuard<'_, Win32D3d11SwapChain> = swapchain_arc
.lock()
.map_err(|_| PlatformError::SurfaceError(ERR_WIN32_D3D11_PRESENT.to_string()))?;
win32_d3d11_present_batch(&mut guard, batch)?
};
self.present_gpu_direct(id, sync_qpc_time, present_count)
}
/// Presents a complete `GpuFrameSubmission` directly on D3D11 + DXGI 1.6 including `DirectGpuScenePass` (`OceanFluid` + `World3d`), dirty-subrect atlas uploads, and uncapped tearing presentation.
///
/// # Arguments
///
/// - `WindowId` - Target Windows window identifier.
/// - `&GpuFrameSubmission` - Direct-GPU batches, optional scene pass, and incremental atlas updates.
///
/// # Returns
///
/// - `Result<(WindowsPresentTelemetry, usize, usize), PlatformError>` - Direct GPU telemetry plus `(draw_calls, uploaded_instances)`.
pub fn present_direct_gpu_submission(
&mut self,
id: WindowId,
submission: &GpuFrameSubmission,
) -> Result<(WindowsPresentTelemetry, usize, usize), PlatformError> {
let (hwnd, dxgi_cfg, existing_sc): (
usize,
Win32DxgiSwapChainConfig,
Option<Arc<Mutex<Win32D3d11SwapChain>>>,
) = {
let rec: &WindowsWindowRecord = self
.get_windows()
.get(&id)
.ok_or(PlatformError::WindowNotFound(id.get_value()))?;
let WindowsWindowRecord { d3d11, .. } = rec;
(rec.get_hwnd(), rec.get_dxgi_config(), d3d11.clone())
};
let swapchain_arc: Arc<Mutex<Win32D3d11SwapChain>> = match existing_sc {
Some(sc) => sc,
None => {
let created: Win32D3d11SwapChain = win32_d3d11_create_swapchain(
hwnd,
submission.get_width(),
submission.get_height(),
dxgi_cfg,
)
.ok_or_else(|| PlatformError::SurfaceError(ERR_WIN32_D3D11_PRESENT.to_string()))?;
let wrapped: Arc<Mutex<Win32D3d11SwapChain>> = Arc::new(Mutex::new(created));
if let Some(rec) = self.get_mut_windows().get_mut(&id) {
let WindowsWindowRecord { d3d11, .. } = rec;
*d3d11 = Some(wrapped.clone());
}
wrapped
}
};
let (sync_qpc_time, present_count, draw_calls, uploaded_instances): (
u64,
u32,
usize,
usize,
) = {
let mut guard: MutexGuard<'_, Win32D3d11SwapChain> = swapchain_arc
.lock()
.map_err(|_| PlatformError::SurfaceError(ERR_WIN32_D3D11_PRESENT.to_string()))?;
win32_d3d11_present_submission(&mut guard, submission)?
};
let telemetry: WindowsPresentTelemetry =
self.present_gpu_direct(id, sync_qpc_time, present_count)?;
Ok((telemetry, draw_calls, uploaded_instances))
}
/// Records a native DXGI/D3D11/D3D12 GPU swapchain direct present (`cpu_mirror_active = false`, `upload_bytes = 0`) with explicit DXGI timing telemetry.
///
/// # Arguments
///
/// - `WindowId` - Target Windows window identifier.
/// - `u64` - `DXGI_FRAME_STATISTICS.SyncQPCTime` tick (`0` when unavailable).
/// - `u32` - `DXGI_FRAME_STATISTICS.PresentCount` counter.
///
/// # Returns
///
/// - `Result<WindowsPresentTelemetry, PlatformError>` - Direct GPU presentation telemetry (`cpu_mirror_active = false`).
pub fn present_gpu_direct(
&mut self,
id: WindowId,
dxgi_sync_qpc_time: u64,
dxgi_present_count: u32,
) -> Result<WindowsPresentTelemetry, PlatformError> {
let (hwnd, should_reveal, dxgi_ready): (usize, bool, bool) = {
let rec: &WindowsWindowRecord = self
.get_windows()
.get(&id)
.ok_or(PlatformError::WindowNotFound(id.get_value()))?;
(
rec.get_hwnd(),
!rec.get_revealed() && rec.get_config().get_visible(),
rec.get_dxgi_config().get_dxgi_available() && rec.get_hwnd() != 0,
)
};
if !dxgi_ready {
if let Some(rec) = self.get_mut_windows().get_mut(&id) {
let mut failed: WindowsPresentTelemetry = rec.get_last_telemetry();
failed.set_failed_frames(failed.get_failed_frames().saturating_add(1));
rec.set_last_telemetry(failed);
}
return Err(PlatformError::SurfaceError(
ERR_WIN32_DXGI_UNAVAILABLE.to_string(),
));
}
if should_reveal {
win32_set_visible(hwnd, true);
}
let timing_source: WindowsPresentTimingSource = if dxgi_sync_qpc_time > 0 {
WindowsPresentTimingSource::DxgiFrameStatistics
} else {
WindowsPresentTimingSource::SubmissionProxy
};
let rec: &mut WindowsWindowRecord = self
.get_mut_windows()
.get_mut(&id)
.ok_or(PlatformError::WindowNotFound(id.get_value()))?;
if should_reveal {
rec.set_revealed(true);
}
let mut tel: WindowsPresentTelemetry = rec.get_last_telemetry();
tel.set_path(WindowsPresentationPath::GpuDirect);
tel.set_cpu_mirror_active(false);
tel.set_timing_source(timing_source);
tel.set_dxgi_sync_qpc_time(dxgi_sync_qpc_time);
tel.set_dxgi_present_count(dxgi_present_count);
tel.set_upload_bytes(0);
tel.set_dirty_rect_count(0);
tel.set_direct_gpu_frames(tel.get_direct_gpu_frames().saturating_add(1));
rec.set_presentation_path(WindowsPresentationPath::GpuDirect);
rec.set_cpu_mirror_active(false);
rec.set_last_telemetry(tel);
Ok(tel)
}
/// Presents `framebuffer` (or only `damage` on 1:1 surfaces) over GDI `StretchDIBits` software fallback (`cpu_mirror_active = true`).
///
/// # Arguments
///
/// - `WindowId` - Target Windows window identifier.
/// - `&Framebuffer` - Rendered RGBA8 CPU framebuffer.
/// - `DamageRegion` - Damaged pixel region updated this frame.
///
/// # Returns
///
/// - `Result<WindowsPresentTelemetry, PlatformError>` - Software GDI telemetry (`cpu_mirror_active = true`).
pub fn present_gdi_fallback(
&mut self,
id: WindowId,
framebuffer: &Framebuffer,
damage: DamageRegion,
) -> Result<WindowsPresentTelemetry, PlatformError> {
let dirty_rect: Option<Rect> = if damage.get_full_damage() {
None
} else {
damage.bounds_rect()
};
let (hwnd, should_reveal): (usize, bool) = self
.get_windows()
.get(&id)
.map(|rec: &WindowsWindowRecord| {
(
rec.get_hwnd(),
!rec.get_revealed() && rec.get_config().get_visible(),
)
})
.ok_or(PlatformError::WindowNotFound(id.get_value()))?;
let upload_bytes: u64 = if let Some(red_val) = dirty_rect {
let fb_w: u32 = framebuffer.get_width();
let fb_h: u32 = framebuffer.get_height();
let x0: u32 = (red_val.get_x().floor().max(0.0) as u32).min(fb_w);
let y0: u32 = (red_val.get_y().floor().max(0.0) as u32).min(fb_h);
let x1: u32 =
((red_val.get_x() + red_val.get_width()).ceil().max(0.0) as u32).min(fb_w);
let y1: u32 =
((red_val.get_y() + red_val.get_height()).ceil().max(0.0) as u32).min(fb_h);
if x1 > x0 && y1 > y0 {
u64::from(x1 - x0)
.saturating_mul(u64::from(y1 - y0))
.saturating_mul(4)
} else {
0
}
} else {
framebuffer.get_pixels().len() as u64
};
let dirty_count: u32 = if damage.get_full_damage() {
1
} else {
damage
.active_rect_count()
.max(usize::from(dirty_rect.is_some())) as u32
};
let res: Result<(), PlatformError> = if hwnd == 0 {
Err(PlatformError::SurfaceError(
ERR_WIN32_GDI_SURFACE_MISSING.to_string(),
))
} else {
win32_present_dib(hwnd, framebuffer, dirty_rect)
};
if let Err(err) = res {
if let Some(rec) = self.get_mut_windows().get_mut(&id) {
let mut failed: WindowsPresentTelemetry = rec.get_last_telemetry();
failed.set_path(WindowsPresentationPath::SoftwareGdi);
failed.set_cpu_mirror_active(true);
failed.set_failed_frames(failed.get_failed_frames().saturating_add(1));
rec.set_presentation_path(WindowsPresentationPath::SoftwareGdi);
rec.set_cpu_mirror_active(true);
rec.set_last_telemetry(failed);
}
return Err(err);
}
if should_reveal {
win32_set_visible(hwnd, true);
}
let rec: &mut WindowsWindowRecord = self
.get_mut_windows()
.get_mut(&id)
.ok_or(PlatformError::WindowNotFound(id.get_value()))?;
if should_reveal {
rec.set_revealed(true);
}
let mut tel: WindowsPresentTelemetry = rec.get_last_telemetry();
tel.set_path(WindowsPresentationPath::SoftwareGdi);
tel.set_cpu_mirror_active(true);
tel.set_timing_source(WindowsPresentTimingSource::SubmissionProxy);
tel.set_dxgi_sync_qpc_time(0);
tel.set_dxgi_present_count(0);
tel.set_upload_bytes(upload_bytes);
tel.set_dirty_rect_count(dirty_count);
tel.set_software_fallback_frames(tel.get_software_fallback_frames().saturating_add(1));
rec.set_presentation_path(WindowsPresentationPath::SoftwareGdi);
rec.set_cpu_mirror_active(true);
rec.set_last_telemetry(tel);
Ok(tel)
}
}
/// `WindowController` implementation translating commands directly to Win32 APIs.
impl WindowController for WindowsPlatform {
/// Applies a `WindowCommand` onto the target `HWND`.
///
/// # Arguments
///
/// - `&Self` - Mutable Windows platform.
/// - `WindowCommand` - Command to apply.
///
/// # Returns
///
/// - `Result<(), PlatformError>` - Execution status.
fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
match command {
WindowCommand::SetTitle(id, title) => {
let rec: &mut WindowsWindowRecord = self
.get_mut_windows()
.get_mut(&id)
.ok_or(PlatformError::WindowNotFound(id.get_value()))?;
win32_set_title(rec.get_hwnd(), &title);
rec.get_mut_config().set_title(title);
Ok(())
}
WindowCommand::SetSize(id, width, height) => {
let rec: &mut WindowsWindowRecord = self
.get_mut_windows()
.get_mut(&id)
.ok_or(PlatformError::WindowNotFound(id.get_value()))?;
let width_val: u32 = width.max(1);
let height_val: u32 = height.max(1);
let scale: f32 = clamp_viewport_scale(rec.get_state().get_scale_factor());
let phys_w: u32 = compute_lossless_physical_dim(f64::from(width_val), scale);
let phys_h: u32 = compute_lossless_physical_dim(f64::from(height_val), scale);
win32_set_size(rec.get_hwnd(), phys_w, phys_h);
rec.get_mut_config().set_width(width_val);
rec.get_mut_config().set_height(height_val);
rec.get_mut_state().set_logical_width(width_val as f32);
rec.get_mut_state().set_logical_height(height_val as f32);
rec.get_mut_state().set_physical_width(phys_w);
rec.get_mut_state().set_physical_height(phys_h);
Ok(())
}
WindowCommand::SetAlwaysOnTop(id, on_top) => {
let rec: &mut WindowsWindowRecord = self
.get_mut_windows()
.get_mut(&id)
.ok_or(PlatformError::WindowNotFound(id.get_value()))?;
win32_set_topmost(rec.get_hwnd(), on_top);
rec.get_mut_config().set_always_on_top(on_top);
Ok(())
}
WindowCommand::SetVisible(id, visible) => {
let rec: &mut WindowsWindowRecord = self
.get_mut_windows()
.get_mut(&id)
.ok_or(PlatformError::WindowNotFound(id.get_value()))?;
win32_set_visible(rec.get_hwnd(), visible);
rec.set_revealed(visible);
rec.get_mut_config().set_visible(visible);
Ok(())
}
WindowCommand::Close(id) => {
let rec: WindowsWindowRecord = self
.get_mut_windows()
.remove(&id)
.ok_or(PlatformError::WindowNotFound(id.get_value()))?;
win32_destroy(rec.get_hwnd());
Ok(())
}
WindowCommand::SetRenderMode(id, mode) => {
let rec: &mut WindowsWindowRecord = self
.get_mut_windows()
.get_mut(&id)
.ok_or(PlatformError::WindowNotFound(id.get_value()))?;
rec.get_mut_config().get_mut_render().set_mode(mode);
Ok(())
}
WindowCommand::RequestRedraw(id) => {
if !self.get_windows().contains_key(&id) {
return Err(PlatformError::WindowNotFound(id.get_value()));
}
self.get_mut_pending_events()
.push(WindowEvent::RedrawRequested(id));
Ok(())
}
WindowCommand::SetFullscreen(id, mode) => {
let rec: &mut WindowsWindowRecord = self
.get_mut_windows()
.get_mut(&id)
.ok_or(PlatformError::WindowNotFound(id.get_value()))?;
let was_fs: bool = rec.get_state().get_fullscreen() != FullscreenMode::Windowed;
let want_fs: bool = mode != FullscreenMode::Windowed;
if was_fs != want_fs {
let hwnd: usize = rec.get_hwnd();
let mut saved_style: i32 = rec.get_saved_window_style();
let mut saved_placement: Win32WindowPlacement = rec.get_saved_placement();
win32_set_fullscreen(hwnd, want_fs, &mut saved_style, &mut saved_placement);
rec.set_saved_window_style(saved_style);
rec.set_saved_placement(saved_placement);
}
rec.get_mut_config().set_fullscreen(mode);
rec.get_mut_state().set_fullscreen(mode);
Ok(())
}
WindowCommand::SetPosition(id, _, _)
| WindowCommand::SetResizable(id, _)
| WindowCommand::SetDecorations(id, _)
| WindowCommand::SetCursor(id, _)
| WindowCommand::SetIme(id, _, _)
| WindowCommand::SetStatusBarStyle(id, _) => {
if !self.get_windows().contains_key(&id) {
return Err(PlatformError::WindowNotFound(id.get_value()));
}
Ok(())
}
}
}
}
/// `PlatformBackend` implementation for native Windows.
impl PlatformBackend for WindowsPlatform {
/// Returns `PlatformKind::Windows`.
///
/// # Arguments
///
/// - `&Self` - Platform reference.
///
/// # Returns
///
/// - `PlatformKind` - `PlatformKind::Windows`.
fn kind(&self) -> PlatformKind {
PlatformKind::Windows
}
/// Returns Windows desktop capabilities.
///
/// # Arguments
///
/// - `&Self` - Platform reference.
///
/// # Returns
///
/// - `PlatformCapabilities` - Windows capability flags.
fn capabilities(&self) -> PlatformCapabilities {
PlatformCapabilities::for_platform(PlatformKind::Windows)
}
/// Creates a real Win32 `HWND`.
///
/// # Arguments
///
/// - `&Self` - Mutable Windows platform.
/// - `&WindowConfig` - Declarative window config.
///
/// # Returns
///
/// - `Result<WindowState, PlatformError>` - Initial window state.
fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
let mut registered: bool = self.get_class_registered();
let (hwnd, hinstance, scale): (usize, usize, f32) =
win32_create_window(config, &mut registered)?;
self.set_class_registered(registered);
let id: WindowId = WindowId::new(self.get_next_id());
self.set_next_id(self.get_next_id().wrapping_add(1));
let mut state: WindowState = WindowState::from_config(id, config, scale);
let hz: f32 = win32_display_refresh_rate_hz(hwnd);
state
.get_mut_display()
.set_refresh_rate_hz(hz.round() as u32);
let dxgi_config: Win32DxgiSwapChainConfig = win32_probe_dxgi_swapchain_config();
let initial_path: WindowsPresentationPath = Self::select_presentation_path(
config.get_render().get_mode(),
dxgi_config.get_dxgi_available(),
);
let initial_cpu_mirror: bool = initial_path != WindowsPresentationPath::GpuDirect;
self.get_mut_windows().insert(
id,
WindowsWindowRecord {
config: config.clone(),
state,
hwnd,
hinstance,
revealed: false,
saved_window_style: 0,
saved_placement: Win32WindowPlacement::default(),
dxgi_config,
presentation_path: initial_path,
cpu_mirror_active: initial_cpu_mirror,
last_telemetry: WindowsPresentTelemetry {
path: initial_path,
cpu_mirror_active: initial_cpu_mirror,
timing_source: WindowsPresentTimingSource::Unobservable,
dxgi_sync_qpc_time: 0,
dxgi_present_count: 0,
upload_bytes: 0,
dirty_rect_count: 0,
direct_gpu_frames: 0,
software_fallback_frames: 0,
failed_frames: 0,
},
d3d11: None,
},
);
Ok(state)
}
/// Queries live `WindowState` for `id`.
///
/// # Arguments
///
/// - `&Self` - Platform reference.
/// - `WindowId` - Window handle.
///
/// # Returns
///
/// - `Option<WindowState>` - Window state if open.
fn window_state(&self, id: WindowId) -> Option<WindowState> {
self.get_windows()
.get(&id)
.map(WindowsWindowRecord::get_state)
}
/// Returns `RawWindowHandle::Win32` for Direct3D / Vulkan surface binding.
///
/// # Arguments
///
/// - `&Self` - Platform reference.
/// - `WindowId` - Window handle.
///
/// # Returns
///
/// - `RawWindowHandle` - Win32 handle pair.
fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
match self.get_windows().get(&id) {
Some(rec) => RawWindowHandle::Win32 {
hwnd: rec.get_hwnd(),
hinstance: rec.get_hinstance(),
},
None => RawWindowHandle::Headless,
}
}
/// Pumps Win32 messages and drains pending events.
///
/// # Arguments
///
/// - `&Self` - Mutable Windows platform.
///
/// # Returns
///
/// - `Vec<WindowEvent>` - Pending events.
fn poll_events(&mut self) -> Vec<WindowEvent> {
let Self {
windows,
pending_events,
..
} = self;
win32_pump_messages(windows, pending_events);
take(pending_events)
}
/// Blocks via Win32 `MsgWaitForMultipleObjects` with zero CPU usage and zero idle wakeups until an OS message or explicit wakeup event arrives, then drains all messages.
///
/// # Arguments
///
/// - `&Self` - Mutable Windows platform.
///
/// # Returns
///
/// - `Vec<WindowEvent>` - Events received upon wake.
fn wait_for_events(&mut self) -> Vec<WindowEvent> {
if self.get_pending_events().is_empty() && !self.get_windows().is_empty() {
let mut wait_handles: [isize; 1] = [0; 1];
let mut handle_count: usize = 0;
let wake_handle: isize = self.get_wake_event();
if wake_handle != 0 {
wait_handles[0] = wake_handle;
handle_count = 1;
}
let _: u32 = win32_wait_for_events(&wait_handles[..handle_count], WIN32_WAIT_INFINITE);
}
self.poll_events()
}
/// Updates Win32 background frame-pump pause state.
///
/// # Arguments
///
/// - `&Self` - Mutable Windows platform.
/// - `bool` - `true` when paused in background; `false` when active.
fn set_frame_pump_paused(&mut self, paused: bool) {
self.set_pump_paused(paused);
}
/// Returns whether the Win32 frame pump is currently paused for background freeze.
///
/// # Arguments
///
/// - `&Self` - Platform reference.
///
/// # Returns
///
/// - `bool` - `true` when paused in background.
fn is_frame_pump_paused(&self) -> bool {
self.get_pump_paused()
}
/// Blits `framebuffer` directly to the Win32 `HWND` via GDI `StretchDIBits`.
///
/// # Arguments
///
/// - `&Self` - Mutable Windows platform.
/// - `WindowId` - Window handle.
/// - `&Framebuffer` - Rendered RGBA8 framebuffer.
///
/// # Returns
///
/// - `Result<(), PlatformError>` - Presentation status.
fn present_framebuffer(
&mut self,
id: WindowId,
framebuffer: &Framebuffer,
) -> Result<(), PlatformError> {
self.present_framebuffer_region(id, framebuffer, DamageRegion::full())
}
/// Blits `framebuffer` (or only `damage` on 1:1 surfaces) onto the Win32 `HWND` and reveals the window after Frame 1.
///
/// # Arguments
///
/// - `WindowId` - Window handle.
/// - `&Framebuffer` - Rendered RGBA8 framebuffer.
/// - `DamageRegion` - Damaged pixel region updated this frame.
///
/// # Returns
///
/// - `Result<(), PlatformError>` - Presentation status.
fn present_framebuffer_region(
&mut self,
id: WindowId,
framebuffer: &Framebuffer,
damage: DamageRegion,
) -> Result<(), PlatformError> {
let _: WindowsPresentTelemetry = self.present_gdi_fallback(id, framebuffer, damage)?;
Ok(())
}
/// Presents `submission` directly to the Win32 window's DXGI 1.6 / D3D11 swapchain without CPU RGBA mirroring.
///
/// # Arguments
///
/// - `&Self` - Mutable Windows platform.
/// - `WindowId` - Window handle.
/// - `&GpuFrameSubmission` - Direct-GPU primitive batches and atlas payloads.
///
/// # Returns
///
/// - `Result<GpuPresentReceipt, PlatformError>` - Direct GPU presentation receipt or unsupported fallback signal.
fn present_gpu_frame(
&mut self,
id: WindowId,
submission: &GpuFrameSubmission,
) -> Result<GpuPresentReceipt, PlatformError> {
let has_hwnd: bool = self
.get_windows()
.get(&id)
.ok_or(PlatformError::WindowNotFound(id.get_value()))?
.get_hwnd()
!= 0;
if !has_hwnd {
return Ok(GpuPresentReceipt::unsupported());
}
match self.present_direct_gpu_submission(id, submission) {
Ok((telemetry, draw_calls, uploaded_instances)) => Ok(GpuPresentReceipt::new(
true,
draw_calls,
uploaded_instances,
telemetry.get_dxgi_sync_qpc_time(),
0,
false,
)),
Err(PlatformError::SurfaceError(_)) => Ok(GpuPresentReceipt::unsupported()),
Err(err) => Err(err),
}
}
/// Reads cached clipboard text.
///
/// # Arguments
///
/// - `&Self` - Platform reference.
///
/// # Returns
///
/// - `Option<String>` - Clipboard contents.
fn read_clipboard(&self) -> Option<String> {
let Self {
clipboard_cache, ..
} = self;
clipboard_cache.clone()
}
/// Writes `text` into clipboard cache.
///
/// # Arguments
///
/// - `&Self` - Mutable platform.
/// - `&str` - Clipboard text.
///
/// # Returns
///
/// - `Result<(), PlatformError>` - Write status.
fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
self.set_clipboard_cache(Some(text.to_string()));
let _: bool = write_system_clipboard(text);
Ok(())
}
/// Returns default system theme mode.
///
/// # Arguments
///
/// - `&Self` - Platform reference.
///
/// # Returns
///
/// - `ThemeMode` - Active appearance mode.
fn system_theme(&self) -> ThemeMode {
ThemeMode::Light
}
/// Queries the active Win32 monitor refresh rate via GDI `GetDeviceCaps`.
///
/// # Arguments
///
/// - `&Self` - Platform reference.
///
/// # Returns
///
/// - `f32` - Active monitor refresh rate in Hertz.
fn display_refresh_rate_hz(&self) -> f32 {
let hwnd: usize = self
.get_windows()
.values()
.next()
.map(WindowsWindowRecord::get_hwnd)
.unwrap_or(0);
win32_display_refresh_rate_hz(hwnd)
}
}