display_server_windows.cpp 102 KB

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