forked from linebender/druid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwindow.rs
2288 lines (2115 loc) · 84.4 KB
/
window.rs
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Creation and management of windows.
#![allow(non_snake_case, clippy::cast_lossless)]
use std::cell::{Cell, RefCell};
use std::mem;
use std::panic::Location;
use std::ptr::{null, null_mut};
use std::rc::{Rc, Weak};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use scopeguard::defer;
use tracing::{debug, error, warn};
use winapi::ctypes::{c_int, c_void};
use winapi::shared::dxgi::*;
use winapi::shared::dxgi1_2::*;
use winapi::shared::dxgiformat::*;
use winapi::shared::dxgitype::*;
use winapi::shared::minwindef::*;
use winapi::shared::windef::*;
use winapi::shared::winerror::*;
use winapi::um::dcomp::{IDCompositionDevice, IDCompositionTarget, IDCompositionVisual};
use winapi::um::dwmapi::{DwmExtendFrameIntoClientArea, DwmSetWindowAttribute};
use winapi::um::errhandlingapi::GetLastError;
use winapi::um::shellscalingapi::MDT_EFFECTIVE_DPI;
use winapi::um::unknwnbase::*;
use winapi::um::uxtheme::*;
use winapi::um::wingdi::*;
use winapi::um::winnt::*;
use winapi::um::winuser::*;
use winapi::Interface;
use wio::com::ComPtr;
#[cfg(feature = "raw-win-handle")]
use raw_window_handle::{windows::WindowsHandle, HasRawWindowHandle, RawWindowHandle};
use piet_common::d2d::{D2DFactory, DeviceContext};
use piet_common::dwrite::DwriteFactory;
use crate::kurbo::{Insets, Point, Rect, Size, Vec2};
use crate::piet::{Piet, PietText, RenderContext};
use super::accels::register_accel;
use super::application::Application;
use super::dcomp::D3D11Device;
use super::dialog::get_file_dialog_path;
use super::error::Error;
use super::keyboard::{self, KeyboardState};
use super::menu::Menu;
use super::paint;
use super::timers::TimerSlots;
use super::util::{self, as_result, FromWide, ToWide, OPTIONAL_FUNCTIONS};
use crate::common_util::IdleCallback;
use crate::dialog::{FileDialogOptions, FileDialogType, FileInfo};
use crate::error::Error as ShellError;
use crate::keyboard::{KbKey, KeyState};
use crate::mouse::{Cursor, CursorDesc, MouseButton, MouseButtons, MouseEvent};
use crate::region::Region;
use crate::scale::{Scalable, Scale, ScaledArea};
use crate::text::{simulate_input, Event};
use crate::window;
use crate::window::{
FileDialogToken, IdleToken, TextFieldToken, TimerToken, WinHandler, WindowLevel,
};
/// The backend target DPI.
///
/// Windows considers 96 the default value which represents a 1.0 scale factor.
pub(crate) const SCALE_TARGET_DPI: f64 = 96.0;
/// Builder abstraction for creating new windows.
pub(crate) struct WindowBuilder {
app: Application,
handler: Option<Box<dyn WinHandler>>,
title: String,
menu: Option<Menu>,
present_strategy: PresentStrategy,
resizable: bool,
show_titlebar: bool,
size: Option<Size>,
transparent: bool,
min_size: Option<Size>,
position: Option<Point>,
level: Option<WindowLevel>,
state: window::WindowState,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
/// It's very tricky to get smooth dynamics (especially resizing) and
/// good performance on Windows. This setting lets clients experiment
/// with different strategies.
#[allow(dead_code)]
pub enum PresentStrategy {
/// Corresponds to the swap effect DXGI_SWAP_EFFECT_SEQUENTIAL. It
/// is compatible with GDI (such as menus), but is not the best in
/// performance.
///
/// In earlier testing, it exhibited diagonal banding artifacts (most
/// likely because of bugs in Nvidia Optimus configurations) and did
/// not do incremental present, but in more recent testing, at least
/// incremental present seems to work fine.
///
/// Also note, this swap effect is not compatible with DX12.
Sequential,
/// Corresponds to the swap effect DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL.
/// In testing, it seems to perform well, but isn't compatible with
/// GDI. Resize can probably be made to work reasonably smoothly with
/// additional synchronization work, but has some artifacts.
Flip,
/// Corresponds to the swap effect DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL
/// but with a redirection surface for GDI compatibility. Resize is
/// very laggy and artifacty.
FlipRedirect,
}
/// An enumeration of operations that might need to be deferred until the `WinHandler` is dropped.
///
/// We work hard to avoid calling into `WinHandler` re-entrantly. Since we use
/// the system's event loop, and since the `WinHandler` gets a `WindowHandle` to use, this implies
/// that none of the `WindowHandle`'s methods can return control to the system's event loop
/// (because if it did, the system could call back into druid-shell with some mouse event, and then
/// we'd try to call the `WinHandler` again).
///
/// The solution is that for every `WindowHandle` method that *wants* to return control to the
/// system's event loop, instead of doing that we queue up a deferrred operation and return
/// immediately. The deferred operations will run whenever the currently running `WinHandler`
/// method returns.
///
/// An example call trace might look like:
/// 1. the system hands a mouse click event to druid-shell
/// 2. druid-shell calls `WinHandler::mouse_up`
/// 3. after some processing, the `WinHandler` calls `WindowHandle::save_as`, which schedules a
/// deferred op and returns immediately
/// 4. after some more processing, `WinHandler::mouse_up` returns
/// 5. druid-shell displays the "save as" dialog that was requested in step 3.
enum DeferredOp {
SaveAs(FileDialogOptions, FileDialogToken),
Open(FileDialogOptions, FileDialogToken),
ContextMenu(Menu, Point),
ShowTitlebar(bool),
SetPosition(Point),
SetSize(Size),
SetResizable(bool),
SetWindowState(window::WindowState),
ReleaseMouseCapture,
}
#[derive(Clone, Debug)]
pub struct WindowHandle {
text: PietText,
state: Weak<WindowState>,
}
impl PartialEq for WindowHandle {
fn eq(&self, other: &Self) -> bool {
match (self.state.upgrade(), other.state.upgrade()) {
(None, None) => true,
(Some(s), Some(o)) => std::rc::Rc::ptr_eq(&s, &o),
(_, _) => false,
}
}
}
impl Eq for WindowHandle {}
#[cfg(feature = "raw-win-handle")]
unsafe impl HasRawWindowHandle for WindowHandle {
fn raw_window_handle(&self) -> RawWindowHandle {
if let Some(hwnd) = self.get_hwnd() {
let handle = WindowsHandle {
hwnd: hwnd as *mut core::ffi::c_void,
hinstance: unsafe {
winapi::um::libloaderapi::GetModuleHandleW(0 as winapi::um::winnt::LPCWSTR)
as *mut core::ffi::c_void
},
..WindowsHandle::empty()
};
RawWindowHandle::Windows(handle)
} else {
error!("Cannot retrieved HWND for window.");
RawWindowHandle::Windows(WindowsHandle::empty())
}
}
}
/// A handle that can get used to schedule an idle handler. Note that
/// this handle is thread safe. If the handle is used after the hwnd
/// has been destroyed, probably not much will go wrong (the DS_RUN_IDLE
/// message may be sent to a stray window).
#[derive(Clone)]
pub struct IdleHandle {
pub(crate) hwnd: HWND,
queue: Arc<Mutex<Vec<IdleKind>>>,
}
/// This represents different Idle Callback Mechanism
enum IdleKind {
Callback(Box<dyn IdleCallback>),
Token(IdleToken),
}
/// This is the low level window state. All mutable contents are protected
/// by interior mutability, so we can handle reentrant calls.
struct WindowState {
hwnd: Cell<HWND>,
scale: Cell<Scale>,
area: Cell<ScaledArea>,
invalid: RefCell<Region>,
has_menu: Cell<bool>,
wndproc: Box<dyn WndProc>,
idle_queue: Arc<Mutex<Vec<IdleKind>>>,
timers: Arc<Mutex<TimerSlots>>,
deferred_queue: RefCell<Vec<DeferredOp>>,
has_titlebar: Cell<bool>,
is_transparent: Cell<bool>,
// For resizable borders, window can still be resized with code.
is_resizable: Cell<bool>,
handle_titlebar: Cell<bool>,
active_text_input: Cell<Option<TextFieldToken>>,
// Is the window focusable ("activatable" in Win32 terminology)?
// False for tooltips, to prevent stealing focus from owner window.
is_focusable: bool,
window_level: WindowLevel,
}
impl std::fmt::Debug for WindowState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.write_str("WindowState{\n")?;
f.write_str(format!("{:p}", self.hwnd.get()).as_str())?;
f.write_str("}")?;
Ok(())
}
}
/// Generic handler trait for the winapi window procedure entry point.
trait WndProc {
fn connect(&self, handle: &WindowHandle, state: WndState);
fn cleanup(&self, hwnd: HWND);
fn window_proc(&self, hwnd: HWND, msg: UINT, wparam: WPARAM, lparam: LPARAM)
-> Option<LRESULT>;
}
// State and logic for the winapi window procedure entry point. Note that this level
// implements policies such as the use of Direct2D for painting.
struct MyWndProc {
app: Application,
handle: RefCell<WindowHandle>,
d2d_factory: D2DFactory,
text: PietText,
state: RefCell<Option<WndState>>,
present_strategy: PresentStrategy,
}
/// The mutable state of the window.
struct WndState {
handler: Box<dyn WinHandler>,
render_target: Option<DeviceContext>,
dxgi_state: Option<DxgiState>,
min_size: Option<Size>,
keyboard_state: KeyboardState,
// Stores a set of all mouse buttons that are currently holding mouse
// capture. When the first mouse button is down on our window we enter
// capture, and we hold it until the last mouse button is up.
captured_mouse_buttons: MouseButtons,
transparent: bool,
// Is this window the topmost window under the mouse cursor
has_mouse_focus: bool,
//TODO: track surrogate orphan
last_click_time: Instant,
last_click_pos: (i32, i32),
click_count: u8,
}
/// State for DXGI swapchains.
struct DxgiState {
swap_chain: *mut IDXGISwapChain1,
// These ComPtrs must live as long as the window
#[allow(dead_code)]
composition_device: Option<ComPtr<IDCompositionDevice>>,
#[allow(dead_code)]
composition_target: Option<ComPtr<IDCompositionTarget>>,
#[allow(dead_code)]
composition_visual: Option<ComPtr<IDCompositionVisual>>,
}
#[derive(Clone, PartialEq)]
pub struct CustomCursor(Arc<HCursor>);
#[derive(PartialEq)]
struct HCursor(HCURSOR);
impl Drop for HCursor {
fn drop(&mut self) {
unsafe {
DestroyIcon(self.0);
}
}
}
/// Message indicating there are idle tasks to run.
const DS_RUN_IDLE: UINT = WM_USER;
/// Message relaying a request to destroy the window.
///
/// Calling `DestroyWindow` from inside the handler is problematic
/// because it will recursively cause a `WM_DESTROY` message to be
/// sent to the window procedure, even while the handler is borrowed.
/// Thus, the message is dropped and the handler doesn't run.
///
/// As a solution, instead of immediately calling `DestroyWindow`, we
/// send this message to request destroying the window, so that at the
/// time it is handled, we can successfully borrow the handler.
pub(crate) const DS_REQUEST_DESTROY: UINT = WM_USER + 1;
impl Default for PresentStrategy {
fn default() -> PresentStrategy {
PresentStrategy::Sequential
}
}
/// Extract the buttons that are being held down from wparam in mouse events.
fn get_buttons(wparam: WPARAM) -> MouseButtons {
let mut buttons = MouseButtons::new();
if wparam & MK_LBUTTON != 0 {
buttons.insert(MouseButton::Left);
}
if wparam & MK_RBUTTON != 0 {
buttons.insert(MouseButton::Right);
}
if wparam & MK_MBUTTON != 0 {
buttons.insert(MouseButton::Middle);
}
if wparam & MK_XBUTTON1 != 0 {
buttons.insert(MouseButton::X1);
}
if wparam & MK_XBUTTON2 != 0 {
buttons.insert(MouseButton::X2);
}
buttons
}
fn is_point_in_client_rect(hwnd: HWND, x: i32, y: i32) -> bool {
unsafe {
let mut client_rect = mem::MaybeUninit::uninit();
if GetClientRect(hwnd, client_rect.as_mut_ptr()) == FALSE {
warn!(
"failed to get client rect: {}",
Error::Hr(HRESULT_FROM_WIN32(GetLastError()))
);
return false;
}
let client_rect = client_rect.assume_init();
let mouse_point = POINT { x, y };
PtInRect(&client_rect, mouse_point) != FALSE
}
}
fn set_style(hwnd: HWND, resizable: bool, titlebar: bool) {
unsafe {
let mut style = GetWindowLongPtrW(hwnd, GWL_STYLE) as u32;
if style == 0 {
warn!(
"failed to get window style: {}",
Error::Hr(HRESULT_FROM_WIN32(GetLastError()))
);
return;
}
if !resizable {
style &= !(WS_THICKFRAME | WS_MAXIMIZEBOX);
} else {
style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
}
if !titlebar {
style &= !(WS_SYSMENU | WS_OVERLAPPED);
} else {
style |= WS_MINIMIZEBOX | WS_SYSMENU | WS_OVERLAPPED;
}
if SetWindowLongPtrW(hwnd, GWL_STYLE, style as _) == 0 {
warn!(
"failed to set the window style: {}",
Error::Hr(HRESULT_FROM_WIN32(GetLastError()))
);
}
if SetWindowPos(
hwnd,
HWND_TOPMOST,
0,
0,
0,
0,
SWP_SHOWWINDOW
| SWP_NOMOVE
| SWP_NOZORDER
| SWP_FRAMECHANGED
| SWP_NOSIZE
| SWP_NOOWNERZORDER
| SWP_NOACTIVATE,
) == 0
{
warn!(
"failed to update window style: {}",
Error::Hr(HRESULT_FROM_WIN32(GetLastError()))
);
};
}
}
impl WndState {
fn rebuild_render_target(&mut self, d2d: &D2DFactory, scale: Scale) -> Result<(), Error> {
unsafe {
let swap_chain = self.dxgi_state.as_ref().unwrap().swap_chain;
match paint::create_render_target_dxgi(d2d, swap_chain, scale, self.transparent) {
Ok(rt) => {
self.render_target =
Some(rt.as_device_context().expect("TODO remove this expect"));
Ok(())
}
Err(e) => Err(e),
}
}
}
// Renders but does not present.
fn render(&mut self, d2d: &D2DFactory, text: &PietText, invalid: &Region) {
let rt = self.render_target.as_mut().unwrap();
rt.begin_draw();
{
let mut piet_ctx = Piet::new(d2d, text.clone(), rt);
// The documentation on DXGI_PRESENT_PARAMETERS says we "must not update any
// pixel outside of the dirty rectangles."
piet_ctx.clip(invalid.to_bez_path());
self.handler.paint(&mut piet_ctx, invalid);
if let Err(e) = piet_ctx.finish() {
error!("piet error on render: {:?}", e);
}
}
// Maybe should deal with lost device here...
let res = rt.end_draw();
if let Err(e) = res {
error!("EndDraw error: {:?}", e);
}
}
fn enter_mouse_capture(&mut self, hwnd: HWND, button: MouseButton) {
if self.captured_mouse_buttons.is_empty() {
unsafe {
SetCapture(hwnd);
}
}
self.captured_mouse_buttons.insert(button);
}
fn exit_mouse_capture(&mut self, button: MouseButton) -> bool {
self.captured_mouse_buttons.remove(button);
self.captured_mouse_buttons.is_empty()
}
}
impl MyWndProc {
fn with_window_state<F, R>(&self, f: F) -> R
where
F: FnOnce(Rc<WindowState>) -> R,
{
f(self
.handle
// There are no mutable borrows to this: we only use a mutable borrow during
// initialization.
.borrow()
.state
.upgrade()
.unwrap()) // WindowState drops after WM_NCDESTROY, so it's always here.
}
#[track_caller]
fn with_wnd_state<F, R>(&self, f: F) -> Option<R>
where
F: FnOnce(&mut WndState) -> R,
{
let ret = if let Ok(mut s) = self.state.try_borrow_mut() {
(*s).as_mut().map(f)
} else {
error!("failed to borrow WndState at {}", Location::caller());
None
};
if ret.is_some() {
self.handle_deferred_queue();
}
ret
}
fn scale(&self) -> Scale {
self.with_window_state(|state| state.scale.get())
}
fn set_scale(&self, scale: Scale) {
self.with_window_state(move |state| state.scale.set(scale))
}
/// Takes the invalid region and returns it, replacing it with the empty region.
fn take_invalid(&self) -> Region {
self.with_window_state(|state| {
std::mem::replace(&mut *state.invalid.borrow_mut(), Region::EMPTY)
})
}
fn invalidate_rect(&self, rect: Rect) {
self.with_window_state(|state| state.invalid.borrow_mut().add_rect(rect));
}
fn set_area(&self, area: ScaledArea) {
self.with_window_state(move |state| state.area.set(area))
}
fn has_menu(&self) -> bool {
self.with_window_state(|state| state.has_menu.get())
}
fn has_titlebar(&self) -> bool {
self.with_window_state(|state| state.has_titlebar.get())
}
fn resizable(&self) -> bool {
self.with_window_state(|state| state.is_resizable.get())
}
fn is_transparent(&self) -> bool {
self.with_window_state(|state| state.is_transparent.get())
}
fn handle_deferred_queue(&self) {
let q = self.with_window_state(move |state| state.deferred_queue.replace(Vec::new()));
for op in q {
self.handle_deferred(op);
}
}
fn handle_deferred(&self, op: DeferredOp) {
if let Some(hwnd) = self.handle.borrow().get_hwnd() {
match op {
DeferredOp::SetSize(size_dp) => unsafe {
let size_px = size_dp.to_px(self.scale());
if SetWindowPos(
hwnd,
HWND_TOPMOST,
0,
0,
size_px.width.round() as i32,
size_px.height.round() as i32,
SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOACTIVATE,
) == 0
{
warn!(
"failed to resize window: {}",
Error::Hr(HRESULT_FROM_WIN32(GetLastError()))
);
};
},
DeferredOp::SetPosition(pos_dp) => unsafe {
let pos_px = pos_dp.to_px(self.scale());
if SetWindowPos(
hwnd,
HWND_TOPMOST,
pos_px.x.round() as i32,
pos_px.y.round() as i32,
0,
0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOACTIVATE,
) == 0
{
warn!(
"failed to move window: {}",
Error::Hr(HRESULT_FROM_WIN32(GetLastError()))
);
};
},
DeferredOp::ShowTitlebar(titlebar) => {
self.with_window_state(|s| s.has_titlebar.set(titlebar));
set_style(hwnd, self.resizable(), titlebar);
}
DeferredOp::SetResizable(resizable) => {
self.with_window_state(|s| s.is_resizable.set(resizable));
set_style(hwnd, resizable, self.has_titlebar());
}
DeferredOp::SetWindowState(val) => {
let show = if self.handle.borrow().is_focusable() {
match val {
window::WindowState::Maximized => SW_MAXIMIZE,
window::WindowState::Minimized => SW_MINIMIZE,
window::WindowState::Restored => SW_RESTORE,
}
} else {
SW_SHOWNOACTIVATE
};
unsafe {
ShowWindow(hwnd, show);
}
}
DeferredOp::SaveAs(options, token) => {
let info = unsafe {
get_file_dialog_path(hwnd, FileDialogType::Save, options)
.ok()
.map(|os_str| FileInfo {
path: os_str.into(),
format: None,
})
};
self.with_wnd_state(|s| s.handler.save_as(token, info));
}
DeferredOp::Open(options, token) => {
let info = unsafe {
get_file_dialog_path(hwnd, FileDialogType::Open, options)
.ok()
.map(|s| FileInfo {
path: s.into(),
format: None,
})
};
self.with_wnd_state(|s| s.handler.open_file(token, info));
}
DeferredOp::ContextMenu(menu, pos) => {
let hmenu = menu.into_hmenu();
let pos = pos.to_px(self.scale()).round();
unsafe {
let mut point = POINT {
x: pos.x as i32,
y: pos.y as i32,
};
ClientToScreen(hwnd, &mut point);
if TrackPopupMenu(hmenu, TPM_LEFTALIGN, point.x, point.y, 0, hwnd, null())
== FALSE
{
warn!("failed to track popup menu");
}
}
}
DeferredOp::ReleaseMouseCapture => unsafe {
if ReleaseCapture() == FALSE {
let result = HRESULT_FROM_WIN32(GetLastError());
// When result is zero, it appears to just mean that the capture was already released
// (which can easily happen since this is deferred).
if result != 0 {
warn!("failed to release mouse capture: {}", Error::Hr(result));
}
}
},
}
} else {
warn!("Could not get HWND");
}
}
fn get_system_metric(&self, metric: c_int) -> i32 {
unsafe {
// This is only supported on windows 10.
if let Some(func) = OPTIONAL_FUNCTIONS.GetSystemMetricsForDpi {
let dpi = self.scale().x() * SCALE_TARGET_DPI;
func(metric, dpi as u32)
}
// Support for older versions of windows
else {
// Note: On Windows 8.1 GetSystemMetrics() is scaled to the DPI the window
// was created with, and not the current DPI of the window
GetSystemMetrics(metric)
}
}
}
}
impl WndProc for MyWndProc {
fn connect(&self, handle: &WindowHandle, state: WndState) {
*self.handle.borrow_mut() = handle.clone();
*self.state.borrow_mut() = Some(state);
self.state
.borrow_mut()
.as_mut()
.unwrap()
.handler
.scale(self.scale());
}
fn cleanup(&self, hwnd: HWND) {
self.app.remove_window(hwnd);
}
#[allow(clippy::cognitive_complexity)]
fn window_proc(
&self,
hwnd: HWND,
msg: UINT,
wparam: WPARAM,
lparam: LPARAM,
) -> Option<LRESULT> {
//println!("wndproc msg: {}", msg);
match msg {
WM_CREATE => {
// Only supported on Windows 10, Could remove this as the 8.1 version below also works on 10..
let scale_factor = if let Some(func) = OPTIONAL_FUNCTIONS.GetDpiForWindow {
unsafe { func(hwnd) as f64 / SCALE_TARGET_DPI }
}
// Windows 8.1 Support
else if let Some(func) = OPTIONAL_FUNCTIONS.GetDpiForMonitor {
unsafe {
let monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
let mut dpiX = 0;
let mut dpiY = 0;
func(monitor, MDT_EFFECTIVE_DPI, &mut dpiX, &mut dpiY);
dpiX as f64 / SCALE_TARGET_DPI
}
} else {
1.0
};
let scale = Scale::new(scale_factor, scale_factor);
self.set_scale(scale);
if let Some(state) = self.handle.borrow().state.upgrade() {
state.hwnd.set(hwnd);
}
if let Some(state) = self.state.borrow_mut().as_mut() {
let dxgi_state = unsafe {
create_dxgi_state(self.present_strategy, hwnd, self.is_transparent())
.unwrap_or_else(|e| {
error!("Creating swapchain failed: {:?}", e);
None
})
};
state.dxgi_state = dxgi_state;
let handle = self.handle.borrow().to_owned();
state.handler.connect(&handle.into());
if let Err(e) = state.rebuild_render_target(&self.d2d_factory, scale) {
error!("error building render target: {}", e);
}
}
Some(0)
}
WM_ACTIVATE => {
if LOWORD(wparam as u32) as u32 != 0 {
unsafe {
if !self.has_titlebar() && !self.is_transparent() {
// This makes windows paint the dropshadow around the window
// since we give it a "1 pixel frame" that we paint over anyway.
// From my testing top seems to be the best option when it comes to avoiding resize artifacts.
let margins = MARGINS {
cxLeftWidth: 0,
cxRightWidth: 0,
cyTopHeight: 1,
cyBottomHeight: 0,
};
DwmExtendFrameIntoClientArea(hwnd, &margins);
}
if SetWindowPos(
hwnd,
HWND_TOPMOST,
0,
0,
0,
0,
SWP_SHOWWINDOW
| SWP_NOMOVE
| SWP_NOZORDER
| SWP_FRAMECHANGED
| SWP_NOSIZE
| SWP_NOOWNERZORDER
| SWP_NOACTIVATE,
) == 0
{
warn!(
"SetWindowPos failed with error: {}",
Error::Hr(HRESULT_FROM_WIN32(GetLastError()))
);
};
}
}
Some(0)
}
WM_ERASEBKGND => Some(0),
WM_SETFOCUS => {
self.with_wnd_state(|s| s.handler.got_focus());
Some(0)
}
WM_KILLFOCUS => {
self.with_wnd_state(|s| s.handler.lost_focus());
Some(0)
}
WM_PAINT => unsafe {
self.with_wnd_state(|s| {
// We call prepare_paint before GetUpdateRect, so that anything invalidated during
// prepare_paint will be reflected in GetUpdateRect.
s.handler.prepare_paint();
let mut rect: RECT = mem::zeroed();
// TODO: use GetUpdateRgn for more conservative invalidation
GetUpdateRect(hwnd, &mut rect, FALSE);
ValidateRect(hwnd, null_mut());
let rect_dp = util::recti_to_rect(rect).to_dp(self.scale());
if rect_dp.area() != 0.0 {
self.invalidate_rect(rect_dp);
}
let invalid = self.take_invalid();
if !invalid.rects().is_empty() {
s.handler.rebuild_resources();
s.render(&self.d2d_factory, &self.text, &invalid);
if let Some(ref mut ds) = s.dxgi_state {
let mut dirty_rects = util::region_to_rectis(&invalid, self.scale());
let params = DXGI_PRESENT_PARAMETERS {
DirtyRectsCount: dirty_rects.len() as u32,
pDirtyRects: dirty_rects.as_mut_ptr(),
pScrollRect: null_mut(),
pScrollOffset: null_mut(),
};
(*ds.swap_chain).Present1(1, 0, ¶ms);
}
}
});
Some(0)
},
WM_DPICHANGED => unsafe {
let x = HIWORD(wparam as u32) as f64 / SCALE_TARGET_DPI;
let y = LOWORD(wparam as u32) as f64 / SCALE_TARGET_DPI;
let scale = Scale::new(x, y);
self.set_scale(scale);
let rect: *mut RECT = lparam as *mut RECT;
SetWindowPos(
hwnd,
HWND_TOPMOST,
(*rect).left,
(*rect).top,
(*rect).right - (*rect).left,
(*rect).bottom - (*rect).top,
SWP_NOZORDER
| SWP_FRAMECHANGED
| SWP_DRAWFRAME
| SWP_NOOWNERZORDER
| SWP_NOACTIVATE,
);
Some(0)
},
WM_NCCALCSIZE => unsafe {
if wparam != 0 && !self.has_titlebar() {
if let Ok(handle) = self.handle.try_borrow() {
if handle.get_window_state() == window::WindowState::Maximized {
// When maximized, windows still adds offsets for the frame
// so we counteract them here.
let s: *mut NCCALCSIZE_PARAMS = lparam as *mut NCCALCSIZE_PARAMS;
if let Some(mut s) = s.as_mut() {
let border = self.get_system_metric(SM_CXPADDEDBORDER);
let frame = self.get_system_metric(SM_CYSIZEFRAME);
s.rgrc[0].top += (border + frame) as i32;
s.rgrc[0].right -= (border + frame) as i32;
s.rgrc[0].left += (border + frame) as i32;
s.rgrc[0].bottom -= (border + frame) as i32;
}
}
}
return Some(0);
}
None
},
WM_NCHITTEST => unsafe {
let mut hit = DefWindowProcW(hwnd, msg, wparam, lparam);
if !self.has_titlebar() && self.resizable() {
if let Ok(handle) = self.handle.try_borrow() {
if handle.get_window_state() != window::WindowState::Maximized {
let mut rect = RECT {
left: 0,
top: 0,
right: 0,
bottom: 0,
};
if GetWindowRect(hwnd, &mut rect) == 0 {
warn!(
"failed to get window rect: {}",
Error::Hr(HRESULT_FROM_WIN32(GetLastError()))
);
};
let y_cord = HIWORD(lparam as u32) as i16 as i32;
let x_cord = LOWORD(lparam as u32) as i16 as i32;
let HIT_SIZE = self.get_system_metric(SM_CYSIZEFRAME)
+ self.get_system_metric(SM_CXPADDEDBORDER);
if y_cord - rect.top <= HIT_SIZE {
if x_cord - rect.left <= HIT_SIZE {
hit = HTTOPLEFT;
} else if rect.right - x_cord <= HIT_SIZE {
hit = HTTOPRIGHT;
} else {
hit = HTTOP;
}
} else if rect.bottom - y_cord <= HIT_SIZE {
if x_cord - rect.left <= HIT_SIZE {
hit = HTBOTTOMLEFT;
} else if rect.right - x_cord <= HIT_SIZE {
hit = HTBOTTOMRIGHT;
} else {
hit = HTBOTTOM;
}
} else if x_cord - rect.left <= HIT_SIZE {
hit = HTLEFT;
} else if rect.right - x_cord <= HIT_SIZE {
hit = HTRIGHT;
}
}
}
}
let mouseDown = GetAsyncKeyState(VK_LBUTTON) < 0;
if self.with_window_state(|state| state.handle_titlebar.get()) && !mouseDown {
self.with_window_state(move |state| state.handle_titlebar.set(false));
};
if self.with_window_state(|state| state.handle_titlebar.get()) && hit == HTCLIENT {
hit = HTCAPTION;
}
Some(hit)
},
WM_SIZE => unsafe {
let width = LOWORD(lparam as u32) as u32;
let height = HIWORD(lparam as u32) as u32;
if width == 0 || height == 0 {
return Some(0);
}
self.with_wnd_state(|s| {
let scale = self.scale();
let area = ScaledArea::from_px((width as f64, height as f64), scale);
let size_dp = area.size_dp();
self.set_area(area);
s.handler.size(size_dp);
let res;
{
s.render_target = None;
res = (*s.dxgi_state.as_mut().unwrap().swap_chain).ResizeBuffers(
0,
width,
height,
DXGI_FORMAT_UNKNOWN,
0,
);
}
if SUCCEEDED(res) {
if let Err(e) = s.rebuild_render_target(&self.d2d_factory, scale) {
error!("error building render target: {}", e);
}
s.render(&self.d2d_factory, &self.text, &size_dp.to_rect().into());
let present_after = match self.present_strategy {
PresentStrategy::Sequential => 1,
_ => 0,
};
if let Some(ref mut dxgi_state) = s.dxgi_state {
(*dxgi_state.swap_chain).Present(present_after, 0);
}
ValidateRect(hwnd, null_mut());
} else {
error!("ResizeBuffers failed: 0x{:x}", res);
}
})
.map(|_| 0)
},
WM_COMMAND => {
self.with_wnd_state(|s| s.handler.command(LOWORD(wparam as u32) as u32));
Some(0)
}
//TODO: WM_SYSCOMMAND
WM_CHAR | WM_SYSCHAR | WM_KEYDOWN | WM_SYSKEYDOWN | WM_KEYUP | WM_SYSKEYUP
| WM_INPUTLANGCHANGE => {
unsafe {
// We must call keyboard::is_last_message outside of the
// WndState borrow below, because is_last_message
// calls PeekMessageW, which can make reentrant calls
// to our window procedure. There is one known real-world
// example of this problem: when Narrator is running
// and the user presses Alt+Tab, Narrator's keyboard event
// preprocessing withholds the key-down event for Alt
// until the user presses Tab, so we receive
// WM_KILLFOCUS while we're processing WM_KEYDOWN.
let is_last = keyboard::is_last_message(hwnd, msg, lparam);
let handled = self.with_wnd_state(|s| {
if let Some(event) = s
.keyboard_state