2
0

os_windows.cpp 110 KB

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