os_windows.cpp 74 KB

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