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