display_server_windows.cpp 100 KB

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