display_server_windows.cpp 104 KB

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