display_server_windows.cpp 102 KB

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