-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathw32_common.c
2480 lines (2171 loc) · 82.1 KB
/
w32_common.c
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
/*
* This file is part of mpv.
*
* mpv is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* mpv is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
#include <assert.h>
#include <limits.h>
#include <stdatomic.h>
#include <stdio.h>
#define _DECL_DLLMAIN
#include <windows.h>
#include <windowsx.h>
#include <dwmapi.h>
#include <ole2.h>
#include <process.h>
#include <shellscalingapi.h>
#include <shobjidl.h>
#include <avrt.h>
#include "options/m_config.h"
#include "options/options.h"
#include "input/keycodes.h"
#include "input/input.h"
#include "input/event.h"
#include "stream/stream.h"
#include "common/msg.h"
#include "common/common.h"
#include "vo.h"
#include "win_state.h"
#include "w32_common.h"
#include "win32/displayconfig.h"
#include "win32/droptarget.h"
#include "win32/menu.h"
#include "osdep/io.h"
#include "osdep/threads.h"
#include "osdep/w32_keyboard.h"
#include "misc/dispatch.h"
#include "misc/rendezvous.h"
#include "mpv_talloc.h"
#define MPV_WINDOW_CLASS_NAME L"mpv"
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
#define HINST_THISCOMPONENT ((HINSTANCE)&__ImageBase)
#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
#define DWMWA_USE_IMMERSIVE_DARK_MODE 20
#endif
#ifndef DWMWA_VISIBLE_FRAME_BORDER_THICKNESS
#define DWMWA_VISIBLE_FRAME_BORDER_THICKNESS 37
#endif
#ifndef DWMWA_WINDOW_CORNER_PREFERENCE
#define DWMWA_WINDOW_CORNER_PREFERENCE 33
#endif
#ifndef DWMWA_SYSTEMBACKDROP_TYPE
#define DWMWA_SYSTEMBACKDROP_TYPE 38
#endif
#define rect_w(r) ((r).right - (r).left)
#define rect_h(r) ((r).bottom - (r).top)
#define WM_SHOWMENU (WM_USER + 1)
struct w32_api {
BOOLEAN (WINAPI *pShouldAppsUseDarkMode)(void);
DWORD (WINAPI *pSetPreferredAppMode)(DWORD mode);
};
struct vo_w32_state {
struct mp_log *log;
struct vo *vo;
struct mp_vo_opts *opts;
struct m_config_cache *opts_cache;
struct input_ctx *input_ctx;
mp_thread thread;
bool terminate;
struct mp_dispatch_queue *dispatch; // used to run stuff on the GUI thread
bool in_dispatch;
struct w32_api api; // stores functions from dynamically loaded DLLs
HWND window;
HWND parent; // 0 normally, set in embedding mode
HHOOK parent_win_hook;
HWINEVENTHOOK parent_evt_hook;
struct menu_ctx *menu_ctx;
HMONITOR monitor; // Handle of the current screen
char *color_profile; // Path of the current screen's color profile
// Has the window seen a WM_DESTROY? If so, don't call DestroyWindow again.
bool destroyed;
bool focused;
// whether the window position and size were initialized
bool window_bounds_initialized;
bool current_fs;
bool toggle_fs; // whether the current fullscreen state needs to be switched
// Note: maximized state doesn't involve nor modify windowrc
RECT windowrc; // currently known normal/fullscreen window client rect
RECT prev_windowrc; // saved normal window client rect while in fullscreen
// video size
uint32_t o_dwidth;
uint32_t o_dheight;
int dpi;
double dpi_scale;
bool disable_screensaver;
bool cursor_visible;
atomic_uint event_flags;
BOOL tracking;
TRACKMOUSEEVENT track_event;
int mouse_x;
int mouse_y;
// Should SetCursor be called when handling VOCTRL_SET_CURSOR_VISIBILITY?
bool can_set_cursor;
// UTF-16 decoding state for WM_CHAR and VK_PACKET
int high_surrogate;
// Fit the window to one monitor working area next time it's not fullscreen
// and not maximized. Used once after every new "untrusted" size comes from
// mpv, else we assume that the last known size is valid and don't fit.
// FIXME: on a multi-monitor setup one bit is not enough, because the first
// fit (autofit etc) should be to one monitor, but later size changes from
// mpv like window-scale (VOCTRL_SET_UNFS_WINDOW_SIZE) should allow the
// entire virtual desktop area - but we still limit to one monitor size.
bool fit_on_screen;
bool win_force_pos;
ITaskbarList2 *taskbar_list;
ITaskbarList3 *taskbar_list3;
UINT tbtn_created_msg;
bool tbtn_created;
struct voctrl_playback_state current_pstate;
// updates on move/resize/displaychange
double display_fps;
bool moving;
union {
uint8_t snapped;
struct {
uint8_t snapped_left : 1;
uint8_t snapped_right : 1;
uint8_t snapped_top : 1;
uint8_t snapped_bottom : 1;
};
};
int snap_dx;
int snap_dy;
HANDLE avrt_handle;
bool cleared;
bool dragging;
bool start_dragging;
BOOL win_arranging;
bool conversion_mode_init;
bool unmaximize;
};
static inline int get_system_metrics(struct vo_w32_state *w32, int metric)
{
return GetSystemMetricsForDpi(metric, w32->dpi);
}
static void adjust_window_rect(struct vo_w32_state *w32, HWND hwnd, RECT *rc)
{
if (!w32->opts->border && !IsMaximized(w32->window))
return;
AdjustWindowRectExForDpi(rc, GetWindowLongPtrW(hwnd, GWL_STYLE), 0,
GetWindowLongPtrW(hwnd, GWL_EXSTYLE), w32->dpi);
}
static bool check_windows10_build(DWORD build)
{
OSVERSIONINFOEXW osvi = {
.dwOSVersionInfoSize = sizeof(osvi),
.dwMajorVersion = HIBYTE(_WIN32_WINNT_WIN10),
.dwMinorVersion = LOBYTE(_WIN32_WINNT_WIN10),
.dwBuildNumber = build,
};
DWORD type = VER_MAJORVERSION | VER_MINORVERSION | VER_BUILDNUMBER;
ULONGLONG mask = 0;
mask = VerSetConditionMask(mask, VER_MAJORVERSION, VER_GREATER_EQUAL);
mask = VerSetConditionMask(mask, VER_MINORVERSION, VER_GREATER_EQUAL);
mask = VerSetConditionMask(mask, VER_BUILDNUMBER, VER_GREATER_EQUAL);
return VerifyVersionInfoW(&osvi, type, mask);
}
// Get adjusted title bar height, only relevant for --title-bar=no
static int get_title_bar_height(struct vo_w32_state *w32)
{
assert(w32->opts->border ? !w32->opts->title_bar : IsMaximized(w32->window));
UINT visible_border = 0;
// Only available on Windows 11, check in case it's backported and breaks
// WM_NCCALCSIZE exception for Windows 10.
if (check_windows10_build(22000)) {
DwmGetWindowAttribute(w32->window, DWMWA_VISIBLE_FRAME_BORDER_THICKNESS,
&visible_border, sizeof(visible_border));
}
int top_bar = IsMaximized(w32->window)
? get_system_metrics(w32, SM_CYFRAME) +
get_system_metrics(w32, SM_CXPADDEDBORDER)
: visible_border;
return top_bar;
}
static void add_window_borders(struct vo_w32_state *w32, HWND hwnd, RECT *rc)
{
RECT win = *rc;
adjust_window_rect(w32, hwnd, rc);
// Adjust for title bar height that will be hidden in WM_NCCALCSIZE
// Keep the frame border. On Windows 10 the top border is not retained.
// It appears that DWM draws the title bar with its full height, extending
// outside the window area. Essentially, there is a bug in DWM, preventing
// the adjustment of the title bar height. This issue occurs when both the
// top and left client areas are non-zero in WM_NCCALCSIZE. If the left NC
// area is set to 0, the title bar is drawn correctly with the adjusted
// height. To mitigate this problem, set the top NC area to zero. The issue
// doesn't happen on Windows 11 or when DWM NC drawing is disabled with
// DWMWA_NCRENDERING_POLICY. We aim to avoid the manual drawing the border
// and want the DWM look and feel, so skip the top border on Windows 10.
// Also DWMWA_VISIBLE_FRAME_BORDER_THICKNESS is available only on Windows 11,
// so it would be hard to guess this size correctly on Windows 10 anyway.
if (w32->opts->border && !w32->opts->title_bar && !w32->current_fs &&
(GetWindowLongPtrW(w32->window, GWL_STYLE) & WS_CAPTION))
{
if (!check_windows10_build(22000) && !IsMaximized(w32->window))
*rc = win;
rc->top = win.top - get_title_bar_height(w32);
}
}
// basically a reverse AdjustWindowRect (win32 doesn't appear to have this)
static void subtract_window_borders(struct vo_w32_state *w32, HWND hwnd, RECT *rc)
{
RECT b = { 0, 0, 0, 0 };
add_window_borders(w32, hwnd, &b);
rc->left -= b.left;
rc->top -= b.top;
rc->right -= b.right;
rc->bottom -= b.bottom;
}
static LRESULT borderless_nchittest(struct vo_w32_state *w32, int x, int y)
{
if (IsMaximized(w32->window))
return HTCLIENT;
RECT rc;
if (!GetWindowRect(w32->window, &rc))
return HTNOWHERE;
POINT frame = {get_system_metrics(w32, SM_CXSIZEFRAME),
get_system_metrics(w32, SM_CYSIZEFRAME)};
if (w32->opts->border) {
frame.x += get_system_metrics(w32, SM_CXPADDEDBORDER);
frame.y += get_system_metrics(w32, SM_CXPADDEDBORDER);
if (!w32->opts->title_bar)
rc.top -= get_system_metrics(w32, SM_CXPADDEDBORDER);
}
InflateRect(&rc, -frame.x, -frame.y);
// Hit-test top border
if (y < rc.top) {
if (x < rc.left)
return HTTOPLEFT;
if (x > rc.right)
return HTTOPRIGHT;
return HTTOP;
}
// Hit-test bottom border
if (y > rc.bottom) {
if (x < rc.left)
return HTBOTTOMLEFT;
if (x > rc.right)
return HTBOTTOMRIGHT;
return HTBOTTOM;
}
// Hit-test side borders
if (x < rc.left)
return HTLEFT;
if (x > rc.right)
return HTRIGHT;
return HTCLIENT;
}
// turn a WMSZ_* input value in v into the border that should be resized
// take into consideration which borders are snapped to avoid detaching
// returns: 0=left, 1=top, 2=right, 3=bottom, -1=undefined
static int get_resize_border(struct vo_w32_state *w32, int v)
{
switch (v) {
case WMSZ_LEFT:
case WMSZ_RIGHT:
return w32->snapped_bottom ? 1 : 3;
case WMSZ_TOP:
case WMSZ_BOTTOM:
return w32->snapped_right ? 0 : 2;
case WMSZ_TOPLEFT: return 1;
case WMSZ_TOPRIGHT: return 1;
case WMSZ_BOTTOMLEFT: return 3;
case WMSZ_BOTTOMRIGHT: return 3;
default: return -1;
}
}
static bool key_state(int vk)
{
return GetKeyState(vk) & 0x8000;
}
static int mod_state(struct vo_w32_state *w32)
{
int res = 0;
// AltGr is represented as LCONTROL+RMENU on Windows
bool alt_gr = mp_input_use_alt_gr(w32->input_ctx) &&
key_state(VK_RMENU) && key_state(VK_LCONTROL);
if (key_state(VK_RCONTROL) || (key_state(VK_LCONTROL) && !alt_gr))
res |= MP_KEY_MODIFIER_CTRL;
if (key_state(VK_SHIFT))
res |= MP_KEY_MODIFIER_SHIFT;
if (key_state(VK_LMENU) || (key_state(VK_RMENU) && !alt_gr))
res |= MP_KEY_MODIFIER_ALT;
return res;
}
static int decode_surrogate_pair(wchar_t lead, wchar_t trail)
{
return 0x10000 + (((lead & 0x3ff) << 10) | (trail & 0x3ff));
}
static int decode_utf16(struct vo_w32_state *w32, wchar_t c)
{
// Decode UTF-16, keeping state in w32->high_surrogate
if (IS_HIGH_SURROGATE(c)) {
w32->high_surrogate = c;
return 0;
}
if (IS_LOW_SURROGATE(c)) {
if (!w32->high_surrogate) {
MP_ERR(w32, "Invalid UTF-16 input\n");
return 0;
}
int codepoint = decode_surrogate_pair(w32->high_surrogate, c);
w32->high_surrogate = 0;
return codepoint;
}
if (w32->high_surrogate != 0) {
w32->high_surrogate = 0;
MP_ERR(w32, "Invalid UTF-16 input\n");
return 0;
}
return c;
}
static void clear_keyboard_buffer(void)
{
static const UINT vkey = VK_DECIMAL;
static const BYTE keys[256] = { 0 };
UINT scancode = MapVirtualKey(vkey, MAPVK_VK_TO_VSC);
wchar_t buf[10];
int ret = 0;
// Use the method suggested by Michael Kaplan to clear any pending dead
// keys from the current keyboard layout. See:
// <https://web.archive.org/web/20101004154432/http://blogs.msdn.com/b/michkap/archive/2006/04/06/569632.aspx>
// <https://web.archive.org/web/20100820152419/http://blogs.msdn.com/b/michkap/archive/2007/10/27/5717859.aspx>
do {
ret = ToUnicode(vkey, scancode, keys, buf, MP_ARRAY_SIZE(buf), 0);
} while (ret < 0);
}
static int to_unicode(UINT vkey, UINT scancode, const BYTE keys[256])
{
// This wraps ToUnicode to be stateless and to return only one character
// Make the buffer 10 code units long to be safe, same as here:
// <https://web.archive.org/web/20101013215215/http://blogs.msdn.com/b/michkap/archive/2006/03/24/559169.aspx>
wchar_t buf[10] = { 0 };
// Dead keys aren't useful for key shortcuts, so clear the keyboard state
clear_keyboard_buffer();
int len = ToUnicode(vkey, scancode, keys, buf, MP_ARRAY_SIZE(buf), 0);
// Return the last complete UTF-16 code point. A negative return value
// indicates a dead key, however there should still be a non-combining
// version of the key in the buffer.
if (len < 0)
len = -len;
if (len >= 2 && IS_SURROGATE_PAIR(buf[len - 2], buf[len - 1]))
return decode_surrogate_pair(buf[len - 2], buf[len - 1]);
if (len >= 1)
return buf[len - 1];
return 0;
}
static int decode_key(struct vo_w32_state *w32, UINT vkey, UINT scancode)
{
BYTE keys[256];
GetKeyboardState(keys);
// If mp_input_use_alt_gr is false, detect and remove AltGr so normal
// characters are generated. Note that AltGr is represented as
// LCONTROL+RMENU on Windows.
if ((keys[VK_RMENU] & 0x80) && (keys[VK_LCONTROL] & 0x80) &&
!mp_input_use_alt_gr(w32->input_ctx))
{
keys[VK_RMENU] = keys[VK_LCONTROL] = 0;
keys[VK_MENU] = keys[VK_LMENU];
keys[VK_CONTROL] = keys[VK_RCONTROL];
}
int c = to_unicode(vkey, scancode, keys);
// Some shift states prevent ToUnicode from working or cause it to produce
// control characters. If this is detected, remove modifiers until it
// starts producing normal characters.
if (c < 0x20 && (keys[VK_MENU] & 0x80)) {
keys[VK_LMENU] = keys[VK_RMENU] = keys[VK_MENU] = 0;
c = to_unicode(vkey, scancode, keys);
}
if (c < 0x20 && (keys[VK_CONTROL] & 0x80)) {
keys[VK_LCONTROL] = keys[VK_RCONTROL] = keys[VK_CONTROL] = 0;
c = to_unicode(vkey, scancode, keys);
}
if (c < 0x20)
return 0;
// Decode lone UTF-16 surrogates (VK_PACKET can generate these)
if (c < 0x10000)
return decode_utf16(w32, c);
return c;
}
static bool handle_appcommand(struct vo_w32_state *w32, UINT cmd)
{
if (!mp_input_use_media_keys(w32->input_ctx))
return false;
int mpkey = mp_w32_appcmd_to_mpkey(cmd);
if (!mpkey)
return false;
mp_input_put_key(w32->input_ctx, mpkey | mod_state(w32));
return true;
}
static void handle_key_down(struct vo_w32_state *w32, UINT vkey, UINT scancode)
{
int mpkey = mp_w32_vkey_to_mpkey(vkey, scancode & KF_EXTENDED);
if (!mpkey) {
mpkey = decode_key(w32, vkey, scancode & (0xff | KF_EXTENDED));
if (!mpkey)
return;
}
int state = w32->opts->native_keyrepeat ? 0 : MP_KEY_STATE_DOWN;
mp_input_put_key(w32->input_ctx, mpkey | mod_state(w32) | state);
}
static void handle_key_up(struct vo_w32_state *w32, UINT vkey, UINT scancode)
{
switch (vkey) {
case VK_MENU:
case VK_CONTROL:
case VK_SHIFT:
break;
default:
// Releasing all keys on key-up is simpler and ensures no keys can be
// get "stuck." This matches the behaviour of other VOs.
mp_input_put_key(w32->input_ctx, MP_INPUT_RELEASE_ALL);
}
}
static bool handle_char(struct vo_w32_state *w32, WPARAM wc, bool decode)
{
int c = decode ? decode_utf16(w32, wc) : wc;
if (c == 0)
return true;
if (c < 0x20)
return false;
mp_input_put_key(w32->input_ctx, c | mod_state(w32));
return true;
}
static void begin_dragging(struct vo_w32_state *w32)
{
if (w32->current_fs ||
mp_input_test_dragging(w32->input_ctx, w32->mouse_x, w32->mouse_y))
return;
// Window dragging hack
ReleaseCapture();
// The dragging model loop is entered at SendMessage() here.
// Unfortunately, the w32->current_fs value is stale because the
// input is handled in a different thread, and we cannot wait for
// an up-to-date value before entering the model loop if dragging
// needs to be kept resonsive.
// Workaround this by intercepting the loop in the WM_MOVING message,
// where the up-to-date value is available.
SystemParametersInfoW(SPI_GETWINARRANGING, 0, &w32->win_arranging, 0);
w32->dragging = true;
SendMessage(w32->window, WM_NCLBUTTONDOWN, HTCAPTION, 0);
w32->dragging = false;
SystemParametersInfoW(SPI_SETWINARRANGING, w32->win_arranging, 0, 0);
mp_input_put_key(w32->input_ctx, MP_INPUT_RELEASE_ALL);
}
// If native touch is enabled and the mouse event is emulated, ignore it.
// See: <https://learn.microsoft.com/en-us/windows/win32/tablet/
// system-events-and-mouse-messages#distinguishing-pen-input-from-mouse-and-touch>
static bool should_ignore_mouse_event(const struct vo_w32_state *w32)
{
return w32->opts->native_touch && ((GetMessageExtraInfo() & 0xFFFFFF00) == 0xFF515700);
}
static void handle_mouse_down(struct vo_w32_state *w32, int btn, int x, int y)
{
if (should_ignore_mouse_event(w32))
return;
btn |= mod_state(w32);
mp_input_put_key(w32->input_ctx, btn | MP_KEY_STATE_DOWN);
SetCapture(w32->window);
}
static void handle_mouse_up(struct vo_w32_state *w32, int btn)
{
if (should_ignore_mouse_event(w32))
return;
btn |= mod_state(w32);
mp_input_put_key(w32->input_ctx, btn | MP_KEY_STATE_UP);
ReleaseCapture();
}
static void handle_mouse_wheel(struct vo_w32_state *w32, bool horiz, int val)
{
int code;
if (horiz)
code = val > 0 ? MP_WHEEL_RIGHT : MP_WHEEL_LEFT;
else
code = val > 0 ? MP_WHEEL_UP : MP_WHEEL_DOWN;
mp_input_put_wheel(w32->input_ctx, code | mod_state(w32), abs(val) / 120.);
}
static void signal_events(struct vo_w32_state *w32, int events)
{
atomic_fetch_or(&w32->event_flags, events);
vo_wakeup(w32->vo);
}
static void wakeup_gui_thread(void *ctx)
{
struct vo_w32_state *w32 = ctx;
// Wake up the window procedure (which processes the dispatch queue)
if (GetWindowThreadProcessId(w32->window, NULL) == GetCurrentThreadId()) {
PostMessageW(w32->window, WM_NULL, 0, 0);
} else {
// Use a sent message when cross-thread, since the queue of sent
// messages is processed in some cases when posted messages are blocked
SendNotifyMessageW(w32->window, WM_NULL, 0, 0);
}
}
static double get_refresh_rate_from_gdi(const wchar_t *device)
{
DEVMODEW dm = { .dmSize = sizeof dm };
if (!EnumDisplaySettingsW(device, ENUM_CURRENT_SETTINGS, &dm))
return 0.0;
// May return 0 or 1 which "represent the display hardware's default refresh rate"
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd183565%28v=vs.85%29.aspx
// mpv validates this value with a threshold of 1, so don't return exactly 1
if (dm.dmDisplayFrequency == 1)
return 0.0;
// dm.dmDisplayFrequency is an integer which is rounded down, so it's
// highly likely that 23 represents 24/1.001, 59 represents 60/1.001, etc.
// A caller can always reproduce the original value by using floor.
double rv = dm.dmDisplayFrequency;
switch (dm.dmDisplayFrequency) {
case 23:
case 29:
case 47:
case 59:
case 71:
case 89:
case 95:
case 119:
case 143:
case 164:
case 239:
case 359:
case 479:
rv = (rv + 1) / 1.001;
}
return rv;
}
static char *get_color_profile(void *ctx, const wchar_t *device)
{
char *name = NULL;
wchar_t *wname = NULL;
HDC ic = CreateICW(device, NULL, NULL, NULL);
if (!ic)
goto done;
wname = talloc_array(NULL, wchar_t, MP_PATH_MAX);
if (!GetICMProfileW(ic, &(DWORD){ MP_PATH_MAX - 1 }, wname))
goto done;
name = mp_to_utf8(ctx, wname);
done:
if (ic)
DeleteDC(ic);
talloc_free(wname);
return name;
}
static void update_dpi(struct vo_w32_state *w32)
{
UINT dpiX, dpiY;
HDC hdc = NULL;
int dpi = 0;
if (GetDpiForMonitor(w32->monitor, MDT_EFFECTIVE_DPI, &dpiX, &dpiY) == S_OK) {
dpi = (int)dpiX;
MP_VERBOSE(w32, "DPI detected from the new API: %d\n", dpi);
} else if ((hdc = GetDC(NULL))) {
dpi = GetDeviceCaps(hdc, LOGPIXELSX);
ReleaseDC(NULL, hdc);
MP_VERBOSE(w32, "DPI detected from the old API: %d\n", dpi);
}
if (dpi <= 0) {
dpi = 96;
MP_VERBOSE(w32, "Couldn't determine DPI, falling back to %d\n", dpi);
}
w32->dpi = dpi;
w32->dpi_scale = w32->dpi / 96.0;
signal_events(w32, VO_EVENT_DPI);
}
static void update_display_info(struct vo_w32_state *w32)
{
HMONITOR monitor = MonitorFromWindow(w32->window, MONITOR_DEFAULTTOPRIMARY);
if (w32->monitor == monitor)
return;
w32->monitor = monitor;
update_dpi(w32);
MONITORINFOEXW mi = { .cbSize = sizeof mi };
GetMonitorInfoW(monitor, (MONITORINFO*)&mi);
// Try to get the monitor refresh rate.
double freq = 0.0;
if (freq == 0.0)
freq = mp_w32_displayconfig_get_refresh_rate(mi.szDevice);
if (freq == 0.0)
freq = get_refresh_rate_from_gdi(mi.szDevice);
if (freq != w32->display_fps) {
MP_VERBOSE(w32, "display-fps: %f\n", freq);
if (freq == 0.0)
MP_WARN(w32, "Couldn't determine monitor refresh rate\n");
w32->display_fps = freq;
signal_events(w32, VO_EVENT_WIN_STATE);
}
char *color_profile = get_color_profile(w32, mi.szDevice);
if ((color_profile == NULL) != (w32->color_profile == NULL) ||
(color_profile && strcmp(color_profile, w32->color_profile)))
{
if (color_profile)
MP_VERBOSE(w32, "color-profile: %s\n", color_profile);
talloc_free(w32->color_profile);
w32->color_profile = color_profile;
color_profile = NULL;
signal_events(w32, VO_EVENT_ICC_PROFILE_CHANGED);
}
talloc_free(color_profile);
}
static void force_update_display_info(struct vo_w32_state *w32)
{
w32->monitor = 0;
update_display_info(w32);
}
static void update_playback_state(struct vo_w32_state *w32)
{
struct voctrl_playback_state *pstate = &w32->current_pstate;
if (!w32->taskbar_list3 || !w32->tbtn_created)
return;
if (!pstate->playing || !pstate->taskbar_progress) {
ITaskbarList3_SetProgressState(w32->taskbar_list3, w32->window,
TBPF_NOPROGRESS);
return;
}
ULONGLONG completed = pstate->position;
ULONGLONG total = UINT8_MAX;
if (!pstate->position) {
completed = 1;
total = MAXULONGLONG;
}
ITaskbarList3_SetProgressValue(w32->taskbar_list3, w32->window,
completed, total);
ITaskbarList3_SetProgressState(w32->taskbar_list3, w32->window,
pstate->paused ? TBPF_PAUSED :
TBPF_NORMAL);
}
struct get_monitor_data {
int i;
int target;
HMONITOR mon;
};
static BOOL CALLBACK get_monitor_proc(HMONITOR mon, HDC dc, LPRECT r, LPARAM p)
{
struct get_monitor_data *data = (struct get_monitor_data*)p;
if (data->i == data->target) {
data->mon = mon;
return FALSE;
}
data->i++;
return TRUE;
}
static HMONITOR get_monitor(int id)
{
struct get_monitor_data data = { .target = id };
EnumDisplayMonitors(NULL, NULL, get_monitor_proc, (LPARAM)&data);
return data.mon;
}
static HMONITOR get_default_monitor(struct vo_w32_state *w32)
{
const int id = w32->current_fs ? w32->opts->fsscreen_id :
w32->opts->screen_id;
// Handle --fs-screen=<all|default> and --screen=default
if (id < 0) {
if (w32->win_force_pos && !w32->current_fs) {
// Get window from forced position
return MonitorFromRect(&w32->windowrc, MONITOR_DEFAULTTOPRIMARY);
} else {
// Let compositor decide
return MonitorFromWindow(w32->window, MONITOR_DEFAULTTOPRIMARY);
}
}
HMONITOR mon = get_monitor(id);
if (mon)
return mon;
MP_VERBOSE(w32, "Screen %d does not exist, falling back to primary\n", id);
return MonitorFromPoint((POINT){0, 0}, MONITOR_DEFAULTTOPRIMARY);
}
static MONITORINFO get_monitor_info(struct vo_w32_state *w32)
{
HMONITOR mon;
if (IsWindowVisible(w32->window) && !w32->current_fs) {
mon = MonitorFromWindow(w32->window, MONITOR_DEFAULTTOPRIMARY);
} else {
// The window is not visible during initialization, so get the
// monitor by --screen or --fs-screen id, or fallback to primary.
mon = get_default_monitor(w32);
}
MONITORINFO mi = { .cbSize = sizeof(mi) };
GetMonitorInfoW(mon, &mi);
return mi;
}
static RECT get_screen_area(struct vo_w32_state *w32)
{
// Handle --fs-screen=all
if (w32->current_fs && w32->opts->fsscreen_id == -2) {
const int x = get_system_metrics(w32, SM_XVIRTUALSCREEN);
const int y = get_system_metrics(w32, SM_YVIRTUALSCREEN);
return (RECT) { x, y, x + get_system_metrics(w32, SM_CXVIRTUALSCREEN),
y + get_system_metrics(w32, SM_CYVIRTUALSCREEN) };
}
return get_monitor_info(w32).rcMonitor;
}
static RECT get_working_area(struct vo_w32_state *w32)
{
return w32->current_fs ? get_screen_area(w32) :
get_monitor_info(w32).rcWork;
}
// Adjust working area boundaries to compensate for invisible borders.
static void adjust_working_area_for_extended_frame(RECT *wa_rect, RECT *wnd_rect, HWND wnd)
{
RECT frame = {0};
if (DwmGetWindowAttribute(wnd, DWMWA_EXTENDED_FRAME_BOUNDS,
&frame, sizeof(RECT)) == S_OK) {
wa_rect->left -= frame.left - wnd_rect->left;
wa_rect->top -= frame.top - wnd_rect->top;
wa_rect->right += wnd_rect->right - frame.right;
wa_rect->bottom += wnd_rect->bottom - frame.bottom;
}
}
static bool snap_to_screen_edges(struct vo_w32_state *w32, RECT *rc)
{
if (w32->parent || w32->current_fs || IsMaximized(w32->window))
return false;
if (!w32->opts->snap_window) {
w32->snapped = 0;
return false;
}
RECT rect;
POINT cursor;
if (!GetWindowRect(w32->window, &rect) || !GetCursorPos(&cursor))
return false;
// Check if window is going to be aero-snapped
if (rect_w(*rc) != rect_w(rect) || rect_h(*rc) != rect_h(rect))
return false;
// Check if window has already been aero-snapped
WINDOWPLACEMENT wp = {0};
wp.length = sizeof(wp);
if (!GetWindowPlacement(w32->window, &wp))
return false;
RECT wr = wp.rcNormalPosition;
if (rect_w(*rc) != rect_w(wr) || rect_h(*rc) != rect_h(wr))
return false;
// Get the work area to let the window snap to taskbar
wr = get_working_area(w32);
adjust_working_area_for_extended_frame(&wr, &rect, w32->window);
// Let the window to unsnap by changing its position,
// otherwise it will stick to the screen edges forever
rect = *rc;
if (w32->snapped) {
OffsetRect(&rect, cursor.x - rect.left - w32->snap_dx,
cursor.y - rect.top - w32->snap_dy);
}
int threshold = (w32->dpi * 16) / 96;
bool was_snapped = !!w32->snapped;
w32->snapped = 0;
// Adjust X position
// snapped_left & snapped_right are mutually exclusive
if (abs(rect.left - wr.left) < threshold) {
w32->snapped_left = 1;
OffsetRect(&rect, wr.left - rect.left, 0);
} else if (abs(rect.right - wr.right) < threshold) {
w32->snapped_right = 1;
OffsetRect(&rect, wr.right - rect.right, 0);
}
// Adjust Y position
// snapped_top & snapped_bottom are mutually exclusive
if (abs(rect.top - wr.top) < threshold) {
w32->snapped_top = 1;
OffsetRect(&rect, 0, wr.top - rect.top);
} else if (abs(rect.bottom - wr.bottom) < threshold) {
w32->snapped_bottom = 1;
OffsetRect(&rect, 0, wr.bottom - rect.bottom);
}
if (!was_snapped && w32->snapped != 0) {
w32->snap_dx = cursor.x - rc->left;
w32->snap_dy = cursor.y - rc->top;
}
*rc = rect;
return true;
}
static bool is_high_contrast(void)
{
HIGHCONTRAST hc = {sizeof(hc)};
SystemParametersInfo(SPI_GETHIGHCONTRAST, sizeof(hc), &hc, 0);
return hc.dwFlags & HCF_HIGHCONTRASTON;
}
static DWORD update_style(struct vo_w32_state *w32, DWORD style)
{
const DWORD NO_FRAME = WS_OVERLAPPED | WS_MINIMIZEBOX | WS_THICKFRAME;
const DWORD FRAME = WS_OVERLAPPEDWINDOW;
const DWORD FULLSCREEN = NO_FRAME & ~WS_THICKFRAME;
style &= ~(NO_FRAME | FRAME | FULLSCREEN);
style |= WS_SYSMENU;
if (w32->current_fs) {
style |= FULLSCREEN;
} else {
style |= (w32->opts->border || w32->opts->window_maximized) ? FRAME : NO_FRAME;
if (!w32->opts->title_bar && is_high_contrast())
style &= ~WS_CAPTION;
}
return style;
}
static DWORD update_exstyle(struct vo_w32_state *w32, DWORD exstyle)
{
exstyle &= ~(WS_EX_TOOLWINDOW);
if (!w32->opts->show_in_taskbar)
exstyle |= WS_EX_TOOLWINDOW;
return exstyle;
}
static void update_window_style(struct vo_w32_state *w32)
{
if (w32->parent)
return;
// SetWindowLongPtr can trigger a WM_SIZE event, so window rect
// has to be saved now and restored after setting the new style.
const RECT wr = w32->windowrc;
const DWORD style = GetWindowLongPtrW(w32->window, GWL_STYLE);
const DWORD exstyle = GetWindowLongPtrW(w32->window, GWL_EXSTYLE);
SetWindowLongPtrW(w32->window, GWL_STYLE, update_style(w32, style));
SetWindowLongPtrW(w32->window, GWL_EXSTYLE, update_exstyle(w32, exstyle));
w32->windowrc = wr;
}
// Resize window rect to width = w and height = h. If window is snapped,
// don't let it detach from snapped borders. Otherwise resize around the center.
static void resize_and_move_rect(struct vo_w32_state *w32, RECT *rc, int w, int h)
{
int x, y;
if (w32->snapped_left)
x = rc->left;
else if (w32->snapped_right)
x = rc->right - w;
else
x = rc->left + rect_w(*rc) / 2 - w / 2;
if (w32->snapped_top)
y = rc->top;
else if (w32->snapped_bottom)
y = rc->bottom - h;
else
y = rc->top + rect_h(*rc) / 2 - h / 2;
SetRect(rc, x, y, x + w, y + h);
}