display_server_windows.cpp 114 KB

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