1 /*************************************************************************/
2 /* os_windows.cpp */
3 /*************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /*************************************************************************/
8 /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
9 /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /*************************************************************************/
30 #include "drivers/gles2/rasterizer_gles2.h"
31
32 #include "drivers/unix/memory_pool_static_malloc.h"
33 #include "drivers/windows/dir_access_windows.h"
34 #include "drivers/windows/file_access_windows.h"
35 #include "drivers/windows/mutex_windows.h"
36 #include "drivers/windows/semaphore_windows.h"
37 #include "drivers/windows/thread_windows.h"
38 #include "main/main.h"
39 #include "os/memory_pool_dynamic_static.h"
40 #include "os_windows.h"
41
42 #include "scene/resources/texture.h"
43 #include "servers/audio/audio_server_sw.h"
44 #include "servers/visual/visual_server_raster.h"
45 #include "servers/visual/visual_server_wrap_mt.h"
46
47 #include "globals.h"
48 #include "io/marshalls.h"
49 #include "joystick.h"
50 #include "lang_table.h"
51 #include "os/memory_pool_dynamic_prealloc.h"
52 #include "packet_peer_udp_winsock.h"
53 #include "stream_peer_winsock.h"
54 #include "tcp_server_winsock.h"
55
56 #include "shlobj.h"
57 #include <process.h>
58 #include <regstr.h>
59
60 static const WORD MAX_CONSOLE_LINES = 1500;
61
62 extern "C" {
63 #ifdef _MSC_VER
64 _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
65 #else
66 __attribute__((visibility("default"))) DWORD NvOptimusEnablement = 0x00000001;
67 #endif
68 }
69
70 // Workaround mingw-w64 < 4.0 bug
71 #ifndef WM_TOUCH
72 #define WM_TOUCH 576
73 #endif
74
75 extern HINSTANCE godot_hinstance;
76
RedirectIOToConsole()77 void RedirectIOToConsole() {
78
79 int hConHandle;
80
81 intptr_t lStdHandle;
82
83 CONSOLE_SCREEN_BUFFER_INFO coninfo;
84
85 FILE *fp;
86
87 // allocate a console for this app
88
89 AllocConsole();
90
91 // set the screen buffer to be big enough to let us scroll text
92
93 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
94
95 &coninfo);
96
97 coninfo.dwSize.Y = MAX_CONSOLE_LINES;
98
99 SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
100
101 coninfo.dwSize);
102
103 // redirect unbuffered STDOUT to the console
104
105 lStdHandle = (intptr_t)GetStdHandle(STD_OUTPUT_HANDLE);
106
107 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
108
109 fp = _fdopen(hConHandle, "w");
110
111 *stdout = *fp;
112
113 setvbuf(stdout, NULL, _IONBF, 0);
114
115 // redirect unbuffered STDIN to the console
116
117 lStdHandle = (intptr_t)GetStdHandle(STD_INPUT_HANDLE);
118
119 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
120
121 fp = _fdopen(hConHandle, "r");
122
123 *stdin = *fp;
124
125 setvbuf(stdin, NULL, _IONBF, 0);
126
127 // redirect unbuffered STDERR to the console
128
129 lStdHandle = (intptr_t)GetStdHandle(STD_ERROR_HANDLE);
130
131 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
132
133 fp = _fdopen(hConHandle, "w");
134
135 *stderr = *fp;
136
137 setvbuf(stderr, NULL, _IONBF, 0);
138
139 // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
140
141 // point to console as well
142 }
143
get_video_driver_count() const144 int OS_Windows::get_video_driver_count() const {
145
146 return 1;
147 }
get_video_driver_name(int p_driver) const148 const char *OS_Windows::get_video_driver_name(int p_driver) const {
149
150 return "GLES2";
151 }
152
get_default_video_mode() const153 OS::VideoMode OS_Windows::get_default_video_mode() const {
154
155 return VideoMode(1024, 600, false);
156 }
157
get_audio_driver_count() const158 int OS_Windows::get_audio_driver_count() const {
159
160 return AudioDriverManagerSW::get_driver_count();
161 }
get_audio_driver_name(int p_driver) const162 const char *OS_Windows::get_audio_driver_name(int p_driver) const {
163
164 AudioDriverSW *driver = AudioDriverManagerSW::get_driver(p_driver);
165 ERR_FAIL_COND_V(!driver, "");
166 return AudioDriverManagerSW::get_driver(p_driver)->get_name();
167 }
168
169 static MemoryPoolStatic *mempool_static = NULL;
170 static MemoryPoolDynamic *mempool_dynamic = NULL;
171
initialize_core()172 void OS_Windows::initialize_core() {
173
174 crash_handler.initialize();
175
176 last_button_state = 0;
177
178 //RedirectIOToConsole();
179 maximized = false;
180 minimized = false;
181 borderless = false;
182
183 ThreadWindows::make_default();
184 SemaphoreWindows::make_default();
185 MutexWindows::make_default();
186
187 FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
188 FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
189 FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
190 //FileAccessBufferedFA<FileAccessWindows>::make_default();
191 DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
192 DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
193 DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);
194
195 TCPServerWinsock::make_default();
196 StreamPeerWinsock::make_default();
197 PacketPeerUDPWinsock::make_default();
198
199 mempool_static = new MemoryPoolStaticMalloc;
200 #if 1
201 mempool_dynamic = memnew(MemoryPoolDynamicStatic);
202 #else
203 #define DYNPOOL_SIZE 4 * 1024 * 1024
204 void *buffer = malloc(DYNPOOL_SIZE);
205 mempool_dynamic = memnew(MemoryPoolDynamicPrealloc(buffer, DYNPOOL_SIZE));
206
207 #endif
208
209 // We need to know how often the clock is updated
210 if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
211 ticks_per_second = 1000;
212 // If timeAtGameStart is 0 then we get the time since
213 // the start of the computer when we call GetGameTime()
214 ticks_start = 0;
215 ticks_start = get_ticks_usec();
216
217 process_map = memnew((Map<ProcessID, ProcessInfo>));
218
219 IP_Unix::make_default();
220
221 cursor_shape = CURSOR_ARROW;
222 }
223
can_draw() const224 bool OS_Windows::can_draw() const {
225
226 return !minimized;
227 };
228
229 #define MI_WP_SIGNATURE 0xFF515700
230 #define SIGNATURE_MASK 0xFFFFFF00
231 #define IsPenEvent(dw) (((dw)&SIGNATURE_MASK) == MI_WP_SIGNATURE)
232
_touch_event(bool p_pressed,int p_x,int p_y,int idx)233 void OS_Windows::_touch_event(bool p_pressed, int p_x, int p_y, int idx) {
234
235 #if WINVER >= 0x0601 // for windows 7
236 // Defensive
237 if (touch_state.has(idx) == p_pressed)
238 return;
239
240 if (p_pressed) {
241 touch_state.insert(idx, Point2i(p_x, p_y));
242 } else {
243 touch_state.erase(idx);
244 }
245 #endif
246
247 InputEvent event;
248 event.type = InputEvent::SCREEN_TOUCH;
249 event.ID = ++last_id;
250 event.screen_touch.index = idx;
251
252 event.screen_touch.pressed = p_pressed;
253
254 event.screen_touch.x = p_x;
255 event.screen_touch.y = p_y;
256
257 if (main_loop) {
258 input->parse_input_event(event);
259 }
260 };
261
_drag_event(int p_x,int p_y,int idx)262 void OS_Windows::_drag_event(int p_x, int p_y, int idx) {
263
264 #if WINVER >= 0x0601 // for windows 7
265 Map<int, Point2i>::Element *curr = touch_state.find(idx);
266 // Defensive
267 if (!curr)
268 return;
269
270 if (curr->get() == Point2i(p_x, p_y))
271 return;
272
273 curr->get() = Point2i(p_x, p_y);
274 #endif
275
276 InputEvent event;
277 event.type = InputEvent::SCREEN_DRAG;
278 event.ID = ++last_id;
279 event.screen_drag.index = idx;
280
281 event.screen_drag.x = p_x;
282 event.screen_drag.y = p_y;
283
284 if (main_loop)
285 input->parse_input_event(event);
286 };
287
WndProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam)288 LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
289
290 switch (uMsg) // Check For Windows Messages
291 {
292 case WM_ACTIVATE: // Watch For Window Activate Message
293 {
294 minimized = HIWORD(wParam) != 0;
295 if (!main_loop) {
296 return 0;
297 };
298 if (LOWORD(wParam) == WA_ACTIVE || LOWORD(wParam) == WA_CLICKACTIVE) {
299
300 main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
301 alt_mem = false;
302 control_mem = false;
303 shift_mem = false;
304 if (mouse_mode == MOUSE_MODE_CAPTURED) {
305 RECT clipRect;
306 GetClientRect(hWnd, &clipRect);
307 ClientToScreen(hWnd, (POINT *)&clipRect.left);
308 ClientToScreen(hWnd, (POINT *)&clipRect.right);
309 ClipCursor(&clipRect);
310 SetCapture(hWnd);
311 }
312 } else {
313 main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
314 alt_mem = false;
315 };
316
317 return 0; // Return To The Message Loop
318 }
319
320 case WM_KILLFOCUS: {
321
322 #if WINVER >= 0x0601 // for windows 7
323 // Release every touch to avoid sticky points
324 for (Map<int, Point2i>::Element *E = touch_state.front(); E; E = E->next()) {
325 _touch_event(false, E->get().x, E->get().y, E->key());
326 }
327 touch_state.clear();
328 #endif
329 } break;
330
331 case WM_PAINT:
332
333 Main::force_redraw();
334 break;
335
336 case WM_SYSCOMMAND: // Intercept System Commands
337 {
338 switch (wParam) // Check System Calls
339 {
340 case SC_SCREENSAVE: // Screensaver Trying To Start?
341 case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
342 return 0; // Prevent From Happening
343 case SC_KEYMENU:
344 if ((lParam >> 16) <= 0)
345 return 0;
346 }
347 break; // Exit
348 }
349
350 case WM_CLOSE: // Did We Receive A Close Message?
351 {
352 if (main_loop)
353 main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
354 //force_quit=true;
355 return 0; // Jump Back
356 }
357 case WM_MOUSELEAVE: {
358
359 old_invalid = true;
360 outside = true;
361 if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
362 main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
363
364 } break;
365 case WM_MOUSEMOVE: {
366
367 if (outside) {
368 //mouse enter
369
370 if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
371 main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
372
373 CursorShape c = cursor_shape;
374 cursor_shape = CURSOR_MAX;
375 set_cursor_shape(c);
376 outside = false;
377
378 //Once-Off notification, must call again....
379 TRACKMOUSEEVENT tme;
380 tme.cbSize = sizeof(TRACKMOUSEEVENT);
381 tme.dwFlags = TME_LEAVE;
382 tme.hwndTrack = hWnd;
383 tme.dwHoverTime = HOVER_DEFAULT;
384 TrackMouseEvent(&tme);
385 }
386
387 /*
388 LPARAM extra = GetMessageExtraInfo();
389 if (IsPenEvent(extra)) {
390
391 int idx = extra & 0x7f;
392 _drag_event(idx, uMsg, wParam, lParam);
393 if (idx != 0) {
394 return 0;
395 };
396 // fallthrough for mouse event
397 };
398 */
399
400 InputEvent event;
401 event.type = InputEvent::MOUSE_MOTION;
402 event.ID = ++last_id;
403 InputEventMouseMotion &mm = event.mouse_motion;
404
405 mm.mod.control = (wParam & MK_CONTROL) != 0;
406 mm.mod.shift = (wParam & MK_SHIFT) != 0;
407 mm.mod.alt = alt_mem;
408
409 mm.button_mask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0;
410 mm.button_mask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0;
411 mm.button_mask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0;
412 last_button_state = mm.button_mask;
413 /*mm.button_mask|=(wParam&MK_XBUTTON1)?(1<<5):0;
414 mm.button_mask|=(wParam&MK_XBUTTON2)?(1<<6):0;*/
415 mm.x = GET_X_LPARAM(lParam);
416 mm.y = GET_Y_LPARAM(lParam);
417
418 if (mouse_mode == MOUSE_MODE_CAPTURED) {
419
420 Point2i c(video_mode.width / 2, video_mode.height / 2);
421 old_x = c.x;
422 old_y = c.y;
423
424 if (Point2i(mm.x, mm.y) == c) {
425 center = c;
426 return 0;
427 }
428
429 Point2i ncenter(mm.x, mm.y);
430 center = ncenter;
431 POINT pos = { (int)c.x, (int)c.y };
432 ClientToScreen(hWnd, &pos);
433 SetCursorPos(pos.x, pos.y);
434 }
435
436 input->set_mouse_pos(Point2(mm.x, mm.y));
437 mm.global_x = mm.x;
438 mm.global_y = mm.y;
439 mm.speed_x = input->get_mouse_speed().x;
440 mm.speed_y = input->get_mouse_speed().y;
441
442 if (old_invalid) {
443
444 old_x = mm.x;
445 old_y = mm.y;
446 old_invalid = false;
447 }
448
449 mm.relative_x = mm.x - old_x;
450 mm.relative_y = mm.y - old_y;
451 old_x = mm.x;
452 old_y = mm.y;
453 if (main_loop)
454 input->parse_input_event(event);
455
456 } break;
457 case WM_LBUTTONDOWN:
458 case WM_LBUTTONUP:
459 case WM_MBUTTONDOWN:
460 case WM_MBUTTONUP:
461 case WM_RBUTTONDOWN:
462 case WM_RBUTTONUP:
463 case WM_MOUSEWHEEL:
464 case WM_MOUSEHWHEEL:
465 case WM_LBUTTONDBLCLK:
466 case WM_MBUTTONDBLCLK:
467 case WM_RBUTTONDBLCLK:
468 /*case WM_XBUTTONDOWN:
469 case WM_XBUTTONUP: */
470 {
471
472 /*
473 LPARAM extra = GetMessageExtraInfo();
474 if (IsPenEvent(extra)) {
475
476 int idx = extra & 0x7f;
477 _touch_event(idx, uMsg, wParam, lParam);
478 if (idx != 0) {
479 return 0;
480 };
481 // fallthrough for mouse event
482 };
483 */
484
485 InputEvent event;
486 event.type = InputEvent::MOUSE_BUTTON;
487 event.ID = ++last_id;
488 InputEventMouseButton &mb = event.mouse_button;
489
490 switch (uMsg) {
491 case WM_LBUTTONDOWN: {
492 mb.pressed = true;
493 mb.button_index = 1;
494 } break;
495 case WM_LBUTTONUP: {
496 mb.pressed = false;
497 mb.button_index = 1;
498 } break;
499 case WM_MBUTTONDOWN: {
500 mb.pressed = true;
501 mb.button_index = 3;
502
503 } break;
504 case WM_MBUTTONUP: {
505 mb.pressed = false;
506 mb.button_index = 3;
507 } break;
508 case WM_RBUTTONDOWN: {
509 mb.pressed = true;
510 mb.button_index = 2;
511 } break;
512 case WM_RBUTTONUP: {
513 mb.pressed = false;
514 mb.button_index = 2;
515 } break;
516 case WM_LBUTTONDBLCLK: {
517
518 mb.pressed = true;
519 mb.button_index = 1;
520 mb.doubleclick = true;
521 } break;
522 case WM_RBUTTONDBLCLK: {
523
524 mb.pressed = true;
525 mb.button_index = 2;
526 mb.doubleclick = true;
527 } break;
528 case WM_MBUTTONDBLCLK: {
529
530 mb.pressed = true;
531 mb.button_index = 3;
532 mb.doubleclick = true;
533 } break;
534 case WM_MOUSEWHEEL: {
535
536 mb.pressed = true;
537 int motion = (short)HIWORD(wParam);
538 if (!motion)
539 return 0;
540
541 if (motion > 0)
542 mb.button_index = BUTTON_WHEEL_UP;
543 else
544 mb.button_index = BUTTON_WHEEL_DOWN;
545
546 } break;
547 case WM_MOUSEHWHEEL: {
548
549 mb.pressed = true;
550 int motion = (short)HIWORD(wParam);
551 if (!motion)
552 return 0;
553
554 if (motion < 0) {
555 mb.button_index = BUTTON_WHEEL_LEFT;
556 mb.factor = fabs((double)motion / (double)WHEEL_DELTA);
557 } else {
558 mb.button_index = BUTTON_WHEEL_RIGHT;
559 mb.factor = fabs((double)motion / (double)WHEEL_DELTA);
560 }
561 } break;
562 /*
563 case WM_XBUTTONDOWN: {
564 mb.pressed=true;
565 mb.button_index=(HIWORD(wParam)==XBUTTON1)?6:7;
566 } break;
567 case WM_XBUTTONUP:
568 mb.pressed=true;
569 mb.button_index=(HIWORD(wParam)==XBUTTON1)?6:7;
570 } break;*/
571 default: { return 0; }
572 }
573
574 mb.mod.control = (wParam & MK_CONTROL) != 0;
575 mb.mod.shift = (wParam & MK_SHIFT) != 0;
576 mb.mod.alt = alt_mem;
577 //mb.mod.alt=(wParam&MK_MENU)!=0;
578 mb.button_mask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0;
579 mb.button_mask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0;
580 mb.button_mask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0;
581
582 last_button_state = mb.button_mask;
583 /*
584 mb.button_mask|=(wParam&MK_XBUTTON1)?(1<<5):0;
585 mb.button_mask|=(wParam&MK_XBUTTON2)?(1<<6):0;*/
586 mb.x = GET_X_LPARAM(lParam);
587 mb.y = GET_Y_LPARAM(lParam);
588
589 if (mouse_mode == MOUSE_MODE_CAPTURED) {
590
591 mb.x = old_x;
592 mb.y = old_y;
593 }
594
595 if (uMsg != WM_MOUSEWHEEL && uMsg != WM_MOUSEHWHEEL) {
596 if (mb.pressed) {
597
598 if (++pressrc > 0)
599 SetCapture(hWnd);
600 } else {
601
602 if (--pressrc <= 0) {
603 ReleaseCapture();
604 pressrc = 0;
605 }
606 }
607 } else if (mouse_mode != MOUSE_MODE_CAPTURED) {
608 // for reasons unknown to mankind, wheel comes in screen cordinates
609 POINT coords;
610 coords.x = mb.x;
611 coords.y = mb.y;
612
613 ScreenToClient(hWnd, &coords);
614
615 mb.x = coords.x;
616 mb.y = coords.y;
617 }
618
619 mb.global_x = mb.x;
620 mb.global_y = mb.y;
621
622 if (main_loop) {
623 input->parse_input_event(event);
624 if (mb.pressed && mb.button_index > 3) {
625 //send release for mouse wheel
626 mb.pressed = false;
627 event.ID = ++last_id;
628 input->parse_input_event(event);
629 }
630 }
631 }
632 break;
633
634 case WM_SIZE: {
635 int window_w = LOWORD(lParam);
636 int window_h = HIWORD(lParam);
637 if (window_w > 0 && window_h > 0) {
638 video_mode.width = window_w;
639 video_mode.height = window_h;
640 }
641 //return 0; // Jump Back
642 } break;
643
644 case WM_ENTERSIZEMOVE: {
645 move_timer_id = SetTimer(hWnd, 1, USER_TIMER_MINIMUM, (TIMERPROC)NULL);
646 } break;
647 case WM_EXITSIZEMOVE: {
648 KillTimer(hWnd, move_timer_id);
649 } break;
650 case WM_TIMER: {
651 if (wParam == move_timer_id) {
652 process_key_events();
653 Main::iteration();
654 }
655 } break;
656
657 case WM_SYSKEYDOWN:
658 case WM_SYSKEYUP:
659 case WM_KEYUP:
660 case WM_KEYDOWN: {
661
662 if (wParam == VK_SHIFT)
663 shift_mem = uMsg == WM_KEYDOWN;
664 if (wParam == VK_CONTROL)
665 control_mem = uMsg == WM_KEYDOWN;
666 if (wParam == VK_MENU) {
667 alt_mem = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN);
668 if (lParam & (1 << 24))
669 gr_mem = alt_mem;
670 }
671
672 //if (wParam==VK_WIN) TODO wtf is this?
673 // meta_mem=uMsg==WM_KEYDOWN;
674
675 } //fallthrough
676 case WM_CHAR: {
677
678 ERR_BREAK(key_event_pos >= KEY_EVENT_BUFFER_SIZE);
679
680 // Make sure we don't include modifiers for the modifier key itself.
681 KeyEvent ke;
682 ke.mod_state.shift = (wParam != VK_SHIFT) ? shift_mem : false;
683 ke.mod_state.alt = (!(wParam == VK_MENU && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN))) ? alt_mem : false;
684 ke.mod_state.control = (wParam != VK_CONTROL) ? control_mem : false;
685 ke.mod_state.meta = meta_mem;
686 ke.uMsg = uMsg;
687
688 if (ke.uMsg == WM_SYSKEYDOWN)
689 ke.uMsg = WM_KEYDOWN;
690 if (ke.uMsg == WM_SYSKEYUP)
691 ke.uMsg = WM_KEYUP;
692
693 /*if (ke.uMsg==WM_KEYDOWN && alt_mem && uMsg!=WM_SYSKEYDOWN) {
694 //altgr hack for intl keyboards, not sure how good it is
695 //windows is weeeeird
696 ke.mod_state.alt=false;
697 ke.mod_state.control=false;
698 print_line("")
699 }*/
700
701 ke.wParam = wParam;
702 ke.lParam = lParam;
703 key_event_buffer[key_event_pos++] = ke;
704
705 } break;
706 case WM_INPUTLANGCHANGEREQUEST: {
707
708 print_line("input lang change");
709 } break;
710
711 #if WINVER >= 0x0601 // for windows 7
712 case WM_TOUCH: {
713
714 BOOL bHandled = FALSE;
715 UINT cInputs = LOWORD(wParam);
716 PTOUCHINPUT pInputs = memnew_arr(TOUCHINPUT, cInputs);
717 if (pInputs) {
718 if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs, sizeof(TOUCHINPUT))) {
719 for (UINT i = 0; i < cInputs; i++) {
720 TOUCHINPUT ti = pInputs[i];
721 //do something with each touch input entry
722 if (ti.dwFlags & TOUCHEVENTF_MOVE) {
723
724 _drag_event(ti.x / 100, ti.y / 100, ti.dwID);
725 } else if (ti.dwFlags & (TOUCHEVENTF_UP | TOUCHEVENTF_DOWN)) {
726
727 _touch_event(ti.dwFlags & TOUCHEVENTF_DOWN, ti.x / 100, ti.y / 100, ti.dwID);
728 };
729 }
730 bHandled = TRUE;
731 } else {
732 /* handle the error here */
733 }
734 memdelete_arr(pInputs);
735 } else {
736 /* handle the error here, probably out of memory */
737 }
738 if (bHandled) {
739 CloseTouchInputHandle((HTOUCHINPUT)lParam);
740 return 0;
741 };
742
743 } break;
744
745 #endif
746 case WM_DEVICECHANGE: {
747
748 joystick->probe_joysticks();
749 } break;
750 case WM_SETCURSOR: {
751
752 if (LOWORD(lParam) == HTCLIENT) {
753 if (mouse_mode == MOUSE_MODE_HIDDEN || mouse_mode == MOUSE_MODE_CAPTURED) {
754 //Hide the cursor
755 if (hCursor == NULL)
756 hCursor = SetCursor(NULL);
757 else
758 SetCursor(NULL);
759 } else {
760 if (hCursor != NULL) {
761 CursorShape c = cursor_shape;
762 cursor_shape = CURSOR_MAX;
763 set_cursor_shape(c);
764 hCursor = NULL;
765 }
766 }
767 }
768
769 } break;
770 case WM_DROPFILES: {
771
772 HDROP hDropInfo = NULL;
773 hDropInfo = (HDROP)wParam;
774 const int buffsize = 4096;
775 wchar_t buf[buffsize];
776
777 int fcount = DragQueryFileW(hDropInfo, 0xFFFFFFFF, NULL, 0);
778
779 Vector<String> files;
780
781 for (int i = 0; i < fcount; i++) {
782
783 DragQueryFileW(hDropInfo, i, buf, buffsize);
784 String file = buf;
785 files.push_back(file);
786 }
787
788 if (files.size() && main_loop) {
789 main_loop->drop_files(files, 0);
790 }
791
792 } break;
793
794 default: {
795
796 if (user_proc) {
797
798 return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
799 };
800 };
801 }
802
803 return DefWindowProcW(hWnd, uMsg, wParam, lParam);
804 }
805
WndProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam)806 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
807
808 OS_Windows *os_win = static_cast<OS_Windows *>(OS::get_singleton());
809 if (os_win)
810 return os_win->WndProc(hWnd, uMsg, wParam, lParam);
811 else
812 return DefWindowProcW(hWnd, uMsg, wParam, lParam);
813 }
814
process_key_events()815 void OS_Windows::process_key_events() {
816
817 for (int i = 0; i < key_event_pos; i++) {
818
819 KeyEvent &ke = key_event_buffer[i];
820 switch (ke.uMsg) {
821
822 case WM_CHAR: {
823 if ((i == 0 && ke.uMsg == WM_CHAR) || (i > 0 && key_event_buffer[i - 1].uMsg == WM_CHAR)) {
824 InputEvent event;
825 event.type = InputEvent::KEY;
826 event.ID = ++last_id;
827 InputEventKey &k = event.key;
828
829 k.mod = ke.mod_state;
830 k.pressed = true;
831 k.scancode = KeyMappingWindows::get_keysym(ke.wParam);
832 k.unicode = ke.wParam;
833 if (k.unicode && gr_mem) {
834 k.mod.alt = false;
835 k.mod.control = false;
836 }
837
838 if (k.unicode < 32)
839 k.unicode = 0;
840
841 input->parse_input_event(event);
842 }
843
844 //do nothing
845 } break;
846 case WM_KEYUP:
847 case WM_KEYDOWN: {
848
849 InputEvent event;
850 event.type = InputEvent::KEY;
851 event.ID = ++last_id;
852 InputEventKey &k = event.key;
853
854 k.mod = ke.mod_state;
855 k.pressed = (ke.uMsg == WM_KEYDOWN);
856
857 if ((ke.lParam & (1 << 24)) && (ke.wParam == VK_RETURN)) {
858 // Special case for Numpad Enter key
859 k.scancode = KEY_ENTER;
860 } else {
861 k.scancode = KeyMappingWindows::get_keysym(ke.wParam);
862 }
863
864 if (i + 1 < key_event_pos && key_event_buffer[i + 1].uMsg == WM_CHAR)
865 k.unicode = key_event_buffer[i + 1].wParam;
866 if (k.unicode && gr_mem) {
867 k.mod.alt = false;
868 k.mod.control = false;
869 }
870
871 if (k.unicode < 32)
872 k.unicode = 0;
873
874 k.echo = (ke.uMsg == WM_KEYDOWN && (ke.lParam & (1 << 30)));
875
876 input->parse_input_event(event);
877
878 } break;
879 }
880 }
881
882 key_event_pos = 0;
883 }
884
885 enum _MonitorDpiType {
886 MDT_Effective_DPI = 0,
887 MDT_Angular_DPI = 1,
888 MDT_Raw_DPI = 2,
889 MDT_Default = MDT_Effective_DPI
890 };
891
QueryDpiForMonitor(HMONITOR hmon,_MonitorDpiType dpiType=MDT_Default)892 static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType = MDT_Default) {
893
894 int dpiX = 96, dpiY = 96;
895
896 static HMODULE Shcore = NULL;
897 typedef HRESULT(WINAPI * GetDPIForMonitor_t)(HMONITOR hmonitor, _MonitorDpiType dpiType, UINT * dpiX, UINT * dpiY);
898 static GetDPIForMonitor_t getDPIForMonitor = NULL;
899
900 if (Shcore == NULL) {
901 Shcore = LoadLibraryW(L"Shcore.dll");
902 getDPIForMonitor = Shcore ? (GetDPIForMonitor_t)GetProcAddress(Shcore, "GetDpiForMonitor") : NULL;
903
904 if ((Shcore == NULL) || (getDPIForMonitor == NULL)) {
905 if (Shcore)
906 FreeLibrary(Shcore);
907 Shcore = (HMODULE)INVALID_HANDLE_VALUE;
908 }
909 }
910
911 UINT x = 0, y = 0;
912 HRESULT hr = E_FAIL;
913 bool bSet = false;
914 if (hmon && (Shcore != (HMODULE)INVALID_HANDLE_VALUE)) {
915 hr = getDPIForMonitor(hmon, dpiType /*MDT_Effective_DPI*/, &x, &y);
916 if (SUCCEEDED(hr) && (x > 0) && (y > 0)) {
917
918 dpiX = (int)x;
919 dpiY = (int)y;
920 }
921 } else {
922 static int overallX = 0, overallY = 0;
923 if (overallX <= 0 || overallY <= 0) {
924 HDC hdc = GetDC(NULL);
925 if (hdc) {
926 overallX = GetDeviceCaps(hdc, LOGPIXELSX);
927 overallY = GetDeviceCaps(hdc, LOGPIXELSY);
928 ReleaseDC(NULL, hdc);
929 }
930 }
931 if (overallX > 0 && overallY > 0) {
932 dpiX = overallX;
933 dpiY = overallY;
934 }
935 }
936
937 return (dpiX + dpiY) / 2;
938 }
939
940 typedef enum _SHC_PROCESS_DPI_AWARENESS {
941 SHC_PROCESS_DPI_UNAWARE = 0,
942 SHC_PROCESS_SYSTEM_DPI_AWARE = 1,
943 SHC_PROCESS_PER_MONITOR_DPI_AWARE = 2
944 } SHC_PROCESS_DPI_AWARENESS;
945
946
initialize(const VideoMode & p_desired,int p_video_driver,int p_audio_driver)947 void OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
948
949 main_loop = NULL;
950 outside = true;
951
952 WNDCLASSEXW wc;
953
954 if (is_hidpi_allowed()) {
955 HMODULE Shcore = LoadLibraryW(L"Shcore.dll");;
956
957 if (Shcore != NULL) {
958 typedef HRESULT (WINAPI *SetProcessDpiAwareness_t)(SHC_PROCESS_DPI_AWARENESS);
959
960 SetProcessDpiAwareness_t SetProcessDpiAwareness = (SetProcessDpiAwareness_t)GetProcAddress(Shcore, "SetProcessDpiAwareness");
961
962 if (SetProcessDpiAwareness) {
963 SetProcessDpiAwareness(SHC_PROCESS_SYSTEM_DPI_AWARE);
964 }
965 }
966 }
967
968
969 video_mode = p_desired;
970 //printf("**************** desired %s, mode %s\n", p_desired.fullscreen?"true":"false", video_mode.fullscreen?"true":"false");
971 RECT WindowRect;
972
973 WindowRect.left = 0;
974 WindowRect.right = video_mode.width;
975 WindowRect.top = 0;
976 WindowRect.bottom = video_mode.height;
977
978 memset(&wc, 0, sizeof(WNDCLASSEXW));
979 wc.cbSize = sizeof(WNDCLASSEXW);
980 wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
981 wc.lpfnWndProc = (WNDPROC)::WndProc;
982 wc.cbClsExtra = 0;
983 wc.cbWndExtra = 0;
984 //wc.hInstance = hInstance;
985 wc.hInstance = godot_hinstance ? godot_hinstance : GetModuleHandle(NULL);
986 wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
987 wc.hCursor = NULL; //LoadCursor(NULL, IDC_ARROW);
988 wc.hbrBackground = NULL;
989 wc.lpszMenuName = NULL;
990 wc.lpszClassName = L"Engine";
991
992 if (!RegisterClassExW(&wc)) {
993 MessageBox(NULL, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
994 return; // Return
995 }
996
997 pre_fs_valid = true;
998 if (video_mode.fullscreen) {
999
1000 DEVMODE current;
1001 memset(¤t, 0, sizeof(current));
1002 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, ¤t);
1003
1004 WindowRect.right = current.dmPelsWidth;
1005 WindowRect.bottom = current.dmPelsHeight;
1006
1007 /* DEVMODE dmScreenSettings;
1008 memset(&dmScreenSettings,0,sizeof(dmScreenSettings));
1009 dmScreenSettings.dmSize=sizeof(dmScreenSettings);
1010 dmScreenSettings.dmPelsWidth = video_mode.width;
1011 dmScreenSettings.dmPelsHeight = video_mode.height;
1012 dmScreenSettings.dmBitsPerPel = current.dmBitsPerPel;
1013 dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
1014
1015 LONG err = ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN);
1016 if (err!=DISP_CHANGE_SUCCESSFUL) {
1017
1018 video_mode.fullscreen=false;
1019 }*/
1020 pre_fs_valid = false;
1021 }
1022
1023 DWORD dwExStyle;
1024 DWORD dwStyle;
1025
1026 if (video_mode.fullscreen || video_mode.borderless_window) {
1027
1028 dwExStyle = WS_EX_APPWINDOW;
1029 dwStyle = WS_POPUP;
1030
1031 } else {
1032 dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
1033 dwStyle = WS_OVERLAPPEDWINDOW;
1034 if (!video_mode.resizable) {
1035 dwStyle &= ~WS_THICKFRAME;
1036 dwStyle &= ~WS_MAXIMIZEBOX;
1037 }
1038 }
1039
1040 AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);
1041
1042 char *windowid = getenv("GODOT_WINDOWID");
1043 if (windowid) {
1044
1045 // strtoull on mingw
1046 #ifdef MINGW_ENABLED
1047 hWnd = (HWND)strtoull(windowid, NULL, 0);
1048 #else
1049 hWnd = (HWND)_strtoui64(windowid, NULL, 0);
1050 #endif
1051 SetLastError(0);
1052 user_proc = (WNDPROC)GetWindowLongPtr(hWnd, GWLP_WNDPROC);
1053 SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)(WNDPROC)::WndProc);
1054 DWORD le = GetLastError();
1055 if (user_proc == 0 && le != 0) {
1056
1057 printf("Error setting WNDPROC: %li\n", le);
1058 };
1059 LONG_PTR proc = GetWindowLongPtr(hWnd, GWLP_WNDPROC);
1060
1061 RECT rect;
1062 if (!GetClientRect(hWnd, &rect)) {
1063 MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
1064 return; // Return FALSE
1065 };
1066 video_mode.width = rect.right;
1067 video_mode.height = rect.bottom;
1068 video_mode.fullscreen = false;
1069 } else {
1070
1071 if (!(hWnd = CreateWindowExW(dwExStyle, L"Engine", L"", dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, (GetSystemMetrics(SM_CXSCREEN) - WindowRect.right) / 2, (GetSystemMetrics(SM_CYSCREEN) - WindowRect.bottom) / 2, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top, NULL, NULL, hInstance, NULL))) {
1072 MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
1073 return; // Return FALSE
1074 }
1075 };
1076
1077 if (video_mode.always_on_top) {
1078 SetWindowPos(hWnd, video_mode.always_on_top ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
1079 }
1080
1081 #if defined(OPENGL_ENABLED) || defined(GLES2_ENABLED) || defined(LEGACYGL_ENABLED)
1082 gl_context = memnew(ContextGL_Win(hWnd, false));
1083 gl_context->initialize();
1084 rasterizer = memnew(RasterizerGLES2);
1085 #else
1086 #ifdef DX9_ENABLED
1087 rasterizer = memnew(RasterizerDX9(hWnd));
1088 #endif
1089 #endif
1090
1091 visual_server = memnew(VisualServerRaster(rasterizer));
1092 if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
1093
1094 visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD));
1095 }
1096
1097 //
1098 physics_server = memnew(PhysicsServerSW);
1099 physics_server->init();
1100
1101 physics_2d_server = Physics2DServerWrapMT::init_server<Physics2DServerSW>();
1102 physics_2d_server->init();
1103
1104 if (!is_no_window_mode_enabled()) {
1105 ShowWindow(hWnd, SW_SHOW); // Show The Window
1106 SetForegroundWindow(hWnd); // Slightly Higher Priority
1107 SetFocus(hWnd); // Sets Keyboard Focus To
1108 }
1109
1110 /*
1111 DEVMODE dmScreenSettings; // Device Mode
1112 memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
1113 dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
1114 dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
1115 dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
1116 dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
1117 dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
1118 if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
1119
1120
1121
1122
1123 */
1124 visual_server->init();
1125
1126 input = memnew(InputDefault);
1127 joystick = memnew(joystick_windows(input, &hWnd));
1128
1129 AudioDriverManagerSW::get_driver(p_audio_driver)->set_singleton();
1130
1131 if (AudioDriverManagerSW::get_driver(p_audio_driver)->init() != OK) {
1132
1133 ERR_PRINT("Initializing audio failed.");
1134 }
1135
1136 sample_manager = memnew(SampleManagerMallocSW);
1137 audio_server = memnew(AudioServerSW(sample_manager));
1138
1139 audio_server->init();
1140
1141 spatial_sound_server = memnew(SpatialSoundServerSW);
1142 spatial_sound_server->init();
1143 spatial_sound_2d_server = memnew(SpatialSound2DServerSW);
1144 spatial_sound_2d_server->init();
1145
1146 TRACKMOUSEEVENT tme;
1147 tme.cbSize = sizeof(TRACKMOUSEEVENT);
1148 tme.dwFlags = TME_LEAVE;
1149 tme.hwndTrack = hWnd;
1150 tme.dwHoverTime = HOVER_DEFAULT;
1151 TrackMouseEvent(&tme);
1152
1153 #if WINVER >= 0x0601 // for windows 7
1154 RegisterTouchWindow(hWnd, 0); // Windows 7
1155 #endif
1156
1157 _ensure_data_dir();
1158
1159 DragAcceptFiles(hWnd, true);
1160
1161 move_timer_id = 1;
1162 }
1163
set_clipboard(const String & p_text)1164 void OS_Windows::set_clipboard(const String &p_text) {
1165
1166 if (!OpenClipboard(hWnd)) {
1167 ERR_EXPLAIN("Unable to open clipboard.");
1168 ERR_FAIL();
1169 };
1170 EmptyClipboard();
1171
1172 HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, (p_text.length() + 1) * sizeof(CharType));
1173 if (mem == NULL) {
1174 ERR_EXPLAIN("Unable to allocate memory for clipboard contents.");
1175 ERR_FAIL();
1176 };
1177 LPWSTR lptstrCopy = (LPWSTR)GlobalLock(mem);
1178 memcpy(lptstrCopy, p_text.c_str(), (p_text.length() + 1) * sizeof(CharType));
1179 //memset((lptstrCopy + p_text.length()), 0, sizeof(CharType));
1180 GlobalUnlock(mem);
1181
1182 SetClipboardData(CF_UNICODETEXT, mem);
1183
1184 // set the CF_TEXT version (not needed?)
1185 CharString utf8 = p_text.utf8();
1186 mem = GlobalAlloc(GMEM_MOVEABLE, utf8.length() + 1);
1187 if (mem == NULL) {
1188 ERR_EXPLAIN("Unable to allocate memory for clipboard contents.");
1189 ERR_FAIL();
1190 };
1191 LPTSTR ptr = (LPTSTR)GlobalLock(mem);
1192 memcpy(ptr, utf8.get_data(), utf8.length());
1193 ptr[utf8.length()] = 0;
1194 GlobalUnlock(mem);
1195
1196 SetClipboardData(CF_TEXT, mem);
1197
1198 CloseClipboard();
1199 };
1200
get_clipboard() const1201 String OS_Windows::get_clipboard() const {
1202
1203 String ret;
1204 if (!OpenClipboard(hWnd)) {
1205 ERR_EXPLAIN("Unable to open clipboard.");
1206 ERR_FAIL_V("");
1207 };
1208
1209 if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
1210
1211 HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
1212 if (mem != NULL) {
1213
1214 LPWSTR ptr = (LPWSTR)GlobalLock(mem);
1215 if (ptr != NULL) {
1216
1217 ret = String((CharType *)ptr);
1218 GlobalUnlock(mem);
1219 };
1220 };
1221
1222 } else if (IsClipboardFormatAvailable(CF_TEXT)) {
1223
1224 HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
1225 if (mem != NULL) {
1226
1227 LPTSTR ptr = (LPTSTR)GlobalLock(mem);
1228 if (ptr != NULL) {
1229
1230 ret.parse_utf8((const char *)ptr);
1231 GlobalUnlock(mem);
1232 };
1233 };
1234 };
1235
1236 CloseClipboard();
1237
1238 return ret;
1239 };
1240
delete_main_loop()1241 void OS_Windows::delete_main_loop() {
1242
1243 if (main_loop)
1244 memdelete(main_loop);
1245 main_loop = NULL;
1246 }
1247
set_main_loop(MainLoop * p_main_loop)1248 void OS_Windows::set_main_loop(MainLoop *p_main_loop) {
1249
1250 input->set_main_loop(p_main_loop);
1251 main_loop = p_main_loop;
1252 }
1253
finalize()1254 void OS_Windows::finalize() {
1255
1256 if (main_loop)
1257 memdelete(main_loop);
1258
1259 main_loop = NULL;
1260
1261 memdelete(joystick);
1262 memdelete(input);
1263 #if WINVER >= 0x0601 // for windows 7
1264 touch_state.clear();
1265 #endif
1266
1267 visual_server->finish();
1268 memdelete(visual_server);
1269 #ifdef OPENGL_ENABLED
1270 if (gl_context)
1271 memdelete(gl_context);
1272 #endif
1273 if (rasterizer)
1274 memdelete(rasterizer);
1275
1276 if (user_proc) {
1277 SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)user_proc);
1278 };
1279
1280 spatial_sound_server->finish();
1281 memdelete(spatial_sound_server);
1282 spatial_sound_2d_server->finish();
1283 memdelete(spatial_sound_2d_server);
1284
1285 //if (debugger_connection_console) {
1286 // memdelete(debugger_connection_console);
1287 //}
1288
1289 memdelete(sample_manager);
1290
1291 audio_server->finish();
1292 memdelete(audio_server);
1293
1294 physics_server->finish();
1295 memdelete(physics_server);
1296
1297 physics_2d_server->finish();
1298 memdelete(physics_2d_server);
1299 }
finalize_core()1300 void OS_Windows::finalize_core() {
1301
1302 memdelete(process_map);
1303
1304 if (mempool_dynamic)
1305 memdelete(mempool_dynamic);
1306 delete mempool_static;
1307
1308 TCPServerWinsock::cleanup();
1309 StreamPeerWinsock::cleanup();
1310 }
1311
vprint(const char * p_format,va_list p_list,bool p_stderr)1312 void OS_Windows::vprint(const char *p_format, va_list p_list, bool p_stderr) {
1313
1314 const unsigned int BUFFER_SIZE = 16384;
1315 char buf[BUFFER_SIZE + 1]; // +1 for the terminating character
1316 int len = vsnprintf(buf, BUFFER_SIZE, p_format, p_list);
1317 if (len <= 0)
1318 return;
1319 if (len >= BUFFER_SIZE)
1320 len = BUFFER_SIZE; // Output is too big, will be truncated
1321 buf[len] = 0;
1322
1323 int wlen = MultiByteToWideChar(CP_UTF8, 0, buf, len, NULL, 0);
1324 if (wlen < 0)
1325 return;
1326
1327 wchar_t *wbuf = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
1328 MultiByteToWideChar(CP_UTF8, 0, buf, len, wbuf, wlen);
1329 wbuf[wlen] = 0;
1330
1331 if (p_stderr)
1332 fwprintf(stderr, L"%ls", wbuf);
1333 else
1334 wprintf(L"%ls", wbuf);
1335
1336 #ifdef STDOUT_FILE
1337 //vwfprintf(stdo,p_format,p_list);
1338 #endif
1339 free(wbuf);
1340
1341 fflush(stdout);
1342 };
1343
alert(const String & p_alert,const String & p_title)1344 void OS_Windows::alert(const String &p_alert, const String &p_title) {
1345
1346 if (!is_no_window_mode_enabled())
1347 MessageBoxW(NULL, p_alert.c_str(), p_title.c_str(), MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
1348 else
1349 print_line("ALERT: " + p_alert);
1350 }
1351
set_mouse_mode(MouseMode p_mode)1352 void OS_Windows::set_mouse_mode(MouseMode p_mode) {
1353
1354 if (mouse_mode == p_mode)
1355 return;
1356 mouse_mode = p_mode;
1357 if (p_mode == MOUSE_MODE_CAPTURED) {
1358 RECT clipRect;
1359 GetClientRect(hWnd, &clipRect);
1360 ClientToScreen(hWnd, (POINT *)&clipRect.left);
1361 ClientToScreen(hWnd, (POINT *)&clipRect.right);
1362 ClipCursor(&clipRect);
1363 SetCapture(hWnd);
1364 center = Point2i(video_mode.width / 2, video_mode.height / 2);
1365 POINT pos = { (int)center.x, (int)center.y };
1366 ClientToScreen(hWnd, &pos);
1367 SetCursorPos(pos.x, pos.y);
1368 } else {
1369 ReleaseCapture();
1370 ClipCursor(NULL);
1371 }
1372
1373 if (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_HIDDEN) {
1374 hCursor = SetCursor(NULL);
1375 } else {
1376 CursorShape c = cursor_shape;
1377 cursor_shape = CURSOR_MAX;
1378 set_cursor_shape(c);
1379 }
1380 }
1381
get_mouse_mode() const1382 OS_Windows::MouseMode OS_Windows::get_mouse_mode() const {
1383
1384 return mouse_mode;
1385 }
1386
warp_mouse_pos(const Point2 & p_to)1387 void OS_Windows::warp_mouse_pos(const Point2 &p_to) {
1388
1389 if (mouse_mode == MOUSE_MODE_CAPTURED) {
1390
1391 old_x = p_to.x;
1392 old_y = p_to.y;
1393 } else {
1394
1395 POINT p;
1396 p.x = p_to.x;
1397 p.y = p_to.y;
1398 ClientToScreen(hWnd, &p);
1399
1400 SetCursorPos(p.x, p.y);
1401 }
1402 }
1403
get_mouse_pos() const1404 Point2 OS_Windows::get_mouse_pos() const {
1405
1406 return Point2(old_x, old_y);
1407 }
1408
get_mouse_button_state() const1409 int OS_Windows::get_mouse_button_state() const {
1410
1411 return last_button_state;
1412 }
1413
set_window_title(const String & p_title)1414 void OS_Windows::set_window_title(const String &p_title) {
1415
1416 SetWindowTextW(hWnd, p_title.c_str());
1417 }
1418
set_video_mode(const VideoMode & p_video_mode,int p_screen)1419 void OS_Windows::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
1420 }
1421
get_video_mode(int p_screen) const1422 OS::VideoMode OS_Windows::get_video_mode(int p_screen) const {
1423
1424 return video_mode;
1425 }
get_fullscreen_mode_list(List<VideoMode> * p_list,int p_screen) const1426 void OS_Windows::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
1427 }
1428
_MonitorEnumProcCount(HMONITOR hMonitor,HDC hdcMonitor,LPRECT lprcMonitor,LPARAM dwData)1429 static BOOL CALLBACK _MonitorEnumProcCount(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
1430
1431 int *data = (int *)dwData;
1432 (*data)++;
1433 return TRUE;
1434 }
1435
get_screen_count() const1436 int OS_Windows::get_screen_count() const {
1437
1438 int data = 0;
1439 EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcCount, (LPARAM)&data);
1440 return data;
1441 }
1442
1443 typedef struct {
1444 int count;
1445 int screen;
1446 HMONITOR monitor;
1447 } EnumScreenData;
1448
_MonitorEnumProcScreen(HMONITOR hMonitor,HDC hdcMonitor,LPRECT lprcMonitor,LPARAM dwData)1449 static BOOL CALLBACK _MonitorEnumProcScreen(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
1450
1451 EnumScreenData *data = (EnumScreenData *)dwData;
1452 if (data->monitor == hMonitor) {
1453 data->screen = data->count;
1454 }
1455
1456 data->count++;
1457 return TRUE;
1458 }
1459
get_current_screen() const1460 int OS_Windows::get_current_screen() const {
1461
1462 EnumScreenData data = { 0, 0, MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST) };
1463 EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcScreen, (LPARAM)&data);
1464 return data.screen;
1465 }
1466
set_current_screen(int p_screen)1467 void OS_Windows::set_current_screen(int p_screen) {
1468
1469 Vector2 ofs = get_window_position() - get_screen_position(get_current_screen());
1470 set_window_position(ofs + get_screen_position(p_screen));
1471 }
1472
1473 typedef struct {
1474 int count;
1475 int screen;
1476 Point2 pos;
1477 } EnumPosData;
1478
_MonitorEnumProcPos(HMONITOR hMonitor,HDC hdcMonitor,LPRECT lprcMonitor,LPARAM dwData)1479 static BOOL CALLBACK _MonitorEnumProcPos(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
1480
1481 EnumPosData *data = (EnumPosData *)dwData;
1482 if (data->count == data->screen) {
1483 data->pos.x = lprcMonitor->left;
1484 data->pos.y = lprcMonitor->top;
1485 }
1486
1487 data->count++;
1488 return TRUE;
1489 }
1490
get_screen_position(int p_screen) const1491 Point2 OS_Windows::get_screen_position(int p_screen) const {
1492
1493 EnumPosData data = { 0, p_screen, Point2() };
1494 EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcPos, (LPARAM)&data);
1495 return data.pos;
1496 }
1497
1498 typedef struct {
1499 int count;
1500 int screen;
1501 Size2 size;
1502 } EnumSizeData;
1503
_MonitorEnumProcSize(HMONITOR hMonitor,HDC hdcMonitor,LPRECT lprcMonitor,LPARAM dwData)1504 static BOOL CALLBACK _MonitorEnumProcSize(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
1505
1506 EnumSizeData *data = (EnumSizeData *)dwData;
1507 if (data->count == data->screen) {
1508 data->size.x = lprcMonitor->right - lprcMonitor->left;
1509 data->size.y = lprcMonitor->bottom - lprcMonitor->top;
1510 }
1511
1512 data->count++;
1513 return TRUE;
1514 }
1515
get_screen_size(int p_screen) const1516 Size2 OS_Windows::get_screen_size(int p_screen) const {
1517
1518 EnumSizeData data = { 0, p_screen, Size2() };
1519 EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcSize, (LPARAM)&data);
1520 return data.size;
1521 }
1522
1523 typedef struct {
1524 int count;
1525 int screen;
1526 int dpi;
1527 } EnumDpiData;
1528
_MonitorEnumProcDpi(HMONITOR hMonitor,HDC hdcMonitor,LPRECT lprcMonitor,LPARAM dwData)1529 static BOOL CALLBACK _MonitorEnumProcDpi(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
1530
1531 EnumDpiData *data = (EnumDpiData *)dwData;
1532 if (data->count == data->screen) {
1533 data->dpi = QueryDpiForMonitor(hMonitor);
1534 }
1535
1536 data->count++;
1537 return TRUE;
1538 }
1539
get_screen_dpi(int p_screen) const1540 int OS_Windows::get_screen_dpi(int p_screen) const {
1541
1542 EnumDpiData data = { 0, p_screen, 72 };
1543 EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcDpi, (LPARAM)&data);
1544 return data.dpi;
1545 }
1546
get_window_position() const1547 Point2 OS_Windows::get_window_position() const {
1548
1549 RECT r;
1550 GetWindowRect(hWnd, &r);
1551 return Point2(r.left, r.top);
1552 }
set_window_position(const Point2 & p_position)1553 void OS_Windows::set_window_position(const Point2 &p_position) {
1554
1555 if (video_mode.fullscreen) return;
1556 RECT r;
1557 GetWindowRect(hWnd, &r);
1558 MoveWindow(hWnd, p_position.x, p_position.y, r.right - r.left, r.bottom - r.top, TRUE);
1559 }
get_window_size() const1560 Size2 OS_Windows::get_window_size() const {
1561
1562 RECT r;
1563 GetClientRect(hWnd, &r);
1564 return Vector2(r.right - r.left, r.bottom - r.top);
1565 }
get_real_window_size() const1566 Size2 OS_Windows::get_real_window_size() const {
1567
1568 RECT r;
1569 GetWindowRect(hWnd, &r);
1570 return Vector2(r.right - r.left, r.bottom - r.top);
1571 }
set_window_size(const Size2 p_size)1572 void OS_Windows::set_window_size(const Size2 p_size) {
1573
1574 video_mode.width = p_size.width;
1575 video_mode.height = p_size.height;
1576
1577 if (video_mode.fullscreen) {
1578 return;
1579 }
1580
1581 int w = p_size.width;
1582 int h = p_size.height;
1583
1584 RECT rect;
1585 GetWindowRect(hWnd, &rect);
1586
1587 if (video_mode.borderless_window == false) {
1588 RECT crect;
1589 GetClientRect(hWnd, &crect);
1590
1591 w += (rect.right - rect.left) - (crect.right - crect.left);
1592 h += (rect.bottom - rect.top) - (crect.bottom - crect.top);
1593 }
1594
1595 MoveWindow(hWnd, rect.left, rect.top, w, h, TRUE);
1596 }
set_window_fullscreen(bool p_enabled)1597 void OS_Windows::set_window_fullscreen(bool p_enabled) {
1598
1599 if (video_mode.fullscreen == p_enabled)
1600 return;
1601
1602 if (p_enabled) {
1603
1604 if (pre_fs_valid) {
1605 GetWindowRect(hWnd, &pre_fs_rect);
1606 //print_line("A: "+itos(pre_fs_rect.left)+","+itos(pre_fs_rect.top)+","+itos(pre_fs_rect.right-pre_fs_rect.left)+","+itos(pre_fs_rect.bottom-pre_fs_rect.top));
1607 //MapWindowPoints(hWnd, GetParent(hWnd), (LPPOINT) &pre_fs_rect, 2);
1608 //print_line("B: "+itos(pre_fs_rect.left)+","+itos(pre_fs_rect.top)+","+itos(pre_fs_rect.right-pre_fs_rect.left)+","+itos(pre_fs_rect.bottom-pre_fs_rect.top));
1609 }
1610
1611 int cs = get_current_screen();
1612 Point2 pos = get_screen_position(cs);
1613 Size2 size = get_screen_size(cs);
1614
1615 video_mode.fullscreen = true;
1616
1617 _update_window_style(false);
1618
1619 MoveWindow(hWnd, pos.x, pos.y, size.width, size.height, TRUE);
1620
1621 } else {
1622
1623 RECT rect;
1624
1625 video_mode.fullscreen = false;
1626
1627 if (pre_fs_valid) {
1628 rect = pre_fs_rect;
1629 } else {
1630 rect.left = 0;
1631 rect.right = video_mode.width;
1632 rect.top = 0;
1633 rect.bottom = video_mode.height;
1634 }
1635
1636 _update_window_style(false);
1637
1638 MoveWindow(hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
1639
1640 pre_fs_valid = true;
1641 }
1642 }
is_window_fullscreen() const1643 bool OS_Windows::is_window_fullscreen() const {
1644
1645 return video_mode.fullscreen;
1646 }
set_window_resizable(bool p_enabled)1647 void OS_Windows::set_window_resizable(bool p_enabled) {
1648
1649 if (video_mode.resizable == p_enabled)
1650 return;
1651
1652 video_mode.resizable = p_enabled;
1653
1654 _update_window_style();
1655 }
is_window_resizable() const1656 bool OS_Windows::is_window_resizable() const {
1657
1658 return video_mode.resizable;
1659 }
set_window_minimized(bool p_enabled)1660 void OS_Windows::set_window_minimized(bool p_enabled) {
1661
1662 if (p_enabled) {
1663 maximized = false;
1664 minimized = true;
1665 ShowWindow(hWnd, SW_MINIMIZE);
1666 } else {
1667 ShowWindow(hWnd, SW_RESTORE);
1668 maximized = false;
1669 minimized = false;
1670 }
1671 }
is_window_minimized() const1672 bool OS_Windows::is_window_minimized() const {
1673
1674 return minimized;
1675 }
set_window_maximized(bool p_enabled)1676 void OS_Windows::set_window_maximized(bool p_enabled) {
1677
1678 if (p_enabled) {
1679 maximized = true;
1680 minimized = false;
1681 ShowWindow(hWnd, SW_MAXIMIZE);
1682 } else {
1683 ShowWindow(hWnd, SW_RESTORE);
1684 maximized = false;
1685 minimized = false;
1686 }
1687 }
is_window_maximized() const1688 bool OS_Windows::is_window_maximized() const {
1689
1690 return maximized;
1691 }
1692
set_window_always_on_top(bool p_enabled)1693 void OS_Windows::set_window_always_on_top(bool p_enabled) {
1694 if (video_mode.always_on_top == p_enabled)
1695 return;
1696
1697 video_mode.always_on_top = p_enabled;
1698
1699 _update_window_style();
1700 }
1701
is_window_always_on_top() const1702 bool OS_Windows::is_window_always_on_top() const {
1703 return video_mode.always_on_top;
1704 }
1705
set_borderless_window(int p_borderless)1706 void OS_Windows::set_borderless_window(int p_borderless) {
1707 if (video_mode.borderless_window == p_borderless)
1708 return;
1709
1710 video_mode.borderless_window = p_borderless;
1711
1712 _update_window_style();
1713 }
1714
get_borderless_window()1715 bool OS_Windows::get_borderless_window() {
1716 return video_mode.borderless_window;
1717 }
1718
_update_window_style(bool repaint)1719 void OS_Windows::_update_window_style(bool repaint) {
1720 if (video_mode.fullscreen || video_mode.borderless_window) {
1721 SetWindowLongPtr(hWnd, GWL_STYLE, WS_SYSMENU | WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE);
1722 } else {
1723 if (video_mode.resizable) {
1724 SetWindowLongPtr(hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE);
1725 } else {
1726 SetWindowLongPtr(hWnd, GWL_STYLE, WS_CAPTION | WS_MINIMIZEBOX | WS_POPUPWINDOW | WS_VISIBLE);
1727 }
1728 }
1729
1730 SetWindowPos(hWnd, video_mode.always_on_top ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
1731
1732 if (repaint) {
1733 RECT rect;
1734 GetWindowRect(hWnd, &rect);
1735 MoveWindow(hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
1736 }
1737 }
1738
request_attention()1739 void OS_Windows::request_attention() {
1740
1741 FLASHWINFO info;
1742 info.cbSize = sizeof(FLASHWINFO);
1743 info.hwnd = hWnd;
1744 info.dwFlags = FLASHW_TRAY;
1745 info.dwTimeout = 0;
1746 info.uCount = 2;
1747 FlashWindowEx(&info);
1748 }
1749
print_error(const char * p_function,const char * p_file,int p_line,const char * p_code,const char * p_rationale,ErrorType p_type)1750 void OS_Windows::print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type) {
1751
1752 HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
1753 if (!hCon || hCon == INVALID_HANDLE_VALUE) {
1754
1755 const char *err_details;
1756 if (p_rationale && p_rationale[0])
1757 err_details = p_rationale;
1758 else
1759 err_details = p_code;
1760
1761 switch (p_type) {
1762 case ERR_ERROR:
1763 print("ERROR: %s: %s\n", p_function, err_details);
1764 print(" At: %s:%i\n", p_file, p_line);
1765 break;
1766 case ERR_WARNING:
1767 print("WARNING: %s: %s\n", p_function, err_details);
1768 print(" At: %s:%i\n", p_file, p_line);
1769 break;
1770 case ERR_SCRIPT:
1771 print("SCRIPT ERROR: %s: %s\n", p_function, err_details);
1772 print(" At: %s:%i\n", p_file, p_line);
1773 break;
1774 }
1775
1776 } else {
1777
1778 CONSOLE_SCREEN_BUFFER_INFO sbi; //original
1779 GetConsoleScreenBufferInfo(hCon, &sbi);
1780
1781 WORD current_fg = sbi.wAttributes & (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
1782 WORD current_bg = sbi.wAttributes & (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY);
1783
1784 uint32_t basecol = 0;
1785 switch (p_type) {
1786 case ERR_ERROR: basecol = FOREGROUND_RED; break;
1787 case ERR_WARNING: basecol = FOREGROUND_RED | FOREGROUND_GREEN; break;
1788 case ERR_SCRIPT: basecol = FOREGROUND_RED | FOREGROUND_BLUE; break;
1789 }
1790
1791 basecol |= current_bg;
1792
1793 if (p_rationale && p_rationale[0]) {
1794
1795 SetConsoleTextAttribute(hCon, basecol | FOREGROUND_INTENSITY);
1796 switch (p_type) {
1797 case ERR_ERROR: print("ERROR: "); break;
1798 case ERR_WARNING: print("WARNING: "); break;
1799 case ERR_SCRIPT: print("SCRIPT ERROR: "); break;
1800 }
1801
1802 SetConsoleTextAttribute(hCon, current_fg | current_bg | FOREGROUND_INTENSITY);
1803 print("%s\n", p_rationale);
1804
1805 SetConsoleTextAttribute(hCon, basecol);
1806 switch (p_type) {
1807 case ERR_ERROR: print(" At: "); break;
1808 case ERR_WARNING: print(" At: "); break;
1809 case ERR_SCRIPT: print(" At: "); break;
1810 }
1811
1812 SetConsoleTextAttribute(hCon, current_fg | current_bg);
1813 print("%s:%i\n", p_file, p_line);
1814
1815 } else {
1816
1817 SetConsoleTextAttribute(hCon, basecol | FOREGROUND_INTENSITY);
1818 switch (p_type) {
1819 case ERR_ERROR: print("ERROR: %s: ", p_function); break;
1820 case ERR_WARNING: print("WARNING: %s: ", p_function); break;
1821 case ERR_SCRIPT: print("SCRIPT ERROR: %s: ", p_function); break;
1822 }
1823
1824 SetConsoleTextAttribute(hCon, current_fg | current_bg | FOREGROUND_INTENSITY);
1825 print("%s\n", p_code);
1826
1827 SetConsoleTextAttribute(hCon, basecol);
1828 switch (p_type) {
1829 case ERR_ERROR: print(" At: "); break;
1830 case ERR_WARNING: print(" At: "); break;
1831 case ERR_SCRIPT: print(" At: "); break;
1832 }
1833
1834 SetConsoleTextAttribute(hCon, current_fg | current_bg);
1835 print("%s:%i\n", p_file, p_line);
1836 }
1837
1838 SetConsoleTextAttribute(hCon, sbi.wAttributes);
1839 }
1840 }
1841
get_name()1842 String OS_Windows::get_name() {
1843
1844 return "Windows";
1845 }
1846
get_date(bool utc) const1847 OS::Date OS_Windows::get_date(bool utc) const {
1848
1849 SYSTEMTIME systemtime;
1850 if (utc)
1851 GetSystemTime(&systemtime);
1852 else
1853 GetLocalTime(&systemtime);
1854
1855 Date date;
1856 date.day = systemtime.wDay;
1857 date.month = Month(systemtime.wMonth);
1858 date.weekday = Weekday(systemtime.wDayOfWeek);
1859 date.year = systemtime.wYear;
1860 date.dst = false;
1861 return date;
1862 }
get_time(bool utc) const1863 OS::Time OS_Windows::get_time(bool utc) const {
1864
1865 SYSTEMTIME systemtime;
1866 if (utc)
1867 GetSystemTime(&systemtime);
1868 else
1869 GetLocalTime(&systemtime);
1870
1871 Time time;
1872 time.hour = systemtime.wHour;
1873 time.min = systemtime.wMinute;
1874 time.sec = systemtime.wSecond;
1875 return time;
1876 }
1877
get_time_zone_info() const1878 OS::TimeZoneInfo OS_Windows::get_time_zone_info() const {
1879 TIME_ZONE_INFORMATION info;
1880 bool daylight = false;
1881 if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT)
1882 daylight = true;
1883
1884 TimeZoneInfo ret;
1885 if (daylight) {
1886 ret.name = info.DaylightName;
1887 } else {
1888 ret.name = info.StandardName;
1889 }
1890
1891 ret.bias = info.Bias;
1892 return ret;
1893 }
1894
get_unix_time() const1895 uint64_t OS_Windows::get_unix_time() const {
1896
1897 FILETIME ft;
1898 SYSTEMTIME st;
1899 GetSystemTime(&st);
1900 SystemTimeToFileTime(&st, &ft);
1901
1902 SYSTEMTIME ep;
1903 ep.wYear = 1970;
1904 ep.wMonth = 1;
1905 ep.wDayOfWeek = 4;
1906 ep.wDay = 1;
1907 ep.wHour = 0;
1908 ep.wMinute = 0;
1909 ep.wSecond = 0;
1910 ep.wMilliseconds = 0;
1911 FILETIME fep;
1912 SystemTimeToFileTime(&ep, &fep);
1913
1914 return (*(uint64_t *)&ft - *(uint64_t *)&fep) / 10000000;
1915 };
1916
get_system_time_secs() const1917 uint64_t OS_Windows::get_system_time_secs() const {
1918
1919 const uint64_t WINDOWS_TICK = 10000000;
1920 const uint64_t SEC_TO_UNIX_EPOCH = 11644473600LL;
1921
1922 SYSTEMTIME st;
1923 GetSystemTime(&st);
1924 FILETIME ft;
1925 SystemTimeToFileTime(&st, &ft);
1926 uint64_t ret;
1927 ret = ft.dwHighDateTime;
1928 ret <<= 32;
1929 ret |= ft.dwLowDateTime;
1930
1931 return (uint64_t)(ret / WINDOWS_TICK - SEC_TO_UNIX_EPOCH);
1932 }
1933
delay_usec(uint32_t p_usec) const1934 void OS_Windows::delay_usec(uint32_t p_usec) const {
1935
1936 if (p_usec < 1000)
1937 Sleep(1);
1938 else
1939 Sleep(p_usec / 1000);
1940 }
get_ticks_usec() const1941 uint64_t OS_Windows::get_ticks_usec() const {
1942
1943 uint64_t ticks;
1944 uint64_t time;
1945 // This is the number of clock ticks since start
1946 if (!QueryPerformanceCounter((LARGE_INTEGER *)&ticks))
1947 ticks = (UINT64)timeGetTime();
1948 // Divide by frequency to get the time in seconds
1949 time = ticks * 1000000L / ticks_per_second;
1950 // Subtract the time at game start to get
1951 // the time since the game started
1952 time -= ticks_start;
1953 return time;
1954 }
1955
process_events()1956 void OS_Windows::process_events() {
1957
1958 MSG msg;
1959
1960 last_id = joystick->process_joysticks(last_id);
1961
1962 while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
1963
1964 TranslateMessage(&msg);
1965 DispatchMessageW(&msg);
1966 }
1967
1968 process_key_events();
1969 }
1970
set_cursor_shape(CursorShape p_shape)1971 void OS_Windows::set_cursor_shape(CursorShape p_shape) {
1972
1973 ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
1974
1975 if (cursor_shape == p_shape)
1976 return;
1977
1978 if (mouse_mode != MOUSE_MODE_VISIBLE) {
1979 cursor_shape = p_shape;
1980 return;
1981 }
1982
1983 static const LPCTSTR win_cursors[CURSOR_MAX] = {
1984 IDC_ARROW,
1985 IDC_IBEAM,
1986 IDC_HAND, //finger
1987 IDC_CROSS,
1988 IDC_WAIT,
1989 IDC_APPSTARTING,
1990 IDC_ARROW,
1991 IDC_ARROW,
1992 IDC_NO,
1993 IDC_SIZENS,
1994 IDC_SIZEWE,
1995 IDC_SIZENESW,
1996 IDC_SIZENWSE,
1997 IDC_SIZEALL,
1998 IDC_SIZENS,
1999 IDC_SIZEWE,
2000 IDC_HELP
2001 };
2002
2003 if (cursors[p_shape] != NULL) {
2004 SetCursor(cursors[p_shape]);
2005 } else {
2006 SetCursor(LoadCursor(hInstance, win_cursors[p_shape]));
2007 }
2008
2009 cursor_shape = p_shape;
2010 }
2011
set_custom_mouse_cursor(const RES & p_cursor,CursorShape p_shape,const Vector2 & p_hotspot)2012 void OS_Windows::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
2013 if (p_cursor.is_valid()) {
2014 Ref<ImageTexture> texture = p_cursor;
2015 Ref<AtlasTexture> atlas_texture = p_cursor;
2016 Size2 texture_size;
2017 Rect2 atlas_rect;
2018
2019 if (!texture.is_valid() && atlas_texture.is_valid()) {
2020 texture = atlas_texture->get_atlas();
2021
2022 atlas_rect.size.width = texture->get_width();
2023 atlas_rect.size.height = texture->get_height();
2024 atlas_rect.pos.x = atlas_texture->get_region().pos.x;
2025 atlas_rect.pos.y = atlas_texture->get_region().pos.y;
2026
2027 texture_size.width = atlas_texture->get_region().size.x;
2028 texture_size.height = atlas_texture->get_region().size.y;
2029 } else if (texture.is_valid()) {
2030 texture_size.width = texture->get_width();
2031 texture_size.height = texture->get_height();
2032 }
2033
2034 ERR_FAIL_COND(!texture.is_valid());
2035 ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
2036
2037 Image image = texture->get_data();
2038
2039 UINT image_size = texture_size.width * texture_size.height;
2040 UINT size = sizeof(UINT) * image_size;
2041
2042 // Create the BITMAP with alpha channel
2043 COLORREF *buffer = (COLORREF *)memalloc(sizeof(COLORREF) * image_size);
2044
2045 for (UINT index = 0; index < image_size; index++) {
2046 int row_index = floor(index / texture_size.width) + atlas_rect.pos.y;
2047 int column_index = (index % int(texture_size.width)) + atlas_rect.pos.x;
2048
2049 if (atlas_texture.is_valid()) {
2050 column_index = MIN(column_index, atlas_rect.size.width - 1);
2051 row_index = MIN(row_index, atlas_rect.size.height - 1);
2052 }
2053
2054 *(buffer + index) = image.get_pixel(column_index, row_index).to_ARGB32();
2055 }
2056
2057 // Using 4 channels, so 4 * 8 bits
2058 HBITMAP bitmap = CreateBitmap(texture_size.width, texture_size.height, 1, 4 * 8, buffer);
2059 COLORREF clrTransparent = -1;
2060
2061 // Create the AND and XOR masks for the bitmap
2062 HBITMAP hAndMask = NULL;
2063 HBITMAP hXorMask = NULL;
2064
2065 GetMaskBitmaps(bitmap, clrTransparent, hAndMask, hXorMask);
2066
2067 if (NULL == hAndMask || NULL == hXorMask) {
2068 memfree(buffer);
2069 DeleteObject(bitmap);
2070 return;
2071 }
2072
2073 // Finally, create the icon
2074 ICONINFO iconinfo = { 0 };
2075 iconinfo.fIcon = FALSE;
2076 iconinfo.xHotspot = p_hotspot.x;
2077 iconinfo.yHotspot = p_hotspot.y;
2078 iconinfo.hbmMask = hAndMask;
2079 iconinfo.hbmColor = hXorMask;
2080
2081 cursors[p_shape] = CreateIconIndirect(&iconinfo);
2082
2083 if (p_shape == CURSOR_ARROW) {
2084 if (mouse_mode == MOUSE_MODE_VISIBLE) {
2085 SetCursor(cursors[p_shape]);
2086 }
2087 }
2088
2089 if (hAndMask != NULL) {
2090 DeleteObject(hAndMask);
2091 }
2092
2093 if (hXorMask != NULL) {
2094 DeleteObject(hXorMask);
2095 }
2096
2097 memfree(buffer);
2098 DeleteObject(bitmap);
2099 }
2100 }
2101
GetMaskBitmaps(HBITMAP hSourceBitmap,COLORREF clrTransparent,OUT HBITMAP & hAndMaskBitmap,OUT HBITMAP & hXorMaskBitmap)2102 void OS_Windows::GetMaskBitmaps(HBITMAP hSourceBitmap, COLORREF clrTransparent, OUT HBITMAP &hAndMaskBitmap, OUT HBITMAP &hXorMaskBitmap) {
2103
2104 // Get the system display DC
2105 HDC hDC = GetDC(NULL);
2106
2107 // Create helper DC
2108 HDC hMainDC = CreateCompatibleDC(hDC);
2109 HDC hAndMaskDC = CreateCompatibleDC(hDC);
2110 HDC hXorMaskDC = CreateCompatibleDC(hDC);
2111
2112 // Get the dimensions of the source bitmap
2113 BITMAP bm;
2114 GetObject(hSourceBitmap, sizeof(BITMAP), &bm);
2115
2116 // Create the mask bitmaps
2117 hAndMaskBitmap = CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); // color
2118 hXorMaskBitmap = CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); // color
2119
2120 // Release the system display DC
2121 ReleaseDC(NULL, hDC);
2122
2123 // Select the bitmaps to helper DC
2124 HBITMAP hOldMainBitmap = (HBITMAP)SelectObject(hMainDC, hSourceBitmap);
2125 HBITMAP hOldAndMaskBitmap = (HBITMAP)SelectObject(hAndMaskDC, hAndMaskBitmap);
2126 HBITMAP hOldXorMaskBitmap = (HBITMAP)SelectObject(hXorMaskDC, hXorMaskBitmap);
2127
2128 // Assign the monochrome AND mask bitmap pixels so that a pixels of the source bitmap
2129 // with 'clrTransparent' will be white pixels of the monochrome bitmap
2130 SetBkColor(hMainDC, clrTransparent);
2131 BitBlt(hAndMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hMainDC, 0, 0, SRCCOPY);
2132
2133 // Assign the color XOR mask bitmap pixels so that a pixels of the source bitmap
2134 // with 'clrTransparent' will be black and rest the pixels same as corresponding
2135 // pixels of the source bitmap
2136 SetBkColor(hXorMaskDC, RGB(0, 0, 0));
2137 SetTextColor(hXorMaskDC, RGB(255, 255, 255));
2138 BitBlt(hXorMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hAndMaskDC, 0, 0, SRCCOPY);
2139 BitBlt(hXorMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hMainDC, 0, 0, SRCAND);
2140
2141 // Deselect bitmaps from the helper DC
2142 SelectObject(hMainDC, hOldMainBitmap);
2143 SelectObject(hAndMaskDC, hOldAndMaskBitmap);
2144 SelectObject(hXorMaskDC, hOldXorMaskBitmap);
2145
2146 // Delete the helper DC
2147 DeleteDC(hXorMaskDC);
2148 DeleteDC(hAndMaskDC);
2149 DeleteDC(hMainDC);
2150 }
2151
execute(const String & p_path,const List<String> & p_arguments,bool p_blocking,ProcessID * r_child_id,String * r_pipe,int * r_exitcode,bool read_stderr)2152 Error OS_Windows::execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id, String *r_pipe, int *r_exitcode, bool read_stderr) {
2153
2154 if (p_blocking && r_pipe) {
2155
2156 String argss;
2157 argss = "\"\"" + p_path + "\"";
2158
2159 for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
2160
2161 argss += String(" \"") + E->get() + "\"";
2162 }
2163
2164 // print_line("ARGS: "+argss);
2165 //argss+"\"";
2166 //argss+=" 2>nul";
2167
2168 FILE *f = _wpopen(argss.c_str(), L"r");
2169
2170 ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
2171
2172 char buf[65535];
2173 while (fgets(buf, 65535, f)) {
2174
2175 (*r_pipe) += buf;
2176 }
2177
2178 int rv = _pclose(f);
2179 if (r_exitcode)
2180 *r_exitcode = rv;
2181
2182 return OK;
2183 }
2184
2185 String cmdline = "\"" + p_path + "\"";
2186 const List<String>::Element *I = p_arguments.front();
2187 while (I) {
2188
2189 cmdline += " \"" + I->get() + "\"";
2190
2191 I = I->next();
2192 };
2193
2194 //cmdline+="\"";
2195
2196 ProcessInfo pi;
2197 ZeroMemory(&pi.si, sizeof(pi.si));
2198 pi.si.cb = sizeof(pi.si);
2199 ZeroMemory(&pi.pi, sizeof(pi.pi));
2200 LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si;
2201
2202 print_line("running cmdline: " + cmdline);
2203 Vector<CharType> modstr; //windows wants to change this no idea why
2204 modstr.resize(cmdline.size());
2205 for (int i = 0; i < cmdline.size(); i++)
2206 modstr[i] = cmdline[i];
2207 int ret = CreateProcessW(NULL, modstr.ptr(), NULL, NULL, 0, NORMAL_PRIORITY_CLASS, NULL, NULL, si_w, &pi.pi);
2208 ERR_FAIL_COND_V(ret == 0, ERR_CANT_FORK);
2209
2210 if (p_blocking) {
2211
2212 DWORD ret = WaitForSingleObject(pi.pi.hProcess, INFINITE);
2213 if (r_exitcode)
2214 *r_exitcode = ret;
2215
2216 } else {
2217
2218 ProcessID pid = pi.pi.dwProcessId;
2219 if (r_child_id) {
2220 *r_child_id = pid;
2221 };
2222 process_map->insert(pid, pi);
2223 };
2224 return OK;
2225 };
2226
kill(const ProcessID & p_pid)2227 Error OS_Windows::kill(const ProcessID &p_pid) {
2228
2229 HANDLE h;
2230
2231 if (process_map->has(p_pid)) {
2232 h = (*process_map)[p_pid].pi.hProcess;
2233 process_map->erase(p_pid);
2234 } else {
2235
2236 ERR_FAIL_COND_V(!process_map->has(p_pid), FAILED);
2237 };
2238
2239 int ret = TerminateProcess(h, 0);
2240
2241 return ret != 0 ? OK : FAILED;
2242 };
2243
get_process_ID() const2244 int OS_Windows::get_process_ID() const {
2245 return _getpid();
2246 }
2247
set_cwd(const String & p_cwd)2248 Error OS_Windows::set_cwd(const String &p_cwd) {
2249
2250 if (_wchdir(p_cwd.c_str()) != 0)
2251 return ERR_CANT_OPEN;
2252
2253 return OK;
2254 }
2255
get_executable_path() const2256 String OS_Windows::get_executable_path() const {
2257
2258 wchar_t bufname[4096];
2259 GetModuleFileNameW(NULL, bufname, 4096);
2260 String s = bufname;
2261 return s;
2262 }
2263
set_icon(const Image & p_icon)2264 void OS_Windows::set_icon(const Image &p_icon) {
2265
2266 Image icon = p_icon;
2267 if (icon.get_format() != Image::FORMAT_RGBA)
2268 icon.convert(Image::FORMAT_RGBA);
2269 int w = icon.get_width();
2270 int h = icon.get_height();
2271
2272 /* Create temporary bitmap buffer */
2273 int icon_len = 40 + h * w * 4;
2274 Vector<BYTE> v;
2275 v.resize(icon_len);
2276 BYTE *icon_bmp = &v[0];
2277
2278 encode_uint32(40, &icon_bmp[0]);
2279 encode_uint32(w, &icon_bmp[4]);
2280 encode_uint32(h * 2, &icon_bmp[8]);
2281 encode_uint16(1, &icon_bmp[12]);
2282 encode_uint16(32, &icon_bmp[14]);
2283 encode_uint32(BI_RGB, &icon_bmp[16]);
2284 encode_uint32(w * h * 4, &icon_bmp[20]);
2285 encode_uint32(0, &icon_bmp[24]);
2286 encode_uint32(0, &icon_bmp[28]);
2287 encode_uint32(0, &icon_bmp[32]);
2288 encode_uint32(0, &icon_bmp[36]);
2289
2290 uint8_t *wr = &icon_bmp[40];
2291 DVector<uint8_t>::Read r = icon.get_data().read();
2292
2293 for (int i = 0; i < h; i++) {
2294
2295 for (int j = 0; j < w; j++) {
2296
2297 const uint8_t *rpx = &r[((h - i - 1) * w + j) * 4];
2298 uint8_t *wpx = &wr[(i * w + j) * 4];
2299 wpx[0] = rpx[2];
2300 wpx[1] = rpx[1];
2301 wpx[2] = rpx[0];
2302 wpx[3] = rpx[3];
2303 }
2304 }
2305
2306 HICON hicon = CreateIconFromResource(icon_bmp, icon_len, TRUE, 0x00030000);
2307
2308 /* Set the icon for the window */
2309 SendMessage(hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hicon);
2310
2311 /* Set the icon in the task manager (should we do this?) */
2312 SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hicon);
2313 }
2314
has_environment(const String & p_var) const2315 bool OS_Windows::has_environment(const String &p_var) const {
2316
2317 return getenv(p_var.utf8().get_data()) != NULL;
2318 };
2319
get_environment(const String & p_var) const2320 String OS_Windows::get_environment(const String &p_var) const {
2321
2322 wchar_t wval[0x7Fff]; // MSDN says 32767 char is the maximum
2323 int wlen = GetEnvironmentVariableW(p_var.c_str(), wval, 0x7Fff);
2324 if (wlen > 0) {
2325 return wval;
2326 }
2327 return "";
2328 }
2329
get_stdin_string(bool p_block)2330 String OS_Windows::get_stdin_string(bool p_block) {
2331
2332 if (p_block) {
2333 char buff[1024];
2334 return fgets(buff, 1024, stdin);
2335 };
2336
2337 return String();
2338 }
2339
enable_for_stealing_focus(ProcessID pid)2340 void OS_Windows::enable_for_stealing_focus(ProcessID pid) {
2341
2342 AllowSetForegroundWindow(pid);
2343 }
2344
move_window_to_foreground()2345 void OS_Windows::move_window_to_foreground() {
2346
2347 SetForegroundWindow(hWnd);
2348 }
2349
shell_open(String p_uri)2350 Error OS_Windows::shell_open(String p_uri) {
2351
2352 ShellExecuteW(NULL, L"open", p_uri.c_str(), NULL, NULL, SW_SHOWNORMAL);
2353 return OK;
2354 }
2355
get_locale() const2356 String OS_Windows::get_locale() const {
2357
2358 const _WinLocale *wl = &_win_locales[0];
2359
2360 LANGID langid = GetUserDefaultUILanguage();
2361 String neutral;
2362 int lang = langid & ((1 << 9) - 1);
2363 int sublang = langid & ~((1 << 9) - 1);
2364
2365 while (wl->locale) {
2366
2367 if (wl->main_lang == lang && wl->sublang == SUBLANG_NEUTRAL)
2368 neutral = wl->locale;
2369
2370 if (lang == wl->main_lang && sublang == wl->sublang)
2371 return wl->locale;
2372
2373 wl++;
2374 }
2375
2376 if (neutral != "")
2377 return neutral;
2378
2379 return "en";
2380 }
2381
get_latin_keyboard_variant() const2382 OS::LatinKeyboardVariant OS_Windows::get_latin_keyboard_variant() const {
2383
2384 unsigned long azerty[] = {
2385 0x00020401, // Arabic (102) AZERTY
2386 0x0001080c, // Belgian (Comma)
2387 0x0000080c, // Belgian French
2388 0x0000040c, // French
2389 0 // <--- STOP MARK
2390 };
2391 unsigned long qwertz[] = {
2392 0x0000041a, // Croation
2393 0x00000405, // Czech
2394 0x00000407, // German
2395 0x00010407, // German (IBM)
2396 0x0000040e, // Hungarian
2397 0x0000046e, // Luxembourgish
2398 0x00010415, // Polish (214)
2399 0x00000418, // Romanian (Legacy)
2400 0x0000081a, // Serbian (Latin)
2401 0x0000041b, // Slovak
2402 0x00000424, // Slovenian
2403 0x0001042e, // Sorbian Extended
2404 0x0002042e, // Sorbian Standard
2405 0x0000042e, // Sorbian Standard (Legacy)
2406 0x0000100c, // Swiss French
2407 0x00000807, // Swiss German
2408 0 // <--- STOP MARK
2409 };
2410 unsigned long dvorak[] = {
2411 0x00010409, // US-Dvorak
2412 0x00030409, // US-Dvorak for left hand
2413 0x00040409, // US-Dvorak for right hand
2414 0 // <--- STOP MARK
2415 };
2416
2417 char name[KL_NAMELENGTH + 1];
2418 name[0] = 0;
2419 GetKeyboardLayoutNameA(name);
2420
2421 unsigned long hex = strtoul(name, NULL, 16);
2422
2423 int i = 0;
2424 while (azerty[i] != 0) {
2425 if (azerty[i] == hex) return LATIN_KEYBOARD_AZERTY;
2426 i++;
2427 }
2428
2429 i = 0;
2430 while (qwertz[i] != 0) {
2431 if (qwertz[i] == hex) return LATIN_KEYBOARD_QWERTZ;
2432 i++;
2433 }
2434
2435 i = 0;
2436 while (dvorak[i] != 0) {
2437 if (dvorak[i] == hex) return LATIN_KEYBOARD_DVORAK;
2438 i++;
2439 }
2440
2441 return LATIN_KEYBOARD_QWERTY;
2442 }
2443
release_rendering_thread()2444 void OS_Windows::release_rendering_thread() {
2445
2446 gl_context->release_current();
2447 }
2448
make_rendering_thread()2449 void OS_Windows::make_rendering_thread() {
2450
2451 gl_context->make_current();
2452 }
2453
swap_buffers()2454 void OS_Windows::swap_buffers() {
2455
2456 gl_context->swap_buffers();
2457 }
2458
run()2459 void OS_Windows::run() {
2460
2461 if (!main_loop)
2462 return;
2463
2464 main_loop->init();
2465
2466 uint64_t last_ticks = get_ticks_usec();
2467
2468 int frames = 0;
2469 uint64_t frame = 0;
2470
2471 while (!force_quit) {
2472
2473 process_events(); // get rid of pending events
2474 if (Main::iteration() == true)
2475 break;
2476 };
2477
2478 main_loop->finish();
2479 }
2480
get_main_loop() const2481 MainLoop *OS_Windows::get_main_loop() const {
2482
2483 return main_loop;
2484 }
2485
get_system_dir(SystemDir p_dir) const2486 String OS_Windows::get_system_dir(SystemDir p_dir) const {
2487
2488 int id;
2489
2490 switch (p_dir) {
2491 case SYSTEM_DIR_DESKTOP: {
2492 id = CSIDL_DESKTOPDIRECTORY;
2493 } break;
2494 case SYSTEM_DIR_DCIM: {
2495 id = CSIDL_MYPICTURES;
2496 } break;
2497 case SYSTEM_DIR_DOCUMENTS: {
2498 id = CSIDL_PERSONAL;
2499 } break;
2500 case SYSTEM_DIR_DOWNLOADS: {
2501 id = 0x000C;
2502 } break;
2503 case SYSTEM_DIR_MOVIES: {
2504 id = CSIDL_MYVIDEO;
2505 } break;
2506 case SYSTEM_DIR_MUSIC: {
2507 id = CSIDL_MYMUSIC;
2508 } break;
2509 case SYSTEM_DIR_PICTURES: {
2510 id = CSIDL_MYPICTURES;
2511 } break;
2512 case SYSTEM_DIR_RINGTONES: {
2513 id = CSIDL_MYMUSIC;
2514 } break;
2515 }
2516
2517 WCHAR szPath[MAX_PATH];
2518 HRESULT res = SHGetFolderPathW(NULL, id, NULL, 0, szPath);
2519 ERR_FAIL_COND_V(res != S_OK, String());
2520 return String(szPath);
2521 }
get_data_dir() const2522 String OS_Windows::get_data_dir() const {
2523
2524 String an = get_safe_application_name();
2525 if (an != "") {
2526
2527 if (has_environment("APPDATA")) {
2528
2529 bool use_godot = Globals::get_singleton()->get("application/use_shared_user_dir");
2530 if (!use_godot)
2531 return (OS::get_singleton()->get_environment("APPDATA") + "/" + an).replace("\\", "/");
2532 else
2533 return (OS::get_singleton()->get_environment("APPDATA") + "/Godot/app_userdata/" + an).replace("\\", "/");
2534 }
2535 }
2536
2537 return Globals::get_singleton()->get_resource_path();
2538 }
2539
is_joy_known(int p_device)2540 bool OS_Windows::is_joy_known(int p_device) {
2541 return input->is_joy_mapped(p_device);
2542 }
2543
get_joy_guid(int p_device) const2544 String OS_Windows::get_joy_guid(int p_device) const {
2545 return input->get_joy_guid_remapped(p_device);
2546 }
2547
set_use_vsync(bool p_enable)2548 void OS_Windows::set_use_vsync(bool p_enable) {
2549
2550 if (gl_context)
2551 gl_context->set_use_vsync(p_enable);
2552 }
2553
is_vsync_enabled() const2554 bool OS_Windows::is_vsync_enabled() const {
2555
2556 if (gl_context)
2557 return gl_context->is_using_vsync();
2558
2559 return true;
2560 }
2561
disable_crash_handler()2562 void OS_Windows::disable_crash_handler() {
2563 crash_handler.disable();
2564 }
2565
is_disable_crash_handler() const2566 bool OS_Windows::is_disable_crash_handler() const {
2567 return crash_handler.is_disabled();
2568 }
2569
move_path_to_trash(String p_dir)2570 Error OS_Windows::move_path_to_trash(String p_dir) {
2571 SHFILEOPSTRUCTA sf;
2572 TCHAR *from = new TCHAR[p_dir.length() + 2];
2573 strcpy(from, p_dir.utf8().get_data());
2574 from[p_dir.length()] = 0;
2575 from[p_dir.length() + 1] = 0;
2576
2577 sf.hwnd = hWnd;
2578 sf.wFunc = FO_DELETE;
2579 sf.pFrom = from;
2580 sf.pTo = NULL;
2581 sf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
2582 sf.fAnyOperationsAborted = FALSE;
2583 sf.hNameMappings = NULL;
2584 sf.lpszProgressTitle = NULL;
2585
2586 int ret = SHFileOperation(&sf);
2587 delete[] from;
2588
2589 if (ret) {
2590 ERR_PRINTS("SHFileOperation error: " + itos(ret));
2591 return FAILED;
2592 }
2593
2594 return OK;
2595 }
2596
OS_Windows(HINSTANCE _hInstance)2597 OS_Windows::OS_Windows(HINSTANCE _hInstance) {
2598
2599 key_event_pos = 0;
2600 force_quit = false;
2601 alt_mem = false;
2602 gr_mem = false;
2603 shift_mem = false;
2604 control_mem = false;
2605 meta_mem = false;
2606 minimized = false;
2607
2608 hInstance = _hInstance;
2609 pressrc = 0;
2610 old_invalid = true;
2611 last_id = 0;
2612 mouse_mode = MOUSE_MODE_VISIBLE;
2613 #ifdef STDOUT_FILE
2614 stdo = fopen("stdout.txt", "wb");
2615 #endif
2616 user_proc = NULL;
2617
2618 #ifdef WASAPI_ENABLED
2619 AudioDriverManagerSW::add_driver(&driver_wasapi);
2620 #endif
2621 #ifdef RTAUDIO_ENABLED
2622 AudioDriverManagerSW::add_driver(&driver_rtaudio);
2623 #endif
2624 }
2625
~OS_Windows()2626 OS_Windows::~OS_Windows() {
2627 #ifdef STDOUT_FILE
2628 fclose(stdo);
2629 #endif
2630 }
2631