display_server_windows.cpp 105 KB

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