display_server_windows.cpp 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011
  1. /*************************************************************************/
  2. /* display_server_windows.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "display_server_windows.h"
  31. #include "core/io/marshalls.h"
  32. #include "core/math/geometry_2d.h"
  33. #include "main/main.h"
  34. #include "os_windows.h"
  35. #include "scene/resources/texture.h"
  36. #include <avrt.h>
  37. #include <dwmapi.h>
  38. #ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
  39. #define DWMWA_USE_IMMERSIVE_DARK_MODE 20
  40. #endif
  41. #if defined(GLES3_ENABLED)
  42. #include "drivers/gles3/rasterizer_gles3.h"
  43. #endif
  44. #if defined(__GNUC__)
  45. // Workaround GCC warning from -Wcast-function-type.
  46. #define GetProcAddress (void *)GetProcAddress
  47. #endif
  48. static String format_error_message(DWORD id) {
  49. LPWSTR messageBuffer = nullptr;
  50. size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  51. nullptr, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, nullptr);
  52. String msg = "Error " + itos(id) + ": " + String::utf16((const char16_t *)messageBuffer, size);
  53. LocalFree(messageBuffer);
  54. return msg;
  55. }
  56. static void track_mouse_leave_event(HWND hWnd) {
  57. TRACKMOUSEEVENT tme;
  58. tme.cbSize = sizeof(TRACKMOUSEEVENT);
  59. tme.dwFlags = TME_LEAVE;
  60. tme.hwndTrack = hWnd;
  61. tme.dwHoverTime = HOVER_DEFAULT;
  62. TrackMouseEvent(&tme);
  63. }
  64. bool DisplayServerWindows::has_feature(Feature p_feature) const {
  65. switch (p_feature) {
  66. case FEATURE_SUBWINDOWS:
  67. case FEATURE_TOUCHSCREEN:
  68. case FEATURE_MOUSE:
  69. case FEATURE_MOUSE_WARP:
  70. case FEATURE_CLIPBOARD:
  71. case FEATURE_CURSOR_SHAPE:
  72. case FEATURE_CUSTOM_CURSOR_SHAPE:
  73. case FEATURE_IME:
  74. case FEATURE_WINDOW_TRANSPARENCY:
  75. case FEATURE_HIDPI:
  76. case FEATURE_ICON:
  77. case FEATURE_NATIVE_ICON:
  78. case FEATURE_SWAP_BUFFERS:
  79. case FEATURE_KEEP_SCREEN_ON:
  80. case FEATURE_TEXT_TO_SPEECH:
  81. return true;
  82. default:
  83. return false;
  84. }
  85. }
  86. String DisplayServerWindows::get_name() const {
  87. return "Windows";
  88. }
  89. void DisplayServerWindows::_set_mouse_mode_impl(MouseMode p_mode) {
  90. if (windows.has(MAIN_WINDOW_ID) && (p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_CONFINED || p_mode == MOUSE_MODE_CONFINED_HIDDEN)) {
  91. // Mouse is grabbed (captured or confined).
  92. WindowID window_id = _get_focused_window_or_popup();
  93. if (!windows.has(window_id)) {
  94. window_id = MAIN_WINDOW_ID;
  95. }
  96. WindowData &wd = windows[window_id];
  97. RECT clipRect;
  98. GetClientRect(wd.hWnd, &clipRect);
  99. ClientToScreen(wd.hWnd, (POINT *)&clipRect.left);
  100. ClientToScreen(wd.hWnd, (POINT *)&clipRect.right);
  101. ClipCursor(&clipRect);
  102. if (p_mode == MOUSE_MODE_CAPTURED) {
  103. center = window_get_size() / 2;
  104. POINT pos = { (int)center.x, (int)center.y };
  105. ClientToScreen(wd.hWnd, &pos);
  106. SetCursorPos(pos.x, pos.y);
  107. SetCapture(wd.hWnd);
  108. _register_raw_input_devices(window_id);
  109. }
  110. } else {
  111. // Mouse is free to move around (not captured or confined).
  112. ReleaseCapture();
  113. ClipCursor(nullptr);
  114. _register_raw_input_devices(INVALID_WINDOW_ID);
  115. }
  116. if (p_mode == MOUSE_MODE_HIDDEN || p_mode == MOUSE_MODE_CAPTURED || p_mode == MOUSE_MODE_CONFINED_HIDDEN) {
  117. if (hCursor == nullptr) {
  118. hCursor = SetCursor(nullptr);
  119. } else {
  120. SetCursor(nullptr);
  121. }
  122. } else {
  123. CursorShape c = cursor_shape;
  124. cursor_shape = CURSOR_MAX;
  125. cursor_set_shape(c);
  126. }
  127. }
  128. DisplayServer::WindowID DisplayServerWindows::_get_focused_window_or_popup() const {
  129. const List<WindowID>::Element *E = popup_list.back();
  130. if (E) {
  131. return E->get();
  132. }
  133. return last_focused_window;
  134. }
  135. void DisplayServerWindows::_register_raw_input_devices(WindowID p_target_window) {
  136. use_raw_input = true;
  137. RAWINPUTDEVICE rid[1] = {};
  138. rid[0].usUsagePage = 0x01;
  139. rid[0].usUsage = 0x02;
  140. rid[0].dwFlags = 0;
  141. if (p_target_window != INVALID_WINDOW_ID && windows.has(p_target_window)) {
  142. // Follow the defined window
  143. rid[0].hwndTarget = windows[p_target_window].hWnd;
  144. } else {
  145. // Follow the keyboard focus
  146. rid[0].hwndTarget = 0;
  147. }
  148. if (RegisterRawInputDevices(rid, 1, sizeof(rid[0])) == FALSE) {
  149. // Registration failed.
  150. use_raw_input = false;
  151. }
  152. }
  153. bool DisplayServerWindows::tts_is_speaking() const {
  154. ERR_FAIL_COND_V(!tts, false);
  155. return tts->is_speaking();
  156. }
  157. bool DisplayServerWindows::tts_is_paused() const {
  158. ERR_FAIL_COND_V(!tts, false);
  159. return tts->is_paused();
  160. }
  161. TypedArray<Dictionary> DisplayServerWindows::tts_get_voices() const {
  162. ERR_FAIL_COND_V(!tts, TypedArray<Dictionary>());
  163. return tts->get_voices();
  164. }
  165. void DisplayServerWindows::tts_speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
  166. ERR_FAIL_COND(!tts);
  167. tts->speak(p_text, p_voice, p_volume, p_pitch, p_rate, p_utterance_id, p_interrupt);
  168. }
  169. void DisplayServerWindows::tts_pause() {
  170. ERR_FAIL_COND(!tts);
  171. tts->pause();
  172. }
  173. void DisplayServerWindows::tts_resume() {
  174. ERR_FAIL_COND(!tts);
  175. tts->resume();
  176. }
  177. void DisplayServerWindows::tts_stop() {
  178. ERR_FAIL_COND(!tts);
  179. tts->stop();
  180. }
  181. void DisplayServerWindows::mouse_set_mode(MouseMode p_mode) {
  182. _THREAD_SAFE_METHOD_
  183. if (mouse_mode == p_mode) {
  184. // Already in the same mode; do nothing.
  185. return;
  186. }
  187. mouse_mode = p_mode;
  188. _set_mouse_mode_impl(p_mode);
  189. }
  190. DisplayServer::MouseMode DisplayServerWindows::mouse_get_mode() const {
  191. return mouse_mode;
  192. }
  193. void DisplayServerWindows::warp_mouse(const Point2i &p_position) {
  194. _THREAD_SAFE_METHOD_
  195. WindowID window_id = _get_focused_window_or_popup();
  196. if (!windows.has(window_id)) {
  197. return; // No focused window?
  198. }
  199. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  200. old_x = p_position.x;
  201. old_y = p_position.y;
  202. } else {
  203. POINT p;
  204. p.x = p_position.x;
  205. p.y = p_position.y;
  206. ClientToScreen(windows[window_id].hWnd, &p);
  207. SetCursorPos(p.x, p.y);
  208. }
  209. }
  210. Point2i DisplayServerWindows::mouse_get_position() const {
  211. POINT p;
  212. GetCursorPos(&p);
  213. return Point2i(p.x, p.y);
  214. }
  215. MouseButton DisplayServerWindows::mouse_get_button_state() const {
  216. return last_button_state;
  217. }
  218. void DisplayServerWindows::clipboard_set(const String &p_text) {
  219. _THREAD_SAFE_METHOD_
  220. if (!windows.has(last_focused_window)) {
  221. return; // No focused window?
  222. }
  223. // Convert LF line endings to CRLF in clipboard content.
  224. // Otherwise, line endings won't be visible when pasted in other software.
  225. String text = p_text.replace("\r\n", "\n").replace("\n", "\r\n"); // Avoid \r\r\n.
  226. if (!OpenClipboard(windows[last_focused_window].hWnd)) {
  227. ERR_FAIL_MSG("Unable to open clipboard.");
  228. }
  229. EmptyClipboard();
  230. Char16String utf16 = text.utf16();
  231. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, (utf16.length() + 1) * sizeof(WCHAR));
  232. ERR_FAIL_COND_MSG(mem == nullptr, "Unable to allocate memory for clipboard contents.");
  233. LPWSTR lptstrCopy = (LPWSTR)GlobalLock(mem);
  234. memcpy(lptstrCopy, utf16.get_data(), (utf16.length() + 1) * sizeof(WCHAR));
  235. GlobalUnlock(mem);
  236. SetClipboardData(CF_UNICODETEXT, mem);
  237. // Set the CF_TEXT version (not needed?).
  238. CharString utf8 = text.utf8();
  239. mem = GlobalAlloc(GMEM_MOVEABLE, utf8.length() + 1);
  240. ERR_FAIL_COND_MSG(mem == nullptr, "Unable to allocate memory for clipboard contents.");
  241. LPTSTR ptr = (LPTSTR)GlobalLock(mem);
  242. memcpy(ptr, utf8.get_data(), utf8.length());
  243. ptr[utf8.length()] = 0;
  244. GlobalUnlock(mem);
  245. SetClipboardData(CF_TEXT, mem);
  246. CloseClipboard();
  247. }
  248. String DisplayServerWindows::clipboard_get() const {
  249. _THREAD_SAFE_METHOD_
  250. if (!windows.has(last_focused_window)) {
  251. return String(); // No focused window?
  252. }
  253. String ret;
  254. if (!OpenClipboard(windows[last_focused_window].hWnd)) {
  255. ERR_FAIL_V_MSG("", "Unable to open clipboard.");
  256. }
  257. if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
  258. HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
  259. if (mem != nullptr) {
  260. LPWSTR ptr = (LPWSTR)GlobalLock(mem);
  261. if (ptr != nullptr) {
  262. ret = String::utf16((const char16_t *)ptr);
  263. GlobalUnlock(mem);
  264. }
  265. }
  266. } else if (IsClipboardFormatAvailable(CF_TEXT)) {
  267. HGLOBAL mem = GetClipboardData(CF_UNICODETEXT);
  268. if (mem != nullptr) {
  269. LPTSTR ptr = (LPTSTR)GlobalLock(mem);
  270. if (ptr != nullptr) {
  271. ret.parse_utf8((const char *)ptr);
  272. GlobalUnlock(mem);
  273. }
  274. }
  275. }
  276. CloseClipboard();
  277. return ret;
  278. }
  279. typedef struct {
  280. int count;
  281. int screen;
  282. HMONITOR monitor;
  283. } EnumScreenData;
  284. static BOOL CALLBACK _MonitorEnumProcScreen(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  285. EnumScreenData *data = (EnumScreenData *)dwData;
  286. if (data->monitor == hMonitor) {
  287. data->screen = data->count;
  288. }
  289. data->count++;
  290. return TRUE;
  291. }
  292. static BOOL CALLBACK _MonitorEnumProcCount(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  293. int *data = (int *)dwData;
  294. (*data)++;
  295. return TRUE;
  296. }
  297. int DisplayServerWindows::get_screen_count() const {
  298. _THREAD_SAFE_METHOD_
  299. int data = 0;
  300. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcCount, (LPARAM)&data);
  301. return data;
  302. }
  303. typedef struct {
  304. int count;
  305. int screen;
  306. Point2 pos;
  307. } EnumPosData;
  308. static BOOL CALLBACK _MonitorEnumProcPos(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  309. EnumPosData *data = (EnumPosData *)dwData;
  310. if (data->count == data->screen) {
  311. data->pos.x = lprcMonitor->left;
  312. data->pos.y = lprcMonitor->top;
  313. }
  314. data->count++;
  315. return TRUE;
  316. }
  317. Point2i DisplayServerWindows::screen_get_position(int p_screen) const {
  318. _THREAD_SAFE_METHOD_
  319. EnumPosData data = { 0, p_screen == SCREEN_OF_MAIN_WINDOW ? window_get_current_screen() : p_screen, Point2() };
  320. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcPos, (LPARAM)&data);
  321. return data.pos;
  322. }
  323. typedef struct {
  324. int count;
  325. int screen;
  326. Size2 size;
  327. } EnumSizeData;
  328. typedef struct {
  329. int count;
  330. int screen;
  331. Rect2i rect;
  332. } EnumRectData;
  333. typedef struct {
  334. int count;
  335. int screen;
  336. float rate;
  337. } EnumRefreshRateData;
  338. static BOOL CALLBACK _MonitorEnumProcSize(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  339. EnumSizeData *data = (EnumSizeData *)dwData;
  340. if (data->count == data->screen) {
  341. data->size.x = lprcMonitor->right - lprcMonitor->left;
  342. data->size.y = lprcMonitor->bottom - lprcMonitor->top;
  343. }
  344. data->count++;
  345. return TRUE;
  346. }
  347. Size2i DisplayServerWindows::screen_get_size(int p_screen) const {
  348. _THREAD_SAFE_METHOD_
  349. EnumSizeData data = { 0, p_screen == SCREEN_OF_MAIN_WINDOW ? window_get_current_screen() : p_screen, Size2() };
  350. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcSize, (LPARAM)&data);
  351. return data.size;
  352. }
  353. static BOOL CALLBACK _MonitorEnumProcUsableSize(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  354. EnumRectData *data = (EnumRectData *)dwData;
  355. if (data->count == data->screen) {
  356. MONITORINFO minfo;
  357. memset(&minfo, 0, sizeof(MONITORINFO));
  358. minfo.cbSize = sizeof(MONITORINFO);
  359. GetMonitorInfoA(hMonitor, &minfo);
  360. data->rect.position.x = minfo.rcWork.left;
  361. data->rect.position.y = minfo.rcWork.top;
  362. data->rect.size.x = minfo.rcWork.right - minfo.rcWork.left;
  363. data->rect.size.y = minfo.rcWork.bottom - minfo.rcWork.top;
  364. }
  365. data->count++;
  366. return TRUE;
  367. }
  368. static BOOL CALLBACK _MonitorEnumProcRefreshRate(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  369. EnumRefreshRateData *data = (EnumRefreshRateData *)dwData;
  370. if (data->count == data->screen) {
  371. MONITORINFOEXW minfo;
  372. memset(&minfo, 0, sizeof(minfo));
  373. minfo.cbSize = sizeof(minfo);
  374. GetMonitorInfoW(hMonitor, &minfo);
  375. DEVMODEW dm;
  376. memset(&dm, 0, sizeof(dm));
  377. dm.dmSize = sizeof(dm);
  378. EnumDisplaySettingsW(minfo.szDevice, ENUM_CURRENT_SETTINGS, &dm);
  379. data->rate = dm.dmDisplayFrequency;
  380. }
  381. data->count++;
  382. return TRUE;
  383. }
  384. Rect2i DisplayServerWindows::screen_get_usable_rect(int p_screen) const {
  385. _THREAD_SAFE_METHOD_
  386. EnumRectData data = { 0, p_screen == SCREEN_OF_MAIN_WINDOW ? window_get_current_screen() : p_screen, Rect2i() };
  387. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcUsableSize, (LPARAM)&data);
  388. return data.rect;
  389. }
  390. typedef struct {
  391. int count;
  392. int screen;
  393. int dpi;
  394. } EnumDpiData;
  395. enum _MonitorDpiType {
  396. MDT_Effective_DPI = 0,
  397. MDT_Angular_DPI = 1,
  398. MDT_Raw_DPI = 2,
  399. MDT_Default = MDT_Effective_DPI
  400. };
  401. static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType = MDT_Default) {
  402. int dpiX = 96, dpiY = 96;
  403. static HMODULE Shcore = nullptr;
  404. typedef HRESULT(WINAPI * GetDPIForMonitor_t)(HMONITOR hmonitor, _MonitorDpiType dpiType, UINT * dpiX, UINT * dpiY);
  405. static GetDPIForMonitor_t getDPIForMonitor = nullptr;
  406. if (Shcore == nullptr) {
  407. Shcore = LoadLibraryW(L"Shcore.dll");
  408. getDPIForMonitor = Shcore ? (GetDPIForMonitor_t)GetProcAddress(Shcore, "GetDpiForMonitor") : nullptr;
  409. if ((Shcore == nullptr) || (getDPIForMonitor == nullptr)) {
  410. if (Shcore) {
  411. FreeLibrary(Shcore);
  412. }
  413. Shcore = (HMODULE)INVALID_HANDLE_VALUE;
  414. }
  415. }
  416. UINT x = 0, y = 0;
  417. if (hmon && (Shcore != (HMODULE)INVALID_HANDLE_VALUE)) {
  418. HRESULT hr = getDPIForMonitor(hmon, dpiType /*MDT_Effective_DPI*/, &x, &y);
  419. if (SUCCEEDED(hr) && (x > 0) && (y > 0)) {
  420. dpiX = (int)x;
  421. dpiY = (int)y;
  422. }
  423. } else {
  424. static int overallX = 0, overallY = 0;
  425. if (overallX <= 0 || overallY <= 0) {
  426. HDC hdc = GetDC(nullptr);
  427. if (hdc) {
  428. overallX = GetDeviceCaps(hdc, LOGPIXELSX);
  429. overallY = GetDeviceCaps(hdc, LOGPIXELSY);
  430. ReleaseDC(nullptr, hdc);
  431. }
  432. }
  433. if (overallX > 0 && overallY > 0) {
  434. dpiX = overallX;
  435. dpiY = overallY;
  436. }
  437. }
  438. return (dpiX + dpiY) / 2;
  439. }
  440. static BOOL CALLBACK _MonitorEnumProcDpi(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
  441. EnumDpiData *data = (EnumDpiData *)dwData;
  442. if (data->count == data->screen) {
  443. data->dpi = QueryDpiForMonitor(hMonitor);
  444. }
  445. data->count++;
  446. return TRUE;
  447. }
  448. int DisplayServerWindows::screen_get_dpi(int p_screen) const {
  449. _THREAD_SAFE_METHOD_
  450. EnumDpiData data = { 0, p_screen == SCREEN_OF_MAIN_WINDOW ? window_get_current_screen() : p_screen, 72 };
  451. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcDpi, (LPARAM)&data);
  452. return data.dpi;
  453. }
  454. float DisplayServerWindows::screen_get_refresh_rate(int p_screen) const {
  455. _THREAD_SAFE_METHOD_
  456. EnumRefreshRateData data = { 0, p_screen == SCREEN_OF_MAIN_WINDOW ? window_get_current_screen() : p_screen, SCREEN_REFRESH_RATE_FALLBACK };
  457. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcRefreshRate, (LPARAM)&data);
  458. return data.rate;
  459. }
  460. bool DisplayServerWindows::screen_is_touchscreen(int p_screen) const {
  461. #ifndef _MSC_VER
  462. #warning touchscreen not working
  463. #endif
  464. return false;
  465. }
  466. void DisplayServerWindows::screen_set_orientation(ScreenOrientation p_orientation, int p_screen) {
  467. }
  468. DisplayServer::ScreenOrientation DisplayServerWindows::screen_get_orientation(int p_screen) const {
  469. return SCREEN_LANDSCAPE;
  470. }
  471. void DisplayServerWindows::screen_set_keep_on(bool p_enable) {
  472. if (keep_screen_on == p_enable) {
  473. return;
  474. }
  475. if (p_enable) {
  476. const String reason = "Godot Engine running with display/window/energy_saving/keep_screen_on = true";
  477. Char16String reason_utf16 = reason.utf16();
  478. REASON_CONTEXT context;
  479. context.Version = POWER_REQUEST_CONTEXT_VERSION;
  480. context.Flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING;
  481. context.Reason.SimpleReasonString = (LPWSTR)(reason_utf16.ptrw());
  482. power_request = PowerCreateRequest(&context);
  483. if (power_request == INVALID_HANDLE_VALUE) {
  484. print_error("Failed to enable screen_keep_on.");
  485. return;
  486. }
  487. if (PowerSetRequest(power_request, POWER_REQUEST_TYPE::PowerRequestSystemRequired) == 0) {
  488. print_error("Failed to request system sleep override.");
  489. return;
  490. }
  491. if (PowerSetRequest(power_request, POWER_REQUEST_TYPE::PowerRequestDisplayRequired) == 0) {
  492. print_error("Failed to request display timeout override.");
  493. return;
  494. }
  495. } else {
  496. PowerClearRequest(power_request, POWER_REQUEST_TYPE::PowerRequestSystemRequired);
  497. PowerClearRequest(power_request, POWER_REQUEST_TYPE::PowerRequestDisplayRequired);
  498. CloseHandle(power_request);
  499. power_request = nullptr;
  500. }
  501. keep_screen_on = p_enable;
  502. }
  503. bool DisplayServerWindows::screen_is_kept_on() const {
  504. return keep_screen_on;
  505. }
  506. Vector<DisplayServer::WindowID> DisplayServerWindows::get_window_list() const {
  507. _THREAD_SAFE_METHOD_
  508. Vector<DisplayServer::WindowID> ret;
  509. for (const KeyValue<WindowID, WindowData> &E : windows) {
  510. ret.push_back(E.key);
  511. }
  512. return ret;
  513. }
  514. DisplayServer::WindowID DisplayServerWindows::get_window_at_screen_position(const Point2i &p_position) const {
  515. POINT p;
  516. p.x = p_position.x;
  517. p.y = p_position.y;
  518. HWND hwnd = WindowFromPoint(p);
  519. for (const KeyValue<WindowID, WindowData> &E : windows) {
  520. if (E.value.hWnd == hwnd) {
  521. return E.key;
  522. }
  523. }
  524. return INVALID_WINDOW_ID;
  525. }
  526. DisplayServer::WindowID DisplayServerWindows::create_sub_window(WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Rect2i &p_rect) {
  527. _THREAD_SAFE_METHOD_
  528. WindowID window_id = _create_window(p_mode, p_vsync_mode, p_flags, p_rect);
  529. ERR_FAIL_COND_V_MSG(window_id == INVALID_WINDOW_ID, INVALID_WINDOW_ID, "Failed to create sub window.");
  530. WindowData &wd = windows[window_id];
  531. if (p_flags & WINDOW_FLAG_RESIZE_DISABLED_BIT) {
  532. wd.resizable = false;
  533. }
  534. if (p_flags & WINDOW_FLAG_BORDERLESS_BIT) {
  535. wd.borderless = true;
  536. }
  537. if (p_flags & WINDOW_FLAG_ALWAYS_ON_TOP_BIT && p_mode != WINDOW_MODE_FULLSCREEN && p_mode != WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  538. wd.always_on_top = true;
  539. }
  540. if (p_flags & WINDOW_FLAG_NO_FOCUS_BIT) {
  541. wd.no_focus = true;
  542. }
  543. if (p_flags & WINDOW_FLAG_POPUP_BIT) {
  544. wd.is_popup = true;
  545. }
  546. // Inherit icons from MAIN_WINDOW for all sub windows.
  547. HICON mainwindow_icon = (HICON)SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_GETICON, ICON_SMALL, 0);
  548. if (mainwindow_icon) {
  549. SendMessage(windows[window_id].hWnd, WM_SETICON, ICON_SMALL, (LPARAM)mainwindow_icon);
  550. }
  551. mainwindow_icon = (HICON)SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_GETICON, ICON_BIG, 0);
  552. if (mainwindow_icon) {
  553. SendMessage(windows[window_id].hWnd, WM_SETICON, ICON_BIG, (LPARAM)mainwindow_icon);
  554. }
  555. return window_id;
  556. }
  557. void DisplayServerWindows::show_window(WindowID p_id) {
  558. ERR_FAIL_COND(!windows.has(p_id));
  559. WindowData &wd = windows[p_id];
  560. popup_open(p_id);
  561. if (p_id != MAIN_WINDOW_ID) {
  562. _update_window_style(p_id);
  563. }
  564. if (wd.maximized) {
  565. ShowWindow(wd.hWnd, SW_SHOWMAXIMIZED);
  566. SetForegroundWindow(wd.hWnd); // Slightly higher priority.
  567. SetFocus(wd.hWnd); // Set keyboard focus.
  568. } else if (wd.minimized) {
  569. ShowWindow(wd.hWnd, SW_SHOWMINIMIZED);
  570. } else if (wd.no_focus || wd.is_popup) {
  571. // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow
  572. ShowWindow(wd.hWnd, SW_SHOWNA);
  573. } else {
  574. ShowWindow(wd.hWnd, SW_SHOW);
  575. SetForegroundWindow(wd.hWnd); // Slightly higher priority.
  576. SetFocus(wd.hWnd); // Set keyboard focus.
  577. }
  578. }
  579. void DisplayServerWindows::delete_sub_window(WindowID p_window) {
  580. _THREAD_SAFE_METHOD_
  581. ERR_FAIL_COND(!windows.has(p_window));
  582. ERR_FAIL_COND_MSG(p_window == MAIN_WINDOW_ID, "Main window cannot be deleted.");
  583. popup_close(p_window);
  584. WindowData &wd = windows[p_window];
  585. while (wd.transient_children.size()) {
  586. window_set_transient(*wd.transient_children.begin(), INVALID_WINDOW_ID);
  587. }
  588. if (wd.transient_parent != INVALID_WINDOW_ID) {
  589. window_set_transient(p_window, INVALID_WINDOW_ID);
  590. }
  591. #ifdef VULKAN_ENABLED
  592. if (context_vulkan) {
  593. context_vulkan->window_destroy(p_window);
  594. }
  595. #endif
  596. #ifdef GLES3_ENABLED
  597. if (gl_manager) {
  598. gl_manager->window_destroy(p_window);
  599. }
  600. #endif
  601. if ((tablet_get_current_driver() == "wintab") && wintab_available && windows[p_window].wtctx) {
  602. wintab_WTClose(windows[p_window].wtctx);
  603. windows[p_window].wtctx = 0;
  604. }
  605. DestroyWindow(windows[p_window].hWnd);
  606. windows.erase(p_window);
  607. }
  608. void DisplayServerWindows::gl_window_make_current(DisplayServer::WindowID p_window_id) {
  609. #if defined(GLES3_ENABLED)
  610. if (gl_manager) {
  611. gl_manager->window_make_current(p_window_id);
  612. }
  613. #endif
  614. }
  615. int64_t DisplayServerWindows::window_get_native_handle(HandleType p_handle_type, WindowID p_window) const {
  616. ERR_FAIL_COND_V(!windows.has(p_window), 0);
  617. switch (p_handle_type) {
  618. case DISPLAY_HANDLE: {
  619. return 0; // Not supported.
  620. }
  621. case WINDOW_HANDLE: {
  622. return (int64_t)windows[p_window].hWnd;
  623. }
  624. case WINDOW_VIEW: {
  625. return 0; // Not supported.
  626. }
  627. default: {
  628. return 0;
  629. }
  630. }
  631. }
  632. void DisplayServerWindows::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
  633. _THREAD_SAFE_METHOD_
  634. ERR_FAIL_COND(!windows.has(p_window));
  635. windows[p_window].instance_id = p_instance;
  636. }
  637. ObjectID DisplayServerWindows::window_get_attached_instance_id(WindowID p_window) const {
  638. _THREAD_SAFE_METHOD_
  639. ERR_FAIL_COND_V(!windows.has(p_window), ObjectID());
  640. return windows[p_window].instance_id;
  641. }
  642. void DisplayServerWindows::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
  643. _THREAD_SAFE_METHOD_
  644. ERR_FAIL_COND(!windows.has(p_window));
  645. windows[p_window].rect_changed_callback = p_callable;
  646. }
  647. void DisplayServerWindows::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
  648. _THREAD_SAFE_METHOD_
  649. ERR_FAIL_COND(!windows.has(p_window));
  650. windows[p_window].event_callback = p_callable;
  651. }
  652. void DisplayServerWindows::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
  653. _THREAD_SAFE_METHOD_
  654. ERR_FAIL_COND(!windows.has(p_window));
  655. windows[p_window].input_event_callback = p_callable;
  656. }
  657. void DisplayServerWindows::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
  658. _THREAD_SAFE_METHOD_
  659. ERR_FAIL_COND(!windows.has(p_window));
  660. windows[p_window].input_text_callback = p_callable;
  661. }
  662. void DisplayServerWindows::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
  663. _THREAD_SAFE_METHOD_
  664. ERR_FAIL_COND(!windows.has(p_window));
  665. windows[p_window].drop_files_callback = p_callable;
  666. }
  667. void DisplayServerWindows::window_set_title(const String &p_title, WindowID p_window) {
  668. _THREAD_SAFE_METHOD_
  669. ERR_FAIL_COND(!windows.has(p_window));
  670. SetWindowTextW(windows[p_window].hWnd, (LPCWSTR)(p_title.utf16().get_data()));
  671. }
  672. void DisplayServerWindows::window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window) {
  673. _THREAD_SAFE_METHOD_
  674. ERR_FAIL_COND(!windows.has(p_window));
  675. windows[p_window].mpath = p_region;
  676. _update_window_mouse_passthrough(p_window);
  677. }
  678. void DisplayServerWindows::_update_window_mouse_passthrough(WindowID p_window) {
  679. ERR_FAIL_COND(!windows.has(p_window));
  680. if (windows[p_window].mpath.size() == 0) {
  681. SetWindowRgn(windows[p_window].hWnd, nullptr, TRUE);
  682. } else {
  683. POINT *points = (POINT *)memalloc(sizeof(POINT) * windows[p_window].mpath.size());
  684. for (int i = 0; i < windows[p_window].mpath.size(); i++) {
  685. if (windows[p_window].borderless) {
  686. points[i].x = windows[p_window].mpath[i].x;
  687. points[i].y = windows[p_window].mpath[i].y;
  688. } else {
  689. points[i].x = windows[p_window].mpath[i].x + GetSystemMetrics(SM_CXSIZEFRAME);
  690. points[i].y = windows[p_window].mpath[i].y + GetSystemMetrics(SM_CYSIZEFRAME) + GetSystemMetrics(SM_CYCAPTION);
  691. }
  692. }
  693. HRGN region = CreatePolygonRgn(points, windows[p_window].mpath.size(), ALTERNATE);
  694. SetWindowRgn(windows[p_window].hWnd, region, TRUE);
  695. DeleteObject(region);
  696. memfree(points);
  697. }
  698. }
  699. int DisplayServerWindows::window_get_current_screen(WindowID p_window) const {
  700. _THREAD_SAFE_METHOD_
  701. ERR_FAIL_COND_V(!windows.has(p_window), -1);
  702. EnumScreenData data = { 0, 0, MonitorFromWindow(windows[p_window].hWnd, MONITOR_DEFAULTTONEAREST) };
  703. EnumDisplayMonitors(nullptr, nullptr, _MonitorEnumProcScreen, (LPARAM)&data);
  704. return data.screen;
  705. }
  706. void DisplayServerWindows::window_set_current_screen(int p_screen, WindowID p_window) {
  707. _THREAD_SAFE_METHOD_
  708. ERR_FAIL_COND(!windows.has(p_window));
  709. ERR_FAIL_INDEX(p_screen, get_screen_count());
  710. const WindowData &wd = windows[p_window];
  711. if (wd.fullscreen) {
  712. int cs = window_get_current_screen(p_window);
  713. if (cs == p_screen) {
  714. return;
  715. }
  716. Point2 pos = screen_get_position(p_screen);
  717. Size2 size = screen_get_size(p_screen);
  718. MoveWindow(wd.hWnd, pos.x, pos.y, size.width, size.height, TRUE);
  719. } else {
  720. Vector2 ofs = window_get_position(p_window) - screen_get_position(window_get_current_screen(p_window));
  721. window_set_position(ofs + screen_get_position(p_screen), p_window);
  722. }
  723. // Don't let the mouse leave the window when resizing to a smaller resolution.
  724. if (mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
  725. RECT crect;
  726. GetClientRect(wd.hWnd, &crect);
  727. ClientToScreen(wd.hWnd, (POINT *)&crect.left);
  728. ClientToScreen(wd.hWnd, (POINT *)&crect.right);
  729. ClipCursor(&crect);
  730. }
  731. }
  732. Point2i DisplayServerWindows::window_get_position(WindowID p_window) const {
  733. _THREAD_SAFE_METHOD_
  734. ERR_FAIL_COND_V(!windows.has(p_window), Point2i());
  735. const WindowData &wd = windows[p_window];
  736. if (wd.minimized) {
  737. return wd.last_pos;
  738. }
  739. POINT point;
  740. point.x = 0;
  741. point.y = 0;
  742. ClientToScreen(wd.hWnd, &point);
  743. return Point2i(point.x, point.y);
  744. }
  745. void DisplayServerWindows::_update_real_mouse_position(WindowID p_window) {
  746. ERR_FAIL_COND(!windows.has(p_window));
  747. POINT mouse_pos;
  748. if (GetCursorPos(&mouse_pos) && ScreenToClient(windows[p_window].hWnd, &mouse_pos)) {
  749. if (mouse_pos.x > 0 && mouse_pos.y > 0 && mouse_pos.x <= windows[p_window].width && mouse_pos.y <= windows[p_window].height) {
  750. old_x = mouse_pos.x;
  751. old_y = mouse_pos.y;
  752. old_invalid = false;
  753. Input::get_singleton()->set_mouse_position(Point2i(mouse_pos.x, mouse_pos.y));
  754. }
  755. }
  756. }
  757. void DisplayServerWindows::window_set_position(const Point2i &p_position, WindowID p_window) {
  758. _THREAD_SAFE_METHOD_
  759. ERR_FAIL_COND(!windows.has(p_window));
  760. WindowData &wd = windows[p_window];
  761. if (wd.fullscreen || wd.maximized) {
  762. return;
  763. }
  764. RECT rc;
  765. rc.left = p_position.x;
  766. rc.right = p_position.x + wd.width;
  767. rc.bottom = p_position.y + wd.height;
  768. rc.top = p_position.y;
  769. const DWORD style = GetWindowLongPtr(wd.hWnd, GWL_STYLE);
  770. const DWORD exStyle = GetWindowLongPtr(wd.hWnd, GWL_EXSTYLE);
  771. AdjustWindowRectEx(&rc, style, false, exStyle);
  772. MoveWindow(wd.hWnd, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, TRUE);
  773. // Don't let the mouse leave the window when moved.
  774. if (mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
  775. RECT rect;
  776. GetClientRect(wd.hWnd, &rect);
  777. ClientToScreen(wd.hWnd, (POINT *)&rect.left);
  778. ClientToScreen(wd.hWnd, (POINT *)&rect.right);
  779. ClipCursor(&rect);
  780. }
  781. wd.last_pos = p_position;
  782. _update_real_mouse_position(p_window);
  783. }
  784. void DisplayServerWindows::window_set_exclusive(WindowID p_window, bool p_exclusive) {
  785. _THREAD_SAFE_METHOD_
  786. ERR_FAIL_COND(!windows.has(p_window));
  787. WindowData &wd = windows[p_window];
  788. if (wd.exclusive != p_exclusive) {
  789. wd.exclusive = p_exclusive;
  790. if (wd.transient_parent != INVALID_WINDOW_ID) {
  791. if (wd.exclusive) {
  792. WindowData &wd_parent = windows[wd.transient_parent];
  793. SetWindowLongPtr(wd.hWnd, GWLP_HWNDPARENT, (LONG_PTR)wd_parent.hWnd);
  794. } else {
  795. SetWindowLongPtr(wd.hWnd, GWLP_HWNDPARENT, (LONG_PTR) nullptr);
  796. }
  797. }
  798. }
  799. }
  800. void DisplayServerWindows::window_set_transient(WindowID p_window, WindowID p_parent) {
  801. _THREAD_SAFE_METHOD_
  802. ERR_FAIL_COND(p_window == p_parent);
  803. ERR_FAIL_COND(!windows.has(p_window));
  804. WindowData &wd_window = windows[p_window];
  805. ERR_FAIL_COND(wd_window.transient_parent == p_parent);
  806. ERR_FAIL_COND_MSG(wd_window.always_on_top, "Windows with the 'on top' can't become transient.");
  807. if (p_parent == INVALID_WINDOW_ID) {
  808. // Remove transient.
  809. ERR_FAIL_COND(wd_window.transient_parent == INVALID_WINDOW_ID);
  810. ERR_FAIL_COND(!windows.has(wd_window.transient_parent));
  811. WindowData &wd_parent = windows[wd_window.transient_parent];
  812. wd_window.transient_parent = INVALID_WINDOW_ID;
  813. wd_parent.transient_children.erase(p_window);
  814. if (wd_window.exclusive) {
  815. SetWindowLongPtr(wd_window.hWnd, GWLP_HWNDPARENT, (LONG_PTR) nullptr);
  816. }
  817. } else {
  818. ERR_FAIL_COND(!windows.has(p_parent));
  819. ERR_FAIL_COND_MSG(wd_window.transient_parent != INVALID_WINDOW_ID, "Window already has a transient parent");
  820. WindowData &wd_parent = windows[p_parent];
  821. wd_window.transient_parent = p_parent;
  822. wd_parent.transient_children.insert(p_window);
  823. if (wd_window.exclusive) {
  824. SetWindowLongPtr(wd_window.hWnd, GWLP_HWNDPARENT, (LONG_PTR)wd_parent.hWnd);
  825. }
  826. }
  827. }
  828. void DisplayServerWindows::window_set_max_size(const Size2i p_size, WindowID p_window) {
  829. _THREAD_SAFE_METHOD_
  830. ERR_FAIL_COND(!windows.has(p_window));
  831. WindowData &wd = windows[p_window];
  832. if ((p_size != Size2()) && ((p_size.x < wd.min_size.x) || (p_size.y < wd.min_size.y))) {
  833. ERR_PRINT("Maximum window size can't be smaller than minimum window size!");
  834. return;
  835. }
  836. wd.max_size = p_size;
  837. }
  838. Size2i DisplayServerWindows::window_get_max_size(WindowID p_window) const {
  839. _THREAD_SAFE_METHOD_
  840. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  841. const WindowData &wd = windows[p_window];
  842. return wd.max_size;
  843. }
  844. void DisplayServerWindows::window_set_min_size(const Size2i p_size, WindowID p_window) {
  845. _THREAD_SAFE_METHOD_
  846. ERR_FAIL_COND(!windows.has(p_window));
  847. WindowData &wd = windows[p_window];
  848. if ((p_size != Size2()) && (wd.max_size != Size2()) && ((p_size.x > wd.max_size.x) || (p_size.y > wd.max_size.y))) {
  849. ERR_PRINT("Minimum window size can't be larger than maximum window size!");
  850. return;
  851. }
  852. wd.min_size = p_size;
  853. }
  854. Size2i DisplayServerWindows::window_get_min_size(WindowID p_window) const {
  855. _THREAD_SAFE_METHOD_
  856. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  857. const WindowData &wd = windows[p_window];
  858. return wd.min_size;
  859. }
  860. void DisplayServerWindows::window_set_size(const Size2i p_size, WindowID p_window) {
  861. _THREAD_SAFE_METHOD_
  862. ERR_FAIL_COND(!windows.has(p_window));
  863. WindowData &wd = windows[p_window];
  864. if (wd.fullscreen || wd.maximized) {
  865. return;
  866. }
  867. int w = p_size.width;
  868. int h = p_size.height;
  869. wd.width = w;
  870. wd.height = h;
  871. #if defined(VULKAN_ENABLED)
  872. if (context_vulkan) {
  873. context_vulkan->window_resize(p_window, w, h);
  874. }
  875. #endif
  876. #if defined(GLES3_ENABLED)
  877. if (gl_manager) {
  878. gl_manager->window_resize(p_window, w, h);
  879. }
  880. #endif
  881. RECT rect;
  882. GetWindowRect(wd.hWnd, &rect);
  883. if (!wd.borderless) {
  884. RECT crect;
  885. GetClientRect(wd.hWnd, &crect);
  886. w += (rect.right - rect.left) - (crect.right - crect.left);
  887. h += (rect.bottom - rect.top) - (crect.bottom - crect.top);
  888. }
  889. MoveWindow(wd.hWnd, rect.left, rect.top, w, h, TRUE);
  890. // Don't let the mouse leave the window when resizing to a smaller resolution.
  891. if (mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
  892. RECT crect;
  893. GetClientRect(wd.hWnd, &crect);
  894. ClientToScreen(wd.hWnd, (POINT *)&crect.left);
  895. ClientToScreen(wd.hWnd, (POINT *)&crect.right);
  896. ClipCursor(&crect);
  897. }
  898. }
  899. Size2i DisplayServerWindows::window_get_size(WindowID p_window) const {
  900. _THREAD_SAFE_METHOD_
  901. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  902. const WindowData &wd = windows[p_window];
  903. // GetClientRect() returns a zero rect for a minimized window, so we need to get the size in another way.
  904. if (wd.minimized) {
  905. return Size2(wd.width, wd.height);
  906. }
  907. RECT r;
  908. if (GetClientRect(wd.hWnd, &r)) { // Retrieves area inside of window border, including decoration.
  909. return Size2(r.right - r.left, r.bottom - r.top);
  910. }
  911. return Size2();
  912. }
  913. Size2i DisplayServerWindows::window_get_real_size(WindowID p_window) const {
  914. _THREAD_SAFE_METHOD_
  915. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  916. const WindowData &wd = windows[p_window];
  917. RECT r;
  918. if (GetWindowRect(wd.hWnd, &r)) { // Retrieves area inside of window border, including decoration.
  919. return Size2(r.right - r.left, r.bottom - r.top);
  920. }
  921. return Size2();
  922. }
  923. void DisplayServerWindows::_get_window_style(bool p_main_window, bool p_fullscreen, bool p_multiwindow_fs, bool p_borderless, bool p_resizable, bool p_maximized, bool p_no_activate_focus, DWORD &r_style, DWORD &r_style_ex) {
  924. // Windows docs for window styles:
  925. // https://docs.microsoft.com/en-us/windows/win32/winmsg/window-styles
  926. // https://docs.microsoft.com/en-us/windows/win32/winmsg/extended-window-styles
  927. r_style = 0;
  928. r_style_ex = WS_EX_WINDOWEDGE;
  929. if (p_main_window) {
  930. r_style_ex |= WS_EX_APPWINDOW;
  931. r_style |= WS_VISIBLE;
  932. }
  933. if (p_fullscreen || p_borderless) {
  934. r_style |= WS_POPUP; // p_borderless was WS_EX_TOOLWINDOW in the past.
  935. if (p_fullscreen && p_multiwindow_fs) {
  936. r_style |= WS_BORDER; // Allows child windows to be displayed on top of full screen.
  937. }
  938. } else {
  939. if (p_resizable) {
  940. if (p_maximized) {
  941. r_style = WS_OVERLAPPEDWINDOW | WS_MAXIMIZE;
  942. } else {
  943. r_style = WS_OVERLAPPEDWINDOW;
  944. }
  945. } else {
  946. r_style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU;
  947. }
  948. }
  949. if (p_no_activate_focus) {
  950. r_style_ex |= WS_EX_TOPMOST | WS_EX_NOACTIVATE;
  951. }
  952. if (!p_borderless && !p_no_activate_focus) {
  953. r_style |= WS_VISIBLE;
  954. }
  955. r_style |= WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
  956. r_style_ex |= WS_EX_ACCEPTFILES;
  957. }
  958. void DisplayServerWindows::_update_window_style(WindowID p_window, bool p_repaint) {
  959. _THREAD_SAFE_METHOD_
  960. ERR_FAIL_COND(!windows.has(p_window));
  961. WindowData &wd = windows[p_window];
  962. DWORD style = 0;
  963. DWORD style_ex = 0;
  964. _get_window_style(p_window == MAIN_WINDOW_ID, wd.fullscreen, wd.multiwindow_fs, wd.borderless, wd.resizable, wd.maximized, wd.no_focus || wd.is_popup, style, style_ex);
  965. SetWindowLongPtr(wd.hWnd, GWL_STYLE, style);
  966. SetWindowLongPtr(wd.hWnd, GWL_EXSTYLE, style_ex);
  967. if (icon.is_valid()) {
  968. set_icon(icon);
  969. }
  970. SetWindowPos(wd.hWnd, wd.always_on_top ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | ((wd.no_focus || wd.is_popup) ? SWP_NOACTIVATE : 0));
  971. if (p_repaint) {
  972. RECT rect;
  973. GetWindowRect(wd.hWnd, &rect);
  974. MoveWindow(wd.hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
  975. }
  976. }
  977. void DisplayServerWindows::window_set_mode(WindowMode p_mode, WindowID p_window) {
  978. _THREAD_SAFE_METHOD_
  979. ERR_FAIL_COND(!windows.has(p_window));
  980. WindowData &wd = windows[p_window];
  981. if (wd.fullscreen && p_mode != WINDOW_MODE_FULLSCREEN && p_mode != WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  982. RECT rect;
  983. wd.fullscreen = false;
  984. wd.multiwindow_fs = false;
  985. wd.maximized = wd.was_maximized;
  986. if (wd.pre_fs_valid) {
  987. rect = wd.pre_fs_rect;
  988. } else {
  989. rect.left = 0;
  990. rect.right = wd.width;
  991. rect.top = 0;
  992. rect.bottom = wd.height;
  993. wd.pre_fs_valid = true;
  994. }
  995. _update_window_style(p_window, false);
  996. MoveWindow(wd.hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
  997. if (restore_mouse_trails > 1) {
  998. SystemParametersInfoA(SPI_SETMOUSETRAILS, restore_mouse_trails, 0, 0);
  999. restore_mouse_trails = 0;
  1000. }
  1001. } else if (p_mode == WINDOW_MODE_WINDOWED) {
  1002. ShowWindow(wd.hWnd, SW_RESTORE);
  1003. wd.maximized = false;
  1004. wd.minimized = false;
  1005. }
  1006. if (p_mode == WINDOW_MODE_MAXIMIZED) {
  1007. ShowWindow(wd.hWnd, SW_MAXIMIZE);
  1008. wd.maximized = true;
  1009. wd.minimized = false;
  1010. }
  1011. if (p_mode == WINDOW_MODE_MINIMIZED) {
  1012. ShowWindow(wd.hWnd, SW_MINIMIZE);
  1013. wd.maximized = false;
  1014. wd.minimized = true;
  1015. }
  1016. if (p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  1017. wd.multiwindow_fs = false;
  1018. _update_window_style(p_window, false);
  1019. } else {
  1020. wd.multiwindow_fs = true;
  1021. _update_window_style(p_window, false);
  1022. }
  1023. if ((p_mode == WINDOW_MODE_FULLSCREEN || p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) && !wd.fullscreen) {
  1024. if (wd.minimized) {
  1025. ShowWindow(wd.hWnd, SW_RESTORE);
  1026. }
  1027. wd.was_maximized = wd.maximized;
  1028. if (wd.pre_fs_valid) {
  1029. GetWindowRect(wd.hWnd, &wd.pre_fs_rect);
  1030. }
  1031. int cs = window_get_current_screen(p_window);
  1032. Point2 pos = screen_get_position(cs);
  1033. Size2 size = screen_get_size(cs);
  1034. wd.fullscreen = true;
  1035. wd.maximized = false;
  1036. wd.minimized = false;
  1037. _update_window_style(p_window, false);
  1038. MoveWindow(wd.hWnd, pos.x, pos.y, size.width, size.height, TRUE);
  1039. // If the user has mouse trails enabled in windows, then sometimes the cursor disappears in fullscreen mode.
  1040. // Save number of trails so we can restore when exiting, then turn off mouse trails
  1041. SystemParametersInfoA(SPI_GETMOUSETRAILS, 0, &restore_mouse_trails, 0);
  1042. if (restore_mouse_trails > 1) {
  1043. SystemParametersInfoA(SPI_SETMOUSETRAILS, 0, 0, 0);
  1044. }
  1045. }
  1046. // Don't let the mouse leave the window when resizing to a smaller resolution.
  1047. if (mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
  1048. RECT crect;
  1049. GetClientRect(wd.hWnd, &crect);
  1050. ClientToScreen(wd.hWnd, (POINT *)&crect.left);
  1051. ClientToScreen(wd.hWnd, (POINT *)&crect.right);
  1052. ClipCursor(&crect);
  1053. }
  1054. }
  1055. DisplayServer::WindowMode DisplayServerWindows::window_get_mode(WindowID p_window) const {
  1056. _THREAD_SAFE_METHOD_
  1057. ERR_FAIL_COND_V(!windows.has(p_window), WINDOW_MODE_WINDOWED);
  1058. const WindowData &wd = windows[p_window];
  1059. if (wd.fullscreen) {
  1060. if (wd.multiwindow_fs) {
  1061. return WINDOW_MODE_FULLSCREEN;
  1062. } else {
  1063. return WINDOW_MODE_EXCLUSIVE_FULLSCREEN;
  1064. }
  1065. } else if (wd.minimized) {
  1066. return WINDOW_MODE_MINIMIZED;
  1067. } else if (wd.maximized) {
  1068. return WINDOW_MODE_MAXIMIZED;
  1069. } else {
  1070. return WINDOW_MODE_WINDOWED;
  1071. }
  1072. }
  1073. bool DisplayServerWindows::window_is_maximize_allowed(WindowID p_window) const {
  1074. _THREAD_SAFE_METHOD_
  1075. ERR_FAIL_COND_V(!windows.has(p_window), false);
  1076. // FIXME: Implement this, or confirm that it should always be true.
  1077. return true;
  1078. }
  1079. void DisplayServerWindows::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
  1080. _THREAD_SAFE_METHOD_
  1081. ERR_FAIL_COND(!windows.has(p_window));
  1082. WindowData &wd = windows[p_window];
  1083. switch (p_flag) {
  1084. case WINDOW_FLAG_RESIZE_DISABLED: {
  1085. wd.resizable = !p_enabled;
  1086. _update_window_style(p_window);
  1087. } break;
  1088. case WINDOW_FLAG_BORDERLESS: {
  1089. wd.borderless = p_enabled;
  1090. _update_window_style(p_window);
  1091. _update_window_mouse_passthrough(p_window);
  1092. ShowWindow(wd.hWnd, (wd.no_focus || wd.is_popup) ? SW_SHOWNOACTIVATE : SW_SHOW); // Show the window.
  1093. } break;
  1094. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  1095. ERR_FAIL_COND_MSG(wd.transient_parent != INVALID_WINDOW_ID && p_enabled, "Transient windows can't become on top");
  1096. wd.always_on_top = p_enabled;
  1097. _update_window_style(p_window);
  1098. } break;
  1099. case WINDOW_FLAG_TRANSPARENT: {
  1100. if (p_enabled) {
  1101. //enable per-pixel alpha
  1102. DWM_BLURBEHIND bb = { 0 };
  1103. HRGN hRgn = CreateRectRgn(0, 0, -1, -1);
  1104. bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
  1105. bb.hRgnBlur = hRgn;
  1106. bb.fEnable = TRUE;
  1107. DwmEnableBlurBehindWindow(wd.hWnd, &bb);
  1108. wd.layered_window = true;
  1109. } else {
  1110. //disable per-pixel alpha
  1111. wd.layered_window = false;
  1112. DWM_BLURBEHIND bb = { 0 };
  1113. HRGN hRgn = CreateRectRgn(0, 0, -1, -1);
  1114. bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
  1115. bb.hRgnBlur = hRgn;
  1116. bb.fEnable = FALSE;
  1117. DwmEnableBlurBehindWindow(wd.hWnd, &bb);
  1118. }
  1119. } break;
  1120. case WINDOW_FLAG_NO_FOCUS: {
  1121. wd.no_focus = p_enabled;
  1122. _update_window_style(p_window);
  1123. } break;
  1124. case WINDOW_FLAG_POPUP: {
  1125. ERR_FAIL_COND_MSG(p_window == MAIN_WINDOW_ID, "Main window can't be popup.");
  1126. ERR_FAIL_COND_MSG(IsWindowVisible(wd.hWnd) && (wd.is_popup != p_enabled), "Popup flag can't changed while window is opened.");
  1127. wd.is_popup = p_enabled;
  1128. } break;
  1129. case WINDOW_FLAG_MAX:
  1130. break;
  1131. }
  1132. }
  1133. bool DisplayServerWindows::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
  1134. _THREAD_SAFE_METHOD_
  1135. ERR_FAIL_COND_V(!windows.has(p_window), false);
  1136. const WindowData &wd = windows[p_window];
  1137. switch (p_flag) {
  1138. case WINDOW_FLAG_RESIZE_DISABLED: {
  1139. return !wd.resizable;
  1140. } break;
  1141. case WINDOW_FLAG_BORDERLESS: {
  1142. return wd.borderless;
  1143. } break;
  1144. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  1145. return wd.always_on_top;
  1146. } break;
  1147. case WINDOW_FLAG_TRANSPARENT: {
  1148. return wd.layered_window;
  1149. } break;
  1150. case WINDOW_FLAG_NO_FOCUS: {
  1151. return wd.no_focus;
  1152. } break;
  1153. case WINDOW_FLAG_POPUP: {
  1154. return wd.is_popup;
  1155. } break;
  1156. case WINDOW_FLAG_MAX:
  1157. break;
  1158. }
  1159. return false;
  1160. }
  1161. void DisplayServerWindows::window_request_attention(WindowID p_window) {
  1162. _THREAD_SAFE_METHOD_
  1163. ERR_FAIL_COND(!windows.has(p_window));
  1164. const WindowData &wd = windows[p_window];
  1165. FLASHWINFO info;
  1166. info.cbSize = sizeof(FLASHWINFO);
  1167. info.hwnd = wd.hWnd;
  1168. info.dwFlags = FLASHW_TRAY;
  1169. info.dwTimeout = 0;
  1170. info.uCount = 2;
  1171. FlashWindowEx(&info);
  1172. }
  1173. void DisplayServerWindows::window_move_to_foreground(WindowID p_window) {
  1174. _THREAD_SAFE_METHOD_
  1175. ERR_FAIL_COND(!windows.has(p_window));
  1176. WindowData &wd = windows[p_window];
  1177. if (!wd.no_focus && !wd.is_popup) {
  1178. SetForegroundWindow(wd.hWnd);
  1179. }
  1180. }
  1181. bool DisplayServerWindows::window_can_draw(WindowID p_window) const {
  1182. _THREAD_SAFE_METHOD_
  1183. ERR_FAIL_COND_V(!windows.has(p_window), false);
  1184. const WindowData &wd = windows[p_window];
  1185. return !wd.minimized;
  1186. }
  1187. bool DisplayServerWindows::can_any_window_draw() const {
  1188. _THREAD_SAFE_METHOD_
  1189. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1190. if (!E.value.minimized) {
  1191. return true;
  1192. }
  1193. }
  1194. return false;
  1195. }
  1196. void DisplayServerWindows::window_set_ime_active(const bool p_active, WindowID p_window) {
  1197. _THREAD_SAFE_METHOD_
  1198. ERR_FAIL_COND(!windows.has(p_window));
  1199. WindowData &wd = windows[p_window];
  1200. if (p_active) {
  1201. ImmAssociateContext(wd.hWnd, wd.im_himc);
  1202. window_set_ime_position(wd.im_position, p_window);
  1203. } else {
  1204. ImmAssociateContext(wd.hWnd, (HIMC)0);
  1205. }
  1206. }
  1207. void DisplayServerWindows::window_set_ime_position(const Point2i &p_pos, WindowID p_window) {
  1208. _THREAD_SAFE_METHOD_
  1209. ERR_FAIL_COND(!windows.has(p_window));
  1210. WindowData &wd = windows[p_window];
  1211. wd.im_position = p_pos;
  1212. HIMC himc = ImmGetContext(wd.hWnd);
  1213. if (himc == (HIMC)0) {
  1214. return;
  1215. }
  1216. COMPOSITIONFORM cps;
  1217. cps.dwStyle = CFS_FORCE_POSITION;
  1218. cps.ptCurrentPos.x = wd.im_position.x;
  1219. cps.ptCurrentPos.y = wd.im_position.y;
  1220. ImmSetCompositionWindow(himc, &cps);
  1221. ImmReleaseContext(wd.hWnd, himc);
  1222. }
  1223. void DisplayServerWindows::cursor_set_shape(CursorShape p_shape) {
  1224. _THREAD_SAFE_METHOD_
  1225. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  1226. if (cursor_shape == p_shape) {
  1227. return;
  1228. }
  1229. if (mouse_mode != MOUSE_MODE_VISIBLE && mouse_mode != MOUSE_MODE_CONFINED) {
  1230. cursor_shape = p_shape;
  1231. return;
  1232. }
  1233. static const LPCTSTR win_cursors[CURSOR_MAX] = {
  1234. IDC_ARROW,
  1235. IDC_IBEAM,
  1236. IDC_HAND, // Finger.
  1237. IDC_CROSS,
  1238. IDC_WAIT,
  1239. IDC_APPSTARTING,
  1240. IDC_SIZEALL,
  1241. IDC_ARROW,
  1242. IDC_NO,
  1243. IDC_SIZENS,
  1244. IDC_SIZEWE,
  1245. IDC_SIZENESW,
  1246. IDC_SIZENWSE,
  1247. IDC_SIZEALL,
  1248. IDC_SIZENS,
  1249. IDC_SIZEWE,
  1250. IDC_HELP
  1251. };
  1252. if (cursors_cache.has(p_shape)) {
  1253. SetCursor(cursors[p_shape]);
  1254. } else {
  1255. SetCursor(LoadCursor(hInstance, win_cursors[p_shape]));
  1256. }
  1257. cursor_shape = p_shape;
  1258. }
  1259. DisplayServer::CursorShape DisplayServerWindows::cursor_get_shape() const {
  1260. return cursor_shape;
  1261. }
  1262. void DisplayServerWindows::cursor_set_custom_image(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  1263. _THREAD_SAFE_METHOD_
  1264. if (p_cursor.is_valid()) {
  1265. RBMap<CursorShape, Vector<Variant>>::Element *cursor_c = cursors_cache.find(p_shape);
  1266. if (cursor_c) {
  1267. if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) {
  1268. cursor_set_shape(p_shape);
  1269. return;
  1270. }
  1271. cursors_cache.erase(p_shape);
  1272. }
  1273. Ref<Texture2D> texture = p_cursor;
  1274. Ref<AtlasTexture> atlas_texture = p_cursor;
  1275. Ref<Image> image;
  1276. Size2 texture_size;
  1277. Rect2 atlas_rect;
  1278. if (texture.is_valid()) {
  1279. image = texture->get_image();
  1280. }
  1281. if (!image.is_valid() && atlas_texture.is_valid()) {
  1282. texture = atlas_texture->get_atlas();
  1283. atlas_rect.size.width = texture->get_width();
  1284. atlas_rect.size.height = texture->get_height();
  1285. atlas_rect.position.x = atlas_texture->get_region().position.x;
  1286. atlas_rect.position.y = atlas_texture->get_region().position.y;
  1287. texture_size.width = atlas_texture->get_region().size.x;
  1288. texture_size.height = atlas_texture->get_region().size.y;
  1289. } else if (image.is_valid()) {
  1290. texture_size.width = texture->get_width();
  1291. texture_size.height = texture->get_height();
  1292. }
  1293. ERR_FAIL_COND(!texture.is_valid());
  1294. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  1295. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  1296. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  1297. image = texture->get_image();
  1298. ERR_FAIL_COND(!image.is_valid());
  1299. UINT image_size = texture_size.width * texture_size.height;
  1300. // Create the BITMAP with alpha channel.
  1301. COLORREF *buffer = nullptr;
  1302. BITMAPV5HEADER bi;
  1303. ZeroMemory(&bi, sizeof(bi));
  1304. bi.bV5Size = sizeof(bi);
  1305. bi.bV5Width = texture_size.width;
  1306. bi.bV5Height = -texture_size.height;
  1307. bi.bV5Planes = 1;
  1308. bi.bV5BitCount = 32;
  1309. bi.bV5Compression = BI_BITFIELDS;
  1310. bi.bV5RedMask = 0x00ff0000;
  1311. bi.bV5GreenMask = 0x0000ff00;
  1312. bi.bV5BlueMask = 0x000000ff;
  1313. bi.bV5AlphaMask = 0xff000000;
  1314. HDC dc = GetDC(nullptr);
  1315. HBITMAP bitmap = CreateDIBSection(dc, reinterpret_cast<BITMAPINFO *>(&bi), DIB_RGB_COLORS, reinterpret_cast<void **>(&buffer), nullptr, 0);
  1316. HBITMAP mask = CreateBitmap(texture_size.width, texture_size.height, 1, 1, nullptr);
  1317. bool fully_transparent = true;
  1318. for (UINT index = 0; index < image_size; index++) {
  1319. int row_index = floor(index / texture_size.width) + atlas_rect.position.y;
  1320. int column_index = (index % int(texture_size.width)) + atlas_rect.position.x;
  1321. if (atlas_texture.is_valid()) {
  1322. column_index = MIN(column_index, atlas_rect.size.width - 1);
  1323. row_index = MIN(row_index, atlas_rect.size.height - 1);
  1324. }
  1325. const Color &c = image->get_pixel(column_index, row_index);
  1326. fully_transparent = fully_transparent && (c.a == 0.f);
  1327. *(buffer + index) = c.to_argb32();
  1328. }
  1329. // Finally, create the icon.
  1330. if (cursors[p_shape]) {
  1331. DestroyIcon(cursors[p_shape]);
  1332. }
  1333. if (fully_transparent) {
  1334. cursors[p_shape] = nullptr;
  1335. } else {
  1336. ICONINFO iconinfo;
  1337. iconinfo.fIcon = FALSE;
  1338. iconinfo.xHotspot = p_hotspot.x;
  1339. iconinfo.yHotspot = p_hotspot.y;
  1340. iconinfo.hbmMask = mask;
  1341. iconinfo.hbmColor = bitmap;
  1342. cursors[p_shape] = CreateIconIndirect(&iconinfo);
  1343. }
  1344. Vector<Variant> params;
  1345. params.push_back(p_cursor);
  1346. params.push_back(p_hotspot);
  1347. cursors_cache.insert(p_shape, params);
  1348. if (p_shape == cursor_shape) {
  1349. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  1350. SetCursor(cursors[p_shape]);
  1351. }
  1352. }
  1353. DeleteObject(mask);
  1354. DeleteObject(bitmap);
  1355. ReleaseDC(nullptr, dc);
  1356. } else {
  1357. // Reset to default system cursor.
  1358. if (cursors[p_shape]) {
  1359. DestroyIcon(cursors[p_shape]);
  1360. }
  1361. cursors[p_shape] = nullptr;
  1362. CursorShape c = cursor_shape;
  1363. cursor_shape = CURSOR_MAX;
  1364. cursor_set_shape(c);
  1365. cursors_cache.erase(p_shape);
  1366. }
  1367. }
  1368. bool DisplayServerWindows::get_swap_cancel_ok() {
  1369. return true;
  1370. }
  1371. void DisplayServerWindows::enable_for_stealing_focus(OS::ProcessID pid) {
  1372. _THREAD_SAFE_METHOD_
  1373. AllowSetForegroundWindow(pid);
  1374. }
  1375. int DisplayServerWindows::keyboard_get_layout_count() const {
  1376. return GetKeyboardLayoutList(0, nullptr);
  1377. }
  1378. int DisplayServerWindows::keyboard_get_current_layout() const {
  1379. HKL cur_layout = GetKeyboardLayout(0);
  1380. int layout_count = GetKeyboardLayoutList(0, nullptr);
  1381. HKL *layouts = (HKL *)memalloc(layout_count * sizeof(HKL));
  1382. GetKeyboardLayoutList(layout_count, layouts);
  1383. for (int i = 0; i < layout_count; i++) {
  1384. if (cur_layout == layouts[i]) {
  1385. memfree(layouts);
  1386. return i;
  1387. }
  1388. }
  1389. memfree(layouts);
  1390. return -1;
  1391. }
  1392. void DisplayServerWindows::keyboard_set_current_layout(int p_index) {
  1393. int layout_count = GetKeyboardLayoutList(0, nullptr);
  1394. ERR_FAIL_INDEX(p_index, layout_count);
  1395. HKL *layouts = (HKL *)memalloc(layout_count * sizeof(HKL));
  1396. GetKeyboardLayoutList(layout_count, layouts);
  1397. ActivateKeyboardLayout(layouts[p_index], KLF_SETFORPROCESS);
  1398. memfree(layouts);
  1399. }
  1400. String DisplayServerWindows::keyboard_get_layout_language(int p_index) const {
  1401. int layout_count = GetKeyboardLayoutList(0, nullptr);
  1402. ERR_FAIL_INDEX_V(p_index, layout_count, "");
  1403. HKL *layouts = (HKL *)memalloc(layout_count * sizeof(HKL));
  1404. GetKeyboardLayoutList(layout_count, layouts);
  1405. WCHAR buf[LOCALE_NAME_MAX_LENGTH];
  1406. memset(buf, 0, LOCALE_NAME_MAX_LENGTH * sizeof(WCHAR));
  1407. LCIDToLocaleName(MAKELCID(LOWORD(layouts[p_index]), SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);
  1408. memfree(layouts);
  1409. return String::utf16((const char16_t *)buf).substr(0, 2);
  1410. }
  1411. Key DisplayServerWindows::keyboard_get_keycode_from_physical(Key p_keycode) const {
  1412. Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
  1413. Key keycode_no_mod = (Key)(p_keycode & KeyModifierMask::CODE_MASK);
  1414. if (keycode_no_mod == Key::PRINT ||
  1415. keycode_no_mod == Key::KP_ADD ||
  1416. keycode_no_mod == Key::KP_5 ||
  1417. (keycode_no_mod >= Key::KEY_0 && keycode_no_mod <= Key::KEY_9)) {
  1418. return p_keycode;
  1419. }
  1420. unsigned int scancode = KeyMappingWindows::get_scancode(keycode_no_mod);
  1421. if (scancode == 0) {
  1422. return p_keycode;
  1423. }
  1424. HKL current_layout = GetKeyboardLayout(0);
  1425. UINT vk = MapVirtualKeyEx(scancode, MAPVK_VSC_TO_VK, current_layout);
  1426. if (vk == 0) {
  1427. return p_keycode;
  1428. }
  1429. UINT char_code = MapVirtualKeyEx(vk, MAPVK_VK_TO_CHAR, current_layout) & 0x7FFF;
  1430. // Unlike a similar Linux/BSD check which matches full Latin-1 range,
  1431. // we limit these to ASCII to fix some layouts, including Arabic ones
  1432. if (char_code >= 32 && char_code <= 127) {
  1433. // Godot uses 'braces' instead of 'brackets'
  1434. if (char_code == (unsigned int)Key::BRACKETLEFT || char_code == (unsigned int)Key::BRACKETRIGHT) {
  1435. char_code += 32;
  1436. }
  1437. return (Key)(char_code | (unsigned int)modifiers);
  1438. }
  1439. return (Key)(KeyMappingWindows::get_keysym(vk) | modifiers);
  1440. }
  1441. String _get_full_layout_name_from_registry(HKL p_layout) {
  1442. String id = "SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts\\" + String::num_int64((int64_t)p_layout, 16, false).lpad(8, "0");
  1443. String ret;
  1444. HKEY hkey;
  1445. WCHAR layout_text[1024];
  1446. memset(layout_text, 0, 1024 * sizeof(WCHAR));
  1447. if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, (LPCWSTR)(id.utf16().get_data()), 0, KEY_QUERY_VALUE, &hkey) != ERROR_SUCCESS) {
  1448. return ret;
  1449. }
  1450. DWORD buffer = 1024;
  1451. DWORD vtype = REG_SZ;
  1452. if (RegQueryValueExW(hkey, L"Layout Text", nullptr, &vtype, (LPBYTE)layout_text, &buffer) == ERROR_SUCCESS) {
  1453. ret = String::utf16((const char16_t *)layout_text);
  1454. }
  1455. RegCloseKey(hkey);
  1456. return ret;
  1457. }
  1458. String DisplayServerWindows::keyboard_get_layout_name(int p_index) const {
  1459. int layout_count = GetKeyboardLayoutList(0, nullptr);
  1460. ERR_FAIL_INDEX_V(p_index, layout_count, "");
  1461. HKL *layouts = (HKL *)memalloc(layout_count * sizeof(HKL));
  1462. GetKeyboardLayoutList(layout_count, layouts);
  1463. 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).
  1464. if (ret.is_empty()) {
  1465. WCHAR buf[LOCALE_NAME_MAX_LENGTH];
  1466. memset(buf, 0, LOCALE_NAME_MAX_LENGTH * sizeof(WCHAR));
  1467. LCIDToLocaleName(MAKELCID(LOWORD(layouts[p_index]), SORT_DEFAULT), buf, LOCALE_NAME_MAX_LENGTH, 0);
  1468. WCHAR name[1024];
  1469. memset(name, 0, 1024 * sizeof(WCHAR));
  1470. GetLocaleInfoEx(buf, LOCALE_SLOCALIZEDDISPLAYNAME, (LPWSTR)&name, 1024);
  1471. ret = String::utf16((const char16_t *)name);
  1472. }
  1473. memfree(layouts);
  1474. return ret;
  1475. }
  1476. void DisplayServerWindows::process_events() {
  1477. _THREAD_SAFE_METHOD_
  1478. MSG msg;
  1479. if (!drop_events) {
  1480. joypad->process_joypads();
  1481. }
  1482. while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
  1483. TranslateMessage(&msg);
  1484. DispatchMessageW(&msg);
  1485. }
  1486. if (!drop_events) {
  1487. _process_key_events();
  1488. Input::get_singleton()->flush_buffered_events();
  1489. }
  1490. }
  1491. void DisplayServerWindows::force_process_and_drop_events() {
  1492. _THREAD_SAFE_METHOD_
  1493. drop_events = true;
  1494. process_events();
  1495. drop_events = false;
  1496. }
  1497. void DisplayServerWindows::release_rendering_thread() {
  1498. }
  1499. void DisplayServerWindows::make_rendering_thread() {
  1500. }
  1501. void DisplayServerWindows::swap_buffers() {
  1502. #if defined(GLES3_ENABLED)
  1503. if (gl_manager) {
  1504. gl_manager->swap_buffers();
  1505. }
  1506. #endif
  1507. }
  1508. void DisplayServerWindows::set_native_icon(const String &p_filename) {
  1509. _THREAD_SAFE_METHOD_
  1510. Ref<FileAccess> f = FileAccess::open(p_filename, FileAccess::READ);
  1511. ERR_FAIL_COND_MSG(f.is_null(), "Cannot open file with icon '" + p_filename + "'.");
  1512. ICONDIR *icon_dir = (ICONDIR *)memalloc(sizeof(ICONDIR));
  1513. int pos = 0;
  1514. icon_dir->idReserved = f->get_32();
  1515. pos += sizeof(WORD);
  1516. f->seek(pos);
  1517. icon_dir->idType = f->get_32();
  1518. pos += sizeof(WORD);
  1519. f->seek(pos);
  1520. ERR_FAIL_COND_MSG(icon_dir->idType != 1, "Invalid icon file format!");
  1521. icon_dir->idCount = f->get_32();
  1522. pos += sizeof(WORD);
  1523. f->seek(pos);
  1524. icon_dir = (ICONDIR *)memrealloc(icon_dir, 3 * sizeof(WORD) + icon_dir->idCount * sizeof(ICONDIRENTRY));
  1525. f->get_buffer((uint8_t *)&icon_dir->idEntries[0], icon_dir->idCount * sizeof(ICONDIRENTRY));
  1526. int small_icon_index = -1; // Select 16x16 with largest color count.
  1527. int small_icon_cc = 0;
  1528. int big_icon_index = -1; // Select largest.
  1529. int big_icon_width = 16;
  1530. int big_icon_cc = 0;
  1531. for (int i = 0; i < icon_dir->idCount; i++) {
  1532. int colors = (icon_dir->idEntries[i].bColorCount == 0) ? 32768 : icon_dir->idEntries[i].bColorCount;
  1533. int width = (icon_dir->idEntries[i].bWidth == 0) ? 256 : icon_dir->idEntries[i].bWidth;
  1534. if (width == 16) {
  1535. if (colors >= small_icon_cc) {
  1536. small_icon_index = i;
  1537. small_icon_cc = colors;
  1538. }
  1539. }
  1540. if (width >= big_icon_width) {
  1541. if (colors >= big_icon_cc) {
  1542. big_icon_index = i;
  1543. big_icon_width = width;
  1544. big_icon_cc = colors;
  1545. }
  1546. }
  1547. }
  1548. ERR_FAIL_COND_MSG(big_icon_index == -1, "No valid icons found!");
  1549. if (small_icon_index == -1) {
  1550. WARN_PRINT("No small icon found, reusing " + itos(big_icon_width) + "x" + itos(big_icon_width) + " @" + itos(big_icon_cc) + " icon!");
  1551. small_icon_index = big_icon_index;
  1552. small_icon_cc = big_icon_cc;
  1553. }
  1554. // Read the big icon.
  1555. DWORD bytecount_big = icon_dir->idEntries[big_icon_index].dwBytesInRes;
  1556. Vector<uint8_t> data_big;
  1557. data_big.resize(bytecount_big);
  1558. pos = icon_dir->idEntries[big_icon_index].dwImageOffset;
  1559. f->seek(pos);
  1560. f->get_buffer((uint8_t *)&data_big.write[0], bytecount_big);
  1561. HICON icon_big = CreateIconFromResource((PBYTE)&data_big.write[0], bytecount_big, TRUE, 0x00030000);
  1562. 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()) + ".");
  1563. // Read the small icon.
  1564. DWORD bytecount_small = icon_dir->idEntries[small_icon_index].dwBytesInRes;
  1565. Vector<uint8_t> data_small;
  1566. data_small.resize(bytecount_small);
  1567. pos = icon_dir->idEntries[small_icon_index].dwImageOffset;
  1568. f->seek(pos);
  1569. f->get_buffer((uint8_t *)&data_small.write[0], bytecount_small);
  1570. HICON icon_small = CreateIconFromResource((PBYTE)&data_small.write[0], bytecount_small, TRUE, 0x00030000);
  1571. ERR_FAIL_COND_MSG(!icon_small, "Could not create 16x16 @" + itos(small_icon_cc) + " icon, error: " + format_error_message(GetLastError()) + ".");
  1572. // Online tradition says to be sure last error is cleared and set the small icon first.
  1573. int err = 0;
  1574. SetLastError(err);
  1575. SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_SETICON, ICON_SMALL, (LPARAM)icon_small);
  1576. err = GetLastError();
  1577. ERR_FAIL_COND_MSG(err, "Error setting ICON_SMALL: " + format_error_message(err) + ".");
  1578. SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_SETICON, ICON_BIG, (LPARAM)icon_big);
  1579. err = GetLastError();
  1580. ERR_FAIL_COND_MSG(err, "Error setting ICON_BIG: " + format_error_message(err) + ".");
  1581. memdelete(icon_dir);
  1582. }
  1583. void DisplayServerWindows::set_icon(const Ref<Image> &p_icon) {
  1584. _THREAD_SAFE_METHOD_
  1585. ERR_FAIL_COND(!p_icon.is_valid());
  1586. if (icon != p_icon) {
  1587. icon = p_icon->duplicate();
  1588. if (icon->get_format() != Image::FORMAT_RGBA8) {
  1589. icon->convert(Image::FORMAT_RGBA8);
  1590. }
  1591. }
  1592. int w = icon->get_width();
  1593. int h = icon->get_height();
  1594. // Create temporary bitmap buffer.
  1595. int icon_len = 40 + h * w * 4;
  1596. Vector<BYTE> v;
  1597. v.resize(icon_len);
  1598. BYTE *icon_bmp = v.ptrw();
  1599. encode_uint32(40, &icon_bmp[0]);
  1600. encode_uint32(w, &icon_bmp[4]);
  1601. encode_uint32(h * 2, &icon_bmp[8]);
  1602. encode_uint16(1, &icon_bmp[12]);
  1603. encode_uint16(32, &icon_bmp[14]);
  1604. encode_uint32(BI_RGB, &icon_bmp[16]);
  1605. encode_uint32(w * h * 4, &icon_bmp[20]);
  1606. encode_uint32(0, &icon_bmp[24]);
  1607. encode_uint32(0, &icon_bmp[28]);
  1608. encode_uint32(0, &icon_bmp[32]);
  1609. encode_uint32(0, &icon_bmp[36]);
  1610. uint8_t *wr = &icon_bmp[40];
  1611. const uint8_t *r = icon->get_data().ptr();
  1612. for (int i = 0; i < h; i++) {
  1613. for (int j = 0; j < w; j++) {
  1614. const uint8_t *rpx = &r[((h - i - 1) * w + j) * 4];
  1615. uint8_t *wpx = &wr[(i * w + j) * 4];
  1616. wpx[0] = rpx[2];
  1617. wpx[1] = rpx[1];
  1618. wpx[2] = rpx[0];
  1619. wpx[3] = rpx[3];
  1620. }
  1621. }
  1622. HICON hicon = CreateIconFromResource(icon_bmp, icon_len, TRUE, 0x00030000);
  1623. // Set the icon for the window.
  1624. SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hicon);
  1625. // Set the icon in the task manager (should we do this?).
  1626. SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_SETICON, ICON_BIG, (LPARAM)hicon);
  1627. }
  1628. void DisplayServerWindows::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) {
  1629. _THREAD_SAFE_METHOD_
  1630. #if defined(VULKAN_ENABLED)
  1631. if (context_vulkan) {
  1632. context_vulkan->set_vsync_mode(p_window, p_vsync_mode);
  1633. }
  1634. #endif
  1635. }
  1636. DisplayServer::VSyncMode DisplayServerWindows::window_get_vsync_mode(WindowID p_window) const {
  1637. _THREAD_SAFE_METHOD_
  1638. #if defined(VULKAN_ENABLED)
  1639. if (context_vulkan) {
  1640. return context_vulkan->get_vsync_mode(p_window);
  1641. }
  1642. #endif
  1643. return DisplayServer::VSYNC_ENABLED;
  1644. }
  1645. void DisplayServerWindows::set_context(Context p_context) {
  1646. }
  1647. #define MI_WP_SIGNATURE 0xFF515700
  1648. #define SIGNATURE_MASK 0xFFFFFF00
  1649. // Keeping the name suggested by Microsoft, but this macro really answers:
  1650. // Is this mouse event emulated from touch or pen input?
  1651. #define IsPenEvent(dw) (((dw)&SIGNATURE_MASK) == MI_WP_SIGNATURE)
  1652. // This one tells whether the event comes from touchscreen (and not from pen).
  1653. #define IsTouchEvent(dw) (IsPenEvent(dw) && ((dw)&0x80))
  1654. void DisplayServerWindows::_touch_event(WindowID p_window, bool p_pressed, float p_x, float p_y, int idx) {
  1655. if (touch_state.has(idx) == p_pressed) {
  1656. return;
  1657. }
  1658. if (p_pressed) {
  1659. touch_state.insert(idx, Vector2(p_x, p_y));
  1660. } else {
  1661. touch_state.erase(idx);
  1662. }
  1663. Ref<InputEventScreenTouch> event;
  1664. event.instantiate();
  1665. event->set_index(idx);
  1666. event->set_window_id(p_window);
  1667. event->set_pressed(p_pressed);
  1668. event->set_position(Vector2(p_x, p_y));
  1669. Input::get_singleton()->parse_input_event(event);
  1670. }
  1671. void DisplayServerWindows::_drag_event(WindowID p_window, float p_x, float p_y, int idx) {
  1672. RBMap<int, Vector2>::Element *curr = touch_state.find(idx);
  1673. if (!curr) {
  1674. return;
  1675. }
  1676. if (curr->get() == Vector2(p_x, p_y)) {
  1677. return;
  1678. }
  1679. Ref<InputEventScreenDrag> event;
  1680. event.instantiate();
  1681. event->set_window_id(p_window);
  1682. event->set_index(idx);
  1683. event->set_position(Vector2(p_x, p_y));
  1684. event->set_relative(Vector2(p_x, p_y) - curr->get());
  1685. Input::get_singleton()->parse_input_event(event);
  1686. curr->get() = Vector2(p_x, p_y);
  1687. }
  1688. void DisplayServerWindows::_send_window_event(const WindowData &wd, WindowEvent p_event) {
  1689. if (!wd.event_callback.is_null()) {
  1690. Variant event = int(p_event);
  1691. Variant *eventp = &event;
  1692. Variant ret;
  1693. Callable::CallError ce;
  1694. wd.event_callback.callp((const Variant **)&eventp, 1, ret, ce);
  1695. }
  1696. }
  1697. void DisplayServerWindows::_dispatch_input_events(const Ref<InputEvent> &p_event) {
  1698. static_cast<DisplayServerWindows *>(get_singleton())->_dispatch_input_event(p_event);
  1699. }
  1700. void DisplayServerWindows::_dispatch_input_event(const Ref<InputEvent> &p_event) {
  1701. _THREAD_SAFE_METHOD_
  1702. if (in_dispatch_input_event) {
  1703. return;
  1704. }
  1705. in_dispatch_input_event = true;
  1706. Variant ev = p_event;
  1707. Variant *evp = &ev;
  1708. Variant ret;
  1709. Callable::CallError ce;
  1710. {
  1711. List<WindowID>::Element *E = popup_list.back();
  1712. if (E && Object::cast_to<InputEventKey>(*p_event)) {
  1713. // Redirect keyboard input to active popup.
  1714. if (windows.has(E->get())) {
  1715. Callable callable = windows[E->get()].input_event_callback;
  1716. if (callable.is_valid()) {
  1717. callable.callp((const Variant **)&evp, 1, ret, ce);
  1718. }
  1719. }
  1720. in_dispatch_input_event = false;
  1721. return;
  1722. }
  1723. }
  1724. Ref<InputEventFromWindow> event_from_window = p_event;
  1725. if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) {
  1726. // Send to a single window.
  1727. if (windows.has(event_from_window->get_window_id())) {
  1728. Callable callable = windows[event_from_window->get_window_id()].input_event_callback;
  1729. if (callable.is_valid()) {
  1730. callable.callp((const Variant **)&evp, 1, ret, ce);
  1731. }
  1732. }
  1733. } else {
  1734. // Send to all windows.
  1735. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1736. const Callable callable = E.value.input_event_callback;
  1737. if (callable.is_valid()) {
  1738. callable.callp((const Variant **)&evp, 1, ret, ce);
  1739. }
  1740. }
  1741. }
  1742. in_dispatch_input_event = false;
  1743. }
  1744. LRESULT CALLBACK MouseProc(int code, WPARAM wParam, LPARAM lParam) {
  1745. DisplayServerWindows *ds_win = static_cast<DisplayServerWindows *>(DisplayServer::get_singleton());
  1746. if (ds_win) {
  1747. return ds_win->MouseProc(code, wParam, lParam);
  1748. } else {
  1749. return ::CallNextHookEx(nullptr, code, wParam, lParam);
  1750. }
  1751. }
  1752. DisplayServer::WindowID DisplayServerWindows::window_get_active_popup() const {
  1753. const List<WindowID>::Element *E = popup_list.back();
  1754. if (E) {
  1755. return E->get();
  1756. } else {
  1757. return INVALID_WINDOW_ID;
  1758. }
  1759. }
  1760. void DisplayServerWindows::window_set_popup_safe_rect(WindowID p_window, const Rect2i &p_rect) {
  1761. _THREAD_SAFE_METHOD_
  1762. ERR_FAIL_COND(!windows.has(p_window));
  1763. WindowData &wd = windows[p_window];
  1764. wd.parent_safe_rect = p_rect;
  1765. }
  1766. Rect2i DisplayServerWindows::window_get_popup_safe_rect(WindowID p_window) const {
  1767. _THREAD_SAFE_METHOD_
  1768. ERR_FAIL_COND_V(!windows.has(p_window), Rect2i());
  1769. const WindowData &wd = windows[p_window];
  1770. return wd.parent_safe_rect;
  1771. }
  1772. void DisplayServerWindows::popup_open(WindowID p_window) {
  1773. _THREAD_SAFE_METHOD_
  1774. const WindowData &wd = windows[p_window];
  1775. if (wd.is_popup) {
  1776. // Find current popup parent, or root popup if new window is not transient.
  1777. List<WindowID>::Element *C = nullptr;
  1778. List<WindowID>::Element *E = popup_list.back();
  1779. while (E) {
  1780. if (wd.transient_parent != E->get() || wd.transient_parent == INVALID_WINDOW_ID) {
  1781. C = E;
  1782. E = E->prev();
  1783. } else {
  1784. break;
  1785. }
  1786. }
  1787. if (C) {
  1788. _send_window_event(windows[C->get()], DisplayServerWindows::WINDOW_EVENT_CLOSE_REQUEST);
  1789. }
  1790. time_since_popup = OS::get_singleton()->get_ticks_msec();
  1791. popup_list.push_back(p_window);
  1792. }
  1793. }
  1794. void DisplayServerWindows::popup_close(WindowID p_window) {
  1795. _THREAD_SAFE_METHOD_
  1796. List<WindowID>::Element *E = popup_list.find(p_window);
  1797. while (E) {
  1798. List<WindowID>::Element *F = E->next();
  1799. WindowID win_id = E->get();
  1800. popup_list.erase(E);
  1801. if (win_id != p_window) {
  1802. // Only request close on related windows, not this window. We are already processing it.
  1803. _send_window_event(windows[win_id], DisplayServerWindows::WINDOW_EVENT_CLOSE_REQUEST);
  1804. }
  1805. E = F;
  1806. }
  1807. }
  1808. LRESULT DisplayServerWindows::MouseProc(int code, WPARAM wParam, LPARAM lParam) {
  1809. _THREAD_SAFE_METHOD_
  1810. uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_popup;
  1811. if (delta > 250) {
  1812. switch (wParam) {
  1813. case WM_NCLBUTTONDOWN:
  1814. case WM_NCRBUTTONDOWN:
  1815. case WM_NCMBUTTONDOWN:
  1816. case WM_LBUTTONDOWN:
  1817. case WM_RBUTTONDOWN:
  1818. case WM_MBUTTONDOWN: {
  1819. MOUSEHOOKSTRUCT *ms = (MOUSEHOOKSTRUCT *)lParam;
  1820. Point2i pos = Point2i(ms->pt.x, ms->pt.y);
  1821. List<WindowID>::Element *C = nullptr;
  1822. List<WindowID>::Element *E = popup_list.back();
  1823. // Find top popup to close.
  1824. while (E) {
  1825. // Popup window area.
  1826. Rect2i win_rect = Rect2i(window_get_position(E->get()), window_get_size(E->get()));
  1827. // Area of the parent window, which responsible for opening sub-menu.
  1828. Rect2i safe_rect = window_get_popup_safe_rect(E->get());
  1829. if (win_rect.has_point(pos)) {
  1830. break;
  1831. } else if (safe_rect != Rect2i() && safe_rect.has_point(pos)) {
  1832. break;
  1833. } else {
  1834. C = E;
  1835. E = E->prev();
  1836. }
  1837. }
  1838. if (C) {
  1839. _send_window_event(windows[C->get()], DisplayServerWindows::WINDOW_EVENT_CLOSE_REQUEST);
  1840. return 1;
  1841. }
  1842. } break;
  1843. }
  1844. }
  1845. return ::CallNextHookEx(mouse_monitor, code, wParam, lParam);
  1846. }
  1847. // Handle a single window message received while CreateWindowEx is still on the stack and our data
  1848. // structures are not fully initialized.
  1849. LRESULT DisplayServerWindows::_handle_early_window_message(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  1850. switch (uMsg) {
  1851. case WM_GETMINMAXINFO: {
  1852. // We receive this during CreateWindowEx and we haven't initialized the window
  1853. // struct, so let Windows figure out the maximized size.
  1854. // Silently forward to user/default.
  1855. } break;
  1856. case WM_NCCREATE: {
  1857. // We tunnel an unowned pointer to our window context (WindowData) through the
  1858. // first possible message (WM_NCCREATE) to fix up our window context collection.
  1859. CREATESTRUCTW *pCreate = (CREATESTRUCTW *)lParam;
  1860. WindowData *pWindowData = reinterpret_cast<WindowData *>(pCreate->lpCreateParams);
  1861. // Fix this up so we can recognize the remaining messages.
  1862. pWindowData->hWnd = hWnd;
  1863. } break;
  1864. default: {
  1865. // Additional messages during window creation should happen after we fixed
  1866. // up the data structures on WM_NCCREATE, but this might change in the future,
  1867. // so report an error here and then we can implement them.
  1868. ERR_PRINT_ONCE(vformat("Unexpected window message 0x%x received for window we cannot recognize in our collection; sequence error.", uMsg));
  1869. } break;
  1870. }
  1871. if (user_proc) {
  1872. return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
  1873. }
  1874. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  1875. }
  1876. // The window procedure for our window class "Engine", used to handle processing of window-related system messages/events.
  1877. // See: https://docs.microsoft.com/en-us/windows/win32/winmsg/window-procedures
  1878. LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  1879. if (drop_events) {
  1880. if (user_proc) {
  1881. return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
  1882. } else {
  1883. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  1884. }
  1885. }
  1886. WindowID window_id = INVALID_WINDOW_ID;
  1887. bool window_created = false;
  1888. // Check whether window exists
  1889. // FIXME this is O(n), where n is the set of currently open windows and subwindows
  1890. // we should have a secondary map from HWND to WindowID or even WindowData* alias, if we want to eliminate all the map lookups below
  1891. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1892. if (E.value.hWnd == hWnd) {
  1893. window_id = E.key;
  1894. window_created = true;
  1895. break;
  1896. }
  1897. }
  1898. // WARNING: we get called with events before the window is registered in our collection
  1899. // specifically, even the call to CreateWindowEx already calls here while still on the stack,
  1900. // so there is no way to store the window handle in our collection before we get here
  1901. if (!window_created) {
  1902. // don't let code below operate on incompletely initialized window objects or missing window_id
  1903. return _handle_early_window_message(hWnd, uMsg, wParam, lParam);
  1904. }
  1905. // Process window messages.
  1906. switch (uMsg) {
  1907. case WM_MOUSEACTIVATE: {
  1908. if (windows[window_id].no_focus) {
  1909. return MA_NOACTIVATEANDEAT; // Do not activate, and discard mouse messages.
  1910. } else if (windows[window_id].is_popup) {
  1911. return MA_NOACTIVATE; // Do not activate, but process mouse messages.
  1912. }
  1913. } break;
  1914. case WM_SETFOCUS: {
  1915. windows[window_id].window_has_focus = true;
  1916. last_focused_window = window_id;
  1917. // Restore mouse mode.
  1918. _set_mouse_mode_impl(mouse_mode);
  1919. if (!app_focused) {
  1920. if (OS::get_singleton()->get_main_loop()) {
  1921. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN);
  1922. }
  1923. app_focused = true;
  1924. }
  1925. } break;
  1926. case WM_KILLFOCUS: {
  1927. windows[window_id].window_has_focus = false;
  1928. last_focused_window = window_id;
  1929. // Release capture unconditionally because it can be set due to dragging, in addition to captured mode.
  1930. ReleaseCapture();
  1931. // Release every touch to avoid sticky points.
  1932. for (const KeyValue<int, Vector2> &E : touch_state) {
  1933. _touch_event(window_id, false, E.value.x, E.value.y, E.key);
  1934. }
  1935. touch_state.clear();
  1936. bool self_steal = false;
  1937. HWND new_hwnd = (HWND)wParam;
  1938. if (IsWindow(new_hwnd)) {
  1939. self_steal = true;
  1940. }
  1941. if (!self_steal) {
  1942. if (OS::get_singleton()->get_main_loop()) {
  1943. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT);
  1944. }
  1945. app_focused = false;
  1946. }
  1947. } break;
  1948. case WM_ACTIVATE: { // Watch for window activate message.
  1949. if (!windows[window_id].window_focused) {
  1950. _process_activate_event(window_id, wParam, lParam);
  1951. } else {
  1952. windows[window_id].saved_wparam = wParam;
  1953. windows[window_id].saved_lparam = lParam;
  1954. // Run a timer to prevent event catching warning if the focused window is closing.
  1955. windows[window_id].focus_timer_id = SetTimer(windows[window_id].hWnd, 2, USER_TIMER_MINIMUM, (TIMERPROC) nullptr);
  1956. }
  1957. if (wParam != WA_INACTIVE) {
  1958. track_mouse_leave_event(hWnd);
  1959. }
  1960. return 0; // Return to the message loop.
  1961. } break;
  1962. case WM_GETMINMAXINFO: {
  1963. if (windows[window_id].resizable && !windows[window_id].fullscreen) {
  1964. // Size of window decorations.
  1965. Size2 decor = window_get_real_size(window_id) - window_get_size(window_id);
  1966. MINMAXINFO *min_max_info = (MINMAXINFO *)lParam;
  1967. if (windows[window_id].min_size != Size2()) {
  1968. min_max_info->ptMinTrackSize.x = windows[window_id].min_size.x + decor.x;
  1969. min_max_info->ptMinTrackSize.y = windows[window_id].min_size.y + decor.y;
  1970. }
  1971. if (windows[window_id].max_size != Size2()) {
  1972. min_max_info->ptMaxTrackSize.x = windows[window_id].max_size.x + decor.x;
  1973. min_max_info->ptMaxTrackSize.y = windows[window_id].max_size.y + decor.y;
  1974. }
  1975. return 0;
  1976. }
  1977. } break;
  1978. case WM_PAINT: {
  1979. Main::force_redraw();
  1980. } break;
  1981. case WM_SETTINGCHANGE: {
  1982. if (lParam && CompareStringOrdinal(reinterpret_cast<LPCWCH>(lParam), -1, L"ImmersiveColorSet", -1, true) == CSTR_EQUAL) {
  1983. if (is_dark_mode_supported() && dark_title_available) {
  1984. BOOL value = is_dark_mode();
  1985. ::DwmSetWindowAttribute(windows[window_id].hWnd, DWMWA_USE_IMMERSIVE_DARK_MODE, &value, sizeof(value));
  1986. }
  1987. }
  1988. } break;
  1989. case WM_THEMECHANGED: {
  1990. if (is_dark_mode_supported() && dark_title_available) {
  1991. BOOL value = is_dark_mode();
  1992. ::DwmSetWindowAttribute(windows[window_id].hWnd, DWMWA_USE_IMMERSIVE_DARK_MODE, &value, sizeof(value));
  1993. }
  1994. } break;
  1995. case WM_SYSCOMMAND: // Intercept system commands.
  1996. {
  1997. switch (wParam) // Check system calls.
  1998. {
  1999. case SC_SCREENSAVE: // Screensaver trying to start?
  2000. case SC_MONITORPOWER: // Monitor trying to enter powersave?
  2001. return 0; // Prevent from happening.
  2002. case SC_KEYMENU:
  2003. if ((lParam >> 16) <= 0) {
  2004. return 0;
  2005. }
  2006. }
  2007. } break;
  2008. case WM_CLOSE: // Did we receive a close message?
  2009. {
  2010. if (windows[window_id].focus_timer_id != 0U) {
  2011. KillTimer(windows[window_id].hWnd, windows[window_id].focus_timer_id);
  2012. }
  2013. _send_window_event(windows[window_id], WINDOW_EVENT_CLOSE_REQUEST);
  2014. return 0; // Jump back.
  2015. }
  2016. case WM_MOUSELEAVE: {
  2017. old_invalid = true;
  2018. windows[window_id].mouse_outside = true;
  2019. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_EXIT);
  2020. } break;
  2021. case WM_INPUT: {
  2022. if (mouse_mode != MOUSE_MODE_CAPTURED || !use_raw_input) {
  2023. break;
  2024. }
  2025. UINT dwSize;
  2026. GetRawInputData((HRAWINPUT)lParam, RID_INPUT, nullptr, &dwSize, sizeof(RAWINPUTHEADER));
  2027. LPBYTE lpb = new BYTE[dwSize];
  2028. if (lpb == nullptr) {
  2029. return 0;
  2030. }
  2031. if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize) {
  2032. OutputDebugString(TEXT("GetRawInputData does not return correct size !\n"));
  2033. }
  2034. RAWINPUT *raw = (RAWINPUT *)lpb;
  2035. if (raw->header.dwType == RIM_TYPEMOUSE) {
  2036. Ref<InputEventMouseMotion> mm;
  2037. mm.instantiate();
  2038. mm->set_window_id(window_id);
  2039. mm->set_ctrl_pressed(control_mem);
  2040. mm->set_shift_pressed(shift_mem);
  2041. mm->set_alt_pressed(alt_mem);
  2042. mm->set_pressure((raw->data.mouse.ulButtons & RI_MOUSE_LEFT_BUTTON_DOWN) ? 1.0f : 0.0f);
  2043. mm->set_button_mask(last_button_state);
  2044. Point2i c(windows[window_id].width / 2, windows[window_id].height / 2);
  2045. // Centering just so it works as before.
  2046. POINT pos = { (int)c.x, (int)c.y };
  2047. ClientToScreen(windows[window_id].hWnd, &pos);
  2048. SetCursorPos(pos.x, pos.y);
  2049. mm->set_position(c);
  2050. mm->set_global_position(c);
  2051. mm->set_velocity(Vector2(0, 0));
  2052. if (raw->data.mouse.usFlags == MOUSE_MOVE_RELATIVE) {
  2053. mm->set_relative(Vector2(raw->data.mouse.lLastX, raw->data.mouse.lLastY));
  2054. } else if (raw->data.mouse.usFlags == MOUSE_MOVE_ABSOLUTE) {
  2055. int nScreenWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN);
  2056. int nScreenHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
  2057. int nScreenLeft = GetSystemMetrics(SM_XVIRTUALSCREEN);
  2058. int nScreenTop = GetSystemMetrics(SM_YVIRTUALSCREEN);
  2059. Vector2 abs_pos(
  2060. (double(raw->data.mouse.lLastX) - 65536.0 / (nScreenWidth)) * nScreenWidth / 65536.0 + nScreenLeft,
  2061. (double(raw->data.mouse.lLastY) - 65536.0 / (nScreenHeight)) * nScreenHeight / 65536.0 + nScreenTop);
  2062. POINT coords; // Client coords.
  2063. coords.x = abs_pos.x;
  2064. coords.y = abs_pos.y;
  2065. ScreenToClient(hWnd, &coords);
  2066. mm->set_relative(Vector2(coords.x - old_x, coords.y - old_y));
  2067. old_x = coords.x;
  2068. old_y = coords.y;
  2069. }
  2070. if ((windows[window_id].window_has_focus || windows[window_id].is_popup) && mm->get_relative() != Vector2()) {
  2071. Input::get_singleton()->parse_input_event(mm);
  2072. }
  2073. }
  2074. delete[] lpb;
  2075. } break;
  2076. case WT_CSRCHANGE:
  2077. case WT_PROXIMITY: {
  2078. if ((tablet_get_current_driver() == "wintab") && wintab_available && windows[window_id].wtctx) {
  2079. AXIS pressure;
  2080. if (wintab_WTInfo(WTI_DEVICES + windows[window_id].wtlc.lcDevice, DVC_NPRESSURE, &pressure)) {
  2081. windows[window_id].min_pressure = int(pressure.axMin);
  2082. windows[window_id].max_pressure = int(pressure.axMax);
  2083. }
  2084. AXIS orientation[3];
  2085. if (wintab_WTInfo(WTI_DEVICES + windows[window_id].wtlc.lcDevice, DVC_ORIENTATION, &orientation)) {
  2086. windows[window_id].tilt_supported = orientation[0].axResolution && orientation[1].axResolution;
  2087. }
  2088. return 0;
  2089. }
  2090. } break;
  2091. case WT_PACKET: {
  2092. if ((tablet_get_current_driver() == "wintab") && wintab_available && windows[window_id].wtctx) {
  2093. PACKET packet;
  2094. if (wintab_WTPacket(windows[window_id].wtctx, wParam, &packet)) {
  2095. POINT coords;
  2096. GetCursorPos(&coords);
  2097. ScreenToClient(windows[window_id].hWnd, &coords);
  2098. windows[window_id].last_pressure_update = 0;
  2099. float pressure = float(packet.pkNormalPressure - windows[window_id].min_pressure) / float(windows[window_id].max_pressure - windows[window_id].min_pressure);
  2100. double azim = (packet.pkOrientation.orAzimuth / 10.0f) * (Math_PI / 180);
  2101. double alt = Math::tan((Math::abs(packet.pkOrientation.orAltitude / 10.0f)) * (Math_PI / 180));
  2102. bool inverted = packet.pkStatus & TPS_INVERT;
  2103. Vector2 tilt = (windows[window_id].tilt_supported) ? Vector2(Math::atan(Math::sin(azim) / alt), Math::atan(Math::cos(azim) / alt)) : Vector2();
  2104. // Nothing changed, ignore event.
  2105. if (!old_invalid && coords.x == old_x && coords.y == old_y && windows[window_id].last_pressure == pressure && windows[window_id].last_tilt == tilt && windows[window_id].last_pen_inverted == inverted) {
  2106. break;
  2107. }
  2108. windows[window_id].last_pressure = pressure;
  2109. windows[window_id].last_tilt = tilt;
  2110. windows[window_id].last_pen_inverted = inverted;
  2111. // Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
  2112. if (!windows[window_id].window_has_focus && mouse_mode == MOUSE_MODE_CAPTURED) {
  2113. break;
  2114. }
  2115. Ref<InputEventMouseMotion> mm;
  2116. mm.instantiate();
  2117. mm->set_window_id(window_id);
  2118. mm->set_ctrl_pressed(GetKeyState(VK_CONTROL) < 0);
  2119. mm->set_shift_pressed(GetKeyState(VK_SHIFT) < 0);
  2120. mm->set_alt_pressed(alt_mem);
  2121. mm->set_pressure(windows[window_id].last_pressure);
  2122. mm->set_tilt(windows[window_id].last_tilt);
  2123. mm->set_pen_inverted(windows[window_id].last_pen_inverted);
  2124. mm->set_button_mask(last_button_state);
  2125. mm->set_position(Vector2(coords.x, coords.y));
  2126. mm->set_global_position(Vector2(coords.x, coords.y));
  2127. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  2128. Point2i c(windows[window_id].width / 2, windows[window_id].height / 2);
  2129. old_x = c.x;
  2130. old_y = c.y;
  2131. if (mm->get_position() == c) {
  2132. center = c;
  2133. return 0;
  2134. }
  2135. Point2i ncenter = mm->get_position();
  2136. center = ncenter;
  2137. POINT pos = { (int)c.x, (int)c.y };
  2138. ClientToScreen(windows[window_id].hWnd, &pos);
  2139. SetCursorPos(pos.x, pos.y);
  2140. }
  2141. mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
  2142. if (old_invalid) {
  2143. old_x = mm->get_position().x;
  2144. old_y = mm->get_position().y;
  2145. old_invalid = false;
  2146. }
  2147. mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
  2148. old_x = mm->get_position().x;
  2149. old_y = mm->get_position().y;
  2150. if (windows[window_id].window_has_focus || window_get_active_popup() == window_id) {
  2151. Input::get_singleton()->parse_input_event(mm);
  2152. }
  2153. }
  2154. return 0;
  2155. }
  2156. } break;
  2157. case WM_POINTERENTER: {
  2158. if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
  2159. break;
  2160. }
  2161. if ((tablet_get_current_driver() != "winink") || !winink_available) {
  2162. break;
  2163. }
  2164. uint32_t pointer_id = LOWORD(wParam);
  2165. POINTER_INPUT_TYPE pointer_type = PT_POINTER;
  2166. if (!win8p_GetPointerType(pointer_id, &pointer_type)) {
  2167. break;
  2168. }
  2169. if (pointer_type != PT_PEN) {
  2170. break;
  2171. }
  2172. windows[window_id].block_mm = true;
  2173. return 0;
  2174. } break;
  2175. case WM_POINTERLEAVE: {
  2176. windows[window_id].block_mm = false;
  2177. return 0;
  2178. } break;
  2179. case WM_POINTERUPDATE: {
  2180. if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
  2181. break;
  2182. }
  2183. if ((tablet_get_current_driver() != "winink") || !winink_available) {
  2184. break;
  2185. }
  2186. uint32_t pointer_id = LOWORD(wParam);
  2187. POINTER_INPUT_TYPE pointer_type = PT_POINTER;
  2188. if (!win8p_GetPointerType(pointer_id, &pointer_type)) {
  2189. break;
  2190. }
  2191. if (pointer_type != PT_PEN) {
  2192. break;
  2193. }
  2194. POINTER_PEN_INFO pen_info;
  2195. if (!win8p_GetPointerPenInfo(pointer_id, &pen_info)) {
  2196. break;
  2197. }
  2198. if (Input::get_singleton()->is_emulating_mouse_from_touch()) {
  2199. // Universal translation enabled; ignore OS translation.
  2200. LPARAM extra = GetMessageExtraInfo();
  2201. if (IsTouchEvent(extra)) {
  2202. break;
  2203. }
  2204. }
  2205. if (windows[window_id].mouse_outside) {
  2206. // Mouse enter.
  2207. if (mouse_mode != MOUSE_MODE_CAPTURED) {
  2208. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
  2209. }
  2210. CursorShape c = cursor_shape;
  2211. cursor_shape = CURSOR_MAX;
  2212. cursor_set_shape(c);
  2213. windows[window_id].mouse_outside = false;
  2214. // Once-off notification, must call again.
  2215. track_mouse_leave_event(hWnd);
  2216. }
  2217. // Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
  2218. if (!windows[window_id].window_has_focus && mouse_mode == MOUSE_MODE_CAPTURED) {
  2219. break;
  2220. }
  2221. Ref<InputEventMouseMotion> mm;
  2222. mm.instantiate();
  2223. mm->set_window_id(window_id);
  2224. if (pen_info.penMask & PEN_MASK_PRESSURE) {
  2225. mm->set_pressure((float)pen_info.pressure / 1024);
  2226. } else {
  2227. mm->set_pressure((HIWORD(wParam) & POINTER_MESSAGE_FLAG_FIRSTBUTTON) ? 1.0f : 0.0f);
  2228. }
  2229. if ((pen_info.penMask & PEN_MASK_TILT_X) && (pen_info.penMask & PEN_MASK_TILT_Y)) {
  2230. mm->set_tilt(Vector2((float)pen_info.tiltX / 90, (float)pen_info.tiltY / 90));
  2231. }
  2232. mm->set_pen_inverted(pen_info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER));
  2233. mm->set_ctrl_pressed(GetKeyState(VK_CONTROL) < 0);
  2234. mm->set_shift_pressed(GetKeyState(VK_SHIFT) < 0);
  2235. mm->set_alt_pressed(alt_mem);
  2236. mm->set_button_mask(last_button_state);
  2237. POINT coords; // Client coords.
  2238. coords.x = GET_X_LPARAM(lParam);
  2239. coords.y = GET_Y_LPARAM(lParam);
  2240. ScreenToClient(windows[window_id].hWnd, &coords);
  2241. mm->set_position(Vector2(coords.x, coords.y));
  2242. mm->set_global_position(Vector2(coords.x, coords.y));
  2243. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  2244. Point2i c(windows[window_id].width / 2, windows[window_id].height / 2);
  2245. old_x = c.x;
  2246. old_y = c.y;
  2247. if (mm->get_position() == c) {
  2248. center = c;
  2249. return 0;
  2250. }
  2251. Point2i ncenter = mm->get_position();
  2252. center = ncenter;
  2253. POINT pos = { (int)c.x, (int)c.y };
  2254. ClientToScreen(hWnd, &pos);
  2255. SetCursorPos(pos.x, pos.y);
  2256. }
  2257. mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
  2258. if (old_invalid) {
  2259. old_x = mm->get_position().x;
  2260. old_y = mm->get_position().y;
  2261. old_invalid = false;
  2262. }
  2263. mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
  2264. old_x = mm->get_position().x;
  2265. old_y = mm->get_position().y;
  2266. if (windows[window_id].window_has_focus || window_get_active_popup() == window_id) {
  2267. Input::get_singleton()->parse_input_event(mm);
  2268. }
  2269. return 0; // Pointer event handled return 0 to avoid duplicate WM_MOUSEMOVE event.
  2270. } break;
  2271. case WM_MOUSEMOVE: {
  2272. if (windows[window_id].block_mm) {
  2273. break;
  2274. }
  2275. if (mouse_mode == MOUSE_MODE_CAPTURED && use_raw_input) {
  2276. break;
  2277. }
  2278. if (Input::get_singleton()->is_emulating_mouse_from_touch()) {
  2279. // Universal translation enabled; ignore OS translation.
  2280. LPARAM extra = GetMessageExtraInfo();
  2281. if (IsTouchEvent(extra)) {
  2282. break;
  2283. }
  2284. }
  2285. if (windows[window_id].mouse_outside) {
  2286. // Mouse enter.
  2287. if (mouse_mode != MOUSE_MODE_CAPTURED) {
  2288. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
  2289. }
  2290. CursorShape c = cursor_shape;
  2291. cursor_shape = CURSOR_MAX;
  2292. cursor_set_shape(c);
  2293. windows[window_id].mouse_outside = false;
  2294. // Once-off notification, must call again.
  2295. track_mouse_leave_event(hWnd);
  2296. }
  2297. // Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
  2298. if (!windows[window_id].window_has_focus && mouse_mode == MOUSE_MODE_CAPTURED) {
  2299. break;
  2300. }
  2301. Ref<InputEventMouseMotion> mm;
  2302. mm.instantiate();
  2303. mm->set_window_id(window_id);
  2304. mm->set_ctrl_pressed((wParam & MK_CONTROL) != 0);
  2305. mm->set_shift_pressed((wParam & MK_SHIFT) != 0);
  2306. mm->set_alt_pressed(alt_mem);
  2307. if ((tablet_get_current_driver() == "wintab") && wintab_available && windows[window_id].wtctx) {
  2308. // Note: WinTab sends both WT_PACKET and WM_xBUTTONDOWN/UP/MOUSEMOVE events, use mouse 1/0 pressure only when last_pressure was not updated recently.
  2309. if (windows[window_id].last_pressure_update < 10) {
  2310. windows[window_id].last_pressure_update++;
  2311. } else {
  2312. windows[window_id].last_tilt = Vector2();
  2313. windows[window_id].last_pressure = (wParam & MK_LBUTTON) ? 1.0f : 0.0f;
  2314. windows[window_id].last_pen_inverted = false;
  2315. }
  2316. } else {
  2317. windows[window_id].last_tilt = Vector2();
  2318. windows[window_id].last_pressure = (wParam & MK_LBUTTON) ? 1.0f : 0.0f;
  2319. windows[window_id].last_pen_inverted = false;
  2320. }
  2321. mm->set_pressure(windows[window_id].last_pressure);
  2322. mm->set_tilt(windows[window_id].last_tilt);
  2323. mm->set_pen_inverted(windows[window_id].last_pen_inverted);
  2324. mm->set_button_mask(last_button_state);
  2325. mm->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  2326. mm->set_global_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  2327. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  2328. Point2i c(windows[window_id].width / 2, windows[window_id].height / 2);
  2329. old_x = c.x;
  2330. old_y = c.y;
  2331. if (mm->get_position() == c) {
  2332. center = c;
  2333. return 0;
  2334. }
  2335. Point2i ncenter = mm->get_position();
  2336. center = ncenter;
  2337. POINT pos = { (int)c.x, (int)c.y };
  2338. ClientToScreen(windows[window_id].hWnd, &pos);
  2339. SetCursorPos(pos.x, pos.y);
  2340. }
  2341. mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
  2342. if (old_invalid) {
  2343. old_x = mm->get_position().x;
  2344. old_y = mm->get_position().y;
  2345. old_invalid = false;
  2346. }
  2347. mm->set_relative(Vector2(mm->get_position() - Vector2(old_x, old_y)));
  2348. old_x = mm->get_position().x;
  2349. old_y = mm->get_position().y;
  2350. if (windows[window_id].window_has_focus || window_get_active_popup() == window_id) {
  2351. Input::get_singleton()->parse_input_event(mm);
  2352. }
  2353. } break;
  2354. case WM_LBUTTONDOWN:
  2355. case WM_LBUTTONUP:
  2356. if (Input::get_singleton()->is_emulating_mouse_from_touch()) {
  2357. // Universal translation enabled; ignore OS translations for left button.
  2358. LPARAM extra = GetMessageExtraInfo();
  2359. if (IsTouchEvent(extra)) {
  2360. break;
  2361. }
  2362. }
  2363. [[fallthrough]];
  2364. case WM_MBUTTONDOWN:
  2365. case WM_MBUTTONUP:
  2366. case WM_RBUTTONDOWN:
  2367. case WM_RBUTTONUP:
  2368. case WM_MOUSEWHEEL:
  2369. case WM_MOUSEHWHEEL:
  2370. case WM_LBUTTONDBLCLK:
  2371. case WM_MBUTTONDBLCLK:
  2372. case WM_RBUTTONDBLCLK:
  2373. case WM_XBUTTONDBLCLK:
  2374. case WM_XBUTTONDOWN:
  2375. case WM_XBUTTONUP: {
  2376. Ref<InputEventMouseButton> mb;
  2377. mb.instantiate();
  2378. mb->set_window_id(window_id);
  2379. switch (uMsg) {
  2380. case WM_LBUTTONDOWN: {
  2381. mb->set_pressed(true);
  2382. mb->set_button_index(MouseButton::LEFT);
  2383. } break;
  2384. case WM_LBUTTONUP: {
  2385. mb->set_pressed(false);
  2386. mb->set_button_index(MouseButton::LEFT);
  2387. } break;
  2388. case WM_MBUTTONDOWN: {
  2389. mb->set_pressed(true);
  2390. mb->set_button_index(MouseButton::MIDDLE);
  2391. } break;
  2392. case WM_MBUTTONUP: {
  2393. mb->set_pressed(false);
  2394. mb->set_button_index(MouseButton::MIDDLE);
  2395. } break;
  2396. case WM_RBUTTONDOWN: {
  2397. mb->set_pressed(true);
  2398. mb->set_button_index(MouseButton::RIGHT);
  2399. } break;
  2400. case WM_RBUTTONUP: {
  2401. mb->set_pressed(false);
  2402. mb->set_button_index(MouseButton::RIGHT);
  2403. } break;
  2404. case WM_LBUTTONDBLCLK: {
  2405. mb->set_pressed(true);
  2406. mb->set_button_index(MouseButton::LEFT);
  2407. mb->set_double_click(true);
  2408. } break;
  2409. case WM_RBUTTONDBLCLK: {
  2410. mb->set_pressed(true);
  2411. mb->set_button_index(MouseButton::RIGHT);
  2412. mb->set_double_click(true);
  2413. } break;
  2414. case WM_MBUTTONDBLCLK: {
  2415. mb->set_pressed(true);
  2416. mb->set_button_index(MouseButton::MIDDLE);
  2417. mb->set_double_click(true);
  2418. } break;
  2419. case WM_MOUSEWHEEL: {
  2420. mb->set_pressed(true);
  2421. int motion = (short)HIWORD(wParam);
  2422. if (!motion) {
  2423. return 0;
  2424. }
  2425. if (motion > 0) {
  2426. mb->set_button_index(MouseButton::WHEEL_UP);
  2427. } else {
  2428. mb->set_button_index(MouseButton::WHEEL_DOWN);
  2429. }
  2430. mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA));
  2431. } break;
  2432. case WM_MOUSEHWHEEL: {
  2433. mb->set_pressed(true);
  2434. int motion = (short)HIWORD(wParam);
  2435. if (!motion) {
  2436. return 0;
  2437. }
  2438. if (motion < 0) {
  2439. mb->set_button_index(MouseButton::WHEEL_LEFT);
  2440. } else {
  2441. mb->set_button_index(MouseButton::WHEEL_RIGHT);
  2442. }
  2443. mb->set_factor(fabs((double)motion / (double)WHEEL_DELTA));
  2444. } break;
  2445. case WM_XBUTTONDOWN: {
  2446. mb->set_pressed(true);
  2447. if (HIWORD(wParam) == XBUTTON1) {
  2448. mb->set_button_index(MouseButton::MB_XBUTTON1);
  2449. } else {
  2450. mb->set_button_index(MouseButton::MB_XBUTTON2);
  2451. }
  2452. } break;
  2453. case WM_XBUTTONUP: {
  2454. mb->set_pressed(false);
  2455. if (HIWORD(wParam) == XBUTTON1) {
  2456. mb->set_button_index(MouseButton::MB_XBUTTON1);
  2457. } else {
  2458. mb->set_button_index(MouseButton::MB_XBUTTON2);
  2459. }
  2460. } break;
  2461. case WM_XBUTTONDBLCLK: {
  2462. mb->set_pressed(true);
  2463. if (HIWORD(wParam) == XBUTTON1) {
  2464. mb->set_button_index(MouseButton::MB_XBUTTON1);
  2465. } else {
  2466. mb->set_button_index(MouseButton::MB_XBUTTON2);
  2467. }
  2468. mb->set_double_click(true);
  2469. } break;
  2470. default: {
  2471. return 0;
  2472. }
  2473. }
  2474. mb->set_ctrl_pressed((wParam & MK_CONTROL) != 0);
  2475. mb->set_shift_pressed((wParam & MK_SHIFT) != 0);
  2476. mb->set_alt_pressed(alt_mem);
  2477. // mb->is_alt_pressed()=(wParam&MK_MENU)!=0;
  2478. if (mb->is_pressed()) {
  2479. last_button_state |= mouse_button_to_mask(mb->get_button_index());
  2480. } else {
  2481. last_button_state &= ~mouse_button_to_mask(mb->get_button_index());
  2482. }
  2483. mb->set_button_mask(last_button_state);
  2484. mb->set_position(Vector2(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
  2485. if (mouse_mode == MOUSE_MODE_CAPTURED && !use_raw_input) {
  2486. mb->set_position(Vector2(old_x, old_y));
  2487. }
  2488. if (uMsg != WM_MOUSEWHEEL && uMsg != WM_MOUSEHWHEEL) {
  2489. if (mb->is_pressed()) {
  2490. if (++pressrc > 0 && mouse_mode != MOUSE_MODE_CAPTURED) {
  2491. SetCapture(hWnd);
  2492. }
  2493. } else {
  2494. if (--pressrc <= 0) {
  2495. if (mouse_mode != MOUSE_MODE_CAPTURED) {
  2496. ReleaseCapture();
  2497. }
  2498. pressrc = 0;
  2499. }
  2500. }
  2501. } else {
  2502. // For reasons unknown to humanity, wheel comes in screen coordinates.
  2503. POINT coords;
  2504. coords.x = mb->get_position().x;
  2505. coords.y = mb->get_position().y;
  2506. ScreenToClient(hWnd, &coords);
  2507. mb->set_position(Vector2(coords.x, coords.y));
  2508. }
  2509. mb->set_global_position(mb->get_position());
  2510. Input::get_singleton()->parse_input_event(mb);
  2511. if (mb->is_pressed() && mb->get_button_index() >= MouseButton::WHEEL_UP && mb->get_button_index() <= MouseButton::WHEEL_RIGHT) {
  2512. // Send release for mouse wheel.
  2513. Ref<InputEventMouseButton> mbd = mb->duplicate();
  2514. mbd->set_window_id(window_id);
  2515. last_button_state &= ~mouse_button_to_mask(mbd->get_button_index());
  2516. mbd->set_button_mask(last_button_state);
  2517. mbd->set_pressed(false);
  2518. Input::get_singleton()->parse_input_event(mbd);
  2519. }
  2520. } break;
  2521. case WM_WINDOWPOSCHANGED: {
  2522. Rect2i window_client_rect;
  2523. Rect2i window_rect;
  2524. {
  2525. RECT rect;
  2526. GetClientRect(hWnd, &rect);
  2527. ClientToScreen(hWnd, (POINT *)&rect.left);
  2528. ClientToScreen(hWnd, (POINT *)&rect.right);
  2529. window_client_rect = Rect2i(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
  2530. RECT wrect;
  2531. GetWindowRect(hWnd, &wrect);
  2532. window_rect = Rect2i(wrect.left, wrect.top, wrect.right - wrect.left, wrect.bottom - wrect.top);
  2533. }
  2534. WINDOWPOS *window_pos_params = (WINDOWPOS *)lParam;
  2535. WindowData &window = windows[window_id];
  2536. bool rect_changed = false;
  2537. if (!(window_pos_params->flags & SWP_NOSIZE) || window_pos_params->flags & SWP_FRAMECHANGED) {
  2538. int screen_id = window_get_current_screen(window_id);
  2539. Size2i screen_size = screen_get_size(screen_id);
  2540. Point2i screen_position = screen_get_position(screen_id);
  2541. window.maximized = false;
  2542. window.minimized = false;
  2543. window.fullscreen = false;
  2544. if (IsIconic(hWnd)) {
  2545. window.minimized = true;
  2546. } else if (IsZoomed(hWnd)) {
  2547. window.maximized = true;
  2548. } else if (window_rect.position == screen_position && window_rect.size == screen_size) {
  2549. window.fullscreen = true;
  2550. }
  2551. if (!window.minimized) {
  2552. window.width = window_client_rect.size.width;
  2553. window.height = window_client_rect.size.height;
  2554. rect_changed = true;
  2555. }
  2556. #if defined(VULKAN_ENABLED)
  2557. if (context_vulkan && window_created) {
  2558. // Note: Trigger resize event to update swapchains when window is minimized/restored, even if size is not changed.
  2559. context_vulkan->window_resize(window_id, window.width, window.height);
  2560. }
  2561. #endif
  2562. }
  2563. if (!window.minimized && (!(window_pos_params->flags & SWP_NOMOVE) || window_pos_params->flags & SWP_FRAMECHANGED)) {
  2564. window.last_pos = window_client_rect.position;
  2565. rect_changed = true;
  2566. }
  2567. if (rect_changed) {
  2568. if (!window.rect_changed_callback.is_null()) {
  2569. Variant size = Rect2i(window.last_pos.x, window.last_pos.y, window.width, window.height);
  2570. const Variant *args[] = { &size };
  2571. Variant ret;
  2572. Callable::CallError ce;
  2573. window.rect_changed_callback.callp(args, 1, ret, ce);
  2574. }
  2575. }
  2576. // Return here to prevent WM_MOVE and WM_SIZE from being sent
  2577. // See: https://docs.microsoft.com/en-us/windows/win32/winmsg/wm-windowposchanged#remarks
  2578. return 0;
  2579. } break;
  2580. case WM_ENTERSIZEMOVE: {
  2581. Input::get_singleton()->release_pressed_events();
  2582. windows[window_id].move_timer_id = SetTimer(windows[window_id].hWnd, 1, USER_TIMER_MINIMUM, (TIMERPROC) nullptr);
  2583. } break;
  2584. case WM_EXITSIZEMOVE: {
  2585. KillTimer(windows[window_id].hWnd, windows[window_id].move_timer_id);
  2586. } break;
  2587. case WM_TIMER: {
  2588. if (wParam == windows[window_id].move_timer_id) {
  2589. _process_key_events();
  2590. if (!Main::is_iterating()) {
  2591. Main::iteration();
  2592. }
  2593. } else if (wParam == windows[window_id].focus_timer_id) {
  2594. _process_activate_event(window_id, windows[window_id].saved_wparam, windows[window_id].saved_lparam);
  2595. KillTimer(windows[window_id].hWnd, wParam);
  2596. windows[window_id].focus_timer_id = 0U;
  2597. }
  2598. } break;
  2599. case WM_SYSKEYDOWN:
  2600. case WM_SYSKEYUP:
  2601. case WM_KEYUP:
  2602. case WM_KEYDOWN: {
  2603. if (wParam == VK_SHIFT) {
  2604. shift_mem = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN);
  2605. }
  2606. if (wParam == VK_CONTROL) {
  2607. control_mem = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN);
  2608. }
  2609. if (wParam == VK_MENU) {
  2610. alt_mem = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN);
  2611. if (lParam & (1 << 24)) {
  2612. gr_mem = alt_mem;
  2613. }
  2614. }
  2615. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  2616. // When SetCapture is used, ALT+F4 hotkey is ignored by Windows, so handle it ourselves
  2617. if (wParam == VK_F4 && alt_mem && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN)) {
  2618. _send_window_event(windows[window_id], WINDOW_EVENT_CLOSE_REQUEST);
  2619. }
  2620. }
  2621. [[fallthrough]];
  2622. }
  2623. case WM_CHAR: {
  2624. ERR_BREAK(key_event_pos >= KEY_EVENT_BUFFER_SIZE);
  2625. // Make sure we don't include modifiers for the modifier key itself.
  2626. KeyEvent ke;
  2627. ke.shift = (wParam != VK_SHIFT) ? shift_mem : false;
  2628. ke.alt = (!(wParam == VK_MENU && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN))) ? alt_mem : false;
  2629. ke.control = (wParam != VK_CONTROL) ? control_mem : false;
  2630. ke.meta = meta_mem;
  2631. ke.uMsg = uMsg;
  2632. ke.window_id = window_id;
  2633. if (ke.uMsg == WM_SYSKEYDOWN) {
  2634. ke.uMsg = WM_KEYDOWN;
  2635. }
  2636. if (ke.uMsg == WM_SYSKEYUP) {
  2637. ke.uMsg = WM_KEYUP;
  2638. }
  2639. ke.wParam = wParam;
  2640. ke.lParam = lParam;
  2641. key_event_buffer[key_event_pos++] = ke;
  2642. } break;
  2643. case WM_INPUTLANGCHANGEREQUEST: {
  2644. // FIXME: Do something?
  2645. } break;
  2646. case WM_TOUCH: {
  2647. BOOL bHandled = FALSE;
  2648. UINT cInputs = LOWORD(wParam);
  2649. PTOUCHINPUT pInputs = memnew_arr(TOUCHINPUT, cInputs);
  2650. if (pInputs) {
  2651. if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs, sizeof(TOUCHINPUT))) {
  2652. for (UINT i = 0; i < cInputs; i++) {
  2653. TOUCHINPUT ti = pInputs[i];
  2654. POINT touch_pos = {
  2655. TOUCH_COORD_TO_PIXEL(ti.x),
  2656. TOUCH_COORD_TO_PIXEL(ti.y),
  2657. };
  2658. ScreenToClient(hWnd, &touch_pos);
  2659. // Do something with each touch input entry.
  2660. if (ti.dwFlags & TOUCHEVENTF_MOVE) {
  2661. _drag_event(window_id, touch_pos.x, touch_pos.y, ti.dwID);
  2662. } else if (ti.dwFlags & (TOUCHEVENTF_UP | TOUCHEVENTF_DOWN)) {
  2663. _touch_event(window_id, ti.dwFlags & TOUCHEVENTF_DOWN, touch_pos.x, touch_pos.y, ti.dwID);
  2664. }
  2665. }
  2666. bHandled = TRUE;
  2667. } else {
  2668. // TODO: Handle the error here.
  2669. }
  2670. memdelete_arr(pInputs);
  2671. } else {
  2672. // TODO: Handle the error here, probably out of memory.
  2673. }
  2674. if (bHandled) {
  2675. CloseTouchInputHandle((HTOUCHINPUT)lParam);
  2676. return 0;
  2677. }
  2678. } break;
  2679. case WM_DEVICECHANGE: {
  2680. joypad->probe_joypads();
  2681. } break;
  2682. case WM_DESTROY: {
  2683. Input::get_singleton()->flush_buffered_events();
  2684. } break;
  2685. case WM_SETCURSOR: {
  2686. if (LOWORD(lParam) == HTCLIENT) {
  2687. if (windows[window_id].window_has_focus && (mouse_mode == MOUSE_MODE_HIDDEN || mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN)) {
  2688. // Hide the cursor.
  2689. if (hCursor == nullptr) {
  2690. hCursor = SetCursor(nullptr);
  2691. } else {
  2692. SetCursor(nullptr);
  2693. }
  2694. } else {
  2695. if (hCursor != nullptr) {
  2696. CursorShape c = cursor_shape;
  2697. cursor_shape = CURSOR_MAX;
  2698. cursor_set_shape(c);
  2699. hCursor = nullptr;
  2700. }
  2701. }
  2702. }
  2703. } break;
  2704. case WM_DROPFILES: {
  2705. HDROP hDropInfo = (HDROP)wParam;
  2706. const int buffsize = 4096;
  2707. WCHAR buf[buffsize];
  2708. int fcount = DragQueryFileW(hDropInfo, 0xFFFFFFFF, nullptr, 0);
  2709. Vector<String> files;
  2710. for (int i = 0; i < fcount; i++) {
  2711. DragQueryFileW(hDropInfo, i, buf, buffsize);
  2712. String file = String::utf16((const char16_t *)buf);
  2713. files.push_back(file);
  2714. }
  2715. if (files.size() && !windows[window_id].drop_files_callback.is_null()) {
  2716. Variant v = files;
  2717. Variant *vp = &v;
  2718. Variant ret;
  2719. Callable::CallError ce;
  2720. windows[window_id].drop_files_callback.callp((const Variant **)&vp, 1, ret, ce);
  2721. }
  2722. } break;
  2723. default: {
  2724. if (user_proc) {
  2725. return CallWindowProcW(user_proc, hWnd, uMsg, wParam, lParam);
  2726. }
  2727. }
  2728. }
  2729. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  2730. }
  2731. LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  2732. DisplayServerWindows *ds_win = static_cast<DisplayServerWindows *>(DisplayServer::get_singleton());
  2733. if (ds_win) {
  2734. return ds_win->WndProc(hWnd, uMsg, wParam, lParam);
  2735. } else {
  2736. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  2737. }
  2738. }
  2739. void DisplayServerWindows::_process_activate_event(WindowID p_window_id, WPARAM wParam, LPARAM lParam) {
  2740. if (LOWORD(wParam) == WA_ACTIVE || LOWORD(wParam) == WA_CLICKACTIVE) {
  2741. _send_window_event(windows[p_window_id], WINDOW_EVENT_FOCUS_IN);
  2742. windows[p_window_id].window_focused = true;
  2743. alt_mem = false;
  2744. control_mem = false;
  2745. shift_mem = false;
  2746. // Restore mouse mode.
  2747. _set_mouse_mode_impl(mouse_mode);
  2748. } else { // WM_INACTIVE.
  2749. Input::get_singleton()->release_pressed_events();
  2750. _send_window_event(windows[p_window_id], WINDOW_EVENT_FOCUS_OUT);
  2751. windows[p_window_id].window_focused = false;
  2752. alt_mem = false;
  2753. }
  2754. if ((tablet_get_current_driver() == "wintab") && wintab_available && windows[p_window_id].wtctx) {
  2755. wintab_WTEnable(windows[p_window_id].wtctx, GET_WM_ACTIVATE_STATE(wParam, lParam));
  2756. }
  2757. }
  2758. void DisplayServerWindows::_process_key_events() {
  2759. for (int i = 0; i < key_event_pos; i++) {
  2760. KeyEvent &ke = key_event_buffer[i];
  2761. switch (ke.uMsg) {
  2762. case WM_CHAR: {
  2763. // Extended keys should only be processed as WM_KEYDOWN message.
  2764. if (!KeyMappingWindows::is_extended_key(ke.wParam) && ((i == 0 && ke.uMsg == WM_CHAR) || (i > 0 && key_event_buffer[i - 1].uMsg == WM_CHAR))) {
  2765. static char32_t prev_wc = 0;
  2766. char32_t unicode = ke.wParam;
  2767. if ((unicode & 0xfffffc00) == 0xd800) {
  2768. if (prev_wc != 0) {
  2769. ERR_PRINT("invalid utf16 surrogate input");
  2770. }
  2771. prev_wc = unicode;
  2772. break; // Skip surrogate.
  2773. } else if ((unicode & 0xfffffc00) == 0xdc00) {
  2774. if (prev_wc == 0) {
  2775. ERR_PRINT("invalid utf16 surrogate input");
  2776. break; // Skip invalid surrogate.
  2777. }
  2778. unicode = (prev_wc << 10UL) + unicode - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  2779. prev_wc = 0;
  2780. } else {
  2781. prev_wc = 0;
  2782. }
  2783. Ref<InputEventKey> k;
  2784. k.instantiate();
  2785. k->set_window_id(ke.window_id);
  2786. k->set_shift_pressed(ke.shift);
  2787. k->set_alt_pressed(ke.alt);
  2788. k->set_ctrl_pressed(ke.control);
  2789. k->set_meta_pressed(ke.meta);
  2790. k->set_pressed(true);
  2791. k->set_keycode((Key)KeyMappingWindows::get_keysym(MapVirtualKey((ke.lParam >> 16) & 0xFF, MAPVK_VSC_TO_VK)));
  2792. k->set_physical_keycode((Key)(KeyMappingWindows::get_scansym((ke.lParam >> 16) & 0xFF, ke.lParam & (1 << 24))));
  2793. k->set_unicode(unicode);
  2794. if (k->get_unicode() && gr_mem) {
  2795. k->set_alt_pressed(false);
  2796. k->set_ctrl_pressed(false);
  2797. }
  2798. if (k->get_unicode() < 32) {
  2799. k->set_unicode(0);
  2800. }
  2801. Input::get_singleton()->parse_input_event(k);
  2802. } else {
  2803. // Do nothing.
  2804. }
  2805. } break;
  2806. case WM_KEYUP:
  2807. case WM_KEYDOWN: {
  2808. Ref<InputEventKey> k;
  2809. k.instantiate();
  2810. k->set_window_id(ke.window_id);
  2811. k->set_shift_pressed(ke.shift);
  2812. k->set_alt_pressed(ke.alt);
  2813. k->set_ctrl_pressed(ke.control);
  2814. k->set_meta_pressed(ke.meta);
  2815. k->set_pressed(ke.uMsg == WM_KEYDOWN);
  2816. if ((ke.lParam & (1 << 24)) && (ke.wParam == VK_RETURN)) {
  2817. // Special case for Numpad Enter key.
  2818. k->set_keycode(Key::KP_ENTER);
  2819. } else {
  2820. k->set_keycode((Key)KeyMappingWindows::get_keysym(ke.wParam));
  2821. }
  2822. k->set_physical_keycode((Key)(KeyMappingWindows::get_scansym((ke.lParam >> 16) & 0xFF, ke.lParam & (1 << 24))));
  2823. if (i + 1 < key_event_pos && key_event_buffer[i + 1].uMsg == WM_CHAR) {
  2824. char32_t unicode = key_event_buffer[i + 1].wParam;
  2825. static char32_t prev_wck = 0;
  2826. if ((unicode & 0xfffffc00) == 0xd800) {
  2827. if (prev_wck != 0) {
  2828. ERR_PRINT("invalid utf16 surrogate input");
  2829. }
  2830. prev_wck = unicode;
  2831. break; // Skip surrogate.
  2832. } else if ((unicode & 0xfffffc00) == 0xdc00) {
  2833. if (prev_wck == 0) {
  2834. ERR_PRINT("invalid utf16 surrogate input");
  2835. break; // Skip invalid surrogate.
  2836. }
  2837. unicode = (prev_wck << 10UL) + unicode - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  2838. prev_wck = 0;
  2839. } else {
  2840. prev_wck = 0;
  2841. }
  2842. k->set_unicode(unicode);
  2843. }
  2844. if (k->get_unicode() && gr_mem) {
  2845. k->set_alt_pressed(false);
  2846. k->set_ctrl_pressed(false);
  2847. }
  2848. if (k->get_unicode() < 32) {
  2849. k->set_unicode(0);
  2850. }
  2851. k->set_echo((ke.uMsg == WM_KEYDOWN && (ke.lParam & (1 << 30))));
  2852. Input::get_singleton()->parse_input_event(k);
  2853. } break;
  2854. }
  2855. }
  2856. key_event_pos = 0;
  2857. }
  2858. void DisplayServerWindows::_update_tablet_ctx(const String &p_old_driver, const String &p_new_driver) {
  2859. for (KeyValue<WindowID, WindowData> &E : windows) {
  2860. WindowData &wd = E.value;
  2861. wd.block_mm = false;
  2862. if ((p_old_driver == "wintab") && wintab_available && wd.wtctx) {
  2863. wintab_WTEnable(wd.wtctx, false);
  2864. wintab_WTClose(wd.wtctx);
  2865. wd.wtctx = 0;
  2866. }
  2867. if ((p_new_driver == "wintab") && wintab_available) {
  2868. wintab_WTInfo(WTI_DEFSYSCTX, 0, &wd.wtlc);
  2869. wd.wtlc.lcOptions |= CXO_MESSAGES;
  2870. wd.wtlc.lcPktData = PK_STATUS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE | PK_ORIENTATION;
  2871. wd.wtlc.lcMoveMask = PK_STATUS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE;
  2872. wd.wtlc.lcPktMode = 0;
  2873. wd.wtlc.lcOutOrgX = 0;
  2874. wd.wtlc.lcOutExtX = wd.wtlc.lcInExtX;
  2875. wd.wtlc.lcOutOrgY = 0;
  2876. wd.wtlc.lcOutExtY = -wd.wtlc.lcInExtY;
  2877. wd.wtctx = wintab_WTOpen(wd.hWnd, &wd.wtlc, false);
  2878. if (wd.wtctx) {
  2879. wintab_WTEnable(wd.wtctx, true);
  2880. AXIS pressure;
  2881. if (wintab_WTInfo(WTI_DEVICES + wd.wtlc.lcDevice, DVC_NPRESSURE, &pressure)) {
  2882. wd.min_pressure = int(pressure.axMin);
  2883. wd.max_pressure = int(pressure.axMax);
  2884. }
  2885. AXIS orientation[3];
  2886. if (wintab_WTInfo(WTI_DEVICES + wd.wtlc.lcDevice, DVC_ORIENTATION, &orientation)) {
  2887. wd.tilt_supported = orientation[0].axResolution && orientation[1].axResolution;
  2888. }
  2889. wintab_WTEnable(wd.wtctx, true);
  2890. } else {
  2891. print_verbose("WinTab context creation failed.");
  2892. }
  2893. }
  2894. }
  2895. }
  2896. DisplayServer::WindowID DisplayServerWindows::_create_window(WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Rect2i &p_rect) {
  2897. DWORD dwExStyle;
  2898. DWORD dwStyle;
  2899. _get_window_style(window_id_counter == MAIN_WINDOW_ID, (p_mode == WINDOW_MODE_FULLSCREEN || p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN), p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN, p_flags & WINDOW_FLAG_BORDERLESS_BIT, !(p_flags & WINDOW_FLAG_RESIZE_DISABLED_BIT), p_mode == WINDOW_MODE_MAXIMIZED, (p_flags & WINDOW_FLAG_NO_FOCUS_BIT), dwStyle, dwExStyle);
  2900. RECT WindowRect;
  2901. WindowRect.left = p_rect.position.x;
  2902. WindowRect.right = p_rect.position.x + p_rect.size.x;
  2903. WindowRect.top = p_rect.position.y;
  2904. WindowRect.bottom = p_rect.position.y + p_rect.size.y;
  2905. if (p_mode == WINDOW_MODE_FULLSCREEN || p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  2906. int nearest_area = 0;
  2907. Rect2i screen_rect;
  2908. for (int i = 0; i < get_screen_count(); i++) {
  2909. Rect2i r;
  2910. r.position = screen_get_position(i);
  2911. r.size = screen_get_size(i);
  2912. Rect2 inters = r.intersection(p_rect);
  2913. int area = inters.size.width * inters.size.height;
  2914. if (area >= nearest_area) {
  2915. screen_rect = r;
  2916. nearest_area = area;
  2917. }
  2918. }
  2919. WindowRect.left = screen_rect.position.x;
  2920. WindowRect.right = screen_rect.position.x + screen_rect.size.x;
  2921. WindowRect.top = screen_rect.position.y;
  2922. WindowRect.bottom = screen_rect.position.y + screen_rect.size.y;
  2923. }
  2924. AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);
  2925. WindowID id = window_id_counter;
  2926. {
  2927. WindowData &wd = windows[id];
  2928. wd.hWnd = CreateWindowExW(
  2929. dwExStyle,
  2930. L"Engine", L"",
  2931. dwStyle,
  2932. // (GetSystemMetrics(SM_CXSCREEN) - WindowRect.right) / 2,
  2933. // (GetSystemMetrics(SM_CYSCREEN) - WindowRect.bottom) / 2,
  2934. WindowRect.left,
  2935. WindowRect.top,
  2936. WindowRect.right - WindowRect.left,
  2937. WindowRect.bottom - WindowRect.top,
  2938. nullptr,
  2939. nullptr,
  2940. hInstance,
  2941. // tunnel the WindowData we need to handle creation message
  2942. // lifetime is ensured because we are still on the stack when this is
  2943. // processed in the window proc
  2944. reinterpret_cast<void *>(&wd));
  2945. if (!wd.hWnd) {
  2946. MessageBoxW(nullptr, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
  2947. windows.erase(id);
  2948. ERR_FAIL_V_MSG(INVALID_WINDOW_ID, "Failed to create Windows OS window.");
  2949. }
  2950. if (p_mode == WINDOW_MODE_FULLSCREEN || p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  2951. wd.fullscreen = true;
  2952. if (p_mode == WINDOW_MODE_FULLSCREEN) {
  2953. wd.multiwindow_fs = true;
  2954. }
  2955. }
  2956. if (p_mode != WINDOW_MODE_FULLSCREEN && p_mode != WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  2957. wd.pre_fs_valid = true;
  2958. }
  2959. if (is_dark_mode_supported() && dark_title_available) {
  2960. BOOL value = is_dark_mode();
  2961. ::DwmSetWindowAttribute(wd.hWnd, DWMWA_USE_IMMERSIVE_DARK_MODE, &value, sizeof(value));
  2962. }
  2963. #ifdef VULKAN_ENABLED
  2964. if (context_vulkan) {
  2965. if (context_vulkan->window_create(id, p_vsync_mode, wd.hWnd, hInstance, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top) == -1) {
  2966. memdelete(context_vulkan);
  2967. context_vulkan = nullptr;
  2968. windows.erase(id);
  2969. ERR_FAIL_V_MSG(INVALID_WINDOW_ID, "Failed to create Vulkan Window.");
  2970. }
  2971. }
  2972. #endif
  2973. #ifdef GLES3_ENABLED
  2974. if (gl_manager) {
  2975. Error err = gl_manager->window_create(id, wd.hWnd, hInstance, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top);
  2976. // shut down OpenGL, to mirror behavior of Vulkan code
  2977. if (err != OK) {
  2978. memdelete(gl_manager);
  2979. gl_manager = nullptr;
  2980. windows.erase(id);
  2981. ERR_FAIL_V_MSG(INVALID_WINDOW_ID, "Failed to create an OpenGL window.");
  2982. }
  2983. }
  2984. #endif
  2985. RegisterTouchWindow(wd.hWnd, 0);
  2986. DragAcceptFiles(wd.hWnd, true);
  2987. if ((tablet_get_current_driver() == "wintab") && wintab_available) {
  2988. wintab_WTInfo(WTI_DEFSYSCTX, 0, &wd.wtlc);
  2989. wd.wtlc.lcOptions |= CXO_MESSAGES;
  2990. wd.wtlc.lcPktData = PK_STATUS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE | PK_ORIENTATION;
  2991. wd.wtlc.lcMoveMask = PK_STATUS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE;
  2992. wd.wtlc.lcPktMode = 0;
  2993. wd.wtlc.lcOutOrgX = 0;
  2994. wd.wtlc.lcOutExtX = wd.wtlc.lcInExtX;
  2995. wd.wtlc.lcOutOrgY = 0;
  2996. wd.wtlc.lcOutExtY = -wd.wtlc.lcInExtY;
  2997. wd.wtctx = wintab_WTOpen(wd.hWnd, &wd.wtlc, false);
  2998. if (wd.wtctx) {
  2999. wintab_WTEnable(wd.wtctx, true);
  3000. AXIS pressure;
  3001. if (wintab_WTInfo(WTI_DEVICES + wd.wtlc.lcDevice, DVC_NPRESSURE, &pressure)) {
  3002. wd.min_pressure = int(pressure.axMin);
  3003. wd.max_pressure = int(pressure.axMax);
  3004. }
  3005. AXIS orientation[3];
  3006. if (wintab_WTInfo(WTI_DEVICES + wd.wtlc.lcDevice, DVC_ORIENTATION, &orientation)) {
  3007. wd.tilt_supported = orientation[0].axResolution && orientation[1].axResolution;
  3008. }
  3009. } else {
  3010. print_verbose("WinTab context creation failed.");
  3011. }
  3012. } else {
  3013. wd.wtctx = 0;
  3014. }
  3015. if (p_mode == WINDOW_MODE_MAXIMIZED) {
  3016. wd.maximized = true;
  3017. wd.minimized = false;
  3018. }
  3019. if (p_mode == WINDOW_MODE_MINIMIZED) {
  3020. wd.maximized = false;
  3021. wd.minimized = true;
  3022. }
  3023. wd.last_pressure = 0;
  3024. wd.last_pressure_update = 0;
  3025. wd.last_tilt = Vector2();
  3026. // IME.
  3027. wd.im_himc = ImmGetContext(wd.hWnd);
  3028. ImmReleaseContext(wd.hWnd, wd.im_himc);
  3029. wd.im_position = Vector2();
  3030. // FIXME this is wrong in cases where the window coordinates were changed due to full screen mode; use WindowRect
  3031. wd.last_pos = p_rect.position;
  3032. wd.width = p_rect.size.width;
  3033. wd.height = p_rect.size.height;
  3034. window_id_counter++;
  3035. }
  3036. return id;
  3037. }
  3038. // WinTab API.
  3039. bool DisplayServerWindows::wintab_available = false;
  3040. WTOpenPtr DisplayServerWindows::wintab_WTOpen = nullptr;
  3041. WTClosePtr DisplayServerWindows::wintab_WTClose = nullptr;
  3042. WTInfoPtr DisplayServerWindows::wintab_WTInfo = nullptr;
  3043. WTPacketPtr DisplayServerWindows::wintab_WTPacket = nullptr;
  3044. WTEnablePtr DisplayServerWindows::wintab_WTEnable = nullptr;
  3045. // UXTheme API.
  3046. bool DisplayServerWindows::dark_title_available = false;
  3047. bool DisplayServerWindows::ux_theme_available = false;
  3048. IsDarkModeAllowedForAppPtr DisplayServerWindows::IsDarkModeAllowedForApp = nullptr;
  3049. ShouldAppsUseDarkModePtr DisplayServerWindows::ShouldAppsUseDarkMode = nullptr;
  3050. GetImmersiveColorFromColorSetExPtr DisplayServerWindows::GetImmersiveColorFromColorSetEx = nullptr;
  3051. GetImmersiveColorTypeFromNamePtr DisplayServerWindows::GetImmersiveColorTypeFromName = nullptr;
  3052. GetImmersiveUserColorSetPreferencePtr DisplayServerWindows::GetImmersiveUserColorSetPreference = nullptr;
  3053. // Windows Ink API.
  3054. bool DisplayServerWindows::winink_available = false;
  3055. GetPointerTypePtr DisplayServerWindows::win8p_GetPointerType = nullptr;
  3056. GetPointerPenInfoPtr DisplayServerWindows::win8p_GetPointerPenInfo = nullptr;
  3057. typedef enum _SHC_PROCESS_DPI_AWARENESS {
  3058. SHC_PROCESS_DPI_UNAWARE = 0,
  3059. SHC_PROCESS_SYSTEM_DPI_AWARE = 1,
  3060. SHC_PROCESS_PER_MONITOR_DPI_AWARE = 2
  3061. } SHC_PROCESS_DPI_AWARENESS;
  3062. bool DisplayServerWindows::is_dark_mode_supported() const {
  3063. return ux_theme_available && IsDarkModeAllowedForApp();
  3064. }
  3065. bool DisplayServerWindows::is_dark_mode() const {
  3066. return ux_theme_available && ShouldAppsUseDarkMode();
  3067. }
  3068. Color DisplayServerWindows::get_accent_color() const {
  3069. if (!ux_theme_available) {
  3070. return Color(0, 0, 0, 0);
  3071. }
  3072. int argb = GetImmersiveColorFromColorSetEx((UINT)GetImmersiveUserColorSetPreference(false, false), GetImmersiveColorTypeFromName(L"ImmersiveSystemAccent"), false, 0);
  3073. return Color((argb & 0xFF) / 255.f, ((argb & 0xFF00) >> 8) / 255.f, ((argb & 0xFF0000) >> 16) / 255.f, ((argb & 0xFF000000) >> 24) / 255.f);
  3074. }
  3075. int DisplayServerWindows::tablet_get_driver_count() const {
  3076. return tablet_drivers.size();
  3077. }
  3078. String DisplayServerWindows::tablet_get_driver_name(int p_driver) const {
  3079. if (p_driver < 0 || p_driver >= tablet_drivers.size()) {
  3080. return "";
  3081. } else {
  3082. return tablet_drivers[p_driver];
  3083. }
  3084. }
  3085. String DisplayServerWindows::tablet_get_current_driver() const {
  3086. return tablet_driver;
  3087. }
  3088. void DisplayServerWindows::tablet_set_current_driver(const String &p_driver) {
  3089. if (tablet_get_driver_count() == 0) {
  3090. return;
  3091. }
  3092. bool found = false;
  3093. for (int i = 0; i < tablet_get_driver_count(); i++) {
  3094. if (p_driver == tablet_get_driver_name(i)) {
  3095. found = true;
  3096. }
  3097. }
  3098. if (found) {
  3099. _update_tablet_ctx(tablet_driver, p_driver);
  3100. tablet_driver = p_driver;
  3101. } else {
  3102. ERR_PRINT("Unknown tablet driver " + p_driver + ".");
  3103. }
  3104. }
  3105. DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
  3106. drop_events = false;
  3107. key_event_pos = 0;
  3108. alt_mem = false;
  3109. gr_mem = false;
  3110. shift_mem = false;
  3111. control_mem = false;
  3112. meta_mem = false;
  3113. hInstance = static_cast<OS_Windows *>(OS::get_singleton())->get_hinstance();
  3114. pressrc = 0;
  3115. old_invalid = true;
  3116. mouse_mode = MOUSE_MODE_VISIBLE;
  3117. rendering_driver = p_rendering_driver;
  3118. // Init TTS
  3119. tts = memnew(TTS_Windows);
  3120. // Enforce default keep screen on value.
  3121. screen_set_keep_on(GLOBAL_GET("display/window/energy_saving/keep_screen_on"));
  3122. // Load Windows version info.
  3123. OSVERSIONINFOW os_ver;
  3124. ZeroMemory(&os_ver, sizeof(OSVERSIONINFOW));
  3125. os_ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
  3126. HMODULE nt_lib = LoadLibraryW(L"ntdll.dll");
  3127. if (nt_lib) {
  3128. RtlGetVersionPtr RtlGetVersion = (RtlGetVersionPtr)GetProcAddress(nt_lib, "RtlGetVersion");
  3129. if (RtlGetVersion) {
  3130. RtlGetVersion(&os_ver);
  3131. }
  3132. FreeLibrary(nt_lib);
  3133. }
  3134. // Load UXTheme.
  3135. HMODULE ux_theme_lib = LoadLibraryW(L"uxtheme.dll");
  3136. if (ux_theme_lib) {
  3137. IsDarkModeAllowedForApp = (IsDarkModeAllowedForAppPtr)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(136));
  3138. ShouldAppsUseDarkMode = (ShouldAppsUseDarkModePtr)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(132));
  3139. GetImmersiveColorFromColorSetEx = (GetImmersiveColorFromColorSetExPtr)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(95));
  3140. GetImmersiveColorTypeFromName = (GetImmersiveColorTypeFromNamePtr)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(96));
  3141. GetImmersiveUserColorSetPreference = (GetImmersiveUserColorSetPreferencePtr)GetProcAddress(ux_theme_lib, MAKEINTRESOURCEA(98));
  3142. ux_theme_available = IsDarkModeAllowedForApp && ShouldAppsUseDarkMode && GetImmersiveColorFromColorSetEx && GetImmersiveColorTypeFromName && GetImmersiveUserColorSetPreference;
  3143. if (os_ver.dwBuildNumber >= 22000) {
  3144. dark_title_available = true;
  3145. }
  3146. }
  3147. // Note: Wacom WinTab driver API for pen input, for devices incompatible with Windows Ink.
  3148. HMODULE wintab_lib = LoadLibraryW(L"wintab32.dll");
  3149. if (wintab_lib) {
  3150. wintab_WTOpen = (WTOpenPtr)GetProcAddress(wintab_lib, "WTOpenW");
  3151. wintab_WTClose = (WTClosePtr)GetProcAddress(wintab_lib, "WTClose");
  3152. wintab_WTInfo = (WTInfoPtr)GetProcAddress(wintab_lib, "WTInfoW");
  3153. wintab_WTPacket = (WTPacketPtr)GetProcAddress(wintab_lib, "WTPacket");
  3154. wintab_WTEnable = (WTEnablePtr)GetProcAddress(wintab_lib, "WTEnable");
  3155. wintab_available = wintab_WTOpen && wintab_WTClose && wintab_WTInfo && wintab_WTPacket && wintab_WTEnable;
  3156. }
  3157. if (wintab_available) {
  3158. tablet_drivers.push_back("wintab");
  3159. }
  3160. // Note: Windows Ink API for pen input, available on Windows 8+ only.
  3161. HMODULE user32_lib = LoadLibraryW(L"user32.dll");
  3162. if (user32_lib) {
  3163. win8p_GetPointerType = (GetPointerTypePtr)GetProcAddress(user32_lib, "GetPointerType");
  3164. win8p_GetPointerPenInfo = (GetPointerPenInfoPtr)GetProcAddress(user32_lib, "GetPointerPenInfo");
  3165. winink_available = win8p_GetPointerType && win8p_GetPointerPenInfo;
  3166. }
  3167. if (winink_available) {
  3168. tablet_drivers.push_back("winink");
  3169. }
  3170. if (OS::get_singleton()->is_hidpi_allowed()) {
  3171. HMODULE Shcore = LoadLibraryW(L"Shcore.dll");
  3172. if (Shcore != nullptr) {
  3173. typedef HRESULT(WINAPI * SetProcessDpiAwareness_t)(SHC_PROCESS_DPI_AWARENESS);
  3174. SetProcessDpiAwareness_t SetProcessDpiAwareness = (SetProcessDpiAwareness_t)GetProcAddress(Shcore, "SetProcessDpiAwareness");
  3175. if (SetProcessDpiAwareness) {
  3176. SetProcessDpiAwareness(SHC_PROCESS_SYSTEM_DPI_AWARE);
  3177. }
  3178. }
  3179. }
  3180. memset(&wc, 0, sizeof(WNDCLASSEXW));
  3181. wc.cbSize = sizeof(WNDCLASSEXW);
  3182. wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
  3183. wc.lpfnWndProc = (WNDPROC)::WndProc;
  3184. wc.cbClsExtra = 0;
  3185. wc.cbWndExtra = 0;
  3186. wc.hInstance = hInstance ? hInstance : GetModuleHandle(nullptr);
  3187. wc.hIcon = LoadIcon(nullptr, IDI_WINLOGO);
  3188. wc.hCursor = nullptr;
  3189. wc.hbrBackground = nullptr;
  3190. wc.lpszMenuName = nullptr;
  3191. wc.lpszClassName = L"Engine";
  3192. if (!RegisterClassExW(&wc)) {
  3193. MessageBox(nullptr, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
  3194. r_error = ERR_UNAVAILABLE;
  3195. return;
  3196. }
  3197. _register_raw_input_devices(INVALID_WINDOW_ID);
  3198. #if defined(VULKAN_ENABLED)
  3199. if (rendering_driver == "vulkan") {
  3200. context_vulkan = memnew(VulkanContextWindows);
  3201. if (context_vulkan->initialize() != OK) {
  3202. memdelete(context_vulkan);
  3203. context_vulkan = nullptr;
  3204. r_error = ERR_UNAVAILABLE;
  3205. return;
  3206. }
  3207. }
  3208. #endif
  3209. // Init context and rendering device
  3210. #if defined(GLES3_ENABLED)
  3211. if (rendering_driver == "opengl3") {
  3212. GLManager_Windows::ContextType opengl_api_type = GLManager_Windows::GLES_3_0_COMPATIBLE;
  3213. gl_manager = memnew(GLManager_Windows(opengl_api_type));
  3214. if (gl_manager->initialize() != OK) {
  3215. memdelete(gl_manager);
  3216. gl_manager = nullptr;
  3217. r_error = ERR_UNAVAILABLE;
  3218. return;
  3219. }
  3220. RasterizerGLES3::make_current();
  3221. }
  3222. #endif
  3223. mouse_monitor = SetWindowsHookEx(WH_MOUSE, ::MouseProc, nullptr, GetCurrentThreadId());
  3224. Point2i window_position(
  3225. (screen_get_size(0).width - p_resolution.width) / 2,
  3226. (screen_get_size(0).height - p_resolution.height) / 2);
  3227. WindowID main_window = _create_window(p_mode, p_vsync_mode, 0, Rect2i(window_position, p_resolution));
  3228. ERR_FAIL_COND_MSG(main_window == INVALID_WINDOW_ID, "Failed to create main window.");
  3229. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  3230. if (p_flags & (1 << i)) {
  3231. window_set_flag(WindowFlags(i), true, main_window);
  3232. }
  3233. }
  3234. show_window(MAIN_WINDOW_ID);
  3235. #if defined(VULKAN_ENABLED)
  3236. if (rendering_driver == "vulkan") {
  3237. rendering_device_vulkan = memnew(RenderingDeviceVulkan);
  3238. rendering_device_vulkan->initialize(context_vulkan);
  3239. RendererCompositorRD::make_current();
  3240. }
  3241. #endif
  3242. if (!Engine::get_singleton()->is_editor_hint() && !OS::get_singleton()->is_in_low_processor_usage_mode()) {
  3243. // Increase priority for projects that are not in low-processor mode (typically games)
  3244. // to reduce the risk of frame stuttering.
  3245. // This is not done for the editor to prevent importers or resource bakers
  3246. // from making the system unresponsive.
  3247. SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
  3248. DWORD index = 0;
  3249. HANDLE handle = AvSetMmThreadCharacteristics("Games", &index);
  3250. if (handle) {
  3251. AvSetMmThreadPriority(handle, AVRT_PRIORITY_CRITICAL);
  3252. }
  3253. // This is needed to make sure that background work does not starve the main thread.
  3254. // This is only setting the priority of this thread, not the whole process.
  3255. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  3256. }
  3257. cursor_shape = CURSOR_ARROW;
  3258. _update_real_mouse_position(MAIN_WINDOW_ID);
  3259. joypad = new JoypadWindows(&windows[MAIN_WINDOW_ID].hWnd);
  3260. r_error = OK;
  3261. static_cast<OS_Windows *>(OS::get_singleton())->set_main_window(windows[MAIN_WINDOW_ID].hWnd);
  3262. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events);
  3263. }
  3264. Vector<String> DisplayServerWindows::get_rendering_drivers_func() {
  3265. Vector<String> drivers;
  3266. #ifdef VULKAN_ENABLED
  3267. drivers.push_back("vulkan");
  3268. #endif
  3269. #ifdef GLES3_ENABLED
  3270. drivers.push_back("opengl3");
  3271. #endif
  3272. return drivers;
  3273. }
  3274. DisplayServer *DisplayServerWindows::create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
  3275. DisplayServer *ds = memnew(DisplayServerWindows(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_resolution, r_error));
  3276. if (r_error != OK) {
  3277. OS::get_singleton()->alert("Your video card driver does not support any of the supported Vulkan or OpenGL versions.\n"
  3278. "Please update your drivers or if you have a very old or integrated GPU upgrade it.",
  3279. "Unable to initialize Video driver");
  3280. }
  3281. return ds;
  3282. }
  3283. void DisplayServerWindows::register_windows_driver() {
  3284. register_create_function("windows", create_func, get_rendering_drivers_func);
  3285. }
  3286. DisplayServerWindows::~DisplayServerWindows() {
  3287. delete joypad;
  3288. touch_state.clear();
  3289. cursors_cache.clear();
  3290. if (mouse_monitor) {
  3291. UnhookWindowsHookEx(mouse_monitor);
  3292. }
  3293. if (user_proc) {
  3294. SetWindowLongPtr(windows[MAIN_WINDOW_ID].hWnd, GWLP_WNDPROC, (LONG_PTR)user_proc);
  3295. }
  3296. // Close power request handle.
  3297. screen_set_keep_on(false);
  3298. #ifdef GLES3_ENABLED
  3299. // destroy windows .. NYI?
  3300. // FIXME wglDeleteContext is never called
  3301. #endif
  3302. if (windows.has(MAIN_WINDOW_ID)) {
  3303. #ifdef VULKAN_ENABLED
  3304. if (context_vulkan) {
  3305. context_vulkan->window_destroy(MAIN_WINDOW_ID);
  3306. }
  3307. #endif
  3308. if (wintab_available && windows[MAIN_WINDOW_ID].wtctx) {
  3309. wintab_WTClose(windows[MAIN_WINDOW_ID].wtctx);
  3310. windows[MAIN_WINDOW_ID].wtctx = 0;
  3311. }
  3312. DestroyWindow(windows[MAIN_WINDOW_ID].hWnd);
  3313. }
  3314. #if defined(VULKAN_ENABLED)
  3315. if (rendering_device_vulkan) {
  3316. rendering_device_vulkan->finalize();
  3317. memdelete(rendering_device_vulkan);
  3318. rendering_device_vulkan = nullptr;
  3319. }
  3320. if (context_vulkan) {
  3321. memdelete(context_vulkan);
  3322. context_vulkan = nullptr;
  3323. }
  3324. #endif
  3325. if (restore_mouse_trails > 1) {
  3326. SystemParametersInfoA(SPI_SETMOUSETRAILS, restore_mouse_trails, 0, 0);
  3327. }
  3328. #ifdef GLES3_ENABLED
  3329. if (gl_manager) {
  3330. memdelete(gl_manager);
  3331. gl_manager = nullptr;
  3332. }
  3333. #endif
  3334. if (tts) {
  3335. memdelete(tts);
  3336. }
  3337. CoUninitialize();
  3338. }