os_windows.cpp 101 KB

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