display_server_windows.cpp 116 KB

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