2
0

os_windows.cpp 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081
  1. /*************************************************************************/
  2. /* os_windows.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. // Must include Winsock before windows.h (included by os_windows.h)
  31. #include "drivers/unix/net_socket_posix.h"
  32. #include "os_windows.h"
  33. #include "core/io/marshalls.h"
  34. #include "core/version_generated.gen.h"
  35. #include "drivers/gles2/rasterizer_gles2.h"
  36. #include "drivers/gles3/rasterizer_gles3.h"
  37. #include "drivers/windows/dir_access_windows.h"
  38. #include "drivers/windows/file_access_windows.h"
  39. #include "drivers/windows/mutex_windows.h"
  40. #include "drivers/windows/rw_lock_windows.h"
  41. #include "drivers/windows/semaphore_windows.h"
  42. #include "drivers/windows/thread_windows.h"
  43. #include "joypad_windows.h"
  44. #include "lang_table.h"
  45. #include "main/main.h"
  46. #include "servers/audio_server.h"
  47. #include "servers/visual/visual_server_raster.h"
  48. #include "servers/visual/visual_server_wrap_mt.h"
  49. #include "windows_terminal_logger.h"
  50. #include <avrt.h>
  51. #include <direct.h>
  52. #include <process.h>
  53. #include <regstr.h>
  54. #include <shlobj.h>
  55. static const WORD MAX_CONSOLE_LINES = 1500;
  56. extern "C" {
  57. __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  58. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  59. }
  60. // Workaround mingw-w64 < 4.0 bug
  61. #ifndef WM_TOUCH
  62. #define WM_TOUCH 576
  63. #endif
  64. typedef struct {
  65. int count;
  66. int screen;
  67. Size2 size;
  68. } EnumSizeData;
  69. typedef struct {
  70. int count;
  71. int screen;
  72. Point2 pos;
  73. } EnumPosData;
  74. static BOOL CALLBACK _MonitorEnumProcSize(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  75. EnumSizeData *data = (EnumSizeData *)dwData;
  76. if (data->count == data->screen) {
  77. data->size.x = lprcMonitor->right - lprcMonitor->left;
  78. data->size.y = lprcMonitor->bottom - lprcMonitor->top;
  79. }
  80. data->count++;
  81. return TRUE;
  82. }
  83. static String format_error_message(DWORD id) {
  84. LPWSTR messageBuffer = NULL;
  85. size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  86. NULL, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, NULL);
  87. String msg = "Error " + itos(id) + ": " + String(messageBuffer, size);
  88. LocalFree(messageBuffer);
  89. return msg;
  90. }
  91. extern HINSTANCE godot_hinstance;
  92. void RedirectIOToConsole() {
  93. int hConHandle;
  94. intptr_t lStdHandle;
  95. CONSOLE_SCREEN_BUFFER_INFO coninfo;
  96. FILE *fp;
  97. // allocate a console for this app
  98. AllocConsole();
  99. // set the screen buffer to be big enough to let us scroll text
  100. GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
  101. &coninfo);
  102. coninfo.dwSize.Y = MAX_CONSOLE_LINES;
  103. SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
  104. coninfo.dwSize);
  105. // redirect unbuffered STDOUT to the console
  106. lStdHandle = (intptr_t)GetStdHandle(STD_OUTPUT_HANDLE);
  107. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  108. fp = _fdopen(hConHandle, "w");
  109. *stdout = *fp;
  110. setvbuf(stdout, NULL, _IONBF, 0);
  111. // redirect unbuffered STDIN to the console
  112. lStdHandle = (intptr_t)GetStdHandle(STD_INPUT_HANDLE);
  113. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  114. fp = _fdopen(hConHandle, "r");
  115. *stdin = *fp;
  116. setvbuf(stdin, NULL, _IONBF, 0);
  117. // redirect unbuffered STDERR to the console
  118. lStdHandle = (intptr_t)GetStdHandle(STD_ERROR_HANDLE);
  119. hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  120. fp = _fdopen(hConHandle, "w");
  121. *stderr = *fp;
  122. setvbuf(stderr, NULL, _IONBF, 0);
  123. // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
  124. // point to console as well
  125. }
  126. BOOL WINAPI HandlerRoutine(_In_ DWORD dwCtrlType) {
  127. if (ScriptDebugger::get_singleton() == NULL)
  128. return FALSE;
  129. switch (dwCtrlType) {
  130. case CTRL_C_EVENT:
  131. ScriptDebugger::get_singleton()->set_depth(-1);
  132. ScriptDebugger::get_singleton()->set_lines_left(1);
  133. return TRUE;
  134. default:
  135. return FALSE;
  136. }
  137. }
  138. void OS_Windows::initialize_debugging() {
  139. SetConsoleCtrlHandler(HandlerRoutine, TRUE);
  140. }
  141. void OS_Windows::initialize_core() {
  142. crash_handler.initialize();
  143. last_button_state = 0;
  144. //RedirectIOToConsole();
  145. maximized = false;
  146. minimized = false;
  147. borderless = false;
  148. ThreadWindows::make_default();
  149. SemaphoreWindows::make_default();
  150. MutexWindows::make_default();
  151. RWLockWindows::make_default();
  152. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
  153. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
  154. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
  155. //FileAccessBufferedFA<FileAccessWindows>::make_default();
  156. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
  157. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
  158. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);
  159. NetSocketPosix::make_default();
  160. // We need to know how often the clock is updated
  161. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
  162. ticks_per_second = 1000;
  163. // If timeAtGameStart is 0 then we get the time since
  164. // the start of the computer when we call GetGameTime()
  165. ticks_start = 0;
  166. ticks_start = get_ticks_usec();
  167. // set minimum resolution for periodic timers, otherwise Sleep(n) may wait at least as
  168. // long as the windows scheduler resolution (~16-30ms) even for calls like Sleep(1)
  169. timeBeginPeriod(1);
  170. process_map = memnew((Map<ProcessID, ProcessInfo>));
  171. IP_Unix::make_default();
  172. cursor_shape = CURSOR_ARROW;
  173. }
  174. bool OS_Windows::can_draw() const {
  175. return !minimized;
  176. };
  177. #define MI_WP_SIGNATURE 0xFF515700
  178. #define SIGNATURE_MASK 0xFFFFFF00
  179. // Keeping the name suggested by Microsoft, but this macro really answers:
  180. // Is this mouse event emulated from touch or pen input?
  181. #define IsPenEvent(dw) (((dw)&SIGNATURE_MASK) == MI_WP_SIGNATURE)
  182. // This one tells whether the event comes from touchscreen (and not from pen)
  183. #define IsTouchEvent(dw) (IsPenEvent(dw) && ((dw)&0x80))
  184. void OS_Windows::_touch_event(bool p_pressed, float p_x, float p_y, int idx) {
  185. // Defensive
  186. if (touch_state.has(idx) == p_pressed)
  187. return;
  188. if (p_pressed) {
  189. touch_state.insert(idx, Vector2(p_x, p_y));
  190. } else {
  191. touch_state.erase(idx);
  192. }
  193. Ref<InputEventScreenTouch> event;
  194. event.instance();
  195. event->set_index(idx);
  196. event->set_pressed(p_pressed);
  197. event->set_position(Vector2(p_x, p_y));
  198. if (main_loop) {
  199. input->accumulate_input_event(event);
  200. }
  201. };
  202. void OS_Windows::_drag_event(float p_x, float p_y, int idx) {
  203. Map<int, Vector2>::Element *curr = touch_state.find(idx);
  204. // Defensive
  205. if (!curr)
  206. return;
  207. if (curr->get() == Vector2(p_x, p_y))
  208. return;
  209. curr->get() = Vector2(p_x, p_y);
  210. Ref<InputEventScreenDrag> event;
  211. event.instance();
  212. event->set_index(idx);
  213. event->set_position(Vector2(p_x, p_y));
  214. if (main_loop)
  215. input->accumulate_input_event(event);
  216. };
  217. LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  218. if (drop_events) {
  219. if (user_proc) {
  220. return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
  221. } else {
  222. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  223. }
  224. };
  225. switch (uMsg) // Check For Windows Messages
  226. {
  227. case WM_SETFOCUS: {
  228. window_has_focus = true;
  229. // Restore mouse mode
  230. _set_mouse_mode_impl(mouse_mode);
  231. break;
  232. }
  233. case WM_KILLFOCUS: {
  234. window_has_focus = false;
  235. // Release capture unconditionally because it can be set due to dragging, in addition to captured mode
  236. ReleaseCapture();
  237. // Release every touch to avoid sticky points
  238. for (Map<int, Vector2>::Element *E = touch_state.front(); E; E = E->next()) {
  239. _touch_event(false, E->get().x, E->get().y, E->key());
  240. }
  241. touch_state.clear();
  242. break;
  243. }
  244. case WM_ACTIVATE: // Watch For Window Activate Message
  245. {
  246. minimized = HIWORD(wParam) != 0;
  247. if (!main_loop) {
  248. return 0;
  249. };
  250. if (LOWORD(wParam) == WA_ACTIVE || LOWORD(wParam) == WA_CLICKACTIVE) {
  251. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
  252. alt_mem = false;
  253. control_mem = false;
  254. shift_mem = false;
  255. } else { // WM_INACTIVE
  256. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  257. alt_mem = false;
  258. };
  259. return 0; // Return To The Message Loop
  260. }
  261. case WM_PAINT:
  262. Main::force_redraw();
  263. break;
  264. case WM_SYSCOMMAND: // Intercept System Commands
  265. {
  266. switch (wParam) // Check System Calls
  267. {
  268. case SC_SCREENSAVE: // Screensaver Trying To Start?
  269. case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
  270. return 0; // Prevent From Happening
  271. case SC_KEYMENU:
  272. if ((lParam >> 16) <= 0)
  273. return 0;
  274. }
  275. break; // Exit
  276. }
  277. case WM_CLOSE: // Did We Receive A Close Message?
  278. {
  279. if (main_loop)
  280. main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  281. //force_quit=true;
  282. return 0; // Jump Back
  283. }
  284. case WM_MOUSELEAVE: {
  285. old_invalid = true;
  286. outside = true;
  287. if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
  288. main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
  289. if (input)
  290. input->set_mouse_in_window(false);
  291. } break;
  292. case WM_INPUT: {
  293. if (mouse_mode != MOUSE_MODE_CAPTURED || !use_raw_input) {
  294. break;
  295. }
  296. UINT dwSize;
  297. GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER));
  298. LPBYTE lpb = new BYTE[dwSize];
  299. if (lpb == NULL) {
  300. return 0;
  301. }
  302. if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize)
  303. OutputDebugString(TEXT("GetRawInputData does not return correct size !\n"));
  304. RAWINPUT *raw = (RAWINPUT *)lpb;
  305. if (raw->header.dwType == RIM_TYPEMOUSE) {
  306. Ref<InputEventMouseMotion> mm;
  307. mm.instance();
  308. mm->set_control(control_mem);
  309. mm->set_shift(shift_mem);
  310. mm->set_alt(alt_mem);
  311. mm->set_button_mask(last_button_state);
  312. Point2i c(video_mode.width / 2, video_mode.height / 2);
  313. // centering just so it works as before
  314. POINT pos = { (int)c.x, (int)c.y };
  315. ClientToScreen(hWnd, &pos);
  316. SetCursorPos(pos.x, pos.y);
  317. mm->set_position(c);
  318. mm->set_global_position(c);
  319. input->set_mouse_position(c);
  320. mm->set_speed(Vector2(0, 0));
  321. if (raw->data.mouse.usFlags == MOUSE_MOVE_RELATIVE) {
  322. mm->set_relative(Vector2(raw->data.mouse.lLastX, raw->data.mouse.lLastY));
  323. } else if (raw->data.mouse.usFlags == MOUSE_MOVE_ABSOLUTE) {
  324. int nScreenWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN);
  325. int nScreenHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
  326. int nScreenLeft = GetSystemMetrics(SM_XVIRTUALSCREEN);
  327. int nScreenTop = GetSystemMetrics(SM_YVIRTUALSCREEN);
  328. Vector2 abs_pos(
  329. (double(raw->data.mouse.lLastX) - 65536.0 / (nScreenWidth)) * nScreenWidth / 65536.0 + nScreenLeft,
  330. (double(raw->data.mouse.lLastY) - 65536.0 / (nScreenHeight)) * nScreenHeight / 65536.0 + nScreenTop);
  331. POINT coords; //client coords
  332. coords.x = abs_pos.x;
  333. coords.y = abs_pos.y;
  334. ScreenToClient(hWnd, &coords);
  335. mm->set_relative(Vector2(coords.x - old_x, coords.y - old_y));
  336. old_x = coords.x;
  337. old_y = coords.y;
  338. /*Input.mi.dx = (int)((((double)(pos.x)-nScreenLeft) * 65536) / nScreenWidth + 65536 / (nScreenWidth));
  339. Input.mi.dy = (int)((((double)(pos.y)-nScreenTop) * 65536) / nScreenHeight + 65536 / (nScreenHeight));
  340. */
  341. }
  342. if (window_has_focus && main_loop && mm->get_relative() != Vector2())
  343. input->accumulate_input_event(mm);
  344. }
  345. delete[] lpb;
  346. } break;
  347. case WM_MOUSEMOVE: {
  348. if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
  349. break;
  350. }
  351. if (input->is_emulating_mouse_from_touch()) {
  352. // Universal translation enabled; ignore OS translation
  353. LPARAM extra = GetMessageExtraInfo();
  354. if (IsTouchEvent(extra)) {
  355. break;
  356. }
  357. }
  358. if (outside) {
  359. //mouse enter
  360. if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
  361. main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
  362. if (input)
  363. input->set_mouse_in_window(true);
  364. CursorShape c = cursor_shape;
  365. cursor_shape = CURSOR_MAX;
  366. set_cursor_shape(c);
  367. outside = false;
  368. //Once-Off notification, must call again....
  369. TRACKMOUSEEVENT tme;
  370. tme.cbSize = sizeof(TRACKMOUSEEVENT);
  371. tme.dwFlags = TME_LEAVE;
  372. tme.hwndTrack = hWnd;
  373. tme.dwHoverTime = HOVER_DEFAULT;
  374. TrackMouseEvent(&tme);
  375. }
  376. // Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
  377. if (!window_has_focus && mouse_mode == MOUSE_MODE_CAPTURED)
  378. break;
  379. Ref<InputEventMouseMotion> mm;
  380. mm.instance();
  381. mm->set_control((wParam & MK_CONTROL) != 0);
  382. mm->set_shift((wParam & MK_SHIFT) != 0);
  383. mm->set_alt(alt_mem);
  384. mm->set_button_mask(last_button_state);
  385. mm->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  386. mm->set_global_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  387. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  388. Point2i c(video_mode.width / 2, video_mode.height / 2);
  389. old_x = c.x;
  390. old_y = c.y;
  391. if (mm->get_position() == c) {
  392. center = c;
  393. return 0;
  394. }
  395. Point2i ncenter = mm->get_position();
  396. center = ncenter;
  397. POINT pos = { (int)c.x, (int)c.y };
  398. ClientToScreen(hWnd, &pos);
  399. SetCursorPos(pos.x, pos.y);
  400. }
  401. input->set_mouse_position(mm->get_position());
  402. mm->set_speed(input->get_last_mouse_speed());
  403. if (old_invalid) {
  404. old_x = mm->get_position().x;
  405. old_y = mm->get_position().y;
  406. old_invalid = false;
  407. }
  408. mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
  409. old_x = mm->get_position().x;
  410. old_y = mm->get_position().y;
  411. if (window_has_focus && main_loop)
  412. input->accumulate_input_event(mm);
  413. } break;
  414. case WM_LBUTTONDOWN:
  415. case WM_LBUTTONUP:
  416. if (input->is_emulating_mouse_from_touch()) {
  417. // Universal translation enabled; ignore OS translations for left button
  418. LPARAM extra = GetMessageExtraInfo();
  419. if (IsTouchEvent(extra)) {
  420. break;
  421. }
  422. }
  423. case WM_MBUTTONDOWN:
  424. case WM_MBUTTONUP:
  425. case WM_RBUTTONDOWN:
  426. case WM_RBUTTONUP:
  427. case WM_MOUSEWHEEL:
  428. case WM_MOUSEHWHEEL:
  429. case WM_LBUTTONDBLCLK:
  430. case WM_MBUTTONDBLCLK:
  431. case WM_RBUTTONDBLCLK:
  432. case WM_XBUTTONDBLCLK:
  433. case WM_XBUTTONDOWN:
  434. case WM_XBUTTONUP: {
  435. Ref<InputEventMouseButton> mb;
  436. mb.instance();
  437. switch (uMsg) {
  438. case WM_LBUTTONDOWN: {
  439. mb->set_pressed(true);
  440. mb->set_button_index(1);
  441. } break;
  442. case WM_LBUTTONUP: {
  443. mb->set_pressed(false);
  444. mb->set_button_index(1);
  445. } break;
  446. case WM_MBUTTONDOWN: {
  447. mb->set_pressed(true);
  448. mb->set_button_index(3);
  449. } break;
  450. case WM_MBUTTONUP: {
  451. mb->set_pressed(false);
  452. mb->set_button_index(3);
  453. } break;
  454. case WM_RBUTTONDOWN: {
  455. mb->set_pressed(true);
  456. mb->set_button_index(2);
  457. } break;
  458. case WM_RBUTTONUP: {
  459. mb->set_pressed(false);
  460. mb->set_button_index(2);
  461. } break;
  462. case WM_LBUTTONDBLCLK: {
  463. mb->set_pressed(true);
  464. mb->set_button_index(1);
  465. mb->set_doubleclick(true);
  466. } break;
  467. case WM_RBUTTONDBLCLK: {
  468. mb->set_pressed(true);
  469. mb->set_button_index(2);
  470. mb->set_doubleclick(true);
  471. } break;
  472. case WM_MBUTTONDBLCLK: {
  473. mb->set_pressed(true);
  474. mb->set_button_index(3);
  475. mb->set_doubleclick(true);
  476. } break;
  477. case WM_MOUSEWHEEL: {
  478. mb->set_pressed(true);
  479. int motion = (short)HIWORD(wParam);
  480. if (!motion)
  481. return 0;
  482. if (motion > 0)
  483. mb->set_button_index(BUTTON_WHEEL_UP);
  484. else
  485. mb->set_button_index(BUTTON_WHEEL_DOWN);
  486. } break;
  487. case WM_MOUSEHWHEEL: {
  488. mb->set_pressed(true);
  489. int motion = (short)HIWORD(wParam);
  490. if (!motion)
  491. return 0;
  492. if (motion < 0) {
  493. mb->set_button_index(BUTTON_WHEEL_LEFT);
  494. mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA));
  495. } else {
  496. mb->set_button_index(BUTTON_WHEEL_RIGHT);
  497. mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA));
  498. }
  499. } break;
  500. case WM_XBUTTONDOWN: {
  501. mb->set_pressed(true);
  502. if (HIWORD(wParam) == XBUTTON1)
  503. mb->set_button_index(BUTTON_XBUTTON1);
  504. else
  505. mb->set_button_index(BUTTON_XBUTTON2);
  506. } break;
  507. case WM_XBUTTONUP: {
  508. mb->set_pressed(false);
  509. if (HIWORD(wParam) == XBUTTON1)
  510. mb->set_button_index(BUTTON_XBUTTON1);
  511. else
  512. mb->set_button_index(BUTTON_XBUTTON2);
  513. } break;
  514. case WM_XBUTTONDBLCLK: {
  515. mb->set_pressed(true);
  516. if (HIWORD(wParam) == XBUTTON1)
  517. mb->set_button_index(BUTTON_XBUTTON1);
  518. else
  519. mb->set_button_index(BUTTON_XBUTTON2);
  520. mb->set_doubleclick(true);
  521. } break;
  522. default: { return 0; }
  523. }
  524. mb->set_control((wParam & MK_CONTROL) != 0);
  525. mb->set_shift((wParam & MK_SHIFT) != 0);
  526. mb->set_alt(alt_mem);
  527. //mb->get_alt()=(wParam&MK_MENU)!=0;
  528. if (mb->is_pressed())
  529. last_button_state |= (1 << (mb->get_button_index() - 1));
  530. else
  531. last_button_state &= ~(1 << (mb->get_button_index() - 1));
  532. mb->set_button_mask(last_button_state);
  533. mb->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  534. if (mouse_mode == MOUSE_MODE_CAPTURED && !use_raw_input) {
  535. mb->set_position(Vector2(old_x, old_y));
  536. }
  537. if (uMsg != WM_MOUSEWHEEL && uMsg != WM_MOUSEHWHEEL) {
  538. if (mb->is_pressed()) {
  539. if (++pressrc > 0 && mouse_mode != MOUSE_MODE_CAPTURED)
  540. SetCapture(hWnd);
  541. } else {
  542. if (--pressrc <= 0) {
  543. if (mouse_mode != MOUSE_MODE_CAPTURED) {
  544. ReleaseCapture();
  545. }
  546. pressrc = 0;
  547. }
  548. }
  549. } else if (mouse_mode != MOUSE_MODE_CAPTURED) {
  550. // for reasons unknown to mankind, wheel comes in screen cordinates
  551. POINT coords;
  552. coords.x = mb->get_position().x;
  553. coords.y = mb->get_position().y;
  554. ScreenToClient(hWnd, &coords);
  555. mb->set_position(Vector2(coords.x, coords.y));
  556. }
  557. mb->set_global_position(mb->get_position());
  558. if (main_loop) {
  559. input->accumulate_input_event(mb);
  560. if (mb->is_pressed() && mb->get_button_index() > 3 && mb->get_button_index() < 8) {
  561. //send release for mouse wheel
  562. Ref<InputEventMouseButton> mbd = mb->duplicate();
  563. last_button_state &= ~(1 << (mbd->get_button_index() - 1));
  564. mbd->set_button_mask(last_button_state);
  565. mbd->set_pressed(false);
  566. input->accumulate_input_event(mbd);
  567. }
  568. }
  569. } break;
  570. case WM_MOVE: {
  571. if (!IsIconic(hWnd)) {
  572. int x = LOWORD(lParam);
  573. int y = HIWORD(lParam);
  574. last_pos = Point2(x, y);
  575. }
  576. } break;
  577. case WM_SIZE: {
  578. // Ignore size when a SIZE_MINIMIZED event is triggered
  579. if (wParam != SIZE_MINIMIZED) {
  580. int window_w = LOWORD(lParam);
  581. int window_h = HIWORD(lParam);
  582. if (window_w > 0 && window_h > 0 && !preserve_window_size) {
  583. video_mode.width = window_w;
  584. video_mode.height = window_h;
  585. } else {
  586. preserve_window_size = false;
  587. set_window_size(Size2(video_mode.width, video_mode.height));
  588. }
  589. }
  590. if (wParam == SIZE_MAXIMIZED) {
  591. maximized = true;
  592. minimized = false;
  593. } else if (wParam == SIZE_MINIMIZED) {
  594. maximized = false;
  595. minimized = true;
  596. } else if (wParam == SIZE_RESTORED) {
  597. maximized = false;
  598. minimized = false;
  599. }
  600. if (is_layered_allowed() && layered_window) {
  601. DeleteObject(hBitmap);
  602. RECT r;
  603. GetWindowRect(hWnd, &r);
  604. dib_size = Size2i(r.right - r.left, r.bottom - r.top);
  605. BITMAPINFO bmi;
  606. ZeroMemory(&bmi, sizeof(BITMAPINFO));
  607. bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
  608. bmi.bmiHeader.biWidth = dib_size.x;
  609. bmi.bmiHeader.biHeight = dib_size.y;
  610. bmi.bmiHeader.biPlanes = 1;
  611. bmi.bmiHeader.biBitCount = 32;
  612. bmi.bmiHeader.biCompression = BI_RGB;
  613. bmi.bmiHeader.biSizeImage = dib_size.x * dib_size.y * 4;
  614. hBitmap = CreateDIBSection(hDC_dib, &bmi, DIB_RGB_COLORS, (void **)&dib_data, NULL, 0x0);
  615. SelectObject(hDC_dib, hBitmap);
  616. ZeroMemory(dib_data, dib_size.x * dib_size.y * 4);
  617. }
  618. //return 0; // Jump Back
  619. } break;
  620. case WM_ENTERSIZEMOVE: {
  621. move_timer_id = SetTimer(hWnd, 1, USER_TIMER_MINIMUM, (TIMERPROC)NULL);
  622. } break;
  623. case WM_EXITSIZEMOVE: {
  624. KillTimer(hWnd, move_timer_id);
  625. } break;
  626. case WM_TIMER: {
  627. if (wParam == move_timer_id) {
  628. process_key_events();
  629. if (!Main::is_iterating()) {
  630. Main::iteration();
  631. }
  632. }
  633. } break;
  634. case WM_SYSKEYDOWN:
  635. case WM_SYSKEYUP:
  636. case WM_KEYUP:
  637. case WM_KEYDOWN: {
  638. if (wParam == VK_SHIFT)
  639. shift_mem = uMsg == WM_KEYDOWN;
  640. if (wParam == VK_CONTROL)
  641. control_mem = uMsg == WM_KEYDOWN;
  642. if (wParam == VK_MENU) {
  643. alt_mem = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN);
  644. if (lParam & (1 << 24))
  645. gr_mem = alt_mem;
  646. }
  647. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  648. // When SetCapture is used, ALT+F4 hotkey is ignored by Windows, so handle it ourselves
  649. if (wParam == VK_F4 && alt_mem && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN)) {
  650. if (main_loop)
  651. main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  652. }
  653. }
  654. /*
  655. if (wParam==VK_WIN) TODO wtf is this?
  656. meta_mem=uMsg==WM_KEYDOWN;
  657. */
  658. } //fallthrough
  659. case WM_CHAR: {
  660. ERR_BREAK(key_event_pos >= KEY_EVENT_BUFFER_SIZE);
  661. // Make sure we don't include modifiers for the modifier key itself.
  662. KeyEvent ke;
  663. ke.shift = (wParam != VK_SHIFT) ? shift_mem : false;
  664. ke.alt = (!(wParam == VK_MENU && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN))) ? alt_mem : false;
  665. ke.control = (wParam != VK_CONTROL) ? control_mem : false;
  666. ke.meta = meta_mem;
  667. ke.uMsg = uMsg;
  668. if (ke.uMsg == WM_SYSKEYDOWN)
  669. ke.uMsg = WM_KEYDOWN;
  670. if (ke.uMsg == WM_SYSKEYUP)
  671. ke.uMsg = WM_KEYUP;
  672. ke.wParam = wParam;
  673. ke.lParam = lParam;
  674. key_event_buffer[key_event_pos++] = ke;
  675. } break;
  676. case WM_INPUTLANGCHANGEREQUEST: {
  677. // FIXME: Do something?
  678. } break;
  679. case WM_TOUCH: {
  680. BOOL bHandled = FALSE;
  681. UINT cInputs = LOWORD(wParam);
  682. PTOUCHINPUT pInputs = memnew_arr(TOUCHINPUT, cInputs);
  683. if (pInputs) {
  684. if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs, sizeof(TOUCHINPUT))) {
  685. for (UINT i = 0; i < cInputs; i++) {
  686. TOUCHINPUT ti = pInputs[i];
  687. POINT touch_pos = {
  688. TOUCH_COORD_TO_PIXEL(ti.x),
  689. TOUCH_COORD_TO_PIXEL(ti.y),
  690. };
  691. ScreenToClient(hWnd, &touch_pos);
  692. //do something with each touch input entry
  693. if (ti.dwFlags & TOUCHEVENTF_MOVE) {
  694. _drag_event(touch_pos.x, touch_pos.y, ti.dwID);
  695. } else if (ti.dwFlags & (TOUCHEVENTF_UP | TOUCHEVENTF_DOWN)) {
  696. _touch_event(ti.dwFlags & TOUCHEVENTF_DOWN, touch_pos.x, touch_pos.y, ti.dwID);
  697. };
  698. }
  699. bHandled = TRUE;
  700. } else {
  701. /* handle the error here */
  702. }
  703. memdelete_arr(pInputs);
  704. } else {
  705. /* handle the error here, probably out of memory */
  706. }
  707. if (bHandled) {
  708. CloseTouchInputHandle((HTOUCHINPUT)lParam);
  709. return 0;
  710. };
  711. } break;
  712. case WM_DEVICECHANGE: {
  713. joypad->probe_joypads();
  714. } break;
  715. case WM_SETCURSOR: {
  716. if (LOWORD(lParam) == HTCLIENT) {
  717. if (window_has_focus && (mouse_mode == MOUSE_MODE_HIDDEN || mouse_mode == MOUSE_MODE_CAPTURED)) {
  718. //Hide the cursor
  719. if (hCursor == NULL)
  720. hCursor = SetCursor(NULL);
  721. else
  722. SetCursor(NULL);
  723. } else {
  724. if (hCursor != NULL) {
  725. CursorShape c = cursor_shape;
  726. cursor_shape = CURSOR_MAX;
  727. set_cursor_shape(c);
  728. hCursor = NULL;
  729. }
  730. }
  731. }
  732. } break;
  733. case WM_DROPFILES: {
  734. HDROP hDropInfo = (HDROP)wParam;
  735. const int buffsize = 4096;
  736. wchar_t buf[buffsize];
  737. int fcount = DragQueryFileW(hDropInfo, 0xFFFFFFFF, NULL, 0);
  738. Vector<String> files;
  739. for (int i = 0; i < fcount; i++) {
  740. DragQueryFileW(hDropInfo, i, buf, buffsize);
  741. String file = buf;
  742. files.push_back(file);
  743. }
  744. if (files.size() && main_loop) {
  745. main_loop->drop_files(files, 0);
  746. }
  747. } break;
  748. default: {
  749. if (user_proc) {
  750. return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
  751. };
  752. };
  753. }
  754. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  755. }
  756. LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  757. OS_Windows *os_win = static_cast<OS_Windows *>(OS::get_singleton());
  758. if (os_win)
  759. return os_win->WndProc(hWnd, uMsg, wParam, lParam);
  760. else
  761. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  762. }
  763. void OS_Windows::process_key_events() {
  764. for (int i = 0; i < key_event_pos; i++) {
  765. KeyEvent &ke = key_event_buffer[i];
  766. switch (ke.uMsg) {
  767. case WM_CHAR: {
  768. if ((i == 0 && ke.uMsg == WM_CHAR) || (i > 0 && key_event_buffer[i - 1].uMsg == WM_CHAR)) {
  769. Ref<InputEventKey> k;
  770. k.instance();
  771. k->set_shift(ke.shift);
  772. k->set_alt(ke.alt);
  773. k->set_control(ke.control);
  774. k->set_metakey(ke.meta);
  775. k->set_pressed(true);
  776. k->set_scancode(KeyMappingWindows::get_keysym(ke.wParam));
  777. k->set_unicode(ke.wParam);
  778. if (k->get_unicode() && gr_mem) {
  779. k->set_alt(false);
  780. k->set_control(false);
  781. }
  782. if (k->get_unicode() < 32)
  783. k->set_unicode(0);
  784. input->accumulate_input_event(k);
  785. }
  786. //do nothing
  787. } break;
  788. case WM_KEYUP:
  789. case WM_KEYDOWN: {
  790. Ref<InputEventKey> k;
  791. k.instance();
  792. k->set_shift(ke.shift);
  793. k->set_alt(ke.alt);
  794. k->set_control(ke.control);
  795. k->set_metakey(ke.meta);
  796. k->set_pressed(ke.uMsg == WM_KEYDOWN);
  797. if ((ke.lParam & (1 << 24)) && (ke.wParam == VK_RETURN)) {
  798. // Special case for Numpad Enter key
  799. k->set_scancode(KEY_KP_ENTER);
  800. } else {
  801. k->set_scancode(KeyMappingWindows::get_keysym(ke.wParam));
  802. }
  803. if (i + 1 < key_event_pos && key_event_buffer[i + 1].uMsg == WM_CHAR) {
  804. k->set_unicode(key_event_buffer[i + 1].wParam);
  805. }
  806. if (k->get_unicode() && gr_mem) {
  807. k->set_alt(false);
  808. k->set_control(false);
  809. }
  810. if (k->get_unicode() < 32)
  811. k->set_unicode(0);
  812. k->set_echo((ke.uMsg == WM_KEYDOWN && (ke.lParam & (1 << 30))));
  813. input->accumulate_input_event(k);
  814. } break;
  815. }
  816. }
  817. key_event_pos = 0;
  818. }
  819. enum _MonitorDpiType {
  820. MDT_Effective_DPI = 0,
  821. MDT_Angular_DPI = 1,
  822. MDT_Raw_DPI = 2,
  823. MDT_Default = MDT_Effective_DPI
  824. };
  825. static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType = MDT_Default) {
  826. int dpiX = 96, dpiY = 96;
  827. static HMODULE Shcore = NULL;
  828. typedef HRESULT(WINAPI * GetDPIForMonitor_t)(HMONITOR hmonitor, _MonitorDpiType dpiType, UINT * dpiX, UINT * dpiY);
  829. static GetDPIForMonitor_t getDPIForMonitor = NULL;
  830. if (Shcore == NULL) {
  831. Shcore = LoadLibraryW(L"Shcore.dll");
  832. getDPIForMonitor = Shcore ? (GetDPIForMonitor_t)GetProcAddress(Shcore, "GetDpiForMonitor") : NULL;
  833. if ((Shcore == NULL) || (getDPIForMonitor == NULL)) {
  834. if (Shcore)
  835. FreeLibrary(Shcore);
  836. Shcore = (HMODULE)INVALID_HANDLE_VALUE;
  837. }
  838. }
  839. UINT x = 0, y = 0;
  840. HRESULT hr = E_FAIL;
  841. if (hmon && (Shcore != (HMODULE)INVALID_HANDLE_VALUE)) {
  842. hr = getDPIForMonitor(hmon, dpiType /*MDT_Effective_DPI*/, &x, &y);
  843. if (SUCCEEDED(hr) && (x > 0) && (y > 0)) {
  844. dpiX = (int)x;
  845. dpiY = (int)y;
  846. }
  847. } else {
  848. static int overallX = 0, overallY = 0;
  849. if (overallX <= 0 || overallY <= 0) {
  850. HDC hdc = GetDC(NULL);
  851. if (hdc) {
  852. overallX = GetDeviceCaps(hdc, LOGPIXELSX);
  853. overallY = GetDeviceCaps(hdc, LOGPIXELSY);
  854. ReleaseDC(NULL, hdc);
  855. }
  856. }
  857. if (overallX > 0 && overallY > 0) {
  858. dpiX = overallX;
  859. dpiY = overallY;
  860. }
  861. }
  862. return (dpiX + dpiY) / 2;
  863. }
  864. typedef enum _SHC_PROCESS_DPI_AWARENESS {
  865. SHC_PROCESS_DPI_UNAWARE = 0,
  866. SHC_PROCESS_SYSTEM_DPI_AWARE = 1,
  867. SHC_PROCESS_PER_MONITOR_DPI_AWARE = 2
  868. } SHC_PROCESS_DPI_AWARENESS;
  869. int OS_Windows::get_current_video_driver() const {
  870. return video_driver_index;
  871. }
  872. Error OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  873. main_loop = NULL;
  874. outside = true;
  875. window_has_focus = true;
  876. WNDCLASSEXW wc;
  877. if (is_hidpi_allowed()) {
  878. HMODULE Shcore = LoadLibraryW(L"Shcore.dll");
  879. if (Shcore != NULL) {
  880. typedef HRESULT(WINAPI * SetProcessDpiAwareness_t)(SHC_PROCESS_DPI_AWARENESS);
  881. SetProcessDpiAwareness_t SetProcessDpiAwareness = (SetProcessDpiAwareness_t)GetProcAddress(Shcore, "SetProcessDpiAwareness");
  882. if (SetProcessDpiAwareness) {
  883. SetProcessDpiAwareness(SHC_PROCESS_SYSTEM_DPI_AWARE);
  884. }
  885. }
  886. }
  887. video_mode = p_desired;
  888. //printf("**************** desired %s, mode %s\n", p_desired.fullscreen?"true":"false", video_mode.fullscreen?"true":"false");
  889. RECT WindowRect;
  890. WindowRect.left = 0;
  891. WindowRect.right = video_mode.width;
  892. WindowRect.top = 0;
  893. WindowRect.bottom = video_mode.height;
  894. memset(&wc, 0, sizeof(WNDCLASSEXW));
  895. wc.cbSize = sizeof(WNDCLASSEXW);
  896. wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
  897. wc.lpfnWndProc = (WNDPROC)::WndProc;
  898. wc.cbClsExtra = 0;
  899. wc.cbWndExtra = 0;
  900. //wc.hInstance = hInstance;
  901. wc.hInstance = godot_hinstance ? godot_hinstance : GetModuleHandle(NULL);
  902. wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
  903. wc.hCursor = NULL; //LoadCursor(NULL, IDC_ARROW);
  904. wc.hbrBackground = NULL;
  905. wc.lpszMenuName = NULL;
  906. wc.lpszClassName = L"Engine";
  907. if (!RegisterClassExW(&wc)) {
  908. MessageBox(NULL, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
  909. return ERR_UNAVAILABLE;
  910. }
  911. use_raw_input = true;
  912. RAWINPUTDEVICE Rid[1];
  913. Rid[0].usUsagePage = 0x01;
  914. Rid[0].usUsage = 0x02;
  915. Rid[0].dwFlags = 0;
  916. Rid[0].hwndTarget = 0;
  917. if (RegisterRawInputDevices(Rid, 1, sizeof(Rid[0])) == FALSE) {
  918. //registration failed.
  919. use_raw_input = false;
  920. }
  921. pre_fs_valid = true;
  922. if (video_mode.fullscreen) {
  923. /* this returns DPI unaware size, commenting
  924. DEVMODE current;
  925. memset(&current, 0, sizeof(current));
  926. EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &current);
  927. WindowRect.right = current.dmPelsWidth;
  928. WindowRect.bottom = current.dmPelsHeight;
  929. */
  930. EnumSizeData data = { 0, 0, Size2() };
  931. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcSize, (LPARAM)&data);
  932. WindowRect.right = data.size.width;
  933. WindowRect.bottom = data.size.height;
  934. /* DEVMODE dmScreenSettings;
  935. memset(&dmScreenSettings,0,sizeof(dmScreenSettings));
  936. dmScreenSettings.dmSize=sizeof(dmScreenSettings);
  937. dmScreenSettings.dmPelsWidth = video_mode.width;
  938. dmScreenSettings.dmPelsHeight = video_mode.height;
  939. dmScreenSettings.dmBitsPerPel = current.dmBitsPerPel;
  940. dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
  941. LONG err = ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN);
  942. if (err!=DISP_CHANGE_SUCCESSFUL) {
  943. video_mode.fullscreen=false;
  944. }*/
  945. pre_fs_valid = false;
  946. }
  947. DWORD dwExStyle;
  948. DWORD dwStyle;
  949. if (video_mode.fullscreen || video_mode.borderless_window) {
  950. dwExStyle = WS_EX_APPWINDOW;
  951. dwStyle = WS_POPUP;
  952. } else {
  953. dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  954. dwStyle = WS_OVERLAPPEDWINDOW;
  955. if (!video_mode.resizable) {
  956. dwStyle &= ~WS_THICKFRAME;
  957. dwStyle &= ~WS_MAXIMIZEBOX;
  958. }
  959. }
  960. AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);
  961. char *windowid;
  962. #ifdef MINGW_ENABLED
  963. windowid = getenv("GODOT_WINDOWID");
  964. #else
  965. size_t len;
  966. _dupenv_s(&windowid, &len, "GODOT_WINDOWID");
  967. #endif
  968. if (windowid) {
  969. // strtoull on mingw
  970. #ifdef MINGW_ENABLED
  971. hWnd = (HWND)strtoull(windowid, NULL, 0);
  972. #else
  973. hWnd = (HWND)_strtoui64(windowid, NULL, 0);
  974. #endif
  975. free(windowid);
  976. SetLastError(0);
  977. user_proc = (WNDPROC)GetWindowLongPtr(hWnd, GWLP_WNDPROC);
  978. SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)(WNDPROC)::WndProc);
  979. DWORD le = GetLastError();
  980. if (user_proc == 0 && le != 0) {
  981. printf("Error setting WNDPROC: %li\n", le);
  982. };
  983. GetWindowLongPtr(hWnd, GWLP_WNDPROC);
  984. RECT rect;
  985. if (!GetClientRect(hWnd, &rect)) {
  986. MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
  987. return ERR_UNAVAILABLE;
  988. };
  989. video_mode.width = rect.right;
  990. video_mode.height = rect.bottom;
  991. video_mode.fullscreen = false;
  992. } else {
  993. hWnd = CreateWindowExW(
  994. dwExStyle,
  995. L"Engine", L"",
  996. dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
  997. (GetSystemMetrics(SM_CXSCREEN) - WindowRect.right) / 2,
  998. (GetSystemMetrics(SM_CYSCREEN) - WindowRect.bottom) / 2,
  999. WindowRect.right - WindowRect.left,
  1000. WindowRect.bottom - WindowRect.top,
  1001. NULL, NULL, hInstance, NULL);
  1002. if (!hWnd) {
  1003. MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
  1004. return ERR_UNAVAILABLE;
  1005. }
  1006. };
  1007. if (video_mode.always_on_top) {
  1008. SetWindowPos(hWnd, video_mode.always_on_top ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
  1009. }
  1010. #if defined(OPENGL_ENABLED)
  1011. bool gles3_context = true;
  1012. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  1013. gles3_context = false;
  1014. }
  1015. bool editor = Engine::get_singleton()->is_editor_hint();
  1016. bool gl_initialization_error = false;
  1017. gl_context = NULL;
  1018. while (!gl_context) {
  1019. gl_context = memnew(ContextGL_Windows(hWnd, gles3_context));
  1020. if (gl_context->initialize() != OK) {
  1021. memdelete(gl_context);
  1022. gl_context = NULL;
  1023. if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) {
  1024. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  1025. gl_initialization_error = true;
  1026. break;
  1027. }
  1028. p_video_driver = VIDEO_DRIVER_GLES2;
  1029. gles3_context = false;
  1030. } else {
  1031. gl_initialization_error = true;
  1032. break;
  1033. }
  1034. }
  1035. }
  1036. while (true) {
  1037. if (gles3_context) {
  1038. if (RasterizerGLES3::is_viable() == OK) {
  1039. RasterizerGLES3::register_config();
  1040. RasterizerGLES3::make_current();
  1041. break;
  1042. } else {
  1043. if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2") || editor) {
  1044. p_video_driver = VIDEO_DRIVER_GLES2;
  1045. gles3_context = false;
  1046. continue;
  1047. } else {
  1048. gl_initialization_error = true;
  1049. break;
  1050. }
  1051. }
  1052. } else {
  1053. if (RasterizerGLES2::is_viable() == OK) {
  1054. RasterizerGLES2::register_config();
  1055. RasterizerGLES2::make_current();
  1056. break;
  1057. } else {
  1058. gl_initialization_error = true;
  1059. break;
  1060. }
  1061. }
  1062. }
  1063. if (gl_initialization_error) {
  1064. OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n"
  1065. "Please update your drivers or if you have a very old or integrated GPU upgrade it.",
  1066. "Unable to initialize Video driver");
  1067. return ERR_UNAVAILABLE;
  1068. }
  1069. video_driver_index = p_video_driver;
  1070. gl_context->set_use_vsync(video_mode.use_vsync);
  1071. #endif
  1072. visual_server = memnew(VisualServerRaster);
  1073. if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
  1074. visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD));
  1075. }
  1076. visual_server->init();
  1077. input = memnew(InputDefault);
  1078. joypad = memnew(JoypadWindows(input, &hWnd));
  1079. power_manager = memnew(PowerWindows);
  1080. AudioDriverManager::initialize(p_audio_driver);
  1081. TRACKMOUSEEVENT tme;
  1082. tme.cbSize = sizeof(TRACKMOUSEEVENT);
  1083. tme.dwFlags = TME_LEAVE;
  1084. tme.hwndTrack = hWnd;
  1085. tme.dwHoverTime = HOVER_DEFAULT;
  1086. TrackMouseEvent(&tme);
  1087. RegisterTouchWindow(hWnd, 0);
  1088. _ensure_user_data_dir();
  1089. DragAcceptFiles(hWnd, true);
  1090. move_timer_id = 1;
  1091. if (!is_no_window_mode_enabled()) {
  1092. ShowWindow(hWnd, SW_SHOW); // Show The Window
  1093. SetForegroundWindow(hWnd); // Slightly Higher Priority
  1094. SetFocus(hWnd); // Sets Keyboard Focus To
  1095. }
  1096. if (p_desired.layered_splash) {
  1097. set_window_per_pixel_transparency_enabled(true);
  1098. }
  1099. // IME
  1100. im_himc = ImmGetContext(hWnd);
  1101. ImmReleaseContext(hWnd, im_himc);
  1102. im_position = Vector2();
  1103. set_ime_active(false);
  1104. if (!OS::get_singleton()->is_in_low_processor_usage_mode()) {
  1105. //SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
  1106. SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
  1107. DWORD index = 0;
  1108. HANDLE handle = AvSetMmThreadCharacteristics("Games", &index);
  1109. if (handle)
  1110. AvSetMmThreadPriority(handle, AVRT_PRIORITY_CRITICAL);
  1111. // This is needed to make sure that background work does not starve the main thread.
  1112. // This is only setting priority of this thread, not the whole process.
  1113. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  1114. }
  1115. update_real_mouse_position();
  1116. return OK;
  1117. }
  1118. void OS_Windows::set_clipboard(const String &p_text) {
  1119. if (!OpenClipboard(hWnd)) {
  1120. ERR_EXPLAIN("Unable to open clipboard.");
  1121. ERR_FAIL();
  1122. };
  1123. EmptyClipboard();
  1124. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, (p_text.length() + 1) * sizeof(CharType));
  1125. if (mem == NULL) {
  1126. ERR_EXPLAIN("Unable to allocate memory for clipboard contents.");
  1127. ERR_FAIL();
  1128. };
  1129. LPWSTR lptstrCopy = (LPWSTR)GlobalLock(mem);
  1130. memcpy(lptstrCopy, p_text.c_str(), (p_text.length() + 1) * sizeof(CharType));
  1131. //memset((lptstrCopy + p_text.length()), 0, sizeof(CharType));
  1132. GlobalUnlock(mem);
  1133. SetClipboardData(CF_UNICODETEXT, mem);
  1134. // set the CF_TEXT version (not needed?)
  1135. CharString utf8 = p_text.utf8();
  1136. mem = GlobalAlloc(GMEM_MOVEABLE, utf8.length() + 1);
  1137. if (mem == NULL) {
  1138. ERR_EXPLAIN("Unable to allocate memory for clipboard contents.");
  1139. ERR_FAIL();
  1140. };
  1141. LPTSTR ptr = (LPTSTR)GlobalLock(mem);
  1142. memcpy(ptr, utf8.get_data(), utf8.length());
  1143. ptr[utf8.length()] = 0;
  1144. GlobalUnlock(mem);
  1145. SetClipboardData(CF_TEXT, mem);
  1146. CloseClipboard();
  1147. };
  1148. String OS_Windows::get_clipboard() const {
  1149. String ret;
  1150. if (!OpenClipboard(hWnd)) {
  1151. ERR_EXPLAIN("Unable to open clipboard.");
  1152. ERR_FAIL_V("");
  1153. };
  1154. if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
  1155. HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
  1156. if (mem != NULL) {
  1157. LPWSTR ptr = (LPWSTR)GlobalLock(mem);
  1158. if (ptr != NULL) {
  1159. ret = String((CharType *)ptr);
  1160. GlobalUnlock(mem);
  1161. };
  1162. };
  1163. } else if (IsClipboardFormatAvailable(CF_TEXT)) {
  1164. HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
  1165. if (mem != NULL) {
  1166. LPTSTR ptr = (LPTSTR)GlobalLock(mem);
  1167. if (ptr != NULL) {
  1168. ret.parse_utf8((const char *)ptr);
  1169. GlobalUnlock(mem);
  1170. };
  1171. };
  1172. };
  1173. CloseClipboard();
  1174. return ret;
  1175. };
  1176. void OS_Windows::delete_main_loop() {
  1177. if (main_loop)
  1178. memdelete(main_loop);
  1179. main_loop = NULL;
  1180. }
  1181. void OS_Windows::set_main_loop(MainLoop *p_main_loop) {
  1182. input->set_main_loop(p_main_loop);
  1183. main_loop = p_main_loop;
  1184. }
  1185. void OS_Windows::finalize() {
  1186. #ifdef WINMIDI_ENABLED
  1187. driver_midi.close();
  1188. #endif
  1189. if (main_loop)
  1190. memdelete(main_loop);
  1191. main_loop = NULL;
  1192. memdelete(joypad);
  1193. memdelete(input);
  1194. touch_state.clear();
  1195. visual_server->finish();
  1196. memdelete(visual_server);
  1197. #ifdef OPENGL_ENABLED
  1198. if (gl_context)
  1199. memdelete(gl_context);
  1200. #endif
  1201. if (user_proc) {
  1202. SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)user_proc);
  1203. };
  1204. }
  1205. void OS_Windows::finalize_core() {
  1206. timeEndPeriod(1);
  1207. memdelete(process_map);
  1208. NetSocketPosix::cleanup();
  1209. }
  1210. void OS_Windows::alert(const String &p_alert, const String &p_title) {
  1211. if (!is_no_window_mode_enabled())
  1212. MessageBoxW(NULL, p_alert.c_str(), p_title.c_str(), MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
  1213. else
  1214. print_line("ALERT: " + p_alert);
  1215. }
  1216. void OS_Windows::set_mouse_mode(MouseMode p_mode) {
  1217. if (mouse_mode == p_mode)
  1218. return;
  1219. _set_mouse_mode_impl(p_mode);
  1220. mouse_mode = p_mode;
  1221. }
  1222. void OS_Windows::_set_mouse_mode_impl(MouseMode p_mode) {
  1223. if (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_CONFINED) {
  1224. RECT clipRect;
  1225. GetClientRect(hWnd, &clipRect);
  1226. ClientToScreen(hWnd, (POINT *)&clipRect.left);
  1227. ClientToScreen(hWnd, (POINT *)&clipRect.right);
  1228. ClipCursor(&clipRect);
  1229. if (p_mode == MOUSE_MODE_CAPTURED) {
  1230. center = Point2i(video_mode.width / 2, video_mode.height / 2);
  1231. POINT pos = { (int)center.x, (int)center.y };
  1232. ClientToScreen(hWnd, &pos);
  1233. SetCursorPos(pos.x, pos.y);
  1234. SetCapture(hWnd);
  1235. }
  1236. } else {
  1237. ReleaseCapture();
  1238. ClipCursor(NULL);
  1239. }
  1240. if (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_HIDDEN) {
  1241. hCursor = SetCursor(NULL);
  1242. } else {
  1243. CursorShape c = cursor_shape;
  1244. cursor_shape = CURSOR_MAX;
  1245. set_cursor_shape(c);
  1246. }
  1247. }
  1248. OS_Windows::MouseMode OS_Windows::get_mouse_mode() const {
  1249. return mouse_mode;
  1250. }
  1251. void OS_Windows::warp_mouse_position(const Point2 &p_to) {
  1252. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  1253. old_x = p_to.x;
  1254. old_y = p_to.y;
  1255. } else {
  1256. POINT p;
  1257. p.x = p_to.x;
  1258. p.y = p_to.y;
  1259. ClientToScreen(hWnd, &p);
  1260. SetCursorPos(p.x, p.y);
  1261. }
  1262. }
  1263. Point2 OS_Windows::get_mouse_position() const {
  1264. return Point2(old_x, old_y);
  1265. }
  1266. void OS_Windows::update_real_mouse_position() {
  1267. POINT mouse_pos;
  1268. if (GetCursorPos(&mouse_pos) && ScreenToClient(hWnd, &mouse_pos)) {
  1269. if (mouse_pos.x > 0 && mouse_pos.y > 0 && mouse_pos.x <= video_mode.width && mouse_pos.y <= video_mode.height) {
  1270. old_x = mouse_pos.x;
  1271. old_y = mouse_pos.y;
  1272. old_invalid = false;
  1273. input->set_mouse_position(Point2i(mouse_pos.x, mouse_pos.y));
  1274. }
  1275. }
  1276. }
  1277. int OS_Windows::get_mouse_button_state() const {
  1278. return last_button_state;
  1279. }
  1280. void OS_Windows::set_window_title(const String &p_title) {
  1281. SetWindowTextW(hWnd, p_title.c_str());
  1282. }
  1283. void OS_Windows::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  1284. }
  1285. OS::VideoMode OS_Windows::get_video_mode(int p_screen) const {
  1286. return video_mode;
  1287. }
  1288. void OS_Windows::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  1289. }
  1290. static BOOL CALLBACK _MonitorEnumProcCount(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1291. int *data = (int *)dwData;
  1292. (*data)++;
  1293. return TRUE;
  1294. }
  1295. int OS_Windows::get_screen_count() const {
  1296. int data = 0;
  1297. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcCount, (LPARAM)&data);
  1298. return data;
  1299. }
  1300. typedef struct {
  1301. int count;
  1302. int screen;
  1303. HMONITOR monitor;
  1304. } EnumScreenData;
  1305. static BOOL CALLBACK _MonitorEnumProcScreen(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1306. EnumScreenData *data = (EnumScreenData *)dwData;
  1307. if (data->monitor == hMonitor) {
  1308. data->screen = data->count;
  1309. }
  1310. data->count++;
  1311. return TRUE;
  1312. }
  1313. int OS_Windows::get_current_screen() const {
  1314. EnumScreenData data = { 0, 0, MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST) };
  1315. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcScreen, (LPARAM)&data);
  1316. return data.screen;
  1317. }
  1318. void OS_Windows::set_current_screen(int p_screen) {
  1319. Vector2 ofs = get_window_position() - get_screen_position(get_current_screen());
  1320. set_window_position(ofs + get_screen_position(p_screen));
  1321. }
  1322. static BOOL CALLBACK _MonitorEnumProcPos(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1323. EnumPosData *data = (EnumPosData *)dwData;
  1324. if (data->count == data->screen) {
  1325. data->pos.x = lprcMonitor->left;
  1326. data->pos.y = lprcMonitor->top;
  1327. }
  1328. data->count++;
  1329. return TRUE;
  1330. }
  1331. Point2 OS_Windows::get_screen_position(int p_screen) const {
  1332. EnumPosData data = { 0, p_screen == -1 ? get_current_screen() : p_screen, Point2() };
  1333. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcPos, (LPARAM)&data);
  1334. return data.pos;
  1335. }
  1336. Size2 OS_Windows::get_screen_size(int p_screen) const {
  1337. EnumSizeData data = { 0, p_screen == -1 ? get_current_screen() : p_screen, Size2() };
  1338. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcSize, (LPARAM)&data);
  1339. return data.size;
  1340. }
  1341. typedef struct {
  1342. int count;
  1343. int screen;
  1344. int dpi;
  1345. } EnumDpiData;
  1346. static BOOL CALLBACK _MonitorEnumProcDpi(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  1347. EnumDpiData *data = (EnumDpiData *)dwData;
  1348. if (data->count == data->screen) {
  1349. data->dpi = QueryDpiForMonitor(hMonitor);
  1350. }
  1351. data->count++;
  1352. return TRUE;
  1353. }
  1354. int OS_Windows::get_screen_dpi(int p_screen) const {
  1355. EnumDpiData data = { 0, p_screen == -1 ? get_current_screen() : p_screen, 72 };
  1356. EnumDisplayMonitors(NULL, NULL, _MonitorEnumProcDpi, (LPARAM)&data);
  1357. return data.dpi;
  1358. }
  1359. Point2 OS_Windows::get_window_position() const {
  1360. if (minimized) {
  1361. return last_pos;
  1362. }
  1363. RECT r;
  1364. GetWindowRect(hWnd, &r);
  1365. return Point2(r.left, r.top);
  1366. }
  1367. void OS_Windows::set_window_position(const Point2 &p_position) {
  1368. if (video_mode.fullscreen) return;
  1369. RECT r;
  1370. GetWindowRect(hWnd, &r);
  1371. MoveWindow(hWnd, p_position.x, p_position.y, r.right - r.left, r.bottom - r.top, TRUE);
  1372. // Don't let the mouse leave the window when moved
  1373. if (mouse_mode == MOUSE_MODE_CONFINED) {
  1374. RECT rect;
  1375. GetClientRect(hWnd, &rect);
  1376. ClientToScreen(hWnd, (POINT *)&rect.left);
  1377. ClientToScreen(hWnd, (POINT *)&rect.right);
  1378. ClipCursor(&rect);
  1379. }
  1380. last_pos = p_position;
  1381. update_real_mouse_position();
  1382. }
  1383. Size2 OS_Windows::get_window_size() const {
  1384. if (minimized) {
  1385. return Size2(video_mode.width, video_mode.height);
  1386. }
  1387. RECT r;
  1388. if (GetClientRect(hWnd, &r)) { // Only area inside of window border
  1389. return Size2(r.right - r.left, r.bottom - r.top);
  1390. }
  1391. return Size2();
  1392. }
  1393. Size2 OS_Windows::get_real_window_size() const {
  1394. RECT r;
  1395. if (GetWindowRect(hWnd, &r)) { // Includes area of the window border
  1396. return Size2(r.right - r.left, r.bottom - r.top);
  1397. }
  1398. return Size2();
  1399. }
  1400. void OS_Windows::set_window_size(const Size2 p_size) {
  1401. int w = p_size.width;
  1402. int h = p_size.height;
  1403. video_mode.width = w;
  1404. video_mode.height = h;
  1405. if (video_mode.fullscreen) {
  1406. return;
  1407. }
  1408. RECT rect;
  1409. GetWindowRect(hWnd, &rect);
  1410. if (!video_mode.borderless_window) {
  1411. RECT crect;
  1412. GetClientRect(hWnd, &crect);
  1413. w += (rect.right - rect.left) - (crect.right - crect.left);
  1414. h += (rect.bottom - rect.top) - (crect.bottom - crect.top);
  1415. }
  1416. MoveWindow(hWnd, rect.left, rect.top, w, h, TRUE);
  1417. // Don't let the mouse leave the window when resizing to a smaller resolution
  1418. if (mouse_mode == MOUSE_MODE_CONFINED) {
  1419. RECT rect;
  1420. GetClientRect(hWnd, &rect);
  1421. ClientToScreen(hWnd, (POINT *)&rect.left);
  1422. ClientToScreen(hWnd, (POINT *)&rect.right);
  1423. ClipCursor(&rect);
  1424. }
  1425. }
  1426. void OS_Windows::set_window_fullscreen(bool p_enabled) {
  1427. if (video_mode.fullscreen == p_enabled)
  1428. return;
  1429. if (layered_window)
  1430. set_window_per_pixel_transparency_enabled(false);
  1431. if (p_enabled) {
  1432. if (pre_fs_valid) {
  1433. GetWindowRect(hWnd, &pre_fs_rect);
  1434. }
  1435. int cs = get_current_screen();
  1436. Point2 pos = get_screen_position(cs);
  1437. Size2 size = get_screen_size(cs);
  1438. video_mode.fullscreen = true;
  1439. _update_window_style(false);
  1440. MoveWindow(hWnd, pos.x, pos.y, size.width, size.height, TRUE);
  1441. } else {
  1442. RECT rect;
  1443. video_mode.fullscreen = false;
  1444. if (pre_fs_valid) {
  1445. rect = pre_fs_rect;
  1446. } else {
  1447. rect.left = 0;
  1448. rect.right = video_mode.width;
  1449. rect.top = 0;
  1450. rect.bottom = video_mode.height;
  1451. }
  1452. _update_window_style(false);
  1453. MoveWindow(hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
  1454. pre_fs_valid = true;
  1455. }
  1456. }
  1457. bool OS_Windows::is_window_fullscreen() const {
  1458. return video_mode.fullscreen;
  1459. }
  1460. void OS_Windows::set_window_resizable(bool p_enabled) {
  1461. if (video_mode.resizable == p_enabled)
  1462. return;
  1463. video_mode.resizable = p_enabled;
  1464. _update_window_style();
  1465. }
  1466. bool OS_Windows::is_window_resizable() const {
  1467. return video_mode.resizable;
  1468. }
  1469. void OS_Windows::set_window_minimized(bool p_enabled) {
  1470. if (p_enabled) {
  1471. maximized = false;
  1472. minimized = true;
  1473. ShowWindow(hWnd, SW_MINIMIZE);
  1474. } else {
  1475. ShowWindow(hWnd, SW_RESTORE);
  1476. maximized = false;
  1477. minimized = false;
  1478. }
  1479. }
  1480. bool OS_Windows::is_window_minimized() const {
  1481. return minimized;
  1482. }
  1483. void OS_Windows::set_window_maximized(bool p_enabled) {
  1484. if (p_enabled) {
  1485. maximized = true;
  1486. minimized = false;
  1487. ShowWindow(hWnd, SW_MAXIMIZE);
  1488. } else {
  1489. ShowWindow(hWnd, SW_RESTORE);
  1490. maximized = false;
  1491. minimized = false;
  1492. }
  1493. }
  1494. bool OS_Windows::is_window_maximized() const {
  1495. return maximized;
  1496. }
  1497. void OS_Windows::set_window_always_on_top(bool p_enabled) {
  1498. if (video_mode.always_on_top == p_enabled)
  1499. return;
  1500. video_mode.always_on_top = p_enabled;
  1501. _update_window_style();
  1502. }
  1503. bool OS_Windows::is_window_always_on_top() const {
  1504. return video_mode.always_on_top;
  1505. }
  1506. bool OS_Windows::get_window_per_pixel_transparency_enabled() const {
  1507. if (!is_layered_allowed()) return false;
  1508. return layered_window;
  1509. }
  1510. void OS_Windows::set_window_per_pixel_transparency_enabled(bool p_enabled) {
  1511. if (!is_layered_allowed()) return;
  1512. if (layered_window != p_enabled) {
  1513. if (p_enabled) {
  1514. set_borderless_window(true);
  1515. //enable per-pixel alpha
  1516. hDC_dib = CreateCompatibleDC(GetDC(hWnd));
  1517. SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  1518. RECT r;
  1519. GetWindowRect(hWnd, &r);
  1520. dib_size = Size2(r.right - r.left, r.bottom - r.top);
  1521. BITMAPINFO bmi;
  1522. ZeroMemory(&bmi, sizeof(BITMAPINFO));
  1523. bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
  1524. bmi.bmiHeader.biWidth = dib_size.x;
  1525. bmi.bmiHeader.biHeight = dib_size.y;
  1526. bmi.bmiHeader.biPlanes = 1;
  1527. bmi.bmiHeader.biBitCount = 32;
  1528. bmi.bmiHeader.biCompression = BI_RGB;
  1529. bmi.bmiHeader.biSizeImage = dib_size.x * dib_size.y * 4;
  1530. hBitmap = CreateDIBSection(hDC_dib, &bmi, DIB_RGB_COLORS, (void **)&dib_data, NULL, 0x0);
  1531. SelectObject(hDC_dib, hBitmap);
  1532. ZeroMemory(dib_data, dib_size.x * dib_size.y * 4);
  1533. layered_window = true;
  1534. } else {
  1535. //disable per-pixel alpha
  1536. layered_window = false;
  1537. SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  1538. //cleanup
  1539. DeleteObject(hBitmap);
  1540. DeleteDC(hDC_dib);
  1541. }
  1542. }
  1543. }
  1544. uint8_t *OS_Windows::get_layered_buffer_data() {
  1545. return (is_layered_allowed() && layered_window) ? dib_data : NULL;
  1546. }
  1547. Size2 OS_Windows::get_layered_buffer_size() {
  1548. return (is_layered_allowed() && layered_window) ? dib_size : Size2();
  1549. }
  1550. void OS_Windows::swap_layered_buffer() {
  1551. if (is_layered_allowed() && layered_window) {
  1552. //premultiply alpha
  1553. for (int y = 0; y < dib_size.y; y++) {
  1554. for (int x = 0; x < dib_size.x; x++) {
  1555. float alpha = (float)dib_data[y * (int)dib_size.x * 4 + x * 4 + 3] / (float)0xFF;
  1556. dib_data[y * (int)dib_size.x * 4 + x * 4 + 0] *= alpha;
  1557. dib_data[y * (int)dib_size.x * 4 + x * 4 + 1] *= alpha;
  1558. dib_data[y * (int)dib_size.x * 4 + x * 4 + 2] *= alpha;
  1559. }
  1560. }
  1561. //swap layered window buffer
  1562. POINT ptSrc = { 0, 0 };
  1563. SIZE sizeWnd = { (long)dib_size.x, (long)dib_size.y };
  1564. BLENDFUNCTION bf;
  1565. bf.BlendOp = AC_SRC_OVER;
  1566. bf.BlendFlags = 0;
  1567. bf.AlphaFormat = AC_SRC_ALPHA;
  1568. bf.SourceConstantAlpha = 0xFF;
  1569. UpdateLayeredWindow(hWnd, NULL, NULL, &sizeWnd, hDC_dib, &ptSrc, 0, &bf, ULW_ALPHA);
  1570. }
  1571. }
  1572. void OS_Windows::set_borderless_window(bool p_borderless) {
  1573. if (video_mode.borderless_window == p_borderless)
  1574. return;
  1575. if (!p_borderless && layered_window)
  1576. set_window_per_pixel_transparency_enabled(false);
  1577. video_mode.borderless_window = p_borderless;
  1578. preserve_window_size = true;
  1579. _update_window_style();
  1580. }
  1581. bool OS_Windows::get_borderless_window() {
  1582. return video_mode.borderless_window;
  1583. }
  1584. void OS_Windows::_update_window_style(bool repaint) {
  1585. if (video_mode.fullscreen || video_mode.borderless_window) {
  1586. SetWindowLongPtr(hWnd, GWL_STYLE, WS_SYSMENU | WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE);
  1587. } else {
  1588. if (video_mode.resizable) {
  1589. SetWindowLongPtr(hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE);
  1590. } else {
  1591. SetWindowLongPtr(hWnd, GWL_STYLE, WS_CAPTION | WS_MINIMIZEBOX | WS_POPUPWINDOW | WS_VISIBLE);
  1592. }
  1593. }
  1594. SetWindowPos(hWnd, video_mode.always_on_top ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE);
  1595. if (repaint) {
  1596. RECT rect;
  1597. GetWindowRect(hWnd, &rect);
  1598. MoveWindow(hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
  1599. }
  1600. }
  1601. Error OS_Windows::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  1602. String path = p_path;
  1603. if (!FileAccess::exists(path)) {
  1604. //this code exists so gdnative can load .dll files from within the executable path
  1605. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  1606. }
  1607. typedef DLL_DIRECTORY_COOKIE(WINAPI * PAddDllDirectory)(PCWSTR);
  1608. typedef BOOL(WINAPI * PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE);
  1609. PAddDllDirectory add_dll_directory = (PAddDllDirectory)GetProcAddress(GetModuleHandle("kernel32.dll"), "AddDllDirectory");
  1610. PRemoveDllDirectory remove_dll_directory = (PRemoveDllDirectory)GetProcAddress(GetModuleHandle("kernel32.dll"), "RemoveDllDirectory");
  1611. bool has_dll_directory_api = ((add_dll_directory != NULL) && (remove_dll_directory != NULL));
  1612. DLL_DIRECTORY_COOKIE cookie = NULL;
  1613. if (p_also_set_library_path && has_dll_directory_api) {
  1614. cookie = add_dll_directory(path.get_base_dir().c_str());
  1615. }
  1616. p_library_handle = (void *)LoadLibraryExW(path.c_str(), NULL, (p_also_set_library_path && has_dll_directory_api) ? LOAD_LIBRARY_SEARCH_DEFAULT_DIRS : 0);
  1617. if (cookie) {
  1618. remove_dll_directory(cookie);
  1619. }
  1620. if (!p_library_handle) {
  1621. ERR_EXPLAIN("Can't open dynamic library: " + p_path + ". Error: " + format_error_message(GetLastError()));
  1622. ERR_FAIL_V(ERR_CANT_OPEN);
  1623. }
  1624. return OK;
  1625. }
  1626. Error OS_Windows::close_dynamic_library(void *p_library_handle) {
  1627. if (!FreeLibrary((HMODULE)p_library_handle)) {
  1628. return FAILED;
  1629. }
  1630. return OK;
  1631. }
  1632. Error OS_Windows::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  1633. p_symbol_handle = (void *)GetProcAddress((HMODULE)p_library_handle, p_name.utf8().get_data());
  1634. if (!p_symbol_handle) {
  1635. if (!p_optional) {
  1636. ERR_EXPLAIN("Can't resolve symbol " + p_name + ". Error: " + String::num(GetLastError()));
  1637. ERR_FAIL_V(ERR_CANT_RESOLVE);
  1638. } else {
  1639. return ERR_CANT_RESOLVE;
  1640. }
  1641. }
  1642. return OK;
  1643. }
  1644. void OS_Windows::request_attention() {
  1645. FLASHWINFO info;
  1646. info.cbSize = sizeof(FLASHWINFO);
  1647. info.hwnd = hWnd;
  1648. info.dwFlags = FLASHW_TRAY;
  1649. info.dwTimeout = 0;
  1650. info.uCount = 2;
  1651. FlashWindowEx(&info);
  1652. }
  1653. String OS_Windows::get_name() {
  1654. return "Windows";
  1655. }
  1656. OS::Date OS_Windows::get_date(bool utc) const {
  1657. SYSTEMTIME systemtime;
  1658. if (utc)
  1659. GetSystemTime(&systemtime);
  1660. else
  1661. GetLocalTime(&systemtime);
  1662. Date date;
  1663. date.day = systemtime.wDay;
  1664. date.month = Month(systemtime.wMonth);
  1665. date.weekday = Weekday(systemtime.wDayOfWeek);
  1666. date.year = systemtime.wYear;
  1667. date.dst = false;
  1668. return date;
  1669. }
  1670. OS::Time OS_Windows::get_time(bool utc) const {
  1671. SYSTEMTIME systemtime;
  1672. if (utc)
  1673. GetSystemTime(&systemtime);
  1674. else
  1675. GetLocalTime(&systemtime);
  1676. Time time;
  1677. time.hour = systemtime.wHour;
  1678. time.min = systemtime.wMinute;
  1679. time.sec = systemtime.wSecond;
  1680. return time;
  1681. }
  1682. OS::TimeZoneInfo OS_Windows::get_time_zone_info() const {
  1683. TIME_ZONE_INFORMATION info;
  1684. bool daylight = false;
  1685. if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT)
  1686. daylight = true;
  1687. TimeZoneInfo ret;
  1688. if (daylight) {
  1689. ret.name = info.DaylightName;
  1690. } else {
  1691. ret.name = info.StandardName;
  1692. }
  1693. // Bias value returned by GetTimeZoneInformation is inverted of what we expect
  1694. // For example on GMT-3 GetTimeZoneInformation return a Bias of 180, so invert the value to get -180
  1695. ret.bias = -info.Bias;
  1696. return ret;
  1697. }
  1698. uint64_t OS_Windows::get_unix_time() const {
  1699. FILETIME ft;
  1700. SYSTEMTIME st;
  1701. GetSystemTime(&st);
  1702. SystemTimeToFileTime(&st, &ft);
  1703. SYSTEMTIME ep;
  1704. ep.wYear = 1970;
  1705. ep.wMonth = 1;
  1706. ep.wDayOfWeek = 4;
  1707. ep.wDay = 1;
  1708. ep.wHour = 0;
  1709. ep.wMinute = 0;
  1710. ep.wSecond = 0;
  1711. ep.wMilliseconds = 0;
  1712. FILETIME fep;
  1713. SystemTimeToFileTime(&ep, &fep);
  1714. return (*(uint64_t *)&ft - *(uint64_t *)&fep) / 10000000;
  1715. };
  1716. uint64_t OS_Windows::get_system_time_secs() const {
  1717. return get_system_time_msecs() / 1000;
  1718. }
  1719. uint64_t OS_Windows::get_system_time_msecs() const {
  1720. const uint64_t WINDOWS_TICK = 10000;
  1721. const uint64_t MSEC_TO_UNIX_EPOCH = 11644473600000LL;
  1722. SYSTEMTIME st;
  1723. GetSystemTime(&st);
  1724. FILETIME ft;
  1725. SystemTimeToFileTime(&st, &ft);
  1726. uint64_t ret;
  1727. ret = ft.dwHighDateTime;
  1728. ret <<= 32;
  1729. ret |= ft.dwLowDateTime;
  1730. return (uint64_t)(ret / WINDOWS_TICK - MSEC_TO_UNIX_EPOCH);
  1731. }
  1732. void OS_Windows::delay_usec(uint32_t p_usec) const {
  1733. if (p_usec < 1000)
  1734. Sleep(1);
  1735. else
  1736. Sleep(p_usec / 1000);
  1737. }
  1738. uint64_t OS_Windows::get_ticks_usec() const {
  1739. uint64_t ticks;
  1740. uint64_t time;
  1741. // This is the number of clock ticks since start
  1742. if (!QueryPerformanceCounter((LARGE_INTEGER *)&ticks))
  1743. ticks = (UINT64)timeGetTime();
  1744. // Divide by frequency to get the time in seconds
  1745. time = ticks * 1000000L / ticks_per_second;
  1746. // Subtract the time at game start to get
  1747. // the time since the game started
  1748. time -= ticks_start;
  1749. return time;
  1750. }
  1751. void OS_Windows::process_events() {
  1752. MSG msg;
  1753. if (!drop_events) {
  1754. joypad->process_joypads();
  1755. }
  1756. while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
  1757. TranslateMessage(&msg);
  1758. DispatchMessageW(&msg);
  1759. }
  1760. if (!drop_events) {
  1761. process_key_events();
  1762. input->flush_accumulated_events();
  1763. }
  1764. }
  1765. void OS_Windows::set_cursor_shape(CursorShape p_shape) {
  1766. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  1767. if (cursor_shape == p_shape)
  1768. return;
  1769. if (mouse_mode != MOUSE_MODE_VISIBLE && mouse_mode != MOUSE_MODE_CONFINED) {
  1770. cursor_shape = p_shape;
  1771. return;
  1772. }
  1773. static const LPCTSTR win_cursors[CURSOR_MAX] = {
  1774. IDC_ARROW,
  1775. IDC_IBEAM,
  1776. IDC_HAND, //finger
  1777. IDC_CROSS,
  1778. IDC_WAIT,
  1779. IDC_APPSTARTING,
  1780. IDC_ARROW,
  1781. IDC_ARROW,
  1782. IDC_NO,
  1783. IDC_SIZENS,
  1784. IDC_SIZEWE,
  1785. IDC_SIZENESW,
  1786. IDC_SIZENWSE,
  1787. IDC_SIZEALL,
  1788. IDC_SIZENS,
  1789. IDC_SIZEWE,
  1790. IDC_HELP
  1791. };
  1792. if (cursors[p_shape] != NULL) {
  1793. SetCursor(cursors[p_shape]);
  1794. } else {
  1795. SetCursor(LoadCursor(hInstance, win_cursors[p_shape]));
  1796. }
  1797. cursor_shape = p_shape;
  1798. }
  1799. void OS_Windows::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  1800. if (p_cursor.is_valid()) {
  1801. Ref<Texture> texture = p_cursor;
  1802. Ref<AtlasTexture> atlas_texture = p_cursor;
  1803. Ref<Image> image;
  1804. Size2 texture_size;
  1805. Rect2 atlas_rect;
  1806. if (texture.is_valid()) {
  1807. image = texture->get_data();
  1808. }
  1809. if (!image.is_valid() && atlas_texture.is_valid()) {
  1810. texture = atlas_texture->get_atlas();
  1811. atlas_rect.size.width = texture->get_width();
  1812. atlas_rect.size.height = texture->get_height();
  1813. atlas_rect.position.x = atlas_texture->get_region().position.x;
  1814. atlas_rect.position.y = atlas_texture->get_region().position.y;
  1815. texture_size.width = atlas_texture->get_region().size.x;
  1816. texture_size.height = atlas_texture->get_region().size.y;
  1817. } else if (image.is_valid()) {
  1818. texture_size.width = texture->get_width();
  1819. texture_size.height = texture->get_height();
  1820. }
  1821. ERR_FAIL_COND(!texture.is_valid());
  1822. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  1823. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  1824. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  1825. image = texture->get_data();
  1826. ERR_FAIL_COND(!image.is_valid());
  1827. UINT image_size = texture_size.width * texture_size.height;
  1828. // Create the BITMAP with alpha channel
  1829. COLORREF *buffer = (COLORREF *)memalloc(sizeof(COLORREF) * image_size);
  1830. image->lock();
  1831. for (UINT index = 0; index < image_size; index++) {
  1832. int row_index = floor(index / texture_size.width) + atlas_rect.position.y;
  1833. int column_index = (index % int(texture_size.width)) + atlas_rect.position.x;
  1834. if (atlas_texture.is_valid()) {
  1835. column_index = MIN(column_index, atlas_rect.size.width - 1);
  1836. row_index = MIN(row_index, atlas_rect.size.height - 1);
  1837. }
  1838. *(buffer + index) = image->get_pixel(column_index, row_index).to_argb32();
  1839. }
  1840. image->unlock();
  1841. // Using 4 channels, so 4 * 8 bits
  1842. HBITMAP bitmap = CreateBitmap(texture_size.width, texture_size.height, 1, 4 * 8, buffer);
  1843. COLORREF clrTransparent = -1;
  1844. // Create the AND and XOR masks for the bitmap
  1845. HBITMAP hAndMask = NULL;
  1846. HBITMAP hXorMask = NULL;
  1847. GetMaskBitmaps(bitmap, clrTransparent, hAndMask, hXorMask);
  1848. if (NULL == hAndMask || NULL == hXorMask) {
  1849. memfree(buffer);
  1850. DeleteObject(bitmap);
  1851. return;
  1852. }
  1853. // Finally, create the icon
  1854. ICONINFO iconinfo = { 0 };
  1855. iconinfo.fIcon = FALSE;
  1856. iconinfo.xHotspot = p_hotspot.x;
  1857. iconinfo.yHotspot = p_hotspot.y;
  1858. iconinfo.hbmMask = hAndMask;
  1859. iconinfo.hbmColor = hXorMask;
  1860. if (cursors[p_shape])
  1861. DestroyIcon(cursors[p_shape]);
  1862. cursors[p_shape] = CreateIconIndirect(&iconinfo);
  1863. if (p_shape == cursor_shape) {
  1864. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  1865. SetCursor(cursors[p_shape]);
  1866. }
  1867. }
  1868. if (hAndMask != NULL) {
  1869. DeleteObject(hAndMask);
  1870. }
  1871. if (hXorMask != NULL) {
  1872. DeleteObject(hXorMask);
  1873. }
  1874. memfree(buffer);
  1875. DeleteObject(bitmap);
  1876. } else {
  1877. // Reset to default system cursor
  1878. cursors[p_shape] = NULL;
  1879. CursorShape c = cursor_shape;
  1880. cursor_shape = CURSOR_MAX;
  1881. set_cursor_shape(c);
  1882. }
  1883. }
  1884. void OS_Windows::GetMaskBitmaps(HBITMAP hSourceBitmap, COLORREF clrTransparent, OUT HBITMAP &hAndMaskBitmap, OUT HBITMAP &hXorMaskBitmap) {
  1885. // Get the system display DC
  1886. HDC hDC = GetDC(NULL);
  1887. // Create helper DC
  1888. HDC hMainDC = CreateCompatibleDC(hDC);
  1889. HDC hAndMaskDC = CreateCompatibleDC(hDC);
  1890. HDC hXorMaskDC = CreateCompatibleDC(hDC);
  1891. // Get the dimensions of the source bitmap
  1892. BITMAP bm;
  1893. GetObject(hSourceBitmap, sizeof(BITMAP), &bm);
  1894. // Create the mask bitmaps
  1895. hAndMaskBitmap = CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); // color
  1896. hXorMaskBitmap = CreateCompatibleBitmap(hDC, bm.bmWidth, bm.bmHeight); // color
  1897. // Release the system display DC
  1898. ReleaseDC(NULL, hDC);
  1899. // Select the bitmaps to helper DC
  1900. HBITMAP hOldMainBitmap = (HBITMAP)SelectObject(hMainDC, hSourceBitmap);
  1901. HBITMAP hOldAndMaskBitmap = (HBITMAP)SelectObject(hAndMaskDC, hAndMaskBitmap);
  1902. HBITMAP hOldXorMaskBitmap = (HBITMAP)SelectObject(hXorMaskDC, hXorMaskBitmap);
  1903. // Assign the monochrome AND mask bitmap pixels so that a pixels of the source bitmap
  1904. // with 'clrTransparent' will be white pixels of the monochrome bitmap
  1905. SetBkColor(hMainDC, clrTransparent);
  1906. BitBlt(hAndMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hMainDC, 0, 0, SRCCOPY);
  1907. // Assign the color XOR mask bitmap pixels so that a pixels of the source bitmap
  1908. // with 'clrTransparent' will be black and rest the pixels same as corresponding
  1909. // pixels of the source bitmap
  1910. SetBkColor(hXorMaskDC, RGB(0, 0, 0));
  1911. SetTextColor(hXorMaskDC, RGB(255, 255, 255));
  1912. BitBlt(hXorMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hAndMaskDC, 0, 0, SRCCOPY);
  1913. BitBlt(hXorMaskDC, 0, 0, bm.bmWidth, bm.bmHeight, hMainDC, 0, 0, SRCAND);
  1914. // Deselect bitmaps from the helper DC
  1915. SelectObject(hMainDC, hOldMainBitmap);
  1916. SelectObject(hAndMaskDC, hOldAndMaskBitmap);
  1917. SelectObject(hXorMaskDC, hOldXorMaskBitmap);
  1918. // Delete the helper DC
  1919. DeleteDC(hXorMaskDC);
  1920. DeleteDC(hAndMaskDC);
  1921. DeleteDC(hMainDC);
  1922. }
  1923. 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) {
  1924. if (p_blocking && r_pipe) {
  1925. String argss;
  1926. argss = "\"\"" + p_path + "\"";
  1927. for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
  1928. argss += String(" \"") + E->get() + "\"";
  1929. }
  1930. FILE *f = _wpopen(argss.c_str(), L"r");
  1931. ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
  1932. char buf[65535];
  1933. while (fgets(buf, 65535, f)) {
  1934. (*r_pipe) += buf;
  1935. }
  1936. int rv = _pclose(f);
  1937. if (r_exitcode)
  1938. *r_exitcode = rv;
  1939. return OK;
  1940. }
  1941. String cmdline = "\"" + p_path + "\"";
  1942. const List<String>::Element *I = p_arguments.front();
  1943. while (I) {
  1944. cmdline += " \"" + I->get() + "\"";
  1945. I = I->next();
  1946. };
  1947. ProcessInfo pi;
  1948. ZeroMemory(&pi.si, sizeof(pi.si));
  1949. pi.si.cb = sizeof(pi.si);
  1950. ZeroMemory(&pi.pi, sizeof(pi.pi));
  1951. LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si;
  1952. Vector<CharType> modstr; //windows wants to change this no idea why
  1953. modstr.resize(cmdline.size());
  1954. for (int i = 0; i < cmdline.size(); i++)
  1955. modstr.write[i] = cmdline[i];
  1956. int ret = CreateProcessW(NULL, modstr.ptrw(), NULL, NULL, 0, NORMAL_PRIORITY_CLASS, NULL, NULL, si_w, &pi.pi);
  1957. ERR_FAIL_COND_V(ret == 0, ERR_CANT_FORK);
  1958. if (p_blocking) {
  1959. DWORD ret = WaitForSingleObject(pi.pi.hProcess, INFINITE);
  1960. if (r_exitcode)
  1961. *r_exitcode = ret;
  1962. CloseHandle(pi.pi.hProcess);
  1963. CloseHandle(pi.pi.hThread);
  1964. } else {
  1965. ProcessID pid = pi.pi.dwProcessId;
  1966. if (r_child_id) {
  1967. *r_child_id = pid;
  1968. };
  1969. process_map->insert(pid, pi);
  1970. };
  1971. return OK;
  1972. };
  1973. Error OS_Windows::kill(const ProcessID &p_pid) {
  1974. ERR_FAIL_COND_V(!process_map->has(p_pid), FAILED);
  1975. const PROCESS_INFORMATION pi = (*process_map)[p_pid].pi;
  1976. process_map->erase(p_pid);
  1977. const int ret = TerminateProcess(pi.hProcess, 0);
  1978. CloseHandle(pi.hProcess);
  1979. CloseHandle(pi.hThread);
  1980. return ret != 0 ? OK : FAILED;
  1981. };
  1982. int OS_Windows::get_process_id() const {
  1983. return _getpid();
  1984. }
  1985. Error OS_Windows::set_cwd(const String &p_cwd) {
  1986. if (_wchdir(p_cwd.c_str()) != 0)
  1987. return ERR_CANT_OPEN;
  1988. return OK;
  1989. }
  1990. String OS_Windows::get_executable_path() const {
  1991. wchar_t bufname[4096];
  1992. GetModuleFileNameW(NULL, bufname, 4096);
  1993. String s = bufname;
  1994. return s;
  1995. }
  1996. void OS_Windows::set_icon(const Ref<Image> &p_icon) {
  1997. ERR_FAIL_COND(!p_icon.is_valid());
  1998. Ref<Image> icon = p_icon->duplicate();
  1999. if (icon->get_format() != Image::FORMAT_RGBA8)
  2000. icon->convert(Image::FORMAT_RGBA8);
  2001. int w = icon->get_width();
  2002. int h = icon->get_height();
  2003. /* Create temporary bitmap buffer */
  2004. int icon_len = 40 + h * w * 4;
  2005. Vector<BYTE> v;
  2006. v.resize(icon_len);
  2007. BYTE *icon_bmp = v.ptrw();
  2008. encode_uint32(40, &icon_bmp[0]);
  2009. encode_uint32(w, &icon_bmp[4]);
  2010. encode_uint32(h * 2, &icon_bmp[8]);
  2011. encode_uint16(1, &icon_bmp[12]);
  2012. encode_uint16(32, &icon_bmp[14]);
  2013. encode_uint32(BI_RGB, &icon_bmp[16]);
  2014. encode_uint32(w * h * 4, &icon_bmp[20]);
  2015. encode_uint32(0, &icon_bmp[24]);
  2016. encode_uint32(0, &icon_bmp[28]);
  2017. encode_uint32(0, &icon_bmp[32]);
  2018. encode_uint32(0, &icon_bmp[36]);
  2019. uint8_t *wr = &icon_bmp[40];
  2020. PoolVector<uint8_t>::Read r = icon->get_data().read();
  2021. for (int i = 0; i < h; i++) {
  2022. for (int j = 0; j < w; j++) {
  2023. const uint8_t *rpx = &r[((h - i - 1) * w + j) * 4];
  2024. uint8_t *wpx = &wr[(i * w + j) * 4];
  2025. wpx[0] = rpx[2];
  2026. wpx[1] = rpx[1];
  2027. wpx[2] = rpx[0];
  2028. wpx[3] = rpx[3];
  2029. }
  2030. }
  2031. HICON hicon = CreateIconFromResource(icon_bmp, icon_len, TRUE, 0x00030000);
  2032. /* Set the icon for the window */
  2033. SendMessage(hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hicon);
  2034. /* Set the icon in the task manager (should we do this?) */
  2035. SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hicon);
  2036. }
  2037. bool OS_Windows::has_environment(const String &p_var) const {
  2038. #ifdef MINGW_ENABLED
  2039. return _wgetenv(p_var.c_str()) != NULL;
  2040. #else
  2041. wchar_t *env;
  2042. size_t len;
  2043. _wdupenv_s(&env, &len, p_var.c_str());
  2044. const bool has_env = env != NULL;
  2045. free(env);
  2046. return has_env;
  2047. #endif
  2048. };
  2049. String OS_Windows::get_environment(const String &p_var) const {
  2050. wchar_t wval[0x7Fff]; // MSDN says 32767 char is the maximum
  2051. int wlen = GetEnvironmentVariableW(p_var.c_str(), wval, 0x7Fff);
  2052. if (wlen > 0) {
  2053. return wval;
  2054. }
  2055. return "";
  2056. }
  2057. bool OS_Windows::set_environment(const String &p_var, const String &p_value) const {
  2058. return (bool)SetEnvironmentVariableW(p_var.c_str(), p_value.c_str());
  2059. }
  2060. String OS_Windows::get_stdin_string(bool p_block) {
  2061. if (p_block) {
  2062. char buff[1024];
  2063. return fgets(buff, 1024, stdin);
  2064. };
  2065. return String();
  2066. }
  2067. void OS_Windows::enable_for_stealing_focus(ProcessID pid) {
  2068. AllowSetForegroundWindow(pid);
  2069. }
  2070. void OS_Windows::move_window_to_foreground() {
  2071. SetForegroundWindow(hWnd);
  2072. }
  2073. Error OS_Windows::shell_open(String p_uri) {
  2074. ShellExecuteW(NULL, L"open", p_uri.c_str(), NULL, NULL, SW_SHOWNORMAL);
  2075. return OK;
  2076. }
  2077. String OS_Windows::get_locale() const {
  2078. const _WinLocale *wl = &_win_locales[0];
  2079. LANGID langid = GetUserDefaultUILanguage();
  2080. String neutral;
  2081. int lang = langid & ((1 << 9) - 1);
  2082. int sublang = langid & ~((1 << 9) - 1);
  2083. while (wl->locale) {
  2084. if (wl->main_lang == lang && wl->sublang == SUBLANG_NEUTRAL)
  2085. neutral = wl->locale;
  2086. if (lang == wl->main_lang && sublang == wl->sublang)
  2087. return wl->locale;
  2088. wl++;
  2089. }
  2090. if (neutral != "")
  2091. return neutral;
  2092. return "en";
  2093. }
  2094. // We need this because GetSystemInfo() is unreliable on WOW64
  2095. // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms724381(v=vs.85).aspx
  2096. // Taken from MSDN
  2097. typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
  2098. LPFN_ISWOW64PROCESS fnIsWow64Process;
  2099. BOOL is_wow64() {
  2100. BOOL wow64 = FALSE;
  2101. fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
  2102. if (fnIsWow64Process) {
  2103. if (!fnIsWow64Process(GetCurrentProcess(), &wow64)) {
  2104. wow64 = FALSE;
  2105. }
  2106. }
  2107. return wow64;
  2108. }
  2109. int OS_Windows::get_processor_count() const {
  2110. SYSTEM_INFO sysinfo;
  2111. if (is_wow64())
  2112. GetNativeSystemInfo(&sysinfo);
  2113. else
  2114. GetSystemInfo(&sysinfo);
  2115. return sysinfo.dwNumberOfProcessors;
  2116. }
  2117. OS::LatinKeyboardVariant OS_Windows::get_latin_keyboard_variant() const {
  2118. unsigned long azerty[] = {
  2119. 0x00020401, // Arabic (102) AZERTY
  2120. 0x0001080c, // Belgian (Comma)
  2121. 0x0000080c, // Belgian French
  2122. 0x0000040c, // French
  2123. 0 // <--- STOP MARK
  2124. };
  2125. unsigned long qwertz[] = {
  2126. 0x0000041a, // Croation
  2127. 0x00000405, // Czech
  2128. 0x00000407, // German
  2129. 0x00010407, // German (IBM)
  2130. 0x0000040e, // Hungarian
  2131. 0x0000046e, // Luxembourgish
  2132. 0x00010415, // Polish (214)
  2133. 0x00000418, // Romanian (Legacy)
  2134. 0x0000081a, // Serbian (Latin)
  2135. 0x0000041b, // Slovak
  2136. 0x00000424, // Slovenian
  2137. 0x0001042e, // Sorbian Extended
  2138. 0x0002042e, // Sorbian Standard
  2139. 0x0000042e, // Sorbian Standard (Legacy)
  2140. 0x0000100c, // Swiss French
  2141. 0x00000807, // Swiss German
  2142. 0 // <--- STOP MARK
  2143. };
  2144. unsigned long dvorak[] = {
  2145. 0x00010409, // US-Dvorak
  2146. 0x00030409, // US-Dvorak for left hand
  2147. 0x00040409, // US-Dvorak for right hand
  2148. 0 // <--- STOP MARK
  2149. };
  2150. char name[KL_NAMELENGTH + 1];
  2151. name[0] = 0;
  2152. GetKeyboardLayoutNameA(name);
  2153. unsigned long hex = strtoul(name, NULL, 16);
  2154. int i = 0;
  2155. while (azerty[i] != 0) {
  2156. if (azerty[i] == hex) return LATIN_KEYBOARD_AZERTY;
  2157. i++;
  2158. }
  2159. i = 0;
  2160. while (qwertz[i] != 0) {
  2161. if (qwertz[i] == hex) return LATIN_KEYBOARD_QWERTZ;
  2162. i++;
  2163. }
  2164. i = 0;
  2165. while (dvorak[i] != 0) {
  2166. if (dvorak[i] == hex) return LATIN_KEYBOARD_DVORAK;
  2167. i++;
  2168. }
  2169. return LATIN_KEYBOARD_QWERTY;
  2170. }
  2171. void OS_Windows::release_rendering_thread() {
  2172. gl_context->release_current();
  2173. }
  2174. void OS_Windows::make_rendering_thread() {
  2175. gl_context->make_current();
  2176. }
  2177. void OS_Windows::swap_buffers() {
  2178. gl_context->swap_buffers();
  2179. }
  2180. void OS_Windows::force_process_input() {
  2181. process_events(); // get rid of pending events
  2182. }
  2183. void OS_Windows::run() {
  2184. if (!main_loop)
  2185. return;
  2186. main_loop->init();
  2187. while (!force_quit) {
  2188. process_events(); // get rid of pending events
  2189. if (Main::iteration())
  2190. break;
  2191. };
  2192. main_loop->finish();
  2193. }
  2194. MainLoop *OS_Windows::get_main_loop() const {
  2195. return main_loop;
  2196. }
  2197. String OS_Windows::get_config_path() const {
  2198. if (has_environment("XDG_CONFIG_HOME")) { // unlikely, but after all why not?
  2199. return get_environment("XDG_CONFIG_HOME");
  2200. } else if (has_environment("APPDATA")) {
  2201. return get_environment("APPDATA");
  2202. } else {
  2203. return ".";
  2204. }
  2205. }
  2206. String OS_Windows::get_data_path() const {
  2207. if (has_environment("XDG_DATA_HOME")) {
  2208. return get_environment("XDG_DATA_HOME");
  2209. } else {
  2210. return get_config_path();
  2211. }
  2212. }
  2213. String OS_Windows::get_cache_path() const {
  2214. if (has_environment("XDG_CACHE_HOME")) {
  2215. return get_environment("XDG_CACHE_HOME");
  2216. } else if (has_environment("TEMP")) {
  2217. return get_environment("TEMP");
  2218. } else {
  2219. return get_config_path();
  2220. }
  2221. }
  2222. // Get properly capitalized engine name for system paths
  2223. String OS_Windows::get_godot_dir_name() const {
  2224. return String(VERSION_SHORT_NAME).capitalize();
  2225. }
  2226. String OS_Windows::get_system_dir(SystemDir p_dir) const {
  2227. int id;
  2228. switch (p_dir) {
  2229. case SYSTEM_DIR_DESKTOP: {
  2230. id = CSIDL_DESKTOPDIRECTORY;
  2231. } break;
  2232. case SYSTEM_DIR_DCIM: {
  2233. id = CSIDL_MYPICTURES;
  2234. } break;
  2235. case SYSTEM_DIR_DOCUMENTS: {
  2236. id = CSIDL_PERSONAL;
  2237. } break;
  2238. case SYSTEM_DIR_DOWNLOADS: {
  2239. id = 0x000C;
  2240. } break;
  2241. case SYSTEM_DIR_MOVIES: {
  2242. id = CSIDL_MYVIDEO;
  2243. } break;
  2244. case SYSTEM_DIR_MUSIC: {
  2245. id = CSIDL_MYMUSIC;
  2246. } break;
  2247. case SYSTEM_DIR_PICTURES: {
  2248. id = CSIDL_MYPICTURES;
  2249. } break;
  2250. case SYSTEM_DIR_RINGTONES: {
  2251. id = CSIDL_MYMUSIC;
  2252. } break;
  2253. }
  2254. WCHAR szPath[MAX_PATH];
  2255. HRESULT res = SHGetFolderPathW(NULL, id, NULL, 0, szPath);
  2256. ERR_FAIL_COND_V(res != S_OK, String());
  2257. return String(szPath);
  2258. }
  2259. String OS_Windows::get_user_data_dir() const {
  2260. String appname = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
  2261. if (appname != "") {
  2262. bool use_custom_dir = ProjectSettings::get_singleton()->get("application/config/use_custom_user_dir");
  2263. if (use_custom_dir) {
  2264. String custom_dir = get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/custom_user_dir_name"), true);
  2265. if (custom_dir == "") {
  2266. custom_dir = appname;
  2267. }
  2268. return get_data_path().plus_file(custom_dir).replace("\\", "/");
  2269. } else {
  2270. return get_data_path().plus_file(get_godot_dir_name()).plus_file("app_userdata").plus_file(appname).replace("\\", "/");
  2271. }
  2272. }
  2273. return ProjectSettings::get_singleton()->get_resource_path();
  2274. }
  2275. String OS_Windows::get_unique_id() const {
  2276. HW_PROFILE_INFO HwProfInfo;
  2277. ERR_FAIL_COND_V(!GetCurrentHwProfile(&HwProfInfo), "");
  2278. return String(HwProfInfo.szHwProfileGuid);
  2279. }
  2280. void OS_Windows::set_ime_active(const bool p_active) {
  2281. if (p_active) {
  2282. ImmAssociateContext(hWnd, im_himc);
  2283. set_ime_position(im_position);
  2284. } else {
  2285. ImmAssociateContext(hWnd, (HIMC)0);
  2286. }
  2287. }
  2288. void OS_Windows::set_ime_position(const Point2 &p_pos) {
  2289. im_position = p_pos;
  2290. HIMC himc = ImmGetContext(hWnd);
  2291. if (himc == (HIMC)0)
  2292. return;
  2293. COMPOSITIONFORM cps;
  2294. cps.dwStyle = CFS_FORCE_POSITION;
  2295. cps.ptCurrentPos.x = im_position.x;
  2296. cps.ptCurrentPos.y = im_position.y;
  2297. ImmSetCompositionWindow(himc, &cps);
  2298. ImmReleaseContext(hWnd, himc);
  2299. }
  2300. bool OS_Windows::is_joy_known(int p_device) {
  2301. return input->is_joy_mapped(p_device);
  2302. }
  2303. String OS_Windows::get_joy_guid(int p_device) const {
  2304. return input->get_joy_guid_remapped(p_device);
  2305. }
  2306. void OS_Windows::_set_use_vsync(bool p_enable) {
  2307. if (gl_context)
  2308. gl_context->set_use_vsync(p_enable);
  2309. }
  2310. /*
  2311. bool OS_Windows::is_vsync_enabled() const {
  2312. if (gl_context)
  2313. return gl_context->is_using_vsync();
  2314. return true;
  2315. }*/
  2316. OS::PowerState OS_Windows::get_power_state() {
  2317. return power_manager->get_power_state();
  2318. }
  2319. int OS_Windows::get_power_seconds_left() {
  2320. return power_manager->get_power_seconds_left();
  2321. }
  2322. int OS_Windows::get_power_percent_left() {
  2323. return power_manager->get_power_percent_left();
  2324. }
  2325. bool OS_Windows::_check_internal_feature_support(const String &p_feature) {
  2326. return p_feature == "pc";
  2327. }
  2328. void OS_Windows::disable_crash_handler() {
  2329. crash_handler.disable();
  2330. }
  2331. bool OS_Windows::is_disable_crash_handler() const {
  2332. return crash_handler.is_disabled();
  2333. }
  2334. void OS_Windows::process_and_drop_events() {
  2335. drop_events = true;
  2336. process_events();
  2337. drop_events = false;
  2338. }
  2339. Error OS_Windows::move_to_trash(const String &p_path) {
  2340. SHFILEOPSTRUCTW sf;
  2341. WCHAR *from = new WCHAR[p_path.length() + 2];
  2342. wcscpy_s(from, p_path.length() + 1, p_path.c_str());
  2343. from[p_path.length() + 1] = 0;
  2344. sf.hwnd = hWnd;
  2345. sf.wFunc = FO_DELETE;
  2346. sf.pFrom = from;
  2347. sf.pTo = NULL;
  2348. sf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
  2349. sf.fAnyOperationsAborted = FALSE;
  2350. sf.hNameMappings = NULL;
  2351. sf.lpszProgressTitle = NULL;
  2352. int ret = SHFileOperationW(&sf);
  2353. delete[] from;
  2354. if (ret) {
  2355. ERR_PRINTS("SHFileOperation error: " + itos(ret));
  2356. return FAILED;
  2357. }
  2358. return OK;
  2359. }
  2360. OS_Windows::OS_Windows(HINSTANCE _hInstance) {
  2361. drop_events = false;
  2362. key_event_pos = 0;
  2363. layered_window = false;
  2364. hBitmap = NULL;
  2365. force_quit = false;
  2366. alt_mem = false;
  2367. gr_mem = false;
  2368. shift_mem = false;
  2369. control_mem = false;
  2370. meta_mem = false;
  2371. minimized = false;
  2372. hInstance = _hInstance;
  2373. pressrc = 0;
  2374. old_invalid = true;
  2375. mouse_mode = MOUSE_MODE_VISIBLE;
  2376. #ifdef STDOUT_FILE
  2377. stdo = fopen("stdout.txt", "wb");
  2378. #endif
  2379. user_proc = NULL;
  2380. #ifdef WASAPI_ENABLED
  2381. AudioDriverManager::add_driver(&driver_wasapi);
  2382. #endif
  2383. #ifdef XAUDIO2_ENABLED
  2384. AudioDriverManager::add_driver(&driver_xaudio2);
  2385. #endif
  2386. Vector<Logger *> loggers;
  2387. loggers.push_back(memnew(WindowsTerminalLogger));
  2388. _set_logger(memnew(CompositeLogger(loggers)));
  2389. }
  2390. OS_Windows::~OS_Windows() {
  2391. if (is_layered_allowed() && layered_window) {
  2392. DeleteObject(hBitmap);
  2393. DeleteDC(hDC_dib);
  2394. }
  2395. #ifdef STDOUT_FILE
  2396. fclose(stdo);
  2397. #endif
  2398. }