2
0

os_windows.cpp 86 KB

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