os_windows.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305
  1. /*************************************************************************/
  2. /* os_windows.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 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 "os_windows.h"
  31. #include "drivers/gles3/rasterizer_gles3.h"
  32. #include "drivers/windows/dir_access_windows.h"
  33. #include "drivers/windows/file_access_windows.h"
  34. #include "drivers/windows/mutex_windows.h"
  35. #include "drivers/windows/rw_lock_windows.h"
  36. #include "drivers/windows/semaphore_windows.h"
  37. #include "drivers/windows/thread_windows.h"
  38. #include "io/marshalls.h"
  39. #include "joypad.h"
  40. #include "lang_table.h"
  41. #include "main/main.h"
  42. #include "packet_peer_udp_winsock.h"
  43. #include "servers/audio_server.h"
  44. #include "servers/visual/visual_server_raster.h"
  45. #include "servers/visual/visual_server_wrap_mt.h"
  46. #include "stream_peer_winsock.h"
  47. #include "tcp_server_winsock.h"
  48. #include "windows_terminal_logger.h"
  49. #include <process.h>
  50. #include <regstr.h>
  51. #include <shlobj.h>
  52. static const WORD MAX_CONSOLE_LINES = 1500;
  53. extern "C" {
  54. #ifdef _MSC_VER
  55. _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
  56. #else
  57. __attribute__((visibility("default"))) DWORD NvOptimusEnablement = 0x00000001;
  58. #endif
  59. }
  60. // Workaround mingw-w64 < 4.0 bug
  61. #ifndef WM_TOUCH
  62. #define WM_TOUCH 576
  63. #endif
  64. extern HINSTANCE godot_hinstance;
  65. void RedirectIOToConsole() {
  66. int hConHandle;
  67. intptr_t lStdHandle;
  68. CONSOLE_SCREEN_BUFFER_INFO coninfo;
  69. FILE *fp;
  70. // allocate a console for this app
  71. AllocConsole();
  72. // set the screen buffer to be big enough to let us scroll text
  73. GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
  74. &coninfo);
  75. coninfo.dwSize.Y = MAX_CONSOLE_LINES;
  76. SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
  77. coninfo.dwSize);
  78. // redirect unbuffered STDOUT to the console
  79. lStdHandle = (intptr_t)GetStdHandle(STD_OUTPUT_HANDLE);
  80. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  81. fp = _fdopen(hConHandle, "w");
  82. *stdout = *fp;
  83. setvbuf(stdout, NULL, _IONBF, 0);
  84. // redirect unbuffered STDIN to the console
  85. lStdHandle = (intptr_t)GetStdHandle(STD_INPUT_HANDLE);
  86. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  87. fp = _fdopen(hConHandle, "r");
  88. *stdin = *fp;
  89. setvbuf(stdin, NULL, _IONBF, 0);
  90. // redirect unbuffered STDERR to the console
  91. lStdHandle = (intptr_t)GetStdHandle(STD_ERROR_HANDLE);
  92. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  93. fp = _fdopen(hConHandle, "w");
  94. *stderr = *fp;
  95. setvbuf(stderr, NULL, _IONBF, 0);
  96. // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
  97. // point to console as well
  98. }
  99. int OS_Windows::get_video_driver_count() const {
  100. return 1;
  101. }
  102. const char *OS_Windows::get_video_driver_name(int p_driver) const {
  103. return "GLES2";
  104. }
  105. OS::VideoMode OS_Windows::get_default_video_mode() const {
  106. return VideoMode(1024, 600, false);
  107. }
  108. int OS_Windows::get_audio_driver_count() const {
  109. return AudioDriverManager::get_driver_count();
  110. }
  111. const char *OS_Windows::get_audio_driver_name(int p_driver) const {
  112. AudioDriver *driver = AudioDriverManager::get_driver(p_driver);
  113. ERR_FAIL_COND_V(!driver, "");
  114. return AudioDriverManager::get_driver(p_driver)->get_name();
  115. }
  116. void OS_Windows::initialize_core() {
  117. crash_handler.initialize();
  118. last_button_state = 0;
  119. //RedirectIOToConsole();
  120. maximized = false;
  121. minimized = false;
  122. borderless = false;
  123. ThreadWindows::make_default();
  124. SemaphoreWindows::make_default();
  125. MutexWindows::make_default();
  126. RWLockWindows::make_default();
  127. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
  128. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
  129. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
  130. //FileAccessBufferedFA<FileAccessWindows>::make_default();
  131. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
  132. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
  133. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);
  134. TCPServerWinsock::make_default();
  135. StreamPeerWinsock::make_default();
  136. PacketPeerUDPWinsock::make_default();
  137. // We need to know how often the clock is updated
  138. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
  139. ticks_per_second = 1000;
  140. // If timeAtGameStart is 0 then we get the time since
  141. // the start of the computer when we call GetGameTime()
  142. ticks_start = 0;
  143. ticks_start = get_ticks_usec();
  144. process_map = memnew((Map<ProcessID, ProcessInfo>));
  145. IP_Unix::make_default();
  146. cursor_shape = CURSOR_ARROW;
  147. }
  148. void OS_Windows::initialize_logger() {
  149. Vector<Logger *> loggers;
  150. loggers.push_back(memnew(WindowsTerminalLogger));
  151. // FIXME: Reenable once we figure out how to get this properly in user://
  152. // instead of littering the user's working dirs (res:// + pwd) with log files (GH-12277)
  153. //loggers.push_back(memnew(RotatedFileLogger("user://logs/log.txt")));
  154. _set_logger(memnew(CompositeLogger(loggers)));
  155. }
  156. bool OS_Windows::can_draw() const {
  157. return !minimized;
  158. };
  159. #define MI_WP_SIGNATURE 0xFF515700
  160. #define SIGNATURE_MASK 0xFFFFFF00
  161. #define IsPenEvent(dw) (((dw)&SIGNATURE_MASK) == MI_WP_SIGNATURE)
  162. void OS_Windows::_touch_event(bool p_pressed, int p_x, int p_y, int idx) {
  163. Ref<InputEventScreenTouch> event;
  164. event.instance();
  165. event->set_index(idx);
  166. event->set_pressed(p_pressed);
  167. event->set_position(Vector2(p_x, p_y));
  168. if (main_loop) {
  169. input->parse_input_event(event);
  170. }
  171. };
  172. void OS_Windows::_drag_event(int p_x, int p_y, int idx) {
  173. Ref<InputEventScreenDrag> event;
  174. event.instance();
  175. event->set_index(idx);
  176. event->set_position(Vector2(p_x, p_y));
  177. if (main_loop)
  178. input->parse_input_event(event);
  179. };
  180. LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  181. switch (uMsg) // Check For Windows Messages
  182. {
  183. case WM_SETFOCUS: {
  184. window_has_focus = true;
  185. // Re-capture cursor if we're in one of the capture modes
  186. if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
  187. SetCapture(hWnd);
  188. }
  189. break;
  190. }
  191. case WM_KILLFOCUS: {
  192. window_has_focus = false;
  193. // Release capture if we're in one of the capture modes
  194. if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
  195. ReleaseCapture();
  196. }
  197. break;
  198. }
  199. case WM_ACTIVATE: // Watch For Window Activate Message
  200. {
  201. minimized = HIWORD(wParam) != 0;
  202. if (!main_loop) {
  203. return 0;
  204. };
  205. if (LOWORD(wParam) == WA_ACTIVE || LOWORD(wParam) == WA_CLICKACTIVE) {
  206. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
  207. alt_mem = false;
  208. control_mem = false;
  209. shift_mem = false;
  210. if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
  211. RECT clipRect;
  212. GetClientRect(hWnd, &clipRect);
  213. ClientToScreen(hWnd, (POINT *)&clipRect.left);
  214. ClientToScreen(hWnd, (POINT *)&clipRect.right);
  215. ClipCursor(&clipRect);
  216. SetCapture(hWnd);
  217. }
  218. } else {
  219. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  220. alt_mem = false;
  221. };
  222. return 0; // Return To The Message Loop
  223. }
  224. case WM_PAINT:
  225. Main::force_redraw();
  226. break;
  227. case WM_SYSCOMMAND: // Intercept System Commands
  228. {
  229. switch (wParam) // Check System Calls
  230. {
  231. case SC_SCREENSAVE: // Screensaver Trying To Start?
  232. case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
  233. return 0; // Prevent From Happening
  234. case SC_KEYMENU:
  235. if ((lParam >> 16) <= 0)
  236. return 0;
  237. }
  238. break; // Exit
  239. }
  240. case WM_CLOSE: // Did We Receive A Close Message?
  241. {
  242. if (main_loop)
  243. main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  244. //force_quit=true;
  245. return 0; // Jump Back
  246. }
  247. case WM_MOUSELEAVE: {
  248. old_invalid = true;
  249. outside = true;
  250. if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
  251. main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
  252. if (input)
  253. input->set_mouse_in_window(false);
  254. } break;
  255. case WM_MOUSEMOVE: {
  256. if (outside) {
  257. //mouse enter
  258. if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
  259. main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
  260. if (input)
  261. input->set_mouse_in_window(true);
  262. CursorShape c = cursor_shape;
  263. cursor_shape = CURSOR_MAX;
  264. set_cursor_shape(c);
  265. outside = false;
  266. //Once-Off notification, must call again....
  267. TRACKMOUSEEVENT tme;
  268. tme.cbSize = sizeof(TRACKMOUSEEVENT);
  269. tme.dwFlags = TME_LEAVE;
  270. tme.hwndTrack = hWnd;
  271. tme.dwHoverTime = HOVER_DEFAULT;
  272. TrackMouseEvent(&tme);
  273. }
  274. // Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
  275. if (!window_has_focus && mouse_mode == MOUSE_MODE_CAPTURED)
  276. break;
  277. /*
  278. LPARAM extra = GetMessageExtraInfo();
  279. if (IsPenEvent(extra)) {
  280. int idx = extra & 0x7f;
  281. _drag_event(idx, uMsg, wParam, lParam);
  282. if (idx != 0) {
  283. return 0;
  284. };
  285. // fallthrough for mouse event
  286. };
  287. */
  288. Ref<InputEventMouseMotion> mm;
  289. mm.instance();
  290. mm->set_control((wParam & MK_CONTROL) != 0);
  291. mm->set_shift((wParam & MK_SHIFT) != 0);
  292. mm->set_alt(alt_mem);
  293. int bmask = 0;
  294. bmask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0;
  295. bmask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0;
  296. bmask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0;
  297. mm->set_button_mask(bmask);
  298. last_button_state = mm->get_button_mask();
  299. /*mm->get_button_mask()|=(wParam&MK_XBUTTON1)?(1<<5):0;
  300. mm->get_button_mask()|=(wParam&MK_XBUTTON2)?(1<<6):0;*/
  301. mm->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  302. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  303. Point2i c(video_mode.width / 2, video_mode.height / 2);
  304. old_x = c.x;
  305. old_y = c.y;
  306. if (mm->get_position() == c) {
  307. center = c;
  308. return 0;
  309. }
  310. Point2i ncenter = mm->get_position();
  311. center = ncenter;
  312. POINT pos = { (int)c.x, (int)c.y };
  313. ClientToScreen(hWnd, &pos);
  314. SetCursorPos(pos.x, pos.y);
  315. }
  316. input->set_mouse_position(mm->get_position());
  317. mm->set_speed(input->get_last_mouse_speed());
  318. if (old_invalid) {
  319. old_x = mm->get_position().x;
  320. old_y = mm->get_position().y;
  321. old_invalid = false;
  322. }
  323. mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
  324. old_x = mm->get_position().x;
  325. old_y = mm->get_position().y;
  326. if (window_has_focus && main_loop)
  327. input->parse_input_event(mm);
  328. } break;
  329. case WM_LBUTTONDOWN:
  330. case WM_LBUTTONUP:
  331. case WM_MBUTTONDOWN:
  332. case WM_MBUTTONUP:
  333. case WM_RBUTTONDOWN:
  334. case WM_RBUTTONUP:
  335. case WM_MOUSEWHEEL:
  336. case WM_MOUSEHWHEEL:
  337. case WM_LBUTTONDBLCLK:
  338. case WM_RBUTTONDBLCLK:
  339. /*case WM_XBUTTONDOWN:
  340. case WM_XBUTTONUP: */ {
  341. /*
  342. LPARAM extra = GetMessageExtraInfo();
  343. if (IsPenEvent(extra)) {
  344. int idx = extra & 0x7f;
  345. _touch_event(idx, uMsg, wParam, lParam);
  346. if (idx != 0) {
  347. return 0;
  348. };
  349. // fallthrough for mouse event
  350. };
  351. */
  352. Ref<InputEventMouseButton> mb;
  353. mb.instance();
  354. switch (uMsg) {
  355. case WM_LBUTTONDOWN: {
  356. mb->set_pressed(true);
  357. mb->set_button_index(1);
  358. } break;
  359. case WM_LBUTTONUP: {
  360. mb->set_pressed(false);
  361. mb->set_button_index(1);
  362. } break;
  363. case WM_MBUTTONDOWN: {
  364. mb->set_pressed(true);
  365. mb->set_button_index(3);
  366. } break;
  367. case WM_MBUTTONUP: {
  368. mb->set_pressed(false);
  369. mb->set_button_index(3);
  370. } break;
  371. case WM_RBUTTONDOWN: {
  372. mb->set_pressed(true);
  373. mb->set_button_index(2);
  374. } break;
  375. case WM_RBUTTONUP: {
  376. mb->set_pressed(false);
  377. mb->set_button_index(2);
  378. } break;
  379. case WM_LBUTTONDBLCLK: {
  380. mb->set_pressed(true);
  381. mb->set_button_index(1);
  382. mb->set_doubleclick(true);
  383. } break;
  384. case WM_RBUTTONDBLCLK: {
  385. mb->set_pressed(true);
  386. mb->set_button_index(2);
  387. mb->set_doubleclick(true);
  388. } break;
  389. case WM_MOUSEWHEEL: {
  390. mb->set_pressed(true);
  391. int motion = (short)HIWORD(wParam);
  392. if (!motion)
  393. return 0;
  394. if (motion > 0)
  395. mb->set_button_index(BUTTON_WHEEL_UP);
  396. else
  397. mb->set_button_index(BUTTON_WHEEL_DOWN);
  398. } break;
  399. case WM_MOUSEHWHEEL: {
  400. mb->set_pressed(true);
  401. int motion = (short)HIWORD(wParam);
  402. if (!motion)
  403. return 0;
  404. if (motion < 0) {
  405. mb->set_button_index(BUTTON_WHEEL_LEFT);
  406. mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA));
  407. } else {
  408. mb->set_button_index(BUTTON_WHEEL_RIGHT);
  409. mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA));
  410. }
  411. } break;
  412. /*
  413. case WM_XBUTTONDOWN: {
  414. mb->is_pressed()=true;
  415. mb->get_button_index()=(HIWORD(wParam)==XBUTTON1)?6:7;
  416. } break;
  417. case WM_XBUTTONUP:
  418. mb->is_pressed()=true;
  419. mb->get_button_index()=(HIWORD(wParam)==XBUTTON1)?6:7;
  420. } break;*/
  421. default: { return 0; }
  422. }
  423. mb->set_control((wParam & MK_CONTROL) != 0);
  424. mb->set_shift((wParam & MK_SHIFT) != 0);
  425. mb->set_alt(alt_mem);
  426. //mb->get_alt()=(wParam&MK_MENU)!=0;
  427. int bmask = 0;
  428. bmask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0;
  429. bmask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0;
  430. bmask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0;
  431. mb->set_button_mask(bmask);
  432. last_button_state = mb->get_button_mask();
  433. /*
  434. mb->get_button_mask()|=(wParam&MK_XBUTTON1)?(1<<5):0;
  435. mb->get_button_mask()|=(wParam&MK_XBUTTON2)?(1<<6):0;*/
  436. mb->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  437. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  438. mb->set_position(Vector2(old_x, old_y));
  439. }
  440. if (uMsg != WM_MOUSEWHEEL) {
  441. if (mb->is_pressed()) {
  442. if (++pressrc > 0)
  443. SetCapture(hWnd);
  444. } else {
  445. if (--pressrc <= 0) {
  446. ReleaseCapture();
  447. pressrc = 0;
  448. }
  449. }
  450. } else if (mouse_mode != MOUSE_MODE_CAPTURED) {
  451. // for reasons unknown to mankind, wheel comes in screen cordinates
  452. POINT coords;
  453. coords.x = mb->get_position().x;
  454. coords.y = mb->get_position().y;
  455. ScreenToClient(hWnd, &coords);
  456. mb->set_position(Vector2(coords.x, coords.y));
  457. }
  458. mb->set_global_position(mb->get_position());
  459. if (main_loop) {
  460. input->parse_input_event(mb);
  461. if (mb->is_pressed() && mb->get_button_index() > 3) {
  462. //send release for mouse wheel
  463. Ref<InputEventMouseButton> mbd = mb->duplicate();
  464. mbd->set_pressed(false);
  465. input->parse_input_event(mbd);
  466. }
  467. }
  468. }
  469. break;
  470. case WM_SIZE: {
  471. int window_w = LOWORD(lParam);
  472. int window_h = HIWORD(lParam);
  473. if (window_w > 0 && window_h > 0) {
  474. video_mode.width = window_w;
  475. video_mode.height = window_h;
  476. }
  477. //return 0; // Jump Back
  478. } break;
  479. case WM_ENTERSIZEMOVE: {
  480. move_timer_id = SetTimer(hWnd, 1, USER_TIMER_MINIMUM, (TIMERPROC)NULL);
  481. } break;
  482. case WM_EXITSIZEMOVE: {
  483. KillTimer(hWnd, move_timer_id);
  484. } break;
  485. case WM_TIMER: {
  486. if (wParam == move_timer_id) {
  487. process_key_events();
  488. Main::iteration();
  489. }
  490. } break;
  491. case WM_SYSKEYDOWN:
  492. case WM_SYSKEYUP:
  493. case WM_KEYUP:
  494. case WM_KEYDOWN: {
  495. if (wParam == VK_SHIFT)
  496. shift_mem = uMsg == WM_KEYDOWN;
  497. if (wParam == VK_CONTROL)
  498. control_mem = uMsg == WM_KEYDOWN;
  499. if (wParam == VK_MENU) {
  500. alt_mem = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN);
  501. if (lParam & (1 << 24))
  502. gr_mem = alt_mem;
  503. }
  504. /*
  505. if (wParam==VK_WIN) TODO wtf is this?
  506. meta_mem=uMsg==WM_KEYDOWN;
  507. */
  508. } //fallthrough
  509. case WM_CHAR: {
  510. ERR_BREAK(key_event_pos >= KEY_EVENT_BUFFER_SIZE);
  511. // Make sure we don't include modifiers for the modifier key itself.
  512. KeyEvent ke;
  513. ke.shift = (wParam != VK_SHIFT) ? shift_mem : false;
  514. ke.alt = (!(wParam == VK_MENU && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN))) ? alt_mem : false;
  515. ke.control = (wParam != VK_CONTROL) ? control_mem : false;
  516. ke.meta = meta_mem;
  517. ke.uMsg = uMsg;
  518. if (ke.uMsg == WM_SYSKEYDOWN)
  519. ke.uMsg = WM_KEYDOWN;
  520. if (ke.uMsg == WM_SYSKEYUP)
  521. ke.uMsg = WM_KEYUP;
  522. /*if (ke.uMsg==WM_KEYDOWN && alt_mem && uMsg!=WM_SYSKEYDOWN) {
  523. //altgr hack for intl keyboards, not sure how good it is
  524. //windows is weeeeird
  525. ke.mod_state.alt=false;
  526. ke.mod_state.control=false;
  527. print_line("")
  528. }*/
  529. ke.wParam = wParam;
  530. ke.lParam = lParam;
  531. key_event_buffer[key_event_pos++] = ke;
  532. } break;
  533. case WM_INPUTLANGCHANGEREQUEST: {
  534. print_line("input lang change");
  535. } break;
  536. #if WINVER >= 0x0601 // for windows 7
  537. case WM_TOUCH: {
  538. BOOL bHandled = FALSE;
  539. UINT cInputs = LOWORD(wParam);
  540. PTOUCHINPUT pInputs = memnew_arr(TOUCHINPUT, cInputs);
  541. if (pInputs) {
  542. if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs, sizeof(TOUCHINPUT))) {
  543. for (UINT i = 0; i < cInputs; i++) {
  544. TOUCHINPUT ti = pInputs[i];
  545. //do something with each touch input entry
  546. if (ti.dwFlags & TOUCHEVENTF_MOVE) {
  547. _drag_event(ti.x / 100, ti.y / 100, ti.dwID);
  548. } else if (ti.dwFlags & (TOUCHEVENTF_UP | TOUCHEVENTF_DOWN)) {
  549. _touch_event(ti.dwFlags & TOUCHEVENTF_DOWN != 0, ti.x / 100, ti.y / 100, ti.dwID);
  550. };
  551. }
  552. bHandled = TRUE;
  553. } else {
  554. /* handle the error here */
  555. }
  556. memdelete_arr(pInputs);
  557. } else {
  558. /* handle the error here, probably out of memory */
  559. }
  560. if (bHandled) {
  561. CloseTouchInputHandle((HTOUCHINPUT)lParam);
  562. return 0;
  563. };
  564. } break;
  565. #endif
  566. case WM_DEVICECHANGE: {
  567. joypad->probe_joypads();
  568. } break;
  569. case WM_SETCURSOR: {
  570. if (LOWORD(lParam) == HTCLIENT) {
  571. if (window_has_focus && (mouse_mode == MOUSE_MODE_HIDDEN || mouse_mode == MOUSE_MODE_CAPTURED)) {
  572. //Hide the cursor
  573. if (hCursor == NULL)
  574. hCursor = SetCursor(NULL);
  575. else
  576. SetCursor(NULL);
  577. } else {
  578. if (hCursor != NULL) {
  579. SetCursor(hCursor);
  580. hCursor = NULL;
  581. }
  582. }
  583. }
  584. } break;
  585. case WM_DROPFILES: {
  586. HDROP hDropInfo = (HDROP)wParam;
  587. const int buffsize = 4096;
  588. wchar_t buf[buffsize];
  589. int fcount = DragQueryFileW(hDropInfo, 0xFFFFFFFF, NULL, 0);
  590. Vector<String> files;
  591. for (int i = 0; i < fcount; i++) {
  592. DragQueryFileW(hDropInfo, i, buf, buffsize);
  593. String file = buf;
  594. files.push_back(file);
  595. }
  596. if (files.size() && main_loop) {
  597. main_loop->drop_files(files, 0);
  598. }
  599. } break;
  600. default: {
  601. if (user_proc) {
  602. return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
  603. };
  604. };
  605. }
  606. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  607. }
  608. LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  609. OS_Windows *os_win = static_cast<OS_Windows *>(OS::get_singleton());
  610. if (os_win)
  611. return os_win->WndProc(hWnd, uMsg, wParam, lParam);
  612. else
  613. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  614. }
  615. void OS_Windows::process_key_events() {
  616. for (int i = 0; i < key_event_pos; i++) {
  617. KeyEvent &ke = key_event_buffer[i];
  618. switch (ke.uMsg) {
  619. case WM_CHAR: {
  620. if ((i == 0 && ke.uMsg == WM_CHAR) || (i > 0 && key_event_buffer[i - 1].uMsg == WM_CHAR)) {
  621. Ref<InputEventKey> k;
  622. k.instance();
  623. k->set_shift(ke.shift);
  624. k->set_alt(ke.alt);
  625. k->set_control(ke.control);
  626. k->set_metakey(ke.meta);
  627. k->set_pressed(true);
  628. k->set_scancode(KeyMappingWindows::get_keysym(ke.wParam));
  629. k->set_unicode(ke.wParam);
  630. if (k->get_unicode() && gr_mem) {
  631. k->set_alt(false);
  632. k->set_control(false);
  633. }
  634. if (k->get_unicode() < 32)
  635. k->set_unicode(0);
  636. input->parse_input_event(k);
  637. }
  638. //do nothing
  639. } break;
  640. case WM_KEYUP:
  641. case WM_KEYDOWN: {
  642. Ref<InputEventKey> k;
  643. k.instance();
  644. k->set_shift(ke.shift);
  645. k->set_alt(ke.alt);
  646. k->set_control(ke.control);
  647. k->set_metakey(ke.meta);
  648. k->set_pressed(ke.uMsg == WM_KEYDOWN);
  649. if ((ke.lParam & (1 << 24)) && (ke.wParam == VK_RETURN)) {
  650. // Special case for Numpad Enter key
  651. k->set_scancode(KEY_KP_ENTER);
  652. } else {
  653. k->set_scancode(KeyMappingWindows::get_keysym(ke.wParam));
  654. }
  655. if (i + 1 < key_event_pos && key_event_buffer[i + 1].uMsg == WM_CHAR) {
  656. k->set_unicode(key_event_buffer[i + 1].wParam);
  657. }
  658. if (k->get_unicode() && gr_mem) {
  659. k->set_alt(false);
  660. k->set_control(false);
  661. }
  662. if (k->get_unicode() < 32)
  663. k->set_unicode(0);
  664. k->set_echo((ke.uMsg == WM_KEYDOWN && (ke.lParam & (1 << 30))));
  665. input->parse_input_event(k);
  666. } break;
  667. }
  668. }
  669. key_event_pos = 0;
  670. }
  671. enum _MonitorDpiType {
  672. MDT_Effective_DPI = 0,
  673. MDT_Angular_DPI = 1,
  674. MDT_Raw_DPI = 2,
  675. MDT_Default = MDT_Effective_DPI
  676. };
  677. static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType = MDT_Default) {
  678. int dpiX = 96, dpiY = 96;
  679. static HMODULE Shcore = NULL;
  680. typedef HRESULT(WINAPI * GetDPIForMonitor_t)(HMONITOR hmonitor, _MonitorDpiType dpiType, UINT * dpiX, UINT * dpiY);
  681. static GetDPIForMonitor_t getDPIForMonitor = NULL;
  682. if (Shcore == NULL) {
  683. Shcore = LoadLibraryW(L"Shcore.dll");
  684. getDPIForMonitor = Shcore ? (GetDPIForMonitor_t)GetProcAddress(Shcore, "GetDpiForMonitor") : NULL;
  685. if ((Shcore == NULL) || (getDPIForMonitor == NULL)) {
  686. if (Shcore)
  687. FreeLibrary(Shcore);
  688. Shcore = (HMODULE)INVALID_HANDLE_VALUE;
  689. }
  690. }
  691. UINT x = 0, y = 0;
  692. HRESULT hr = E_FAIL;
  693. bool bSet = false;
  694. if (hmon && (Shcore != (HMODULE)INVALID_HANDLE_VALUE)) {
  695. hr = getDPIForMonitor(hmon, dpiType /*MDT_Effective_DPI*/, &x, &y);
  696. if (SUCCEEDED(hr) && (x > 0) && (y > 0)) {
  697. dpiX = (int)x;
  698. dpiY = (int)y;
  699. }
  700. } else {
  701. static int overallX = 0, overallY = 0;
  702. if (overallX <= 0 || overallY <= 0) {
  703. HDC hdc = GetDC(NULL);
  704. if (hdc) {
  705. overallX = GetDeviceCaps(hdc, LOGPIXELSX);
  706. overallY = GetDeviceCaps(hdc, LOGPIXELSY);
  707. ReleaseDC(NULL, hdc);
  708. }
  709. }
  710. if (overallX > 0 && overallY > 0) {
  711. dpiX = overallX;
  712. dpiY = overallY;
  713. }
  714. }
  715. return (dpiX + dpiY) / 2;
  716. }
  717. typedef enum _SHC_PROCESS_DPI_AWARENESS {
  718. SHC_PROCESS_DPI_UNAWARE = 0,
  719. SHC_PROCESS_SYSTEM_DPI_AWARE = 1,
  720. SHC_PROCESS_PER_MONITOR_DPI_AWARE = 2
  721. } SHC_PROCESS_DPI_AWARENESS;
  722. void OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  723. main_loop = NULL;
  724. outside = true;
  725. window_has_focus = true;
  726. WNDCLASSEXW wc;
  727. if (is_hidpi_allowed()) {
  728. HMODULE Shcore = LoadLibraryW(L"Shcore.dll");
  729. if (Shcore != NULL) {
  730. typedef HRESULT(WINAPI * SetProcessDpiAwareness_t)(SHC_PROCESS_DPI_AWARENESS);
  731. SetProcessDpiAwareness_t SetProcessDpiAwareness = (SetProcessDpiAwareness_t)GetProcAddress(Shcore, "SetProcessDpiAwareness");
  732. if (SetProcessDpiAwareness) {
  733. SetProcessDpiAwareness(SHC_PROCESS_SYSTEM_DPI_AWARE);
  734. }
  735. }
  736. }
  737. video_mode = p_desired;
  738. //printf("**************** desired %s, mode %s\n", p_desired.fullscreen?"true":"false", video_mode.fullscreen?"true":"false");
  739. RECT WindowRect;
  740. WindowRect.left = 0;
  741. WindowRect.right = video_mode.width;
  742. WindowRect.top = 0;
  743. WindowRect.bottom = video_mode.height;
  744. memset(&wc, 0, sizeof(WNDCLASSEXW));
  745. wc.cbSize = sizeof(WNDCLASSEXW);
  746. wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
  747. wc.lpfnWndProc = (WNDPROC)::WndProc;
  748. wc.cbClsExtra = 0;
  749. wc.cbWndExtra = 0;
  750. //wc.hInstance = hInstance;
  751. wc.hInstance = godot_hinstance ? godot_hinstance : GetModuleHandle(NULL);
  752. wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
  753. wc.hCursor = NULL; //LoadCursor(NULL, IDC_ARROW);
  754. wc.hbrBackground = NULL;
  755. wc.lpszMenuName = NULL;
  756. wc.lpszClassName = L"Engine";
  757. if (!RegisterClassExW(&wc)) {
  758. MessageBox(NULL, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
  759. return; // Return
  760. }
  761. pre_fs_valid = true;
  762. if (video_mode.fullscreen) {
  763. DEVMODE current;
  764. memset(&current, 0, sizeof(current));
  765. EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &current);
  766. WindowRect.right = current.dmPelsWidth;
  767. WindowRect.bottom = current.dmPelsHeight;
  768. /* DEVMODE dmScreenSettings;
  769. memset(&dmScreenSettings,0,sizeof(dmScreenSettings));
  770. dmScreenSettings.dmSize=sizeof(dmScreenSettings);
  771. dmScreenSettings.dmPelsWidth = video_mode.width;
  772. dmScreenSettings.dmPelsHeight = video_mode.height;
  773. dmScreenSettings.dmBitsPerPel = current.dmBitsPerPel;
  774. dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
  775. LONG err = ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN);
  776. if (err!=DISP_CHANGE_SUCCESSFUL) {
  777. video_mode.fullscreen=false;
  778. }*/
  779. pre_fs_valid = false;
  780. }
  781. DWORD dwExStyle;
  782. DWORD dwStyle;
  783. if (video_mode.fullscreen || video_mode.borderless_window) {
  784. dwExStyle = WS_EX_APPWINDOW;
  785. dwStyle = WS_POPUP;
  786. } else {
  787. dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  788. dwStyle = WS_OVERLAPPEDWINDOW;
  789. if (!video_mode.resizable) {
  790. dwStyle &= ~WS_THICKFRAME;
  791. dwStyle &= ~WS_MAXIMIZEBOX;
  792. }
  793. }
  794. AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);
  795. char *windowid = getenv("GODOT_WINDOWID");
  796. if (windowid) {
  797. // strtoull on mingw
  798. #ifdef MINGW_ENABLED
  799. hWnd = (HWND)strtoull(windowid, NULL, 0);
  800. #else
  801. hWnd = (HWND)_strtoui64(windowid, NULL, 0);
  802. #endif
  803. SetLastError(0);
  804. user_proc = (WNDPROC)GetWindowLongPtr(hWnd, GWLP_WNDPROC);
  805. SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)(WNDPROC)::WndProc);
  806. DWORD le = GetLastError();
  807. if (user_proc == 0 && le != 0) {
  808. printf("Error setting WNDPROC: %li\n", le);
  809. };
  810. LONG_PTR proc = GetWindowLongPtr(hWnd, GWLP_WNDPROC);
  811. RECT rect;
  812. if (!GetClientRect(hWnd, &rect)) {
  813. MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
  814. return; // Return FALSE
  815. };
  816. video_mode.width = rect.right;
  817. video_mode.height = rect.bottom;
  818. video_mode.fullscreen = false;
  819. } else {
  820. hWnd = CreateWindowExW(
  821. dwExStyle,
  822. L"Engine", L"",
  823. dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
  824. (GetSystemMetrics(SM_CXSCREEN) - WindowRect.right) / 2,
  825. (GetSystemMetrics(SM_CYSCREEN) - WindowRect.bottom) / 2,
  826. WindowRect.right - WindowRect.left,
  827. WindowRect.bottom - WindowRect.top,
  828. NULL, NULL, hInstance, NULL);
  829. if (!hWnd) {
  830. MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
  831. return; // Return FALSE
  832. }
  833. };
  834. #if defined(OPENGL_ENABLED)
  835. gl_context = memnew(ContextGL_Win(hWnd, true));
  836. gl_context->initialize();
  837. RasterizerGLES3::register_config();
  838. RasterizerGLES3::make_current();
  839. #endif
  840. visual_server = memnew(VisualServerRaster);
  841. if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
  842. visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD));
  843. }
  844. if (!is_no_window_mode_enabled()) {
  845. ShowWindow(hWnd, SW_SHOW); // Show The Window
  846. SetForegroundWindow(hWnd); // Slightly Higher Priority
  847. SetFocus(hWnd); // Sets Keyboard Focus To
  848. }
  849. /*
  850. DEVMODE dmScreenSettings; // Device Mode
  851. memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
  852. dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
  853. dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
  854. dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
  855. dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
  856. dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
  857. if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
  858. */
  859. visual_server->init();
  860. input = memnew(InputDefault);
  861. joypad = memnew(JoypadWindows(input, &hWnd));
  862. power_manager = memnew(PowerWindows);
  863. AudioDriverManager::initialize(p_audio_driver);
  864. TRACKMOUSEEVENT tme;
  865. tme.cbSize = sizeof(TRACKMOUSEEVENT);
  866. tme.dwFlags = TME_LEAVE;
  867. tme.hwndTrack = hWnd;
  868. tme.dwHoverTime = HOVER_DEFAULT;
  869. TrackMouseEvent(&tme);
  870. //RegisterTouchWindow(hWnd, 0); // Windows 7
  871. _ensure_data_dir();
  872. DragAcceptFiles(hWnd, true);
  873. move_timer_id = 1;
  874. }
  875. void OS_Windows::set_clipboard(const String &p_text) {
  876. if (!OpenClipboard(hWnd)) {
  877. ERR_EXPLAIN("Unable to open clipboard.");
  878. ERR_FAIL();
  879. };
  880. EmptyClipboard();
  881. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, (p_text.length() + 1) * sizeof(CharType));
  882. if (mem == NULL) {
  883. ERR_EXPLAIN("Unable to allocate memory for clipboard contents.");
  884. ERR_FAIL();
  885. };
  886. LPWSTR lptstrCopy = (LPWSTR)GlobalLock(mem);
  887. memcpy(lptstrCopy, p_text.c_str(), (p_text.length() + 1) * sizeof(CharType));
  888. //memset((lptstrCopy + p_text.length()), 0, sizeof(CharType));
  889. GlobalUnlock(mem);
  890. SetClipboardData(CF_UNICODETEXT, mem);
  891. // set the CF_TEXT version (not needed?)
  892. CharString utf8 = p_text.utf8();
  893. mem = GlobalAlloc(GMEM_MOVEABLE, utf8.length() + 1);
  894. if (mem == NULL) {
  895. ERR_EXPLAIN("Unable to allocate memory for clipboard contents.");
  896. ERR_FAIL();
  897. };
  898. LPTSTR ptr = (LPTSTR)GlobalLock(mem);
  899. memcpy(ptr, utf8.get_data(), utf8.length());
  900. ptr[utf8.length()] = 0;
  901. GlobalUnlock(mem);
  902. SetClipboardData(CF_TEXT, mem);
  903. CloseClipboard();
  904. };
  905. String OS_Windows::get_clipboard() const {
  906. String ret;
  907. if (!OpenClipboard(hWnd)) {
  908. ERR_EXPLAIN("Unable to open clipboard.");
  909. ERR_FAIL_V("");
  910. };
  911. if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
  912. HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
  913. if (mem != NULL) {
  914. LPWSTR ptr = (LPWSTR)GlobalLock(mem);
  915. if (ptr != NULL) {
  916. ret = String((CharType *)ptr);
  917. GlobalUnlock(mem);
  918. };
  919. };
  920. } else if (IsClipboardFormatAvailable(CF_TEXT)) {
  921. HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
  922. if (mem != NULL) {
  923. LPTSTR ptr = (LPTSTR)GlobalLock(mem);
  924. if (ptr != NULL) {
  925. ret.parse_utf8((const char *)ptr);
  926. GlobalUnlock(mem);
  927. };
  928. };
  929. };
  930. CloseClipboard();
  931. return ret;
  932. };
  933. void OS_Windows::delete_main_loop() {
  934. if (main_loop)
  935. memdelete(main_loop);
  936. main_loop = NULL;
  937. }
  938. void OS_Windows::set_main_loop(MainLoop *p_main_loop) {
  939. input->set_main_loop(p_main_loop);
  940. main_loop = p_main_loop;
  941. }
  942. void OS_Windows::finalize() {
  943. if (main_loop)
  944. memdelete(main_loop);
  945. main_loop = NULL;
  946. memdelete(joypad);
  947. memdelete(input);
  948. visual_server->finish();
  949. memdelete(visual_server);
  950. #ifdef OPENGL_ENABLED
  951. if (gl_context)
  952. memdelete(gl_context);
  953. #endif
  954. if (user_proc) {
  955. SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)user_proc);
  956. };
  957. /*
  958. if (debugger_connection_console) {
  959. memdelete(debugger_connection_console);
  960. }
  961. */
  962. }
  963. void OS_Windows::finalize_core() {
  964. memdelete(process_map);
  965. TCPServerWinsock::cleanup();
  966. StreamPeerWinsock::cleanup();
  967. }
  968. void OS_Windows::alert(const String &p_alert, const String &p_title) {
  969. if (!is_no_window_mode_enabled())
  970. MessageBoxW(NULL, p_alert.c_str(), p_title.c_str(), MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
  971. else
  972. print_line("ALERT: " + p_alert);
  973. }
  974. void OS_Windows::set_mouse_mode(MouseMode p_mode) {
  975. if (mouse_mode == p_mode)
  976. return;
  977. mouse_mode = p_mode;
  978. if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
  979. RECT clipRect;
  980. GetClientRect(hWnd, &clipRect);
  981. ClientToScreen(hWnd, (POINT *)&clipRect.left);
  982. ClientToScreen(hWnd, (POINT *)&clipRect.right);
  983. ClipCursor(&clipRect);
  984. center = Point2i(video_mode.width / 2, video_mode.height / 2);
  985. POINT pos = { (int)center.x, (int)center.y };
  986. ClientToScreen(hWnd, &pos);
  987. if (mouse_mode == MOUSE_MODE_CAPTURED)
  988. SetCursorPos(pos.x, pos.y);
  989. } else {
  990. ReleaseCapture();
  991. ClipCursor(NULL);
  992. }
  993. if (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_HIDDEN) {
  994. hCursor = SetCursor(NULL);
  995. } else {
  996. SetCursor(hCursor);
  997. }
  998. }
  999. OS_Windows::MouseMode OS_Windows::get_mouse_mode() const {
  1000. return mouse_mode;
  1001. }
  1002. void OS_Windows::warp_mouse_position(const Point2 &p_to) {
  1003. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  1004. old_x = p_to.x;
  1005. old_y = p_to.y;
  1006. } else {
  1007. POINT p;
  1008. p.x = p_to.x;
  1009. p.y = p_to.y;
  1010. ClientToScreen(hWnd, &p);
  1011. SetCursorPos(p.x, p.y);
  1012. }
  1013. }
  1014. Point2 OS_Windows::get_mouse_position() const {
  1015. return Point2(old_x, old_y);
  1016. }
  1017. int OS_Windows::get_mouse_button_state() const {
  1018. return last_button_state;
  1019. }
  1020. void OS_Windows::set_window_title(const String &p_title) {
  1021. SetWindowTextW(hWnd, p_title.c_str());
  1022. }
  1023. void OS_Windows::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  1024. }
  1025. OS::VideoMode OS_Windows::get_video_mode(int p_screen) const {
  1026. return video_mode;
  1027. }
  1028. void OS_Windows::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  1029. }
  1030. static BOOL CALLBACK _MonitorEnumProcCount(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1031. int *data = (int *)dwData;
  1032. (*data)++;
  1033. return TRUE;
  1034. }
  1035. int OS_Windows::get_screen_count() const {
  1036. int data = 0;
  1037. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcCount, (LPARAM)&data);
  1038. return data;
  1039. }
  1040. typedef struct {
  1041. int count;
  1042. int screen;
  1043. HMONITOR monitor;
  1044. } EnumScreenData;
  1045. static BOOL CALLBACK _MonitorEnumProcScreen(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1046. EnumScreenData *data = (EnumScreenData *)dwData;
  1047. if (data->monitor == hMonitor) {
  1048. data->screen = data->count;
  1049. }
  1050. data->count++;
  1051. return TRUE;
  1052. }
  1053. int OS_Windows::get_current_screen() const {
  1054. EnumScreenData data = { 0, 0, MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST) };
  1055. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcScreen, (LPARAM)&data);
  1056. return data.screen;
  1057. }
  1058. void OS_Windows::set_current_screen(int p_screen) {
  1059. Vector2 ofs = get_window_position() - get_screen_position(get_current_screen());
  1060. set_window_position(ofs + get_screen_position(p_screen));
  1061. }
  1062. typedef struct {
  1063. int count;
  1064. int screen;
  1065. Point2 pos;
  1066. } EnumPosData;
  1067. static BOOL CALLBACK _MonitorEnumProcPos(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1068. EnumPosData *data = (EnumPosData *)dwData;
  1069. if (data->count == data->screen) {
  1070. data->pos.x = lprcMonitor->left;
  1071. data->pos.y = lprcMonitor->top;
  1072. }
  1073. data->count++;
  1074. return TRUE;
  1075. }
  1076. Point2 OS_Windows::get_screen_position(int p_screen) const {
  1077. EnumPosData data = { 0, p_screen == -1 ? get_current_screen() : p_screen, Point2() };
  1078. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcPos, (LPARAM)&data);
  1079. return data.pos;
  1080. }
  1081. typedef struct {
  1082. int count;
  1083. int screen;
  1084. Size2 size;
  1085. } EnumSizeData;
  1086. static BOOL CALLBACK _MonitorEnumProcSize(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1087. EnumSizeData *data = (EnumSizeData *)dwData;
  1088. if (data->count == data->screen) {
  1089. data->size.x = lprcMonitor->right - lprcMonitor->left;
  1090. data->size.y = lprcMonitor->bottom - lprcMonitor->top;
  1091. }
  1092. data->count++;
  1093. return TRUE;
  1094. }
  1095. Size2 OS_Windows::get_screen_size(int p_screen) const {
  1096. EnumSizeData data = { 0, p_screen == -1 ? get_current_screen() : p_screen, Size2() };
  1097. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcSize, (LPARAM)&data);
  1098. return data.size;
  1099. }
  1100. typedef struct {
  1101. int count;
  1102. int screen;
  1103. int dpi;
  1104. } EnumDpiData;
  1105. static BOOL CALLBACK _MonitorEnumProcDpi(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1106. EnumDpiData *data = (EnumDpiData *)dwData;
  1107. if (data->count == data->screen) {
  1108. data->dpi = QueryDpiForMonitor(hMonitor);
  1109. }
  1110. data->count++;
  1111. return TRUE;
  1112. }
  1113. int OS_Windows::get_screen_dpi(int p_screen) const {
  1114. EnumDpiData data = { 0, p_screen == -1 ? get_current_screen() : p_screen, 72 };
  1115. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcDpi, (LPARAM)&data);
  1116. return data.dpi;
  1117. }
  1118. Point2 OS_Windows::get_window_position() const {
  1119. RECT r;
  1120. GetWindowRect(hWnd, &r);
  1121. return Point2(r.left, r.top);
  1122. }
  1123. void OS_Windows::set_window_position(const Point2 &p_position) {
  1124. if (video_mode.fullscreen) return;
  1125. RECT r;
  1126. GetWindowRect(hWnd, &r);
  1127. MoveWindow(hWnd, p_position.x, p_position.y, r.right - r.left, r.bottom - r.top, TRUE);
  1128. }
  1129. Size2 OS_Windows::get_window_size() const {
  1130. RECT r;
  1131. GetClientRect(hWnd, &r);
  1132. return Vector2(r.right - r.left, r.bottom - r.top);
  1133. }
  1134. void OS_Windows::set_window_size(const Size2 p_size) {
  1135. video_mode.width = p_size.width;
  1136. video_mode.height = p_size.height;
  1137. if (video_mode.fullscreen) {
  1138. return;
  1139. }
  1140. int w = p_size.width;
  1141. int h = p_size.height;
  1142. RECT rect;
  1143. GetWindowRect(hWnd, &rect);
  1144. if (video_mode.borderless_window == false) {
  1145. RECT crect;
  1146. GetClientRect(hWnd, &crect);
  1147. w += (rect.right - rect.left) - (crect.right - crect.left);
  1148. h += (rect.bottom - rect.top) - (crect.bottom - crect.top);
  1149. }
  1150. MoveWindow(hWnd, rect.left, rect.top, w, h, TRUE);
  1151. }
  1152. void OS_Windows::set_window_fullscreen(bool p_enabled) {
  1153. if (video_mode.fullscreen == p_enabled)
  1154. return;
  1155. if (p_enabled) {
  1156. if (pre_fs_valid) {
  1157. GetWindowRect(hWnd, &pre_fs_rect);
  1158. //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));
  1159. //MapWindowPoints(hWnd, GetParent(hWnd), (LPPOINT) &pre_fs_rect, 2);
  1160. //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));
  1161. }
  1162. int cs = get_current_screen();
  1163. Point2 pos = get_screen_position(cs);
  1164. Size2 size = get_screen_size(cs);
  1165. video_mode.fullscreen = true;
  1166. _update_window_style(false);
  1167. MoveWindow(hWnd, pos.x, pos.y, size.width, size.height, TRUE);
  1168. } else {
  1169. RECT rect;
  1170. video_mode.fullscreen = false;
  1171. if (pre_fs_valid) {
  1172. rect = pre_fs_rect;
  1173. } else {
  1174. rect.left = 0;
  1175. rect.right = video_mode.width;
  1176. rect.top = 0;
  1177. rect.bottom = video_mode.height;
  1178. }
  1179. _update_window_style(false);
  1180. MoveWindow(hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
  1181. pre_fs_valid = true;
  1182. }
  1183. }
  1184. bool OS_Windows::is_window_fullscreen() const {
  1185. return video_mode.fullscreen;
  1186. }
  1187. void OS_Windows::set_window_resizable(bool p_enabled) {
  1188. if (video_mode.resizable == p_enabled)
  1189. return;
  1190. video_mode.resizable = p_enabled;
  1191. _update_window_style();
  1192. }
  1193. bool OS_Windows::is_window_resizable() const {
  1194. return video_mode.resizable;
  1195. }
  1196. void OS_Windows::set_window_minimized(bool p_enabled) {
  1197. if (p_enabled) {
  1198. maximized = false;
  1199. minimized = true;
  1200. ShowWindow(hWnd, SW_MINIMIZE);
  1201. } else {
  1202. ShowWindow(hWnd, SW_RESTORE);
  1203. maximized = false;
  1204. minimized = false;
  1205. }
  1206. }
  1207. bool OS_Windows::is_window_minimized() const {
  1208. return minimized;
  1209. }
  1210. void OS_Windows::set_window_maximized(bool p_enabled) {
  1211. if (p_enabled) {
  1212. maximized = true;
  1213. minimized = false;
  1214. ShowWindow(hWnd, SW_MAXIMIZE);
  1215. } else {
  1216. ShowWindow(hWnd, SW_RESTORE);
  1217. maximized = false;
  1218. minimized = false;
  1219. }
  1220. }
  1221. bool OS_Windows::is_window_maximized() const {
  1222. return maximized;
  1223. }
  1224. void OS_Windows::set_borderless_window(int p_borderless) {
  1225. if (video_mode.borderless_window == p_borderless)
  1226. return;
  1227. video_mode.borderless_window = p_borderless;
  1228. _update_window_style();
  1229. }
  1230. bool OS_Windows::get_borderless_window() {
  1231. return video_mode.borderless_window;
  1232. }
  1233. void OS_Windows::_update_window_style(bool repaint) {
  1234. if (video_mode.fullscreen || video_mode.borderless_window) {
  1235. SetWindowLongPtr(hWnd, GWL_STYLE, WS_SYSMENU | WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE);
  1236. } else {
  1237. if (video_mode.resizable) {
  1238. SetWindowLongPtr(hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE);
  1239. } else {
  1240. SetWindowLongPtr(hWnd, GWL_STYLE, WS_CAPTION | WS_MINIMIZEBOX | WS_POPUPWINDOW | WS_VISIBLE);
  1241. }
  1242. }
  1243. if (repaint) {
  1244. RECT rect;
  1245. GetWindowRect(hWnd, &rect);
  1246. MoveWindow(hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
  1247. }
  1248. }
  1249. Error OS_Windows::open_dynamic_library(const String p_path, void *&p_library_handle) {
  1250. p_library_handle = (void *)LoadLibrary(p_path.utf8().get_data());
  1251. if (!p_library_handle) {
  1252. ERR_EXPLAIN("Can't open dynamic library: " + p_path + ". Error: " + String::num(GetLastError()));
  1253. ERR_FAIL_V(ERR_CANT_OPEN);
  1254. }
  1255. return OK;
  1256. }
  1257. Error OS_Windows::close_dynamic_library(void *p_library_handle) {
  1258. if (!FreeLibrary((HMODULE)p_library_handle)) {
  1259. return FAILED;
  1260. }
  1261. return OK;
  1262. }
  1263. Error OS_Windows::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  1264. p_symbol_handle = (void *)GetProcAddress((HMODULE)p_library_handle, p_name.utf8().get_data());
  1265. if (!p_symbol_handle) {
  1266. if (!p_optional) {
  1267. ERR_EXPLAIN("Can't resolve symbol " + p_name + ". Error: " + String::num(GetLastError()));
  1268. ERR_FAIL_V(ERR_CANT_RESOLVE);
  1269. } else {
  1270. return ERR_CANT_RESOLVE;
  1271. }
  1272. }
  1273. return OK;
  1274. }
  1275. void OS_Windows::request_attention() {
  1276. FLASHWINFO info;
  1277. info.cbSize = sizeof(FLASHWINFO);
  1278. info.hwnd = hWnd;
  1279. info.dwFlags = FLASHW_TRAY;
  1280. info.dwTimeout = 0;
  1281. info.uCount = 2;
  1282. FlashWindowEx(&info);
  1283. }
  1284. String OS_Windows::get_name() {
  1285. return "Windows";
  1286. }
  1287. OS::Date OS_Windows::get_date(bool utc) const {
  1288. SYSTEMTIME systemtime;
  1289. if (utc)
  1290. GetSystemTime(&systemtime);
  1291. else
  1292. GetLocalTime(&systemtime);
  1293. Date date;
  1294. date.day = systemtime.wDay;
  1295. date.month = Month(systemtime.wMonth);
  1296. date.weekday = Weekday(systemtime.wDayOfWeek);
  1297. date.year = systemtime.wYear;
  1298. date.dst = false;
  1299. return date;
  1300. }
  1301. OS::Time OS_Windows::get_time(bool utc) const {
  1302. SYSTEMTIME systemtime;
  1303. if (utc)
  1304. GetSystemTime(&systemtime);
  1305. else
  1306. GetLocalTime(&systemtime);
  1307. Time time;
  1308. time.hour = systemtime.wHour;
  1309. time.min = systemtime.wMinute;
  1310. time.sec = systemtime.wSecond;
  1311. return time;
  1312. }
  1313. OS::TimeZoneInfo OS_Windows::get_time_zone_info() const {
  1314. TIME_ZONE_INFORMATION info;
  1315. bool daylight = false;
  1316. if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT)
  1317. daylight = true;
  1318. TimeZoneInfo ret;
  1319. if (daylight) {
  1320. ret.name = info.DaylightName;
  1321. } else {
  1322. ret.name = info.StandardName;
  1323. }
  1324. ret.bias = info.Bias;
  1325. return ret;
  1326. }
  1327. uint64_t OS_Windows::get_unix_time() const {
  1328. FILETIME ft;
  1329. SYSTEMTIME st;
  1330. GetSystemTime(&st);
  1331. SystemTimeToFileTime(&st, &ft);
  1332. SYSTEMTIME ep;
  1333. ep.wYear = 1970;
  1334. ep.wMonth = 1;
  1335. ep.wDayOfWeek = 4;
  1336. ep.wDay = 1;
  1337. ep.wHour = 0;
  1338. ep.wMinute = 0;
  1339. ep.wSecond = 0;
  1340. ep.wMilliseconds = 0;
  1341. FILETIME fep;
  1342. SystemTimeToFileTime(&ep, &fep);
  1343. return (*(uint64_t *)&ft - *(uint64_t *)&fep) / 10000000;
  1344. };
  1345. uint64_t OS_Windows::get_system_time_secs() const {
  1346. const uint64_t WINDOWS_TICK = 10000000;
  1347. const uint64_t SEC_TO_UNIX_EPOCH = 11644473600LL;
  1348. SYSTEMTIME st;
  1349. GetSystemTime(&st);
  1350. FILETIME ft;
  1351. SystemTimeToFileTime(&st, &ft);
  1352. uint64_t ret;
  1353. ret = ft.dwHighDateTime;
  1354. ret <<= 32;
  1355. ret |= ft.dwLowDateTime;
  1356. return (uint64_t)(ret / WINDOWS_TICK - SEC_TO_UNIX_EPOCH);
  1357. }
  1358. void OS_Windows::delay_usec(uint32_t p_usec) const {
  1359. if (p_usec < 1000)
  1360. Sleep(1);
  1361. else
  1362. Sleep(p_usec / 1000);
  1363. }
  1364. uint64_t OS_Windows::get_ticks_usec() const {
  1365. uint64_t ticks;
  1366. uint64_t time;
  1367. // This is the number of clock ticks since start
  1368. if (!QueryPerformanceCounter((LARGE_INTEGER *)&ticks))
  1369. ticks = (UINT64)timeGetTime();
  1370. // Divide by frequency to get the time in seconds
  1371. time = ticks * 1000000L / ticks_per_second;
  1372. // Subtract the time at game start to get
  1373. // the time since the game started
  1374. time -= ticks_start;
  1375. return time;
  1376. }
  1377. void OS_Windows::process_events() {
  1378. MSG msg;
  1379. joypad->process_joypads();
  1380. while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
  1381. TranslateMessage(&msg);
  1382. DispatchMessageW(&msg);
  1383. }
  1384. process_key_events();
  1385. }
  1386. void OS_Windows::set_cursor_shape(CursorShape p_shape) {
  1387. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  1388. if (cursor_shape == p_shape)
  1389. return;
  1390. static const LPCTSTR win_cursors[CURSOR_MAX] = {
  1391. IDC_ARROW,
  1392. IDC_IBEAM,
  1393. IDC_HAND, //finger
  1394. IDC_CROSS,
  1395. IDC_WAIT,
  1396. IDC_APPSTARTING,
  1397. IDC_ARROW,
  1398. IDC_ARROW,
  1399. IDC_NO,
  1400. IDC_SIZENS,
  1401. IDC_SIZEWE,
  1402. IDC_SIZENESW,
  1403. IDC_SIZENWSE,
  1404. IDC_SIZEALL,
  1405. IDC_SIZENS,
  1406. IDC_SIZEWE,
  1407. IDC_HELP
  1408. };
  1409. SetCursor(LoadCursor(hInstance, win_cursors[p_shape]));
  1410. cursor_shape = p_shape;
  1411. }
  1412. 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) {
  1413. if (p_blocking && r_pipe) {
  1414. String argss;
  1415. argss = "\"\"" + p_path + "\"";
  1416. for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
  1417. argss += String(" \"") + E->get() + "\"";
  1418. }
  1419. //print_line("ARGS: "+argss);
  1420. //argss+"\"";
  1421. //argss+=" 2>nul";
  1422. FILE *f = _wpopen(argss.c_str(), L"r");
  1423. ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
  1424. char buf[65535];
  1425. while (fgets(buf, 65535, f)) {
  1426. (*r_pipe) += buf;
  1427. }
  1428. int rv = _pclose(f);
  1429. if (r_exitcode)
  1430. *r_exitcode = rv;
  1431. return OK;
  1432. }
  1433. String cmdline = "\"" + p_path + "\"";
  1434. const List<String>::Element *I = p_arguments.front();
  1435. while (I) {
  1436. cmdline += " \"" + I->get() + "\"";
  1437. I = I->next();
  1438. };
  1439. //cmdline+="\"";
  1440. ProcessInfo pi;
  1441. ZeroMemory(&pi.si, sizeof(pi.si));
  1442. pi.si.cb = sizeof(pi.si);
  1443. ZeroMemory(&pi.pi, sizeof(pi.pi));
  1444. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si;
  1445. print_line("running cmdline: " + cmdline);
  1446. Vector<CharType> modstr; //windows wants to change this no idea why
  1447. modstr.resize(cmdline.size());
  1448. for (int i = 0; i < cmdline.size(); i++)
  1449. modstr[i] = cmdline[i];
  1450. int ret = CreateProcessW(NULL, modstr.ptr(), NULL, NULL, 0, NORMAL_PRIORITY_CLASS, NULL, NULL, si_w, &pi.pi);
  1451. ERR_FAIL_COND_V(ret == 0, ERR_CANT_FORK);
  1452. if (p_blocking) {
  1453. DWORD ret = WaitForSingleObject(pi.pi.hProcess, INFINITE);
  1454. if (r_exitcode)
  1455. *r_exitcode = ret;
  1456. } else {
  1457. ProcessID pid = pi.pi.dwProcessId;
  1458. if (r_child_id) {
  1459. *r_child_id = pid;
  1460. };
  1461. process_map->insert(pid, pi);
  1462. };
  1463. return OK;
  1464. };
  1465. Error OS_Windows::kill(const ProcessID &p_pid) {
  1466. HANDLE h;
  1467. if (process_map->has(p_pid)) {
  1468. h = (*process_map)[p_pid].pi.hProcess;
  1469. process_map->erase(p_pid);
  1470. } else {
  1471. ERR_FAIL_COND_V(!process_map->has(p_pid), FAILED);
  1472. };
  1473. int ret = TerminateProcess(h, 0);
  1474. return ret != 0 ? OK : FAILED;
  1475. };
  1476. int OS_Windows::get_process_id() const {
  1477. return _getpid();
  1478. }
  1479. Error OS_Windows::set_cwd(const String &p_cwd) {
  1480. if (_wchdir(p_cwd.c_str()) != 0)
  1481. return ERR_CANT_OPEN;
  1482. return OK;
  1483. }
  1484. String OS_Windows::get_executable_path() const {
  1485. wchar_t bufname[4096];
  1486. GetModuleFileNameW(NULL, bufname, 4096);
  1487. String s = bufname;
  1488. return s;
  1489. }
  1490. void OS_Windows::set_icon(const Ref<Image> &p_icon) {
  1491. ERR_FAIL_COND(!p_icon.is_valid());
  1492. Ref<Image> icon = p_icon->duplicate();
  1493. if (icon->get_format() != Image::FORMAT_RGBA8)
  1494. icon->convert(Image::FORMAT_RGBA8);
  1495. int w = icon->get_width();
  1496. int h = icon->get_height();
  1497. /* Create temporary bitmap buffer */
  1498. int icon_len = 40 + h * w * 4;
  1499. Vector<BYTE> v;
  1500. v.resize(icon_len);
  1501. BYTE *icon_bmp = &v[0];
  1502. encode_uint32(40, &icon_bmp[0]);
  1503. encode_uint32(w, &icon_bmp[4]);
  1504. encode_uint32(h * 2, &icon_bmp[8]);
  1505. encode_uint16(1, &icon_bmp[12]);
  1506. encode_uint16(32, &icon_bmp[14]);
  1507. encode_uint32(BI_RGB, &icon_bmp[16]);
  1508. encode_uint32(w * h * 4, &icon_bmp[20]);
  1509. encode_uint32(0, &icon_bmp[24]);
  1510. encode_uint32(0, &icon_bmp[28]);
  1511. encode_uint32(0, &icon_bmp[32]);
  1512. encode_uint32(0, &icon_bmp[36]);
  1513. uint8_t *wr = &icon_bmp[40];
  1514. PoolVector<uint8_t>::Read r = icon->get_data().read();
  1515. for (int i = 0; i < h; i++) {
  1516. for (int j = 0; j < w; j++) {
  1517. const uint8_t *rpx = &r[((h - i - 1) * w + j) * 4];
  1518. uint8_t *wpx = &wr[(i * w + j) * 4];
  1519. wpx[0] = rpx[2];
  1520. wpx[1] = rpx[1];
  1521. wpx[2] = rpx[0];
  1522. wpx[3] = rpx[3];
  1523. }
  1524. }
  1525. HICON hicon = CreateIconFromResource(icon_bmp, icon_len, TRUE, 0x00030000);
  1526. /* Set the icon for the window */
  1527. SendMessage(hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hicon);
  1528. /* Set the icon in the task manager (should we do this?) */
  1529. SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hicon);
  1530. }
  1531. bool OS_Windows::has_environment(const String &p_var) const {
  1532. return getenv(p_var.utf8().get_data()) != NULL;
  1533. };
  1534. String OS_Windows::get_environment(const String &p_var) const {
  1535. wchar_t wval[0x7Fff]; // MSDN says 32767 char is the maximum
  1536. int wlen = GetEnvironmentVariableW(p_var.c_str(), wval, 0x7Fff);
  1537. if (wlen > 0) {
  1538. return wval;
  1539. }
  1540. return "";
  1541. }
  1542. String OS_Windows::get_stdin_string(bool p_block) {
  1543. if (p_block) {
  1544. char buff[1024];
  1545. return fgets(buff, 1024, stdin);
  1546. };
  1547. return String();
  1548. }
  1549. void OS_Windows::enable_for_stealing_focus(ProcessID pid) {
  1550. AllowSetForegroundWindow(pid);
  1551. }
  1552. void OS_Windows::move_window_to_foreground() {
  1553. SetForegroundWindow(hWnd);
  1554. }
  1555. Error OS_Windows::shell_open(String p_uri) {
  1556. ShellExecuteW(NULL, L"open", p_uri.c_str(), NULL, NULL, SW_SHOWNORMAL);
  1557. return OK;
  1558. }
  1559. String OS_Windows::get_locale() const {
  1560. const _WinLocale *wl = &_win_locales[0];
  1561. LANGID langid = GetUserDefaultUILanguage();
  1562. String neutral;
  1563. int lang = langid & ((1 << 9) - 1);
  1564. int sublang = langid & ~((1 << 9) - 1);
  1565. while (wl->locale) {
  1566. if (wl->main_lang == lang && wl->sublang == SUBLANG_NEUTRAL)
  1567. neutral = wl->locale;
  1568. if (lang == wl->main_lang && sublang == wl->sublang)
  1569. return wl->locale;
  1570. wl++;
  1571. }
  1572. if (neutral != "")
  1573. return neutral;
  1574. return "en";
  1575. }
  1576. OS::LatinKeyboardVariant OS_Windows::get_latin_keyboard_variant() const {
  1577. unsigned long azerty[] = {
  1578. 0x00020401, // Arabic (102) AZERTY
  1579. 0x0001080c, // Belgian (Comma)
  1580. 0x0000080c, // Belgian French
  1581. 0x0000040c, // French
  1582. 0 // <--- STOP MARK
  1583. };
  1584. unsigned long qwertz[] = {
  1585. 0x0000041a, // Croation
  1586. 0x00000405, // Czech
  1587. 0x00000407, // German
  1588. 0x00010407, // German (IBM)
  1589. 0x0000040e, // Hungarian
  1590. 0x0000046e, // Luxembourgish
  1591. 0x00010415, // Polish (214)
  1592. 0x00000418, // Romanian (Legacy)
  1593. 0x0000081a, // Serbian (Latin)
  1594. 0x0000041b, // Slovak
  1595. 0x00000424, // Slovenian
  1596. 0x0001042e, // Sorbian Extended
  1597. 0x0002042e, // Sorbian Standard
  1598. 0x0000042e, // Sorbian Standard (Legacy)
  1599. 0x0000100c, // Swiss French
  1600. 0x00000807, // Swiss German
  1601. 0 // <--- STOP MARK
  1602. };
  1603. unsigned long dvorak[] = {
  1604. 0x00010409, // US-Dvorak
  1605. 0x00030409, // US-Dvorak for left hand
  1606. 0x00040409, // US-Dvorak for right hand
  1607. 0 // <--- STOP MARK
  1608. };
  1609. char name[KL_NAMELENGTH + 1];
  1610. name[0] = 0;
  1611. GetKeyboardLayoutNameA(name);
  1612. unsigned long hex = strtoul(name, NULL, 16);
  1613. int i = 0;
  1614. while (azerty[i] != 0) {
  1615. if (azerty[i] == hex) return LATIN_KEYBOARD_AZERTY;
  1616. i++;
  1617. }
  1618. i = 0;
  1619. while (qwertz[i] != 0) {
  1620. if (qwertz[i] == hex) return LATIN_KEYBOARD_QWERTZ;
  1621. i++;
  1622. }
  1623. i = 0;
  1624. while (dvorak[i] != 0) {
  1625. if (dvorak[i] == hex) return LATIN_KEYBOARD_DVORAK;
  1626. i++;
  1627. }
  1628. return LATIN_KEYBOARD_QWERTY;
  1629. }
  1630. void OS_Windows::release_rendering_thread() {
  1631. gl_context->release_current();
  1632. }
  1633. void OS_Windows::make_rendering_thread() {
  1634. gl_context->make_current();
  1635. }
  1636. void OS_Windows::swap_buffers() {
  1637. gl_context->swap_buffers();
  1638. }
  1639. void OS_Windows::run() {
  1640. if (!main_loop)
  1641. return;
  1642. main_loop->init();
  1643. uint64_t last_ticks = get_ticks_usec();
  1644. int frames = 0;
  1645. uint64_t frame = 0;
  1646. while (!force_quit) {
  1647. process_events(); // get rid of pending events
  1648. if (Main::iteration() == true)
  1649. break;
  1650. };
  1651. main_loop->finish();
  1652. }
  1653. MainLoop *OS_Windows::get_main_loop() const {
  1654. return main_loop;
  1655. }
  1656. String OS_Windows::get_system_dir(SystemDir p_dir) const {
  1657. int id;
  1658. switch (p_dir) {
  1659. case SYSTEM_DIR_DESKTOP: {
  1660. id = CSIDL_DESKTOPDIRECTORY;
  1661. } break;
  1662. case SYSTEM_DIR_DCIM: {
  1663. id = CSIDL_MYPICTURES;
  1664. } break;
  1665. case SYSTEM_DIR_DOCUMENTS: {
  1666. id = CSIDL_PERSONAL;
  1667. } break;
  1668. case SYSTEM_DIR_DOWNLOADS: {
  1669. id = 0x000C;
  1670. } break;
  1671. case SYSTEM_DIR_MOVIES: {
  1672. id = CSIDL_MYVIDEO;
  1673. } break;
  1674. case SYSTEM_DIR_MUSIC: {
  1675. id = CSIDL_MYMUSIC;
  1676. } break;
  1677. case SYSTEM_DIR_PICTURES: {
  1678. id = CSIDL_MYPICTURES;
  1679. } break;
  1680. case SYSTEM_DIR_RINGTONES: {
  1681. id = CSIDL_MYMUSIC;
  1682. } break;
  1683. }
  1684. WCHAR szPath[MAX_PATH];
  1685. HRESULT res = SHGetFolderPathW(NULL, id, NULL, 0, szPath);
  1686. ERR_FAIL_COND_V(res != S_OK, String());
  1687. return String(szPath);
  1688. }
  1689. String OS_Windows::get_data_dir() const {
  1690. String an = get_safe_application_name();
  1691. if (an != "") {
  1692. if (has_environment("APPDATA")) {
  1693. bool use_godot = ProjectSettings::get_singleton()->get("application/config/use_shared_user_dir");
  1694. if (!use_godot)
  1695. return (OS::get_singleton()->get_environment("APPDATA") + "/" + an).replace("\\", "/");
  1696. else
  1697. return (OS::get_singleton()->get_environment("APPDATA") + "/Godot/app_userdata/" + an).replace("\\", "/");
  1698. }
  1699. }
  1700. return ProjectSettings::get_singleton()->get_resource_path();
  1701. }
  1702. bool OS_Windows::is_joy_known(int p_device) {
  1703. return input->is_joy_mapped(p_device);
  1704. }
  1705. String OS_Windows::get_joy_guid(int p_device) const {
  1706. return input->get_joy_guid_remapped(p_device);
  1707. }
  1708. void OS_Windows::set_use_vsync(bool p_enable) {
  1709. if (gl_context)
  1710. gl_context->set_use_vsync(p_enable);
  1711. }
  1712. bool OS_Windows::is_vsync_enabled() const {
  1713. if (gl_context)
  1714. return gl_context->is_using_vsync();
  1715. return true;
  1716. }
  1717. OS::PowerState OS_Windows::get_power_state() {
  1718. return power_manager->get_power_state();
  1719. }
  1720. int OS_Windows::get_power_seconds_left() {
  1721. return power_manager->get_power_seconds_left();
  1722. }
  1723. int OS_Windows::get_power_percent_left() {
  1724. return power_manager->get_power_percent_left();
  1725. }
  1726. bool OS_Windows::_check_internal_feature_support(const String &p_feature) {
  1727. return p_feature == "pc" || p_feature == "s3tc";
  1728. }
  1729. void OS_Windows::disable_crash_handler() {
  1730. crash_handler.disable();
  1731. }
  1732. bool OS_Windows::is_disable_crash_handler() const {
  1733. return crash_handler.is_disabled();
  1734. }
  1735. Error OS_Windows::move_to_trash(const String &p_path) {
  1736. SHFILEOPSTRUCTA sf;
  1737. TCHAR *from = new TCHAR[p_path.length() + 2];
  1738. strcpy(from, p_path.utf8().get_data());
  1739. from[p_path.length()] = 0;
  1740. from[p_path.length() + 1] = 0;
  1741. sf.hwnd = hWnd;
  1742. sf.wFunc = FO_DELETE;
  1743. sf.pFrom = from;
  1744. sf.pTo = NULL;
  1745. sf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
  1746. sf.fAnyOperationsAborted = FALSE;
  1747. sf.hNameMappings = NULL;
  1748. sf.lpszProgressTitle = NULL;
  1749. int ret = SHFileOperation(&sf);
  1750. delete[] from;
  1751. if (ret) {
  1752. ERR_PRINTS("SHFileOperation error: " + itos(ret));
  1753. return FAILED;
  1754. }
  1755. return OK;
  1756. }
  1757. OS_Windows::OS_Windows(HINSTANCE _hInstance) {
  1758. key_event_pos = 0;
  1759. force_quit = false;
  1760. alt_mem = false;
  1761. gr_mem = false;
  1762. shift_mem = false;
  1763. control_mem = false;
  1764. meta_mem = false;
  1765. minimized = false;
  1766. hInstance = _hInstance;
  1767. pressrc = 0;
  1768. old_invalid = true;
  1769. mouse_mode = MOUSE_MODE_VISIBLE;
  1770. #ifdef STDOUT_FILE
  1771. stdo = fopen("stdout.txt", "wb");
  1772. #endif
  1773. user_proc = NULL;
  1774. #ifdef WASAPI_ENABLED
  1775. AudioDriverManager::add_driver(&driver_wasapi);
  1776. #endif
  1777. #ifdef RTAUDIO_ENABLED
  1778. AudioDriverManager::add_driver(&driver_rtaudio);
  1779. #endif
  1780. #ifdef XAUDIO2_ENABLED
  1781. AudioDriverManager::add_driver(&driver_xaudio2);
  1782. #endif
  1783. _set_logger(memnew(WindowsTerminalLogger));
  1784. }
  1785. OS_Windows::~OS_Windows() {
  1786. #ifdef STDOUT_FILE
  1787. fclose(stdo);
  1788. #endif
  1789. }