os_windows.cpp 98 KB

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