os_windows.cpp 58 KB

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