display_server_windows.cpp 119 KB

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