os_windows.cpp 99 KB

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